// -------------------------------------------------------------------------
  // 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;
  }
  private String getHierarchyOrgunit(OrganisationUnit orgunit) {
    String hierarchyOrgunit = orgunit.getName();

    while (orgunit.getParent() != null) {
      hierarchyOrgunit = orgunit.getParent().getName() + " / " + hierarchyOrgunit;

      orgunit = orgunit.getParent();
    }

    return hierarchyOrgunit;
  }
  protected String getUniquenessStatement(Object object) {
    OrganisationUnit unit = (OrganisationUnit) object;

    Map<String, String> fieldMap = new HashMap<String, String>();

    fieldMap.put("name", unit.getName());
    fieldMap.put("shortname", unit.getShortName());
    fieldMap.put("code", unit.getOrganisationUnitCode());

    return statementBuilder.getValueStatement(tableName, "organisationunitid", fieldMap, false);
  }
  @Ignore
  @Test
  public void testImportOrganisationUnitRelationships() {
    importObjectService.addImportObject(ImportObjectStatus.NEW, organisationUnitAModified, null);
    importObjectService.addImportObject(ImportObjectStatus.NEW, organisationUnitBModified, null);
    importObjectService.addImportObject(ImportObjectStatus.NEW, organisationUnitCModified, null);

    importObjectService.addImportObject(
        ImportObjectStatus.NEW,
        GroupMemberType.ORGANISATIONUNITRELATIONSHIP,
        relationshipAssociationA);
    importObjectService.addImportObject(
        ImportObjectStatus.NEW,
        GroupMemberType.ORGANISATIONUNITRELATIONSHIP,
        relationshipAssociationB);

    dbmsManager.clearSession();

    importObjectService.importAll();

    organisationUnitAModified =
        organisationUnitService.getOrganisationUnitByName(organisationUnitAModified.getName());
    organisationUnitBModified =
        organisationUnitService.getOrganisationUnitByName(organisationUnitBModified.getName());
    organisationUnitCModified =
        organisationUnitService.getOrganisationUnitByName(organisationUnitCModified.getName());

    assertNotNull(organisationUnitAModified);
    assertNotNull(organisationUnitBModified);
    assertNotNull(organisationUnitCModified);

    assertNull(organisationUnitAModified.getParent());
    assertNotNull(organisationUnitBModified.getParent());
    assertNotNull(organisationUnitCModified.getParent());

    assertTrue(organisationUnitBModified.getParent().equals(organisationUnitAModified));
    assertTrue(organisationUnitCModified.getParent().equals(organisationUnitBModified));

    assertEquals(importObjectService.getImportObjects(OrganisationUnit.class).size(), 0);
    assertEquals(importObjectService.getImportObjects(GroupMemberAssociation.class).size(), 0);
  }
Пример #5
0
  public static void updateParents(Collection<OrganisationUnit> organisationUnits) {
    Map<String, OrganisationUnit> organisationUnitMap = getOrganisationUnitMap(organisationUnits);

    for (OrganisationUnit organisationUnit : organisationUnits) {
      OrganisationUnit parent = organisationUnit.getParent();

      if (parent != null) {
        if (parent.getUid() != null) {
          parent = organisationUnitMap.get(parent.getUid());
        } else if (parent.getCode() != null) {
          parent = organisationUnitMap.get(parent.getCode());
        } else if (parent.getName() != null) {
          parent = organisationUnitMap.get(parent.getName());
        } else if (parent.getShortName() != null) {
          parent = organisationUnitMap.get(parent.getShortName());
        }
      }

      if (parent != null) {
        organisationUnit.setParent(parent);
      }
    }
  }
Пример #6
0
  public void handleRow(Object object) {
    OrganisationUnit unit = (OrganisationUnit) object;

    NameMappingUtil.addOrganisationUnitMapping(unit.getId(), unit.getName());

    unit.setUuid(UUIdUtils.getUUId());

    if (unit.getOrganisationUnitCode() != null
        && unit.getOrganisationUnitCode().trim().length() == 0) {
      unit.setOrganisationUnitCode(null);
    }

    read(unit, OrganisationUnit.class, GroupMemberType.NONE, params);
  }
Пример #7
0
  private static Map<String, OrganisationUnit> getOrganisationUnitMap(
      Collection<OrganisationUnit> organisationUnits) {
    Map<String, OrganisationUnit> organisationUnitMap = new HashMap<String, OrganisationUnit>();

    for (OrganisationUnit organisationUnit : organisationUnits) {
      if (organisationUnit.getUid() != null) {
        organisationUnitMap.put(organisationUnit.getUid(), organisationUnit);
      }

      if (organisationUnit.getCode() != null) {
        organisationUnitMap.put(organisationUnit.getCode(), organisationUnit);
      }

      if (organisationUnit.getName() != null) {
        organisationUnitMap.put(organisationUnit.getName(), organisationUnit);
      }

      if (organisationUnit.getShortName() != null) {
        organisationUnitMap.put(organisationUnit.getShortName(), organisationUnit);
      }
    }

    return organisationUnitMap;
  }
