@Override
  public String execute() throws Exception {
    Program program = programService.getProgram(programId);

    Collection<OrganisationUnit> orgunits = selectionTreeManager.getRootOrganisationUnits();

    program = programService.getProgram(programId);

    // ---------------------------------------------------------------------
    // Get orgunitIds
    // ---------------------------------------------------------------------

    Collection<Integer> orgunitIds = new HashSet<>();

    for (OrganisationUnit orgunit : orgunits) {
      if (facilityLB.equals("selected")) {
        orgunitIds.add(orgunit.getId());
      } else if (facilityLB.equals("childrenOnly")) {
        orgunitIds.addAll(
            organisationUnitService.getOrganisationUnitHierarchy().getChildren(orgunit.getId()));
        orgunitIds.remove(orgunit.getId());
      } else {
        orgunitIds.addAll(
            organisationUnitService.getOrganisationUnitHierarchy().getChildren(orgunit.getId()));
      }
    }

    if (orgunitIds.size() > 0) {
      grid =
          programStageInstanceService.getCompletenessProgramStageInstance(
              orgunitIds, program, startDate, endDate, i18n);
    }

    return (type == null) ? SUCCESS : type;
  }
  private Collection<OrganisationUnit> reloadOrganisationUnits(Collection<OrganisationUnit> units) {
    Set<OrganisationUnit> reloadedUnits = new HashSet<>();

    int noTotal = organisationUnitService.getNumberOfOrganisationUnits();

    int noSelected = units.size();

    if ((double) noSelected / noTotal
        > PERCENTAGE_OF_MULTIPLE_RELOADING_ORG_UNITS) // Select all at once
    {
      Collection<OrganisationUnit> allOrgUnits = organisationUnitService.getAllOrganisationUnits();

      for (OrganisationUnit unit : allOrgUnits) {
        if (units.contains(unit)) {
          reloadedUnits.add(unit);
        }
      }
    } else // Select one by one
    {
      for (OrganisationUnit unit : units) {
        OrganisationUnit reloadedUnit = reloadOrganisationUnit(unit);

        if (reloadedUnit != null) {
          reloadedUnits.add(reloadedUnit);
        }
      }
    }
    return reloadedUnits;
  }
  public String execute() throws Exception {
    // ---------------------------------------------------------------------
    // Get parent
    // ---------------------------------------------------------------------

    OrganisationUnit newParent;

    if (newParentOrganisationUnitId != null) {
      newParent =
          organisationUnitService.getOrganisationUnit(newParentOrganisationUnitId.intValue());
    } else {
      newParent = selectionManager.getRootOrganisationUnitsParent();
    }

    // ---------------------------------------------------------------------
    // Update unit to move
    // ---------------------------------------------------------------------

    OrganisationUnit unitToMove =
        organisationUnitService.getOrganisationUnit(organisationUnitToMoveId.intValue());

    unitToMove.setParent(newParent);

    organisationUnitService.updateOrganisationUnit(unitToMove);

    organisationUnitService.addOrganisationUnitHierarchy(new Date());

    return SUCCESS;
  }
  private Collection<OrganisationUnit> getHierarchy() {
    Collection<OrganisationUnit> hierarchy = new ArrayList<OrganisationUnit>();

    Collection<OrganisationUnit> roots = organisationUnitService.getRootOrganisationUnits();

    for (OrganisationUnit root : roots) {
      hierarchy.addAll(organisationUnitService.getOrganisationUnitWithChildren(root.getId()));
    }

    return hierarchy;
  }
  @Override
  protected OrganisationUnitLevel getMatching(OrganisationUnitLevel object) {
    OrganisationUnitLevel match =
        organisationUnitService.getOrganisationUnitLevelByLevel(object.getLevel());

    if (match == null) {
      List<OrganisationUnitLevel> organisationUnitLevelByName =
          organisationUnitService.getOrganisationUnitLevelByName(object.getName());
      match = organisationUnitLevelByName.isEmpty() ? null : organisationUnitLevelByName.get(0);
    }

    return match;
  }
  @Override
  protected void importMatching(OrganisationUnitLevel object, OrganisationUnitLevel match) {
    match.setLevel(object.getLevel());
    match.setName(object.getName());

    organisationUnitService.updateOrganisationUnitLevel(match);
  }
  public String execute() {

    //        System.out.println("ID in GetNumberofLevelsAction : "+id);
    levels = organisationUnitService.getOrganisationUnitLevels();
    ;

    return SUCCESS;
  }
  public void postObject(
      HttpServletResponse response, HttpServletRequest request, Message message) {
    List<User> users = new ArrayList<User>(message.getUsers());
    message.getUsers().clear();

    for (OrganisationUnit ou : message.getOrganisationUnits()) {
      OrganisationUnit organisationUnit = organisationUnitService.getOrganisationUnit(ou.getUid());

      if (organisationUnit == null) {
        ContextUtils.conflictResponse(response, "Organisation Unit does not exist: " + ou.getUid());
        return;
      }

      message.getUsers().addAll(organisationUnit.getUsers());
    }

    for (User u : users) {
      User user = userService.getUser(u.getUid());

      if (user == null) {
        ContextUtils.conflictResponse(response, "User does not exist: " + u.getUid());
        return;
      }

      message.getUsers().add(user);
    }

    for (UserGroup ug : message.getUserGroups()) {
      UserGroup userGroup = userGroupService.getUserGroup(ug.getUid());

      if (userGroup == null) {
        ContextUtils.conflictResponse(response, "User Group does not exist: " + ug.getUid());
        return;
      }

      message.getUsers().addAll(userGroup.getMembers());
    }

    if (message.getUsers().isEmpty()) {
      ContextUtils.conflictResponse(response, "No recipients selected.");
      return;
    }

    String metaData =
        MessageService.META_USER_AGENT + request.getHeader(ContextUtils.HEADER_USER_AGENT);

    int id =
        messageService.sendMessage(
            message.getSubject(), message.getText(), metaData, message.getUsers());

    MessageConversation conversation = messageService.getMessageConversation(id);

    ContextUtils.createdResponse(
        response,
        "Message conversation created",
        MessageConversationController.RESOURCE_PATH + "/" + conversation.getUid());
  }
  @Override
  public Collection<OrganisationUnit> getRootOrganisationUnits() {
    Collection<OrganisationUnit> rootUnits = getCollectionFromSession(SESSION_KEY_ROOT_ORG_UNITS);

    if (rootUnits == null) {
      return organisationUnitService.getRootOrganisationUnits();
    }

    return reloadOrganisationUnits(rootUnits);
  }
  // -------------------------------------------------------------------------
  // Action implementation
  // -------------------------------------------------------------------------
  public String execute() throws Exception {
    statementManager.initialise();

    Program selProgram = programService.getProgram(programList);

    OrganisationUnit selOrgUnit = organisationUnitService.getOrganisationUnit(ouIDTB);

    System.out.println(
        "NBITS Report_"
            + selOrgUnit.getName()
            + "_"
            + selProgram.getName()
            + "_StartTime: "
            + new Date());

    List<OrganisationUnit> orgUnitList =
        new ArrayList<OrganisationUnit>(
            organisationUnitService.getOrganisationUnitWithChildren(ouIDTB));

    List<OrganisationUnit> programOrgUnits =
        new ArrayList<OrganisationUnit>(selProgram.getOrganisationUnits());

    orgUnitList.retainAll(programOrgUnits);

    Date sDate = format.parseDate(startDate);

    Date eDate = format.parseDate(endDate);

    System.out.println("Start Date" + sDate + "-----" + "End Date: " + eDate);
    generateReport(selProgram, orgUnitList, sDate, eDate);

    System.out.println(
        "NBITS Report_"
            + selOrgUnit.getName()
            + "_"
            + selProgram.getName()
            + "_EndTime: "
            + new Date());

    statementManager.destroy();

    return SUCCESS;
  }
  @Test
  public void testAverageIntDataElement() {
    DataElement dataElement = createDataElement('A', categoryCombo);

    dataElement.setType(DataElement.VALUE_TYPE_INT);
    dataElement.setAggregationOperator(DataElement.AGGREGATION_OPERATOR_AVERAGE_SUM);

    dataElementIds.add(dataElementService.addDataElement(dataElement));

    DataSet dataSet = createDataSet('A', new YearlyPeriodType());
    dataSet.getDataElements().add(dataElement);
    dataSetService.addDataSet(dataSet);
    dataElement.getDataSets().add(dataSet);
    dataElementService.updateDataElement(dataElement);

    Period dataPeriod =
        createPeriod(new YearlyPeriodType(), getDate(2000, 1, 1), getDate(2000, 12, 31));

    OrganisationUnit unit = createOrganisationUnit('A');

    organisationUnitIds.add(organisationUnitService.addOrganisationUnit(unit));

    dataValueService.addDataValue(
        createDataValue(dataElement, dataPeriod, unit, "100", categoryOptionCombo));

    Period periodA =
        createPeriod(new MonthlyPeriodType(), getDate(2000, 3, 1), getDate(2000, 3, 31));
    Period periodB =
        createPeriod(new MonthlyPeriodType(), getDate(2000, 4, 1), getDate(2000, 4, 30));
    Period periodC =
        createPeriod(new QuarterlyPeriodType(), getDate(2000, 3, 1), getDate(2000, 5, 31));

    periodIds.add(periodService.addPeriod(periodA));
    periodIds.add(periodService.addPeriod(periodB));
    periodIds.add(periodService.addPeriod(periodC));

    dataMartEngine.export(dataElementIds, indicatorIds, periodIds, organisationUnitIds);

    assertEquals(
        100.0,
        aggregatedDataValueService.getAggregatedValue(
            dataElement, categoryOptionCombo, periodA, unit),
        DELTA);
    assertEquals(
        100.0,
        aggregatedDataValueService.getAggregatedValue(
            dataElement, categoryOptionCombo, periodB, unit),
        DELTA);
    assertEquals(
        100.0,
        aggregatedDataValueService.getAggregatedValue(
            dataElement, categoryOptionCombo, periodC, unit),
        DELTA);
  }
  @Override
  public void scheduledRun() {
    log.info("Starting scheduled monitoring task");

    // Find all the rules belonging to groups that will send alerts to user roles.

    Set<ValidationRule> rules = getAlertRules();

    Collection<OrganisationUnit> sources = organisationUnitService.getAllOrganisationUnits();

    Set<Period> periods = getAlertPeriodsFromRules(rules);

    Date lastScheduledRun =
        (Date) systemSettingManager.getSystemSetting(SystemSettingManager.KEY_LAST_MONITORING_RUN);

    // Any database changes after this moment will contribute to the next run.

    Date thisRun = new Date();

    log.info(
        "Scheduled monitoring run sources: "
            + sources.size()
            + ", periods: "
            + periods.size()
            + ", rules:"
            + rules.size()
            + ", last run: "
            + (lastScheduledRun == null ? "[none]" : lastScheduledRun));

    Collection<ValidationResult> results =
        Validator.validate(
            sources,
            periods,
            rules,
            null,
            lastScheduledRun,
            constantService,
            expressionService,
            periodService,
            dataValueService,
            dataElementCategoryService,
            userService,
            currentUserService);

    log.info("Validation run result count: " + results.size());

    if (!results.isEmpty()) {
      postAlerts(results, thisRun);
    }

    log.info("Posted alerts, monitoring task done");

    systemSettingManager.saveSystemSetting(SystemSettingManager.KEY_LAST_MONITORING_RUN, thisRun);
  }
