class TenderPercentagesController extends GenericOCDSController {

    @ApiOperation("Percentage of tenders that are associated in releases that "
            + "have the planning.budget.amount non empty,"
            + "meaning there really is a planning entity correlated with the tender entity."
            + "This endpoint uses tender.tenderPeriod.startDate to calculate the tender year.")
    @RequestMapping(value = "/api/percentTendersWithLinkedProcurementPlan",
            method = {RequestMethod.POST, RequestMethod.GET}, produces = "application/json")
    public List<Document> percentTendersWithLinkedProcurementPlan(@ModelAttribute
                                                                  @Valid final YearFilterPagingRequest filter) {

        DBObject project1 = new BasicDBObject();
        addYearlyMonthlyProjection(filter, project1, "$tender.tenderPeriod.startDate");
        project1.put("tender._id", 1);
        project1.put("planning.budget.amount", 1);

        DBObject group = new BasicDBObject();
        addYearlyMonthlyReferenceToGroup(filter, group);
        group.put(Keys.TOTAL_TENDERS, new BasicDBObject("$sum", 1));
        group.put(Keys.TOTAL_TENDERS_WITH_LINKED_PROCUREMENT_PLAN, new BasicDBObject("$sum", new BasicDBObject(
                "$cond",
                Arrays.asList(new BasicDBObject("$gt", Arrays.asList("$planning.budget.amount", null)), 1, 0)
        )));

        DBObject project2 = new BasicDBObject();
        project2.put(Keys.YEAR, 1);
        project2.put("month", 1);
        project2.put(Keys.TOTAL_TENDERS, 1);
        project2.put(Keys.TOTAL_TENDERS_WITH_LINKED_PROCUREMENT_PLAN, 1);
        project2.put(
                Keys.PERCENT_TENDERS,
                new BasicDBObject(
                        "$multiply",
                        Arrays.asList(
                                new BasicDBObject("$divide", Arrays.asList(
                                        "$" + Keys.TOTAL_TENDERS_WITH_LINKED_PROCUREMENT_PLAN,
                                        "$" + Keys.TOTAL_TENDERS
                                )),
                                100
                        )
                )
        );

        Aggregation agg = newAggregation(
                match(where("tender.tenderPeriod.startDate").exists(true)
                        .andOperator(getYearDefaultFilterCriteria(filter, "tender.tenderPeriod.startDate"))),
                new CustomProjectionOperation(project1), new CustomGroupingOperation(group),
                transformYearlyGrouping(filter).andInclude(Keys.TOTAL_TENDERS,
                        Keys.TOTAL_TENDERS_WITH_LINKED_PROCUREMENT_PLAN, Keys.PERCENT_TENDERS
                ),
                new CustomProjectionOperation(project2),
                getSortByYearMonth(filter), skip(filter.getSkip()), limit(filter.getPageSize())
        );

        return releaseAgg(agg);
    }

}