private void fillSchedule(DeliveryZoneProgramSchedule deliveryZoneProgramSchedule) {
    ProcessingSchedule schedule =
        scheduleService.getByCode(deliveryZoneProgramSchedule.getSchedule().getCode());
    if (schedule == null) throw new DataException("schedule.code.invalid");

    deliveryZoneProgramSchedule.setSchedule(schedule);
  }
  public void fillFieldsForInitiatedRequisition(
      Rnr requisition, ProgramRnrTemplate rnrTemplate, RegimenTemplate regimenTemplate) {
    List<ProcessingPeriod> fivePreviousPeriods =
        processingScheduleService.getNPreviousPeriodsInDescOrder(
            requisition.getPeriod(), MAX_NUMBER_OF_PERIODS_TO_TRACK);

    if (fivePreviousPeriods.size() == 0) {
      requisition.setFieldsAccordingToTemplateFrom(null, rnrTemplate, regimenTemplate);
      fillPreviousNCsInLineItems(
          requisition,
          requisition.getPeriod().getNumberOfMonths(),
          requisition.getPeriod().getStartDate());
      return;
    }

    Rnr previousRequisition =
        requisitionRepository.getRegularRequisitionWithLineItems(
            requisition.getFacility(), requisition.getProgram(), fivePreviousPeriods.get(0));
    requisition.setFieldsAccordingToTemplateFrom(previousRequisition, rnrTemplate, regimenTemplate);

    Integer numberOfMonths = fivePreviousPeriods.get(0).getNumberOfMonths();
    Date trackingDate = fivePreviousPeriods.get(0).getStartDate();

    int lastPeriodIndex = MAX_NUMBER_OF_PERIODS_TO_TRACK - 1;
    int secondPeriodIndex = 1;

    if (numberOfMonths == 1) {
      trackingDate = getStartDateForNthPreviousPeriod(fivePreviousPeriods, lastPeriodIndex);
    } else if (numberOfMonths == 2) {
      trackingDate = getStartDateForNthPreviousPeriod(fivePreviousPeriods, secondPeriodIndex);
    }

    fillPreviousNCsInLineItems(requisition, numberOfMonths, trackingDate);
  }
 @RequestMapping(value = "/schedules/{scheduleId}/periods", method = GET, headers = ACCEPT_JSON)
 @PreAuthorize("@permissionEvaluator.hasPermission(principal,'MANAGE_SCHEDULE')")
 public ResponseEntity<OpenLmisResponse> getAll(@PathVariable("scheduleId") Long scheduleId) {
   List<ProcessingPeriod> periodList = processingScheduleService.getAllPeriods(scheduleId);
   ResponseEntity<OpenLmisResponse> response = OpenLmisResponse.response(PERIODS, periodList);
   if (!periodList.isEmpty())
     response.getBody().addData(NEXT_START_DATE, periodList.get(0).getNextStartDate());
   return response;
 }
 @RequestMapping(value = "/periods/{id}", method = DELETE, headers = ACCEPT_JSON)
 @PreAuthorize("@permissionEvaluator.hasPermission(principal,'MANAGE_SCHEDULE')")
 public ResponseEntity<OpenLmisResponse> delete(@PathVariable("id") Long id) {
   try {
     processingScheduleService.deletePeriod(id);
   } catch (DataException e) {
     return error(e, HttpStatus.BAD_REQUEST);
   }
   return success(messageService.message("message.period.deleted.success"));
 }
  @RequestMapping(value = "/schedules/{scheduleId}/periods", method = POST, headers = ACCEPT_JSON)
  @PreAuthorize("@permissionEvaluator.hasPermission(principal,'MANAGE_SCHEDULE')")
  public ResponseEntity<OpenLmisResponse> save(
      @PathVariable("scheduleId") Long scheduleId,
      @RequestBody ProcessingPeriod processingPeriod,
      HttpServletRequest request) {
    processingPeriod.setScheduleId(scheduleId);

    processingPeriod.setModifiedBy(loggedInUserId(request));

    processingPeriod.setCreatedBy(loggedInUserId(request));

    try {
      processingScheduleService.savePeriod(processingPeriod);
    } catch (Exception e) {
      return error(new DataException(e.getMessage()), HttpStatus.BAD_REQUEST);
    }
    ResponseEntity<OpenLmisResponse> successResponse =
        success(messageService.message("message.period.added.success"));
    successResponse.getBody().addData("id", processingPeriod.getId());
    return successResponse;
  }
  public void fillReportingDays(Rnr requisition) {
    Date startDate = requisition.getPeriod().getStartDate();
    Integer numberOfMonths = requisition.getPeriod().getNumberOfMonths();

    List<ProcessingPeriod> twoPreviousPeriods =
        processingScheduleService.getNPreviousPeriodsInDescOrder(requisition.getPeriod(), 2);

    if (twoPreviousPeriods.size() != 0) {
      numberOfMonths = twoPreviousPeriods.get(0).getNumberOfMonths();
      startDate =
          (numberOfMonths < 3 && twoPreviousPeriods.size() != 1)
              ? twoPreviousPeriods.get(1).getStartDate()
              : twoPreviousPeriods.get(0).getStartDate();
    }

    for (RnrLineItem lineItem : requisition.getNonSkippedLineItems()) {
      Integer reportingDays =
          getReportingDaysBasedOnRequisition(
              requisition, lineItem.getProductCode(), startDate, numberOfMonths);
      lineItem.setReportingDays(reportingDays);
    }
  }
 @RequestMapping(value = "/periods/{id}", method = GET, headers = ACCEPT_JSON)
 @PreAuthorize("@permissionEvaluator.hasPermission(principal,'MANAGE_DISTRIBUTION')")
 public ResponseEntity<OpenLmisResponse> get(@PathVariable("id") Long id) {
   ProcessingPeriod processingPeriod = processingScheduleService.getPeriodById(id);
   return response("period", processingPeriod);
 }
 public List<ProcessingPeriod> getPeriodsForDeliveryZoneAndProgram(Long zoneId, Long programId) {
   ProcessingSchedule schedule =
       repository.getProcessingScheduleByZoneAndProgram(zoneId, programId);
   return scheduleService.getAllPeriodsBefore(schedule.getId(), null);
 }