示例#13
0
  @Override
  public void setUpTest() {
    organisationUnit = createOrganisationUnit('A');
    organisationUnitLevel = new OrganisationUnitLevel(1, "Level");

    organisationUnitService.addOrganisationUnit(organisationUnit);
    organisationUnitService.addOrganisationUnitLevel(organisationUnitLevel);

    indicatorGroup = createIndicatorGroup('A');
    indicatorService.addIndicatorGroup(indicatorGroup);

    indicatorType = createIndicatorType('A');
    indicatorService.addIndicatorType(indicatorType);

    indicator = createIndicator('A', indicatorType);
    indicatorService.addIndicator(indicator);

    dataElement = createDataElement('A');
    dataElementService.addDataElement(dataElement);

    dataElementGroup = createDataElementGroup('A');
    dataElementGroup.getMembers().add(dataElement);
    dataElementService.addDataElementGroup(dataElementGroup);

    periodType = periodService.getPeriodTypeByName(MonthlyPeriodType.NAME);
    period = createPeriod(periodType, getDate(2000, 1, 1), getDate(2000, 2, 1));
    periodService.addPeriod(period);

    mapLegendSet = createLegendSet('A');
    legendService.addLegendSet(mapLegendSet);

    internalMapLayer = new InternalMapLayer();
    internalMapLayer.setRadiusLow(15);
    internalMapLayer.setRadiusHigh(35);
    internalMapLayer.setColorLow(Color.YELLOW);
    internalMapLayer.setColorHigh(Color.RED);
    internalMapLayer.setOpacity(0.5f);
  }
  @Override
  public void setUpTest() {
    organisationUnit = createOrganisationUnit('A');
    organisationUnitService.addOrganisationUnit(organisationUnit);

    Program program = createProgram('A', new HashSet<ProgramStage>(), organisationUnit);
    programService.addProgram(program);

    stageA = new ProgramStage("A", program);
    programStageService.saveProgramStage(stageA);

    DataElement dataElementA = createDataElement('A');
    DataElement dataElementB = createDataElement('B');

    dataElementService.addDataElement(dataElementA);
    dataElementService.addDataElement(dataElementB);

    ProgramStageDataElement stageDeA = new ProgramStageDataElement(stageA, dataElementA, false, 1);
    ProgramStageDataElement stageDeB = new ProgramStageDataElement(stageA, dataElementB, false, 2);

    programStageDataElementService.addProgramStageDataElement(stageDeA);
    programStageDataElementService.addProgramStageDataElement(stageDeB);

    List<ProgramStageDataElement> psDataElements = new ArrayList<>();
    psDataElements.add(stageDeA);
    psDataElements.add(stageDeB);

    stageB = new ProgramStage("B", program);
    programStageService.saveProgramStage(stageB);

    Set<ProgramStage> programStages = new HashSet<>();
    programStages.add(stageA);
    programStages.add(stageB);
    program.setProgramStages(programStages);
    programService.updateProgram(program);

    sectionA = new ProgramStageSection();
    sectionA.setName("A");
    sectionA.setProgramStageDataElements(psDataElements);
    sectionA.setSortOrder(1);

    sectionB = new ProgramStageSection();
    sectionB.setName("B");
    sectionB.setSortOrder(2);

    Set<ProgramStageSection> sections = new HashSet<>();
    sections.add(sectionA);
    sections.add(sectionB);
    stageA.setProgramStageSections(sections);
  }
  @Override
  public Set<OrganisationUnitLevel> getOrganisationUnitApprovalLevels() {
    Set<OrganisationUnitLevel> orgUnitLevels = new HashSet<>();

    List<DataApprovalLevel> dataApprovalLevels = dataApprovalLevelStore.getAllDataApprovalLevels();

    for (DataApprovalLevel level : dataApprovalLevels) {
      OrganisationUnitLevel orgUnitLevel =
          organisationUnitService.getOrganisationUnitLevelByLevel(level.getOrgUnitLevel());

      if (orgUnitLevel != null) {
        orgUnitLevels.add(orgUnitLevel);
      }
    }

    return orgUnitLevels;
  }
  public String execute() throws Exception {
    // OrganisationUnit organisationUnit = selectedStateManager.getSelectedOrganisationUnit();
    organisationUnit = organisationUnitService.getOrganisationUnit(ouIDTB);
    // ---------------------------------------------------------------------
    // Get all of patients into the selected organisation unit
    // ---------------------------------------------------------------------
    /*
        if ( listAll != null && listAll )
        {
            listAllPatient( organisationUnit );

            return SUCCESS;
        }
    */
    // ---------------------------------------------------------------------
    // Search patients by attributes
    // ---------------------------------------------------------------------

    // System.out.println( "searchingAttributeId= "  + searchingAttributeId + "---,searchText= " +
    // searchText );

    // System.out.println( "OrganisationUnit= "  + ouIDTB + "---,is Selected Org checked = " +
    // isSelectedOrg );

    raFolderName = reportService.getRAFolderName();

    programList = new ArrayList<ProgramDetail>();

    for (Integer attributeId : searchingAttributeId) {
      if (attributeId != null && attributeId != 0) {
        patientAttributes.add(patientAttributeService.getPatientAttribute(attributeId));
      }
    }

    if (isSelectedOrg) {
      searchPatientByNameAndOrgUnit(searchText, organisationUnit);
    } else {
      searchPatientByAttributes(searchingAttributeId, searchText);
      // searchPatientByNameAndOrgUnit( searchText , organisationUnit );
    }

    getProgramDetailList();

    return SUCCESS;
  }
  @Override
  public Map<OrganisationUnit, Integer> getUserReadApprovalLevels(DataApprovalLevel approvalLevel) {
    Map<OrganisationUnit, Integer> map = new HashMap<>();

    User user = currentUserService.getCurrentUser();

    Collection<OrganisationUnit> orgUnits = user.getDataViewOrganisationUnits();

    if (orgUnits == null || orgUnits.isEmpty()) {
      orgUnits = organisationUnitService.getRootOrganisationUnits();
    }

    for (OrganisationUnit orgUnit : orgUnits) {
      map.put(orgUnit, approvalLevel.getLevel());
    }

    return map;
  }
  @Override
  public List<DataApprovalLevel> getAllDataApprovalLevels() {
    List<DataApprovalLevel> dataApprovalLevels = dataApprovalLevelStore.getAllDataApprovalLevels();

    for (DataApprovalLevel dataApprovalLevel : dataApprovalLevels) {
      int ouLevelNumber = dataApprovalLevel.getOrgUnitLevel();

      OrganisationUnitLevel ouLevel =
          organisationUnitService.getOrganisationUnitLevelByLevel(ouLevelNumber);

      String ouLevelName =
          ouLevel != null ? ouLevel.getName() : "Organisation unit level " + ouLevelNumber;

      dataApprovalLevel.setOrgUnitLevelName(ouLevelName);
    }

    return dataApprovalLevels;
  }
  @Override
  public Map<OrganisationUnit, Integer> getUserReadApprovalLevels() {
    Map<OrganisationUnit, Integer> map = new HashMap<>();

    User user = currentUserService.getCurrentUser();

    List<DataApprovalLevel> approvalLevels = getAllDataApprovalLevels();

    // ---------------------------------------------------------------------
    // Add user organisation units if authorized to approve at lower levels
    // ---------------------------------------------------------------------

    if (user.getUserCredentials().isAuthorized(DataApproval.AUTH_APPROVE_LOWER_LEVELS)) {
      for (OrganisationUnit orgUnit : user.getOrganisationUnits()) {
        map.put(orgUnit, APPROVAL_LEVEL_UNAPPROVED);
      }
    } else {
      for (OrganisationUnit orgUnit : user.getOrganisationUnits()) {
        int level = requiredApprovalLevel(orgUnit, user, approvalLevels);

        map.put(orgUnit, level);
      }
    }

    // ---------------------------------------------------------------------
    // Add data view organisation units with approval levels
    // ---------------------------------------------------------------------

    Collection<OrganisationUnit> dataViewOrgUnits = user.getDataViewOrganisationUnits();

    if (dataViewOrgUnits == null || dataViewOrgUnits.isEmpty()) {
      dataViewOrgUnits = organisationUnitService.getRootOrganisationUnits();
    }

    for (OrganisationUnit orgUnit : dataViewOrgUnits) {
      if (!map.containsKey(orgUnit)) {
        int level = requiredApprovalLevel(orgUnit, user, approvalLevels);

        map.put(orgUnit, level);
      }
    }

    return map;
  }
  public String execute() throws Exception {
    try {
      OrganisationUnit unit = organisationUnitService.getOrganisationUnit(id);

      if (unit == null) {
        throw new RuntimeException("OrganisationUnit with id " + id + " doesn't exist");
      }

      selectedUnits = selectionManager.getSelectedOrganisationUnits();
      selectedUnits.remove(unit);
      selectionManager.setSelectedOrganisationUnits(selectedUnits);
    } catch (Exception e) {
      LOG.error(e.getMessage(), e);

      throw e;
    }

    return SUCCESS;
  }
  private List<DataSet> getDataSetsForCurrentUser(int id) {
    OrganisationUnit organisationUnit = organisationUnitService.getOrganisationUnit(id);

    if (organisationUnit == null) {
      return new ArrayList<DataSet>();
    }

    List<DataSet> dataSets = new ArrayList<DataSet>();

    if (organisationUnit.getDataSets() != null) {
      dataSets.addAll(organisationUnit.getDataSets());
    }

    UserCredentials userCredentials = currentUserService.getCurrentUser().getUserCredentials();

    if (!userCredentials.isSuper()) {
      dataSets.retainAll(userCredentials.getAllDataSets());
    }

    return dataSets;
  }
  public String execute() {
    DataElement dataElement = dataElementService.getDataElement(dataElementId);
    DataElementCategoryOptionCombo categoryOptionCombo =
        categoryService.getDataElementCategoryOptionCombo(categoryOptionComboId);
    Period period = PeriodType.createPeriodExternalId(periodId);
    OrganisationUnit source = organisationUnitService.getOrganisationUnit(organisationUnitId);

    DataValue dataValue =
        dataValueService.getDataValue(source, dataElement, period, categoryOptionCombo);

    boolean isMarked = dataValue.isFollowup();

    dataValue.setFollowup(!isMarked);

    dataValueService.updateDataValue(dataValue);

    message = !isMarked ? "marked" : "unmarked";

    log.info(!isMarked ? "Data value marked for follow-up" : "Data value unmarked for follow-up");

    return SUCCESS;
  }
  private void applyAggregationLevels(List<AnalyticsTable> tables) {
    int maxLevels = organisationUnitService.getNumberOfOrganisationalLevels();

    boolean hasAggLevels = false;

    levelLoop:
    for (int i = 0; i < maxLevels; i++) {
      int level = maxLevels - i;

      Collection<String> dataElements =
          IdentifiableObjectUtils.getUids(
              dataElementService.getDataElementsByAggregationLevel(level));

      if (dataElements.isEmpty()) {
        continue levelLoop;
      }

      hasAggLevels = true;

      ConcurrentLinkedQueue<AnalyticsTable> tableQ = new ConcurrentLinkedQueue<>(tables);

      List<Future<?>> futures = new ArrayList<>();

      for (int j = 0; j < getProcessNo(); j++) {
        futures.add(tableManager.applyAggregationLevels(tableQ, dataElements, level));
      }

      ConcurrentUtils.waitForCompletion(futures);
    }

    if (hasAggLevels) {
      vacuumTables(tables);

      log.info("Vacuumed tables");
    }
  }