Пример #8
0
  /**
   * Creates a table with the given unit
   *
   * @param unit The organization unit
   * @param i18n i18n object
   * @param format
   * @param HEADER3 The header3 font
   * @param ITALIC The italic font
   * @param TEXT The text font
   * @param keepTogether Indicates whether the table could be broken across multiple pages or should
   *     be kept at one page.
   * @param columnWidths The column widths.
   */
  public static PdfPTable printOrganisationUnit(
      OrganisationUnit unit,
      I18n i18n,
      I18nFormat format,
      boolean keepTogether,
      float... columnWidths) {
    PdfPTable table = getPdfPTable(keepTogether, columnWidths);

    table.addCell(getHeaderCell(unit.getName(), 2));

    table.addCell(getEmptyCell(2, 15));

    table.addCell(getItalicCell(i18n.getString("short_name")));
    table.addCell(getTextCell(unit.getShortName()));

    if (nullIfEmpty(unit.getCode()) != null) {
      table.addCell(getItalicCell(i18n.getString("code")));
      table.addCell(getTextCell(unit.getCode()));
    }

    table.addCell(getItalicCell(i18n.getString("opening_date")));
    table.addCell(
        getTextCell(
            unit.getOpeningDate() != null ? format.formatDate(unit.getOpeningDate()) : EMPTY));

    if (unit.getClosedDate() != null) {
      table.addCell(getItalicCell(i18n.getString("closed_date")));
      table.addCell(getTextCell(format.formatDate(unit.getClosedDate())));
    }

    table.addCell(getItalicCell(i18n.getString("active")));

    if (nullIfEmpty(unit.getComment()) != null) {
      table.addCell(getItalicCell(i18n.getString("comment")));
      table.addCell(getTextCell(unit.getComment()));
    }

    for (AttributeValue value : unit.getAttributeValues()) {
      table.addCell(getItalicCell(value.getAttribute().getName()));
      table.addCell(getTextCell(value.getValue()));
    }

    table.addCell(getEmptyCell(2, 30));

    return table;
  }
  @Override
  public Collection<ValidationResult> validate(
      DataSet dataSet,
      Period period,
      OrganisationUnit source,
      DataElementCategoryOptionCombo attributeCombo) {
    log.info(
        "Validate data set: "
            + dataSet.getName()
            + " period: "
            + period.getPeriodType().getName()
            + " "
            + period.getStartDate()
            + " "
            + period.getEndDate()
            + " source: "
            + source.getName()
            + " attribute combo: "
            + (attributeCombo == null ? "[none]" : attributeCombo.getName()));

    Collection<Period> periods = new ArrayList<>();
    periods.add(period);

    Collection<ValidationRule> rules =
        getValidationTypeRulesForDataElements(dataSet.getDataElements());

    log.debug("Using validation rules: " + rules.size());

    Collection<OrganisationUnit> sources = new HashSet<>();
    sources.add(source);

    return Validator.validate(
        sources,
        periods,
        rules,
        attributeCombo,
        null,
        constantService,
        expressionService,
        periodService,
        dataValueService,
        dataElementCategoryService,
        userService,
        currentUserService);
  }
  protected void addValues(Object object) {
    OrganisationUnit unit = (OrganisationUnit) object;

    statementBuilder.setInt(unit.getId());
    statementBuilder.setString(unit.getUuid());
    statementBuilder.setString(unit.getName());
    statementBuilder.setString(
        unit.getParent() != null ? String.valueOf(unit.getParent().getId()) : null);
    statementBuilder.setString(unit.getShortName());
    statementBuilder.setString(unit.getOrganisationUnitCode());
    statementBuilder.setDate(unit.getOpeningDate());
    statementBuilder.setDate(unit.getClosedDate());
    statementBuilder.setBoolean(unit.isActive());
    statementBuilder.setString(unit.getComment());
    statementBuilder.setString(unit.getGeoCode());
    statementBuilder.setString(unit.getLatitude());
    statementBuilder.setString(unit.getLongitude());
  }
  public void write(Document document, ExportParams params) {
    I18n i18n = params.getI18n();
    I18nFormat format = params.getFormat();

    PDFUtils.printObjectFrontPage(
        document, params.getOrganisationUnits(), i18n, format, "organisation_unit_hierarchy");

    if (params.getOrganisationUnits() != null && params.getOrganisationUnits().size() > 0) {
      Collection<OrganisationUnit> hierarchy = getHierarchy();

      PdfPTable table = getPdfPTable(false, 0.100f);

      for (OrganisationUnit unit : hierarchy) {
        String indent = getIndent(unit.getLevel());

        table.addCell(getTextCell(indent + unit.getName()));
      }

      addTableToDocument(document, table);

      moveToNewPage(document);
    }
  }
  private Grid generateGrid() {
    final Grid orgUnitGrid = new ListGrid().setTitle("Organisation unit search result");

    orgUnitGrid.addHeader(new GridHeader("Code", false, true));
    orgUnitGrid.addHeader(new GridHeader("Name", false, true));

    for (OrganisationUnitGroupSet groupSet : groupSets) {
      orgUnitGrid.addHeader(new GridHeader(groupSet.getName(), false, true));
    }

    for (OrganisationUnit unit : organisationUnits) {
      orgUnitGrid.addRow();

      orgUnitGrid.addValue(unit.getCode());
      orgUnitGrid.addValue(unit.getName());

      for (OrganisationUnitGroupSet groupSet : groupSets) {
        orgUnitGrid.addValue(unit.getGroupNameInGroupSet(groupSet));
      }
    }

    return orgUnitGrid;
  }
Пример #13
0
  @Override
  public Collection<ValidationResult> validate(
      Date startDate, Date endDate, OrganisationUnit source) {
    log.info("Validate start: " + startDate + " end: " + endDate + " source: " + source.getName());

    Collection<Period> periods = periodService.getPeriodsBetweenDates(startDate, endDate);
    Collection<ValidationRule> rules = getAllValidationRules();
    Collection<OrganisationUnit> sources = new HashSet<>();
    sources.add(source);

    return Validator.validate(
        sources,
        periods,
        rules,
        null,
        null,
        constantService,
        expressionService,
        periodService,
        dataValueService,
        dataElementCategoryService,
        userService,
        currentUserService);
  }
  // -------------------------------------------------------------------------
  // 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;
    }
  }