示例#24
0
  @Override
  public String execute() throws Exception {
    ExportParams params = new ExportParams();

    if (dataValue || dataValueDaily) {
      params.setCategories(null);
      params.setCategoryCombos(null);
      params.setCategoryOptions(null);
      params.setCategoryOptionCombos(null);
      /*
       * params.setDataElementGroups( null );
       * params.setDataElementGroupSets( null ); params.setIndicators(
       * null ); params.setIndicatorTypes( null );
       * params.setIndicatorGroups( null ); params.setIndicatorGroupSets(
       * null ); params.setDataDictionaries( null ); params.setDataSets(
       * null ); params.setOrganisationUnitGroups( null );
       * params.setOrganisationUnitGroupSets( null );
       * params.setOrganisationUnitLevels( null );
       * params.setValidationRules( null ); params.setReports( null );
       * params.setReportTables( null ); params.setPeriods( null ); //
       * TODO Include only relevant periods params.setCharts( null );
       * params.setPeriods( null );
       */

      Set<Integer> dataElementz = new HashSet<>();

      Collection<DataElement> children = dataElementService.getAllDataElements();

      for (DataElement child : children) {
        dataElementz.add(child.getId());
      }

      params.setDataElements(dataElementz);

      Set<Integer> orgUnits = new HashSet<>();

      Collection<OrganisationUnit> orgChildren = organisationUnitService.getAllOrganisationUnits();

      for (OrganisationUnit child : orgChildren) {
        orgUnits.add(child.getId());
      }

      params.setOrganisationUnits(orgUnits);
    }

    if (dataValue) {
      params.setMetaData(false);
    }

    if (dataValueDaily) {
      params.setMetaData(false);
    }

    // params.setMetaData( true );
    params.setIncludeDataValues(true);
    params.setCurrentUser(currentUserService.getCurrentUser());
    params.setDataValue(dataValue);
    params.setDataValueDaily(dataValueDaily);

    params.setI18n(i18n);
    params.setFormat(format);
    params.setStartDate(getMediumDate(startDate));
    params.setEndDate(getMediumDate(endDate));

    ExportService exportService = serviceProvider.provide(exportFormat);

    inputStream = exportService.exportData(params);

    fileName = FILENAME;

    return SUCCESS;
  }
  public String execute() {
    levels = organisationUnitService.getFilledOrganisationUnitLevels();

    return SUCCESS;
  }
  // -------------------------------------------------------------------------
  // Action Implementation
  // -------------------------------------------------------------------------
  public String execute() throws Exception {
    statementManager.initialise();

    // Initialization
    raFolderName = reportService.getRAFolderName();
    String deCodesXMLFileName = "";
    simpleDateFormat = new SimpleDateFormat("MMM-yyyy");
    monthFormat = new SimpleDateFormat("MMMM");
    yearFormat = new SimpleDateFormat("yyyy");
    simpleMonthFormat = new SimpleDateFormat("MMM");
    String parentUnit = "";

    Report_in selReportObj = reportService.getReport(Integer.parseInt(reportList));

    deCodesXMLFileName = selReportObj.getXmlTemplateName();

    reportModelTB = selReportObj.getModel();
    reportFileNameTB = selReportObj.getExcelTemplateName();

    String inputTemplatePath =
        System.getenv("DHIS2_HOME")
            + File.separator
            + raFolderName
            + File.separator
            + "template"
            + File.separator
            + reportFileNameTB;
    // String outputReportFolderPath = System.getenv( "DHIS2_HOME" ) + File.separator + raFolderName
    // + File.separator + "output" + File.separator + UUID.randomUUID().toString();
    String outputReportFolderPath =
        System.getenv("DHIS2_HOME")
            + File.separator
            + Configuration_IN.DEFAULT_TEMPFOLDER
            + File.separator
            + UUID.randomUUID().toString();
    File newdir = new File(outputReportFolderPath);
    if (!newdir.exists()) {
      newdir.mkdirs();
    }

    if (reportModelTB.equalsIgnoreCase("STATIC")
        || reportModelTB.equalsIgnoreCase("STATIC-DATAELEMENTS")
        || reportModelTB.equalsIgnoreCase("STATIC-FINANCIAL")) {
      orgUnitList =
          new ArrayList<OrganisationUnit>(
              organisationUnitService.getOrganisationUnitWithChildren(ouIDTB));
      OrganisationUnitGroup orgUnitGroup = selReportObj.getOrgunitGroup();

      orgUnitList.retainAll(orgUnitGroup.getMembers());
    } else {
      return INPUT;
    }

    // System.out.println(  "---Size of Org Unit List ----: " + orgUnitList.size() + ",Report Group
    // name is :---" + selReportObj.getOrgunitGroup().getName() + ", Size of Group member is ----:"
    // + selReportObj.getOrgunitGroup().getMembers().size()  );

    System.out.println(" ---- Size of OrgUnit List is ---- " + orgUnitList.size());

    OrganisationUnit selOrgUnit = organisationUnitService.getOrganisationUnit(ouIDTB);

    System.out.println(
        selOrgUnit.getName()
            + " : "
            + selReportObj.getName()
            + " : Report Generation Start Time is : "
            + new Date());

    selectedPeriod = periodService.getPeriod(availablePeriods);

    sDate = format.parseDate(String.valueOf(selectedPeriod.getStartDate()));

    eDate = format.parseDate(String.valueOf(selectedPeriod.getEndDate()));

    Workbook templateWorkbook = Workbook.getWorkbook(new File(inputTemplatePath));

    // collect periodId by commaSepareted
    List<Period> tempPeriodList =
        new ArrayList<Period>(periodService.getIntersectingPeriods(sDate, eDate));

    Collection<Integer> tempPeriodIds =
        new ArrayList<Integer>(getIdentifiers(Period.class, tempPeriodList));

    String periodIdsByComma = getCommaDelimitedString(tempPeriodIds);

    // Getting DataValues
    List<Report_inDesign> reportDesignList = reportService.getReportDesign(deCodesXMLFileName);

    // collect dataElementIDs by commaSepareted
    String dataElmentIdsByComma = reportService.getDataelementIds(reportDesignList);

    int orgUnitCount = 0;

    Iterator<OrganisationUnit> it = orgUnitList.iterator();
    while (it.hasNext()) {
      OrganisationUnit currentOrgUnit = (OrganisationUnit) it.next();

      String outPutFileName = reportFileNameTB.replace(".xls", "");
      outPutFileName += "_" + currentOrgUnit.getShortName();
      outPutFileName += "_" + simpleDateFormat.format(selectedPeriod.getStartDate()) + ".xls";

      String outputReportPath = outputReportFolderPath + File.separator + outPutFileName;
      WritableWorkbook outputReportWorkbook =
          Workbook.createWorkbook(new File(outputReportPath), templateWorkbook);

      Map<String, String> aggDeMap = new HashMap<String, String>();
      if (aggData.equalsIgnoreCase(USEEXISTINGAGGDATA)) {
        aggDeMap.putAll(
            reportService.getResultDataValueFromAggregateTable(
                currentOrgUnit.getId(), dataElmentIdsByComma, periodIdsByComma));
      } else if (aggData.equalsIgnoreCase(GENERATEAGGDATA)) {
        List<OrganisationUnit> childOrgUnitTree =
            new ArrayList<OrganisationUnit>(
                organisationUnitService.getOrganisationUnitWithChildren(currentOrgUnit.getId()));
        List<Integer> childOrgUnitTreeIds =
            new ArrayList<Integer>(getIdentifiers(OrganisationUnit.class, childOrgUnitTree));
        String childOrgUnitsByComma = getCommaDelimitedString(childOrgUnitTreeIds);

        aggDeMap.putAll(
            reportService.getAggDataFromDataValueTable(
                childOrgUnitsByComma, dataElmentIdsByComma, periodIdsByComma));
      } else if (aggData.equalsIgnoreCase(USECAPTUREDDATA)) {
        aggDeMap.putAll(
            reportService.getAggDataFromDataValueTable(
                "" + currentOrgUnit.getId(), dataElmentIdsByComma, periodIdsByComma));
      }

      int count1 = 0;
      Iterator<Report_inDesign> reportDesignIterator = reportDesignList.iterator();
      while (reportDesignIterator.hasNext()) {
        Report_inDesign report_inDesign = (Report_inDesign) reportDesignIterator.next();

        String deType = report_inDesign.getPtype();
        String sType = report_inDesign.getStype();
        String deCodeString = report_inDesign.getExpression();
        String tempStr = "";

        Calendar tempStartDate = Calendar.getInstance();
        Calendar tempEndDate = Calendar.getInstance();
        List<Calendar> calendarList =
            new ArrayList<Calendar>(reportService.getStartingEndingPeriods(deType, selectedPeriod));
        if (calendarList == null || calendarList.isEmpty()) {
          tempStartDate.setTime(selectedPeriod.getStartDate());
          tempEndDate.setTime(selectedPeriod.getEndDate());
          return SUCCESS;
        } else {
          tempStartDate = calendarList.get(0);
          tempEndDate = calendarList.get(1);
        }

        if (deCodeString.equalsIgnoreCase("FACILITY")) {
          tempStr = currentOrgUnit.getName();
        } else if (deCodeString.equalsIgnoreCase("FACILITY-NOREPEAT")) {
          tempStr = parentUnit;
        } else if (deCodeString.equalsIgnoreCase("FACILITYP")) {
          tempStr = currentOrgUnit.getParent().getName();
        } else if (deCodeString.equalsIgnoreCase("FACILITYPP")) {
          tempStr = currentOrgUnit.getParent().getParent().getName();
        } else if (deCodeString.equalsIgnoreCase("FACILITYPPP")) {
          tempStr = currentOrgUnit.getParent().getParent().getParent().getName();
        } else if (deCodeString.equalsIgnoreCase("FACILITYPPPP")) {
          tempStr = currentOrgUnit.getParent().getParent().getParent().getParent().getName();
        } else if (deCodeString.equalsIgnoreCase("PERIOD")
            || deCodeString.equalsIgnoreCase("PERIOD-NOREPEAT")) {
          tempStr = simpleDateFormat.format(sDate);
        } else if (deCodeString.equalsIgnoreCase("PERIOD-MONTH")) {
          tempStr = monthFormat.format(sDate);
        } else if (deCodeString.equalsIgnoreCase("PERIOD-YEAR")) {
          tempStr = yearFormat.format(sDate);
        } else if (deCodeString.equalsIgnoreCase("MONTH-START-SHORT")) {
          tempStr = simpleMonthFormat.format(sDate);
        } else if (deCodeString.equalsIgnoreCase("MONTH-END-SHORT")) {
          tempStr = simpleMonthFormat.format(eDate);
        } else if (deCodeString.equalsIgnoreCase("MONTH-START")) {
          tempStr = monthFormat.format(sDate);
        } else if (deCodeString.equalsIgnoreCase("MONTH-END")) {
          tempStr = monthFormat.format(eDate);
        } else if (deCodeString.equalsIgnoreCase("SLNO")) {
          tempStr = "" + (orgUnitCount + 1);
        } else if (deCodeString.equalsIgnoreCase("NA")) {
          tempStr = " ";
        } else {
          if (sType.equalsIgnoreCase("dataelement")) {
            if (aggData.equalsIgnoreCase(USECAPTUREDDATA)) {
              tempStr = getAggVal(deCodeString, aggDeMap);
              // tempStr = reportService.getIndividualResultDataValue(deCodeString,
              // tempStartDate.getTime(), tempEndDate.getTime(), currentOrgUnit, reportModelTB );
            } else if (aggData.equalsIgnoreCase(GENERATEAGGDATA)) {
              tempStr = getAggVal(deCodeString, aggDeMap);
              // tempStr = reportService.getResultDataValue( deCodeString, tempStartDate.getTime(),
              // tempEndDate.getTime(), currentOrgUnit, reportModelTB );
            } else if (aggData.equalsIgnoreCase(USEEXISTINGAGGDATA)) {

              tempStr = getAggVal(deCodeString, aggDeMap);
              /*
              List<Period> periodList = new ArrayList<Period>( periodService.getPeriodsBetweenDates( tempStartDate.getTime(), tempEndDate.getTime() ) );
              Collection<Integer> periodIds = new ArrayList<Integer>( getIdentifiers(Period.class, periodList ) );
              tempStr = reportService.getResultDataValueFromAggregateTable( deCodeString, periodIds, currentOrgUnit, reportModelTB );
              */
            }
          } else if (sType.equalsIgnoreCase("dataelement-boolean")) {
            if (aggData.equalsIgnoreCase(USECAPTUREDDATA)) {
              tempStr =
                  reportService.getBooleanDataValue(
                      deCodeString,
                      tempStartDate.getTime(),
                      tempEndDate.getTime(),
                      currentOrgUnit,
                      reportModelTB);
            } else if (aggData.equalsIgnoreCase(GENERATEAGGDATA)) {
              tempStr =
                  reportService.getBooleanDataValue(
                      deCodeString,
                      tempStartDate.getTime(),
                      tempEndDate.getTime(),
                      currentOrgUnit,
                      reportModelTB);
            } else if (aggData.equalsIgnoreCase(USEEXISTINGAGGDATA)) {
              tempStr =
                  reportService.getBooleanDataValue(
                      deCodeString,
                      tempStartDate.getTime(),
                      tempEndDate.getTime(),
                      currentOrgUnit,
                      reportModelTB);
            }
          } else {
            if (aggData.equalsIgnoreCase(USECAPTUREDDATA)) {
              tempStr =
                  reportService.getIndividualResultIndicatorValue(
                      deCodeString, tempStartDate.getTime(), tempEndDate.getTime(), currentOrgUnit);
            } else if (aggData.equalsIgnoreCase(GENERATEAGGDATA)) {
              tempStr =
                  reportService.getResultIndicatorValue(
                      deCodeString, tempStartDate.getTime(), tempEndDate.getTime(), currentOrgUnit);
            } else if (aggData.equalsIgnoreCase(USEEXISTINGAGGDATA)) {
              // List<Period> periodList = new ArrayList<Period>(
              // periodService.getPeriodsBetweenDates( tempStartDate.getTime(),
              // tempEndDate.getTime() ) );
              // Collection<Integer> periodIds = new ArrayList<Integer>(
              // getIdentifiers(Period.class, periodList ) );
              tempStr =
                  reportService.getResultIndicatorValue(
                      deCodeString, tempStartDate.getTime(), tempEndDate.getTime(), currentOrgUnit);
            }
          }
        }

        int tempRowNo = report_inDesign.getRowno();
        int tempColNo = report_inDesign.getColno();
        int sheetNo = report_inDesign.getSheetno();
        WritableSheet sheet0 = outputReportWorkbook.getSheet(sheetNo);

        if (tempStr == null || tempStr.equals(" ")) {
          tempColNo += orgUnitCount;

          WritableCellFormat wCellformat = new WritableCellFormat();
          wCellformat.setBorder(Border.ALL, BorderLineStyle.THIN);
          wCellformat.setWrap(true);
          wCellformat.setAlignment(Alignment.CENTRE);

          sheet0.addCell(new Blank(tempColNo, tempRowNo, wCellformat));
        } else {
          if (reportModelTB.equalsIgnoreCase("DYNAMIC-ORGUNIT")) {
            if (deCodeString.equalsIgnoreCase("FACILITYP")
                || deCodeString.equalsIgnoreCase("FACILITYPP")
                || deCodeString.equalsIgnoreCase("FACILITYPPP")
                || deCodeString.equalsIgnoreCase("FACILITYPPPP")) {
            } else if (deCodeString.equalsIgnoreCase("PERIOD")
                || deCodeString.equalsIgnoreCase("PERIOD-NOREPEAT")
                || deCodeString.equalsIgnoreCase("PERIOD-WEEK")
                || deCodeString.equalsIgnoreCase("PERIOD-MONTH")
                || deCodeString.equalsIgnoreCase("PERIOD-QUARTER")
                || deCodeString.equalsIgnoreCase("PERIOD-YEAR")
                || deCodeString.equalsIgnoreCase("MONTH-START")
                || deCodeString.equalsIgnoreCase("MONTH-END")
                || deCodeString.equalsIgnoreCase("MONTH-START-SHORT")
                || deCodeString.equalsIgnoreCase("MONTH-END-SHORT")
                || deCodeString.equalsIgnoreCase("SIMPLE-QUARTER")
                || deCodeString.equalsIgnoreCase("QUARTER-MONTHS-SHORT")
                || deCodeString.equalsIgnoreCase("QUARTER-MONTHS")
                || deCodeString.equalsIgnoreCase("QUARTER-START-SHORT")
                || deCodeString.equalsIgnoreCase("QUARTER-END-SHORT")
                || deCodeString.equalsIgnoreCase("QUARTER-START")
                || deCodeString.equalsIgnoreCase("QUARTER-END")
                || deCodeString.equalsIgnoreCase("SIMPLE-YEAR")
                || deCodeString.equalsIgnoreCase("YEAR-END")
                || deCodeString.equalsIgnoreCase("YEAR-FROMTO")) {
            } else {
              tempColNo += orgUnitCount;
            }
          } else if (reportModelTB.equalsIgnoreCase("dynamicwithrootfacility")) {
            if (deCodeString.equalsIgnoreCase("FACILITYP")
                || deCodeString.equalsIgnoreCase("FACILITY-NOREPEAT")
                || deCodeString.equalsIgnoreCase("FACILITYPP")
                || deCodeString.equalsIgnoreCase("FACILITYPPP")
                || deCodeString.equalsIgnoreCase("FACILITYPPPP")) {
            } else if (deCodeString.equalsIgnoreCase("PERIOD")
                || deCodeString.equalsIgnoreCase("PERIOD-NOREPEAT")
                || deCodeString.equalsIgnoreCase("PERIOD-WEEK")
                || deCodeString.equalsIgnoreCase("PERIOD-MONTH")
                || deCodeString.equalsIgnoreCase("PERIOD-QUARTER")
                || deCodeString.equalsIgnoreCase("PERIOD-YEAR")
                || deCodeString.equalsIgnoreCase("MONTH-START")
                || deCodeString.equalsIgnoreCase("MONTH-END")
                || deCodeString.equalsIgnoreCase("MONTH-START-SHORT")
                || deCodeString.equalsIgnoreCase("MONTH-END-SHORT")
                || deCodeString.equalsIgnoreCase("SIMPLE-QUARTER")
                || deCodeString.equalsIgnoreCase("QUARTER-MONTHS-SHORT")
                || deCodeString.equalsIgnoreCase("QUARTER-MONTHS")
                || deCodeString.equalsIgnoreCase("QUARTER-START-SHORT")
                || deCodeString.equalsIgnoreCase("QUARTER-END-SHORT")
                || deCodeString.equalsIgnoreCase("QUARTER-START")
                || deCodeString.equalsIgnoreCase("QUARTER-END")
                || deCodeString.equalsIgnoreCase("SIMPLE-YEAR")
                || deCodeString.equalsIgnoreCase("YEAR-END")
                || deCodeString.equalsIgnoreCase("YEAR-FROMTO")) {
            } else {
              tempRowNo += orgUnitCount;
            }
          }

          WritableCell cell = sheet0.getWritableCell(tempColNo, tempRowNo);

          CellFormat cellFormat = cell.getCellFormat();
          WritableCellFormat wCellformat = new WritableCellFormat();
          wCellformat.setBorder(Border.ALL, BorderLineStyle.THIN);
          wCellformat.setWrap(true);
          wCellformat.setAlignment(Alignment.CENTRE);

          if (cell.getType() == CellType.LABEL) {
            Label l = (Label) cell;
            l.setString(tempStr);
            l.setCellFormat(cellFormat);
          } else {
            try {
              sheet0.addCell(
                  new Number(tempColNo, tempRowNo, Double.parseDouble(tempStr), wCellformat));
            } catch (Exception e) {
              sheet0.addCell(new Label(tempColNo, tempRowNo, tempStr, wCellformat));
            }
          }
        }

        count1++;
      } // inner while loop end

      outputReportWorkbook.write();
      outputReportWorkbook.close();

      orgUnitCount++;
    } // outer while loop end

    statementManager.destroy();

    if (zipDirectory(outputReportFolderPath, outputReportFolderPath + ".zip")) {
      System.out.println(
          selOrgUnit.getName()
              + " : "
              + selReportObj.getName()
              + " Report Generation End Time is : "
              + new Date());

      fileName = reportFileNameTB.replace(".xls", "");
      fileName += "_" + selOrgUnit.getShortName();
      fileName += "_" + simpleDateFormat.format(selectedPeriod.getStartDate()) + ".zip";

      File outputReportFile = new File(outputReportFolderPath + ".zip");
      inputStream = new BufferedInputStream(new FileInputStream(outputReportFile));

      return SUCCESS;
    } else {
      return INPUT;
    }
  }
 private OrganisationUnit reloadOrganisationUnit(OrganisationUnit unit) {
   return unit == null ? null : organisationUnitService.getOrganisationUnit(unit.getId());
 }