Пример #15
0
  public String execute() throws Exception {
    int monthDays[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

    navigationString = "Dashboard";
    orgUnitList = new ArrayList<OrganisationUnit>();

    if (aggOption == null || aggOption.trim().equals("")) {
      aggOption = AlertUtility.USEEXISTINGAGGDATA;
    }

    // Period Info

    Date toDay = new Date();
    Calendar endCal = Calendar.getInstance();
    endCal.setTime(toDay);
    endCal.add(Calendar.MONTH, -1);
    endCal.set(Calendar.DATE, 1);

    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
    // String periodId = "Monthly_"+simpleDateFormat.format( cal.getTime() )+"_";

    if ((endCal.get(Calendar.YEAR) % 400 == 0 || endCal.get(Calendar.YEAR) % 4 == 0)
        && endCal.get(Calendar.MONTH) == 1) {
      endCal.set(Calendar.DATE, monthDays[Calendar.MONTH] + 1);
    } else {
      endCal.set(Calendar.DATE, monthDays[Calendar.MONTH]);
    }
    Date eDate = endCal.getTime();

    if (endCal.get(Calendar.MONTH) < Calendar.APRIL) {
      endCal.roll(Calendar.YEAR, -1);
    }
    endCal.set(Calendar.MONTH, Calendar.APRIL);
    endCal.set(Calendar.DATE, 1);

    // periodId += simpleDateFormat.format( cal.getTime() );
    Date sDate = endCal.getTime();

    List<Period> periodList =
        new ArrayList<Period>(periodService.getIntersectingPeriods(sDate, eDate));

    Collection<Integer> periodIds =
        new ArrayList<Integer>(getIdentifiers(Period.class, periodList));

    String periodIdsByComma = getCommaDelimitedString(periodIds);

    // Period selectedPeriod = periodService.getPeriodByExternalId( periodId );

    DataSet selectedDataSet = dataSetService.getDataSetByCode(DASHBOARD_DATASET);

    List<OrganisationUnit> rootOrgUnitList = new ArrayList<OrganisationUnit>();
    rootOrgUnitList.addAll(currentUserService.getCurrentUser().getOrganisationUnits());

    if (drillDownOrgUnitId == null) {
      if (rootOrgUnitList != null && rootOrgUnitList.size() > 0) {
        navigationString += " -> " + rootOrgUnitList.get(0).getName();
        selOrgUnit = rootOrgUnitList.get(0);
      } else {
        navigationString += " -> NO FACILITY";
      }
    } else {
      selOrgUnit =
          organisationUnitService.getOrganisationUnit(Integer.parseInt(drillDownOrgUnitId));
      navigationString += " -> " + selOrgUnit.getName();
    }

    navigationString +=
        " ( " + simpleDateFormat.format(sDate) + " TO " + simpleDateFormat.format(eDate) + " )";

    for (OrganisationUnit orgUnit : rootOrgUnitList) {
      List<OrganisationUnit> tempOuList = new ArrayList<OrganisationUnit>(orgUnit.getChildren());
      Collections.sort(tempOuList, new IdentifiableObjectNameComparator());

      orgUnitList.add(orgUnit);
      orgUnitList.addAll(tempOuList);
    }

    if (selectedDataSet == null || selOrgUnit == null || periodIdsByComma == null) {
      customDataEntryFormCode = " ";
    } else {
      customDataEntryFormCode =
          alertUtility.getCustomDataSetReport(
              selectedDataSet, selOrgUnit, periodIdsByComma, aggOption, format);
    }

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

    // Initialization
    raFolderName = reportService.getRAFolderName();

    String colArray[] = {
      "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S",
      "T", "U", "V", "W", "X", "Y", "Z", "AA", "AB", "AC", "AD", "AE", "AF", "AG", "AH", "AI", "AJ",
      "AK", "AL", "AM", "AN", "AO", "AP", "AQ", "AR", "AS", "AT", "AU", "AV", "AW", "AX", "AY",
      "AZ", "BA", "BB", "BC", "BD", "BE", "BF", "BG", "BH", "BI", "BJ", "BK", "BL", "BM", "BN",
      "BO", "BP", "BQ", "BR", "BS", "BT", "BU", "BV", "BW", "BX", "BY", "BZ"
    };

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

    // OrgUnit Info
    OrganisationUnit currentOrgUnit = organisationUnitService.getOrganisationUnit(ouIDTB);

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

    List<OrganisationUnit> childOrgUnitTree =
        new ArrayList<OrganisationUnit>(
            organisationUnitService.getOrganisationUnitWithChildren(ouIDTB));
    List<Integer> childOrgUnitTreeIds =
        new ArrayList<Integer>(getIdentifiers(OrganisationUnit.class, childOrgUnitTree));
    String childOrgUnitsByComma = getCommaDelimitedString(childOrgUnitTreeIds);

    // Report Info
    String deCodesXMLFileName = selReportObj.getXmlTemplateName();
    String reportModelTB = selReportObj.getModel();
    String reportFileNameTB = selReportObj.getExcelTemplateName();

    String inputTemplatePath =
        System.getenv("DHIS2_HOME")
            + File.separator
            + raFolderName
            + File.separator
            + "template"
            + File.separator
            + reportFileNameTB;
    // String outputReportPath = System.getenv( "DHIS2_HOME" ) + File.separator + raFolderName +
    // File.separator + "output" + File.separator + UUID.randomUUID().toString() + ".xls";

    String outputReportPath =
        System.getenv("DHIS2_HOME") + File.separator + Configuration_IN.DEFAULT_TEMPFOLDER;
    File newdir = new File(outputReportPath);
    if (!newdir.exists()) {
      newdir.mkdirs();
    }
    outputReportPath += File.separator + UUID.randomUUID().toString() + ".xls";

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

    WritableWorkbook outputReportWorkbook =
        Workbook.createWorkbook(new File(outputReportPath), templateWorkbook);
    WritableCellFormat wCellformat = new WritableCellFormat();
    wCellformat.setBorder(Border.ALL, BorderLineStyle.THIN);
    wCellformat.setAlignment(Alignment.CENTRE);
    wCellformat.setVerticalAlignment(VerticalAlignment.CENTRE);
    wCellformat.setWrap(true);

    // Period Info
    selectedPeriod = periodService.getPeriod(availablePeriods);
    selectedEndPeriod = periodService.getPeriod(availablePeriodsto);

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

    PeriodType periodType = periodService.getPeriodTypeByName(periodTypeId);
    List<Period> periodList =
        new ArrayList<Period>(periodService.getPeriodsBetweenDates(periodType, sDate, eDate));
    // List<Period> periodList = new ArrayList<Period>( periodService.getIntersectingPeriods( sDate,
    // eDate ) );
    Collections.sort(periodList, new PeriodStartDateComparator());

    if (periodTypeId.equalsIgnoreCase("monthly")) {
      simpleDateFormat = new SimpleDateFormat("MMM-yyyy");
    } else if (periodTypeId.equalsIgnoreCase("yearly")) {
      simpleDateFormat = new SimpleDateFormat("yyyy");
    } else {
      simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
    }

    // To get Aggregation Data

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

    // String dataElmentIdsByComma = reportService.getDataelementIds( reportDesignList );
    String dataElmentIdsByComma =
        reportService.getDataelementIdsByStype(reportDesignList, Report_inDesign.ST_DATAELEMENT);
    String nonNumberDataElementIdsByComma =
        reportService.getDataelementIdsByStype(
            reportDesignList, Report_inDesign.ST_NON_NUMBER_DATAELEMENT);

    // Collection<Integer> periodIds1 = new ArrayList<Integer>( getIdentifiers(Period.class,
    // periodList ) );
    String periodsByComma = "";
    // getCommaDelimitedString( periodIds1 );

    int colCount = 0;
    for (Period period : periodList) {
      if (periodTypeId.equalsIgnoreCase("daily")) {
        periodsByComma = "" + period.getId();
      } else {
        Collection<Integer> periodIds =
            new ArrayList<Integer>(
                getIdentifiers(
                    Period.class,
                    periodService.getIntersectingPeriods(
                        period.getStartDate(), period.getEndDate())));
        periodsByComma = getCommaDelimitedString(periodIds);
      }

      Map<String, String> aggDeMap = new HashMap<String, String>();
      if (aggData.equalsIgnoreCase(USEEXISTINGAGGDATA)) {
        aggDeMap.putAll(
            reportService.getResultDataValueFromAggregateTable(
                currentOrgUnit.getId(), dataElmentIdsByComma, periodsByComma));
      } else if (aggData.equalsIgnoreCase(GENERATEAGGDATA)) {
        aggDeMap.putAll(
            reportService.getAggDataFromDataValueTable(
                childOrgUnitsByComma, dataElmentIdsByComma, periodsByComma));
        aggDeMap.putAll(
            reportService.getAggNonNumberDataFromDataValueTable(
                childOrgUnitsByComma, nonNumberDataElementIdsByComma, periodsByComma));
        System.out.println(
            childOrgUnitsByComma + " \n " + dataElmentIdsByComma + " \n " + periodsByComma);
      } else if (aggData.equalsIgnoreCase(USECAPTUREDDATA)) {
        aggDeMap.putAll(
            reportService.getAggDataFromDataValueTable(
                "" + currentOrgUnit.getId(), dataElmentIdsByComma, periodsByComma));
        aggDeMap.putAll(
            reportService.getAggNonNumberDataFromDataValueTable(
                "" + currentOrgUnit.getId(), nonNumberDataElementIdsByComma, periodsByComma));
      }
      System.out.println("aggDeMap size : " + aggDeMap.size());

      Iterator<Report_inDesign> reportDesignIterator = reportDesignList.iterator();
      while (reportDesignIterator.hasNext()) {
        Report_inDesign reportDesign = reportDesignIterator.next();
        String deCodeString = reportDesign.getExpression();

        String sType = reportDesign.getStype();
        String tempStr = "";

        tempRowNo = reportDesign.getRowno();
        tempColNo = reportDesign.getColno();
        sheetNo = reportDesign.getSheetno();

        if (deCodeString.equalsIgnoreCase("FACILITY")) {
          tempStr = currentOrgUnit.getName();
        } else if (deCodeString.equalsIgnoreCase("PERIOD-RANGE")) {
          tempStr =
              simpleDateFormat.format(selectedPeriod.getStartDate())
                  + " To "
                  + simpleDateFormat.format(selectedEndPeriod.getEndDate());
        } else if (deCodeString.equalsIgnoreCase("PROGRESSIVE-PERIOD")) {
          tempStr = simpleDateFormat.format(period.getStartDate());
        } else if (deCodeString.equalsIgnoreCase("NA")) {
          tempStr = " ";
        } else {
          if (sType.equalsIgnoreCase("dataelement")) {
            if (aggData.equalsIgnoreCase(USECAPTUREDDATA)) {
              // tempStr = reportService.getIndividualResultDataValue( deCodeString,
              // period.getStartDate(), period.getEndDate(), currentOrgUnit, reportModelTB );
              tempStr = getAggVal(deCodeString, aggDeMap);
            } else if (aggData.equalsIgnoreCase(GENERATEAGGDATA)) {
              // tempStr = reportService.getResultDataValue( deCodeString, period.getStartDate(),
              // period.getEndDate(), currentOrgUnit, reportModelTB );
              tempStr = getAggVal(deCodeString, aggDeMap);
            } else if (aggData.equalsIgnoreCase(USEEXISTINGAGGDATA)) {
              tempStr = getAggVal(deCodeString, aggDeMap);
            }
          } else if (sType.equalsIgnoreCase(Report_inDesign.ST_DATAELEMENT_NO_REPEAT)) {
            deCodeString = deCodeString.replaceAll(":", "\\.");
            deCodeString = deCodeString.replaceAll("[", "");
            deCodeString = deCodeString.replaceAll("]", "");
            System.out.println("deCodeString : " + deCodeString);
            tempStr = aggDeMap.get(deCodeString);
          }
        }

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

          WritableSheet sheet0 = outputReportWorkbook.getSheet(sheetNo);

          sheet0.addCell(new Blank(tempColNo, tempRowNo, wCellformat));
        } else {
          if (reportModelTB.equalsIgnoreCase("PROGRESSIVE-PERIOD")) {
            if (deCodeString.equalsIgnoreCase("FACILITY")
                || deCodeString.equalsIgnoreCase("PERIOD-RANGE")) {
            } else {
              tempColNo += colCount;
            }

            WritableSheet sheet0 = outputReportWorkbook.getSheet(sheetNo);

            try {
              try {
                sheet0.addCell(
                    new Number(tempColNo, tempRowNo, Double.parseDouble(tempStr), wCellformat));
              } catch (Exception e) {
                sheet0.addCell(new Label(tempColNo, tempRowNo, tempStr, wCellformat));
              }
            } catch (Exception e) {
              System.out.println("Cannot write to Excel");
            }
          }
        }
      } // inner while loop end

      colCount++;
    } // outer while loop end

    // ---------------------------------------------------------------------
    // Writing Total Values
    // ---------------------------------------------------------------------

    Iterator<Report_inDesign> reportDesignIterator = reportDesignList.iterator();
    while (reportDesignIterator.hasNext()) {
      Report_inDesign reportDesign = reportDesignIterator.next();

      String deCodeString = reportDesign.getExpression();

      if (deCodeString.equalsIgnoreCase("FACILITY")
          || deCodeString.equalsIgnoreCase("PERIOD-RANGE")) {
        continue;
      }

      tempRowNo = reportDesign.getRowno();
      tempColNo = reportDesign.getColno();
      sheetNo = reportDesign.getSheetno();

      String colStart = "" + colArray[tempColNo];
      String colEnd = "" + colArray[tempColNo + colCount - 1];

      String tempFormula =
          "SUM(" + colStart + (tempRowNo + 1) + ":" + colEnd + (tempRowNo + 1) + ")";

      WritableSheet totalSheet = outputReportWorkbook.getSheet(sheetNo);
      WritableFont arialBold = new WritableFont(WritableFont.ARIAL, 10, WritableFont.BOLD);
      WritableCellFormat totalCellformat = new WritableCellFormat(arialBold);
      totalCellformat.setBorder(Border.ALL, BorderLineStyle.THIN);
      totalCellformat.setAlignment(Alignment.CENTRE);
      totalCellformat.setVerticalAlignment(VerticalAlignment.CENTRE);
      totalCellformat.setWrap(true);

      if (deCodeString.equalsIgnoreCase("PROGRESSIVE-PERIOD")) {
        totalSheet.addCell(new Label(tempColNo + colCount, tempRowNo, "Total", totalCellformat));
      } else if (deCodeString.equalsIgnoreCase("NA")) {
        totalSheet.addCell(new Label(tempColNo + colCount, tempRowNo, " ", totalCellformat));
      } else {
        totalSheet.addCell(
            new Formula(tempColNo + colCount, tempRowNo, tempFormula, totalCellformat));
      }
    }

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

    fileName = reportFileNameTB.replace(".xls", "");
    fileName += "_" + currentOrgUnit.getShortName();
    fileName += "_" + simpleDateFormat.format(selectedPeriod.getStartDate()) + ".xls";
    File outputReportFile = new File(outputReportPath);
    inputStream = new BufferedInputStream(new FileInputStream(outputReportFile));

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

    outputReportFile.deleteOnExit();

    statementManager.destroy();

    return SUCCESS;
  }
  public void generateReport(
      Program selProgram, List<OrganisationUnit> orgUnitList, Date sDate, Date eDate)
      throws Exception {
    String raFolderName = reportService.getRAFolderName();
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
    String query = "";
    int rowStart = 3;
    int colStart = 1;
    int rowCount = rowStart;
    int colCount = colStart;

    // String outputReportPath = System.getenv( "DHIS2_HOME" ) + File.separator + raFolderName +
    // File.separator + "output" + File.separator + UUID.randomUUID().toString() + ".xls";

    String outputReportPath =
        System.getenv("DHIS2_HOME") + File.separator + Configuration_IN.DEFAULT_TEMPFOLDER;
    File newdir = new File(outputReportPath);
    if (!newdir.exists()) {
      newdir.mkdirs();
    }
    outputReportPath += File.separator + UUID.randomUUID().toString() + ".xls";

    WritableWorkbook outputReportWorkbook = Workbook.createWorkbook(new File(outputReportPath));
    WritableSheet sheet0 = outputReportWorkbook.createSheet(selProgram.getName(), 0);

    try {
      List<PatientIdentifierType> patientIdentifierTypes =
          new ArrayList<PatientIdentifierType>(
              patientIdentifierTypeService.getAllPatientIdentifierTypes());
      Collections.sort(patientIdentifierTypes, new PatientIdentifierTypeComparator());

      List<PatientAttribute> patientAttributes =
          new ArrayList<PatientAttribute>(patientAttributeService.getAllPatientAttributes());
      Collections.sort(patientAttributes, new PatientAttributeComparator());

      List<ProgramStage> programStages = new ArrayList<ProgramStage>(selProgram.getProgramStages());
      Collections.sort(programStages, new ProgramStageOrderComparator());

      Map<ProgramStage, List<DataElement>> programStageDataElementMap =
          new HashMap<ProgramStage, List<DataElement>>();
      for (ProgramStage programStage : programStages) {
        List<ProgramStageDataElement> programStageDataElements =
            new ArrayList<ProgramStageDataElement>(programStage.getProgramStageDataElements());

        List<DataElement> dataElements = new ArrayList<DataElement>();
        for (ProgramStageDataElement programStageDataElement : programStageDataElements) {
          dataElements.add(programStageDataElement.getDataElement());
        }

        Collections.sort(dataElements, new IdentifiableObjectNameComparator());
        programStageDataElementMap.put(programStage, dataElements);
      }

      // Printing Header Information
      sheet0.mergeCells(colCount, rowCount - 1, colCount, rowCount);
      sheet0.addCell(new Label(colCount, rowCount - 1, "OrgUnit Hierarchy", getCellFormat1()));
      colCount++;
      sheet0.mergeCells(colCount, rowCount - 1, colCount, rowCount);
      sheet0.addCell(new Label(colCount, rowCount - 1, "OrgUnit", getCellFormat1()));
      colCount++;
      for (PatientIdentifierType patientIdentifierType : patientIdentifierTypes) {
        sheet0.mergeCells(colCount, rowCount - 1, colCount, rowCount);
        sheet0.addCell(
            new Label(colCount, rowCount - 1, patientIdentifierType.getName(), getCellFormat1()));
        colCount++;
      }

      sheet0.mergeCells(colCount, rowCount - 1, colCount, rowCount);
      sheet0.addCell(new Label(colCount, rowCount - 1, "Benificiary ID", getCellFormat1()));
      colCount++;

      sheet0.mergeCells(colCount, rowCount - 1, colCount, rowCount);
      sheet0.addCell(new Label(colCount, rowCount - 1, "Benificiary Name", getCellFormat1()));
      colCount++;
      sheet0.mergeCells(colCount, rowCount - 1, colCount, rowCount);
      sheet0.addCell(new Label(colCount, rowCount - 1, "Gender", getCellFormat1()));
      colCount++;
      sheet0.mergeCells(colCount, rowCount - 1, colCount, rowCount);
      sheet0.addCell(new Label(colCount, rowCount - 1, "Age", getCellFormat1()));
      colCount++;
      sheet0.mergeCells(colCount, rowCount - 1, colCount, rowCount);
      sheet0.addCell(new Label(colCount, rowCount - 1, "Data of Birth", getCellFormat1()));
      colCount++;
      sheet0.mergeCells(colCount, rowCount - 1, colCount, rowCount);
      sheet0.addCell(new Label(colCount, rowCount - 1, "Blood Group", getCellFormat1()));
      colCount++;
      sheet0.mergeCells(colCount, rowCount - 1, colCount, rowCount);
      sheet0.addCell(new Label(colCount, rowCount - 1, "Registration Date", getCellFormat1()));
      colCount++;

      for (PatientAttribute patientAttribute : patientAttributes) {
        sheet0.mergeCells(colCount, rowCount - 1, colCount, rowCount);
        sheet0.addCell(
            new Label(colCount, rowCount - 1, patientAttribute.getName(), getCellFormat1()));
        colCount++;
      }

      sheet0.mergeCells(colCount, rowCount - 1, colCount, rowCount);
      sheet0.addCell(new Label(colCount, rowCount - 1, "Incident Date", getCellFormat1()));
      colCount++;

      sheet0.mergeCells(colCount, rowCount - 1, colCount, rowCount);
      sheet0.addCell(new Label(colCount, rowCount - 1, "Enrollment Date", getCellFormat1()));
      colCount++;
      for (ProgramStage programStage : programStages) {
        List<DataElement> dataElementList =
            new ArrayList<DataElement>(programStageDataElementMap.get(programStage));
        sheet0.mergeCells(
            colCount, rowCount - 1, colCount + dataElementList.size() + 1, rowCount - 1);
        sheet0.addCell(new Label(colCount, rowCount - 1, programStage.getName(), getCellFormat1()));

        sheet0.addCell(new Label(colCount, rowCount, "Due Date", getCellFormat1()));
        colCount++;
        sheet0.addCell(new Label(colCount, rowCount, "Execution Date", getCellFormat1()));
        colCount++;

        for (DataElement dataElement : dataElementList) {
          sheet0.addCell(
              new Label(
                  colCount,
                  rowCount,
                  dataElement.getName() + "--" + dataElement.getType(),
                  getCellFormat1()));
          colCount++;
        }
      }

      rowCount++;

      for (OrganisationUnit orgUnit : orgUnitList) {
        if (sDate != null && eDate != null) {
          query =
              "SELECT patient.patientid, programinstance.programinstanceid,programinstance.dateofincident,programinstance.enrollmentdate FROM programinstance INNER JOIN patient "
                  + " ON programinstance.patientid = patient.patientid "
                  + " WHERE patient.organisationunitid = "
                  + orgUnit.getId()
                  + " AND programinstance.programid = "
                  + selProgram.getId()
                  + " AND patient.registrationdate >= '"
                  + startDate
                  + "'"
                  + " AND patient.registrationdate <= '"
                  + endDate
                  + "' "
                  + " AND enddate IS NULL";
        } else {
          query =
              "SELECT patient.patientid, programinstance.programinstanceid,programinstance.dateofincident,programinstance.enrollmentdate FROM programinstance INNER JOIN patient "
                  + " ON programinstance.patientid = patient.patientid "
                  + " WHERE patient.organisationunitid = "
                  + orgUnit.getId()
                  + " AND programinstance.programid = "
                  + selProgram.getId()
                  + " AND enddate IS NULL";
        }

        SqlRowSet sqlResultSet = jdbcTemplate.queryForRowSet(query);

        if (sqlResultSet != null) {
          int count = 1;
          String orgUnitBranch = "";
          sqlResultSet.beforeFirst();
          while (sqlResultSet.next()) {
            colCount = colStart;

            if (orgUnit.getParent() != null) {
              orgUnitBranch = getOrgunitBranch(orgUnit.getParent());
            } else {
              orgUnitBranch = " ";
            }

            sheet0.addCell(new Label(colCount, rowCount, orgUnitBranch, getCellFormat2()));
            colCount++;
            sheet0.addCell(new Label(colCount, rowCount, orgUnit.getName(), getCellFormat2()));
            colCount++;

            int patientId = sqlResultSet.getInt(1);
            int programInstanceId = sqlResultSet.getInt(2);
            Date dateOfIncident = sqlResultSet.getDate(3);
            Date dateOfEnrollment = sqlResultSet.getDate(4);

            Patient patient = patientService.getPatient(patientId);

            // Patient Identifier Details
            for (PatientIdentifierType patientIdentifierType : patientIdentifierTypes) {
              query =
                  "SELECT identifier from patientidentifier WHERE patientidentifiertypeid = "
                      + patientIdentifierType.getId()
                      + " AND patientid = "
                      + patient.getId();

              SqlRowSet sqlResultSet1 = jdbcTemplate.queryForRowSet(query);
              if (sqlResultSet1 != null && sqlResultSet1.next()) {
                String value = sqlResultSet1.getString(1);
                if (value != null && !value.trim().equalsIgnoreCase("")) {
                  sheet0.addCell(new Label(colCount, rowCount, value, getCellFormat2()));
                } else {
                  sheet0.addCell(new Label(colCount, rowCount, "-", getCellFormat2()));
                }
              } else {
                sheet0.addCell(new Label(colCount, rowCount, "-", getCellFormat2()));
              }

              colCount++;
            }

            // Patient Properties

            sheet0.addCell(
                new Label(colCount, rowCount, patient.getId().toString(), getCellFormat2()));
            colCount++;
            sheet0.addCell(new Label(colCount, rowCount, patient.getFullName(), getCellFormat2()));
            colCount++;
            sheet0.addCell(
                new Label(colCount, rowCount, patient.getTextGender(), getCellFormat2()));
            colCount++;
            sheet0.addCell(new Label(colCount, rowCount, patient.getAge(), getCellFormat2()));
            colCount++;
            sheet0.addCell(
                new Label(
                    colCount,
                    rowCount,
                    simpleDateFormat.format(patient.getBirthDate()),
                    getCellFormat2()));
            colCount++;
            /**
             * TODO BloodGroup is removed from Patient Object, so need to change this accordingly
             */
            sheet0.addCell(
                new Label(colCount, rowCount, "" /*patient.getBloodGroup()*/, getCellFormat2()));
            colCount++;
            sheet0.addCell(
                new Label(
                    colCount,
                    rowCount,
                    simpleDateFormat.format(patient.getRegistrationDate()),
                    getCellFormat2()));
            colCount++;

            // Patient Attribute Values
            for (PatientAttribute patientAttribute : patientAttributes) {
              query =
                  "SELECT value from patientattributevalue WHERE patientid = "
                      + patient.getId()
                      + " AND patientattributeid = "
                      + patientAttribute.getId();

              SqlRowSet sqlResultSet1 = jdbcTemplate.queryForRowSet(query);
              if (sqlResultSet1 != null && sqlResultSet1.next()) {
                String value = sqlResultSet1.getString(1);
                if (value != null && !value.trim().equalsIgnoreCase("")) {
                  sheet0.addCell(new Label(colCount, rowCount, value, getCellFormat2()));
                } else {
                  sheet0.addCell(new Label(colCount, rowCount, "-", getCellFormat2()));
                }
              } else {
                sheet0.addCell(new Label(colCount, rowCount, "-", getCellFormat2()));
              }

              colCount++;
            }

            // Program Enrollment Details
            sheet0.addCell(
                new Label(
                    colCount, rowCount, simpleDateFormat.format(dateOfIncident), getCellFormat2()));
            colCount++;
            sheet0.addCell(
                new Label(
                    colCount,
                    rowCount,
                    simpleDateFormat.format(dateOfEnrollment),
                    getCellFormat2()));
            colCount++;

            // ProgramStage Values
            for (ProgramStage programStage : programStages) {
              query =
                  "SELECT programstageinstanceid,duedate,executiondate from programstageinstance "
                      + " WHERE programinstanceid = "
                      + programInstanceId
                      + " AND programstageid = "
                      + programStage.getId();

              SqlRowSet sqlResultSet2 = jdbcTemplate.queryForRowSet(query);
              Integer programStageInstanceId = 0;
              if (sqlResultSet2 != null && sqlResultSet2.next()) {
                programStageInstanceId = sqlResultSet2.getInt(1);

                // ProgramStage DueDate and Execution Date
                Date dueDate = sqlResultSet2.getDate(2);
                Date exeDate = sqlResultSet2.getDate(3);

                if (dueDate != null) {
                  String dueDateStr = simpleDateFormat.format(dueDate);
                  sheet0.addCell(new Label(colCount, rowCount, dueDateStr, getCellFormat3()));
                } else {
                  sheet0.addCell(new Label(colCount, rowCount, "-", getCellFormat3()));
                }
                colCount++;

                if (exeDate != null) {
                  String exeDateStr = simpleDateFormat.format(exeDate);
                  sheet0.addCell(new Label(colCount, rowCount, exeDateStr, getCellFormat3()));
                } else {
                  sheet0.addCell(new Label(colCount, rowCount, "-", getCellFormat3()));
                }

                colCount++;
              } else {
                sheet0.addCell(new Label(colCount, rowCount, "-", getCellFormat3()));
                colCount++;
                sheet0.addCell(new Label(colCount, rowCount, "-", getCellFormat3()));
                colCount++;
              }

              for (DataElement dataElement : programStageDataElementMap.get(programStage)) {
                query =
                    "SELECT value from patientdatavalue WHERE programstageinstanceid = "
                        + programStageInstanceId
                        + " AND dataelementid = "
                        + dataElement.getId();
                // " AND organisationunitid = " + orgUnit.getId();

                SqlRowSet sqlResultSet3 = jdbcTemplate.queryForRowSet(query);

                if (sqlResultSet3 != null && sqlResultSet3.next()) {
                  String value = sqlResultSet3.getString(1);

                  if (dataElement.getType().equalsIgnoreCase(DataElement.VALUE_TYPE_BOOL)) {
                    if (value.equalsIgnoreCase("false")) value = "No";
                    else value = "Yes";
                  }

                  if (value != null && !value.trim().equalsIgnoreCase("")) {
                    sheet0.addCell(new Label(colCount, rowCount, value, getCellFormat2()));
                  } else {
                    sheet0.addCell(new Label(colCount, rowCount, "-", getCellFormat2()));
                  }
                } else {
                  sheet0.addCell(new Label(colCount, rowCount, "-", getCellFormat2()));
                }

                colCount++;
              }
            }

            rowCount++;
          }
        }
      }
    } catch (Exception e) {
      System.out.println("Exception: " + e.getMessage());
      e.printStackTrace();
    }

    outputReportWorkbook.write();
    outputReportWorkbook.close();
    fileName = selProgram.getName() + ".xls";
    File outputReportFile = new File(outputReportPath);
    inputStream = new BufferedInputStream(new FileInputStream(outputReportFile));
    outputReportFile.deleteOnExit();
  }