示例#28
0
  @Override
  public void setUpTest() {
    mockDataValueBatchHandler = new MockBatchHandler<>();
    mockBatchHandlerFactory = new MockBatchHandlerFactory();
    mockBatchHandlerFactory.registerBatchHandler(
        DataValueBatchHandler.class, mockDataValueBatchHandler);
    setDependency(dataValueSetService, "batchHandlerFactory", mockBatchHandlerFactory);

    categoryOptionA = createCategoryOption('A');
    categoryOptionB = createCategoryOption('B');
    categoryA = createDataElementCategory('A', categoryOptionA, categoryOptionB);
    categoryComboA = createCategoryCombo('A', categoryA);
    ocDef = categoryService.getDefaultDataElementCategoryOptionCombo();

    ocA = createCategoryOptionCombo(categoryComboA, categoryOptionA);
    ocB = createCategoryOptionCombo(categoryComboA, categoryOptionB);
    deA = createDataElement('A');
    deB = createDataElement('B');
    deC = createDataElement('C');
    deD = createDataElement('D');
    dsA = createDataSet('A', new MonthlyPeriodType());
    ouA = createOrganisationUnit('A');
    ouB = createOrganisationUnit('B');
    ouC = createOrganisationUnit('C');
    peA =
        createPeriod(
            PeriodType.getByNameIgnoreCase(MonthlyPeriodType.NAME),
            getDate(2012, 1, 1),
            getDate(2012, 1, 31));
    peB =
        createPeriod(
            PeriodType.getByNameIgnoreCase(MonthlyPeriodType.NAME),
            getDate(2012, 2, 1),
            getDate(2012, 2, 29));

    ocA.setUid("kjuiHgy67hg");
    ocB.setUid("Gad33qy67g5");
    deA.setUid("f7n9E0hX8qk");
    deB.setUid("Ix2HsbDMLea");
    deC.setUid("eY5ehpbEsB7");
    dsA.setUid("pBOMPrpg1QX");
    ouA.setUid("DiszpKrYNg8");
    ouB.setUid("BdfsJfj87js");
    ouC.setUid("j7Hg26FpoIa");

    ocA.setCode("OC_A");
    ocB.setCode("OC_B");
    deA.setCode("DE_A");
    deB.setCode("DE_B");
    deC.setCode("DE_C");
    deD.setCode("DE_D");
    dsA.setCode("DS_A");
    ouA.setCode("OU_A");
    ouB.setCode("OU_B");
    ouC.setCode("OU_C");

    categoryService.addDataElementCategoryOption(categoryOptionA);
    categoryService.addDataElementCategoryOption(categoryOptionB);
    categoryService.addDataElementCategory(categoryA);
    categoryService.addDataElementCategoryCombo(categoryComboA);
    categoryService.addDataElementCategoryOptionCombo(ocA);
    categoryService.addDataElementCategoryOptionCombo(ocB);

    dataElementService.addDataElement(deA);
    dataElementService.addDataElement(deB);
    dataElementService.addDataElement(deC);
    dataElementService.addDataElement(deD);
    dataSetService.addDataSet(dsA);
    organisationUnitService.addOrganisationUnit(ouA);
    organisationUnitService.addOrganisationUnit(ouB);
    organisationUnitService.addOrganisationUnit(ouC);
    periodService.addPeriod(peA);
    periodService.addPeriod(peB);

    user = createUser('A');
    user.setOrganisationUnits(Sets.newHashSet(ouA, ouB));
    CurrentUserService currentUserService = new MockCurrentUserService(user);
    setDependency(dataValueSetService, "currentUserService", currentUserService);
  }