Пример #18
0
  /**
   * Creates a table with the given validation rule
   *
   * @param user The User
   * @param i18n i18n object
   * @param format I18nFormat object
   * @param keepTogether Indicates whether the table could be broken across multiple pages or should
   *     be kept at one page.
   * @param columnWidths The column widths.
   */
  public static PdfPTable printUser(
      UserCredentials userCredentials,
      I18n i18n,
      I18nFormat format,
      boolean keepTogether,
      float... columnWidths) {
    User user = userCredentials.getUser();

    PdfPTable table = getPdfPTable(keepTogether, columnWidths);

    table.addCell(getHeaderCell(user.getFirstName() + ", " + user.getSurname(), 2));

    table.addCell(getEmptyCell(2, 15));

    table.addCell(getItalicCell(i18n.getString("username")));
    table.addCell(getTextCell(userCredentials.getUsername()));

    if (nullIfEmpty(user.getEmail()) != null) {
      table.addCell(getItalicCell(i18n.getString("email")));
      table.addCell(getTextCell(user.getEmail()));
    }

    if (nullIfEmpty(user.getPhoneNumber()) != null) {
      table.addCell(getItalicCell(i18n.getString("phone_number")));
      table.addCell(getTextCell(user.getPhoneNumber()));
    }

    table.addCell(getItalicCell(i18n.getString("last_login")));
    table.addCell(
        getTextCell(
            userCredentials.getLastLogin() != null
                ? format.formatDate(userCredentials.getLastLogin())
                : EMPTY));

    String temp = "";

    for (OrganisationUnit unit : user.getOrganisationUnits()) {
      temp += unit.getName().concat(", ");
    }

    temp = temp.trim();
    temp = temp.substring(0, temp.isEmpty() ? 0 : temp.length() - 1);

    table.addCell(getItalicCell(i18n.getString("organisation_units")));
    table.addCell(getTextCell(temp));

    temp = "";

    for (UserAuthorityGroup role : userCredentials.getUserAuthorityGroups()) {
      temp += role.getName().concat(", ");
    }

    temp = temp.trim();
    temp = temp.substring(0, temp.isEmpty() ? 0 : temp.length() - 1);

    table.addCell(getItalicCell(i18n.getString("roles")));
    table.addCell(getTextCell(temp));

    for (AttributeValue value : user.getAttributeValues()) {
      table.addCell(getItalicCell(value.getAttribute().getName()));
      table.addCell(getTextCell(value.getValue()));
    }

    table.addCell(getEmptyCell(2, 30));

    return table;
  }