示例#29
0
  @RequestMapping(method = RequestMethod.POST, produces = "text/plain")
  public void saveDataValue(
      @RequestParam String de,
      @RequestParam String cc,
      @RequestParam String pe,
      @RequestParam String ou,
      @RequestParam String value,
      HttpServletResponse response) {
    DataElement dataElement = dataElementService.getDataElement(de);

    if (dataElement == null) {
      ContextUtils.conflictResponse(response, "Illegal data element identifier: " + de);
      return;
    }

    DataElementCategoryOptionCombo categoryOptionCombo =
        categoryService.getDataElementCategoryOptionCombo(cc);

    if (categoryOptionCombo == null) {
      ContextUtils.conflictResponse(response, "Illegal category option combo identifier: " + cc);
      return;
    }

    Period period = PeriodType.getPeriodFromIsoString(pe);

    if (period == null) {
      ContextUtils.conflictResponse(response, "Illegal period identifier: " + pe);
      return;
    }

    OrganisationUnit organisationUnit = organisationUnitService.getOrganisationUnit(ou);

    if (organisationUnit == null) {
      ContextUtils.conflictResponse(response, "Illegal organisation unit identifier: " + ou);
      return;
    }

    if (dataSetService.isLocked(dataElement, period, organisationUnit, null)) {
      ContextUtils.conflictResponse(response, "Data set is locked");
      return;
    }

    value = StringUtils.trimToNull(value);

    String storedBy = currentUserService.getCurrentUsername();

    Date now = new Date();

    DataValue dataValue =
        dataValueService.getDataValue(organisationUnit, dataElement, period, categoryOptionCombo);

    if (dataValue == null) {
      if (value != null) {
        dataValue =
            new DataValue(
                dataElement,
                period,
                organisationUnit,
                value,
                storedBy,
                now,
                null,
                categoryOptionCombo);
        dataValueService.addDataValue(dataValue);
      }
    } else {
      dataValue.setValue(value);
      dataValue.setTimestamp(now);
      dataValue.setStoredBy(storedBy);

      dataValueService.updateDataValue(dataValue);
    }
  }
 @Override
 protected void importUnique(OrganisationUnitLevel object) {
   organisationUnitService.addOrganisationUnitLevel(object);
 }