Exemplo n.º 1
0
  @Override
  public void createDatePeriodStructure() {
    try {
      jdbcTemplate.execute("DROP TABLE IF EXISTS " + TABLE_NAME_DATE_PERIOD_STRUCTURE);
    } catch (BadSqlGrammarException ex) {
      // Do nothing, table does not exist
    }

    String quote = statementBuilder.getColumnQuote();

    String sql =
        "CREATE TABLE "
            + TABLE_NAME_DATE_PERIOD_STRUCTURE
            + " (dateperiod DATE NOT NULL PRIMARY KEY";

    for (PeriodType periodType : PeriodType.PERIOD_TYPES) {
      sql += ", " + quote + periodType.getName().toLowerCase() + quote + " VARCHAR(15)";
    }

    sql += ")";

    log.info("Create date period structure SQL: " + sql);

    jdbcTemplate.execute(sql);
  }
Exemplo n.º 2
0
  @Override
  public void createPeriodStructure() {
    try {
      jdbcTemplate.execute("DROP TABLE IF EXISTS " + TABLE_NAME_PERIOD_STRUCTURE);
    } catch (BadSqlGrammarException ex) {
      // Do nothing, table does not exist
    }

    String quote = statementBuilder.getColumnQuote();

    String sql =
        "CREATE TABLE "
            + TABLE_NAME_PERIOD_STRUCTURE
            + " (periodid INTEGER NOT NULL PRIMARY KEY, iso VARCHAR(15) NOT NULL, daysno INTEGER NOT NULL";

    for (PeriodType periodType : PeriodType.PERIOD_TYPES) {
      sql += ", " + quote + periodType.getName().toLowerCase() + quote + " VARCHAR(15)";
    }

    sql += ")";

    log.info("Create period structure SQL: " + sql);

    jdbcTemplate.execute(sql);

    final String isoInSql = "create unique index in_periodstructure_iso on _periodstructure(iso)";

    jdbcTemplate.execute(isoInSql);
  }
  public static PeriodType getByNameIgnoreCase(String name) {
    for (PeriodType periodType : getAvailablePeriodTypes()) {
      if (name != null
          && periodType.getName().toLowerCase().trim().equals(name.toLowerCase().trim())) {
        return periodType;
      }
    }

    return null;
  }
  /**
   * Returns a period based on the given date string in ISO format. Returns null if the date string
   * cannot be parsed to a period.
   *
   * @param isoPeriod the date string in ISO format.
   * @return a period.
   */
  public static Period getPeriodFromIsoString(String isoPeriod) {
    if (isoPeriod != null) {
      PeriodType periodType = getPeriodTypeFromIsoString(isoPeriod);

      try {
        return periodType != null ? periodType.createPeriod(isoPeriod) : null;
      } catch (Exception ex) {
        // Do nothing and return null
      }
    }

    return null;
  }
Exemplo n.º 5
0
  @Override
  public int getActiveUsersCount(int days) {
    Calendar cal = PeriodType.createCalendarInstance();
    cal.add(Calendar.DAY_OF_YEAR, (days * -1));

    return getActiveUsersCount(cal.getTime());
  }
  @Override
  public String execute() throws Exception {
    statementManager.initialise();

    selectedPeriod = PeriodType.createPeriodExternalId(selectionManager.getSelectedPeriodIndex());

    this.installPeriod();

    List<ExportReport> reports = new ArrayList<ExportReport>();

    for (String id : selectionManager.getListObject()) {
      reports.add(exportReportService.getExportReport(Integer.parseInt(id)));
    }

    resetDecimalFormatByLocale(Locale.GERMAN);
    applyPatternDecimalFormat(PATTERN_DECIMAL_FORMAT1);

    executeGenerateOutputFile(reports);

    this.complete();

    statementManager.destroy();

    return SUCCESS;
  }
  @Override
  public boolean equals(Object o) {
    if (this == o) {
      return true;
    }

    if (o == null) {
      return false;
    }

    if (!(o instanceof PeriodType)) {
      return false;
    }

    final PeriodType other = (PeriodType) o;

    return getName().equals(other.getName());
  }
Exemplo n.º 8
0
  public Period getPeriod(String isoPeriod) {
    Period period = PeriodType.getPeriodFromIsoString(isoPeriod);

    if (period != null) {
      period =
          periodStore.getPeriod(period.getStartDate(), period.getEndDate(), period.getPeriodType());
    }

    return period;
  }
  public String execute() throws Exception {
    // ---------------------------------------------------------------------
    // Prepare values
    // ---------------------------------------------------------------------

    code = nullIfEmpty(code);
    shortName = nullIfEmpty(shortName);
    description = nullIfEmpty(description);

    PeriodType periodType = PeriodType.getPeriodTypeByName(frequencySelect);

    DataSet dataSet = new DataSet(name, shortName, code, periodType);

    MapLegendSet legendSet = mappingService.getMapLegendSet(selectedLegendSetId);

    dataSet.setExpiryDays(expiryDays);
    dataSet.setTimelyDays(timelyDays);
    dataSet.setSkipAggregation(skipAggregation);

    for (String id : dataElementsSelectedList) {
      dataSet.addDataElement(dataElementService.getDataElement(Integer.parseInt(id)));
    }

    Set<Indicator> indicators = new HashSet<Indicator>();

    for (String id : indicatorsSelectedList) {
      indicators.add(indicatorService.getIndicator(Integer.parseInt(id)));
    }

    if (categoryComboId != null) {
      dataSet.setCategoryCombo(categoryService.getDataElementCategoryCombo(categoryComboId));
    }

    dataSet.setDescription(description);
    dataSet.setVersion(1);
    dataSet.setMobile(false);
    dataSet.setIndicators(indicators);
    dataSet.setNotificationRecipients(userGroupService.getUserGroup(notificationRecipients));
    dataSet.setAllowFuturePeriods(allowFuturePeriods);
    dataSet.setFieldCombinationRequired(fieldCombinationRequired);
    dataSet.setValidCompleteOnly(validCompleteOnly);
    dataSet.setNotifyCompletingUser(notifyCompletingUser);
    dataSet.setApproveData(approveData);
    dataSet.setSkipOffline(skipOffline);
    dataSet.setDataElementDecoration(dataElementDecoration);
    dataSet.setRenderAsTabs(renderAsTabs);
    dataSet.setRenderHorizontally(renderHorizontally);
    dataSet.setLegendSet(legendSet);

    dataSetService.addDataSet(dataSet);

    userService.assignDataSetToUserRole(dataSet);

    return SUCCESS;
  }
  @Override
  public String execute() throws Exception {
    TaskId taskId = new TaskId(TaskCategory.DATAMART, currentUserService.getCurrentUser());

    notifier.clear(taskId);

    ScheduledTasks tasks = new ScheduledTasks();

    // ---------------------------------------------------------------------
    // Analytics
    // ---------------------------------------------------------------------

    if (analytics) {
      analyticsTableTask.setTaskId(taskId);

      tasks.addTask(resourceTableTask);
      tasks.addTask(analyticsTableTask);
    }

    // ---------------------------------------------------------------------
    // Data mart
    // ---------------------------------------------------------------------

    if (dataMart) {
      Date start = DateUtils.getMediumDate(startDate);
      Date end = DateUtils.getMediumDate(endDate);

      List<Period> periods = new ArrayList<Period>();

      for (String type : periodTypes) {
        CalendarPeriodType periodType = (CalendarPeriodType) PeriodType.getPeriodTypeByName(type);

        periods.addAll(periodType.generatePeriods(start, end));
      }

      if (periods.size() > 0) {
        dataMartTask.setPeriods(periods);
        dataMartTask.setTaskId(taskId);

        tasks.addTask(dataMartTask);
      }
    }

    if (!tasks.isEmpty()) {
      scheduler.executeTask(tasks);
    }

    return SUCCESS;
  }
Exemplo n.º 11
0
  @Override
  public Collection<DataElementOperand> filterOperands(
      final Collection<DataElementOperand> operands, final PeriodType periodType) {
    final Collection<DataElementOperand> filteredOperands = new HashSet<>();

    for (final DataElementOperand operand : operands) {
      if (operand.getValueType().equals(VALUE_TYPE_INT)
          && operand.getAggregationOperator().equals(AGGREGATION_OPERATOR_SUM)
          && operand.getFrequencyOrder() <= periodType.getFrequencyOrder()) // Ignore disaggregation
      {
        filteredOperands.add(operand);
      }
    }

    return filteredOperands;
  }
Exemplo n.º 12
0
  private void handleUserQueryParams(UserQueryParams params) {
    boolean canGrantOwnRoles =
        (Boolean)
            systemSettingManager.getSystemSetting(KEY_CAN_GRANT_OWN_USER_AUTHORITY_GROUPS, false);
    params.setDisjointRoles(!canGrantOwnRoles);

    if (params.getUser() == null) {
      params.setUser(currentUserService.getCurrentUser());
    }

    if (params.getUser() != null && params.getUser().isSuper()) {
      params.setCanManage(false);
      params.setAuthSubset(false);
      params.setDisjointRoles(false);
    }

    if (params.getInactiveMonths() != null) {
      Calendar cal = PeriodType.createCalendarInstance();
      cal.add(Calendar.MONTH, (params.getInactiveMonths() * -1));
      params.setInactiveSince(cal.getTime());
    }
  }
Exemplo n.º 13
0
  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;
  }
  public String execute() throws Exception {

    String periodType = "Quarterly";

    // periodType = periodType != null && !periodType.isEmpty() ? periodType :
    // MonthlyPeriodType.NAME;

    CalendarPeriodType _periodType =
        (CalendarPeriodType) CalendarPeriodType.getPeriodTypeByName(periodType);

    int thisYear = Calendar.getInstance().get(Calendar.YEAR);

    int currentYear = (Integer) SessionUtils.getSessionVar(SessionUtils.KEY_CURRENT_YEAR, thisYear);

    Calendar cal = PeriodType.createCalendarInstance();

    // Cannot go to next year if current year equals this year

    if (!(currentYear == thisYear && year > 0)) {
      cal.set(Calendar.YEAR, currentYear);
      cal.add(Calendar.YEAR, year);

      SessionUtils.setSessionVar(SessionUtils.KEY_CURRENT_YEAR, cal.get(Calendar.YEAR));
    }

    periods = _periodType.generatePeriods(cal.getTime());

    FilterUtils.filter(periods, new PastAndCurrentPeriodFilter());

    Collections.reverse(periods);

    for (Period period : periods) {
      period.setName(format.formatPeriod(period));
    }

    return SUCCESS;
  }
Exemplo n.º 15
0
  @Override
  public String execute() throws Exception {
    for (String aggregateValue : aggregateValues) {
      // -----------------------------------------------------------------
      // Get params
      // -----------------------------------------------------------------

      String[] info = aggregateValue.split(SEPERATE_SIGN);

      int dataElementId = Integer.parseInt(info[0]);
      int optionComboId = Integer.parseInt(info[1]);
      String periodIsoId = info[2];
      int orgunitId = Integer.parseInt(info[3]);
      String resultValue = info[4];

      // -----------------------------------------------------------------
      // Create objects
      // -----------------------------------------------------------------

      DataElement dataElement = dataElementService.getDataElement(dataElementId);
      DataElementCategoryOptionCombo optionCombo =
          categoryService.getDataElementCategoryOptionCombo(optionComboId);

      DataElementCategoryOptionCombo attributeOptioncombo =
          categoryService.getDefaultDataElementCategoryOptionCombo();

      Period period = PeriodType.getPeriodFromIsoString(periodIsoId);

      OrganisationUnit orgunit = organisationUnitService.getOrganisationUnit(orgunitId);

      DataValue dataValue =
          dataValueService.getDataValue(
              dataElement, period, orgunit, optionCombo, attributeOptioncombo);

      // -----------------------------------------------------------------
      // Save/Update/Delete data-values
      // -----------------------------------------------------------------

      if (resultValue != "0.0") {
        if (dataValue == null) {
          dataValue =
              new DataValue(
                  dataElement,
                  period,
                  orgunit,
                  optionCombo,
                  attributeOptioncombo,
                  "" + resultValue,
                  CaseAggregationCondition.AUTO_STORED_BY,
                  new Date(),
                  null);
          dataValueService.addDataValue(dataValue);
        } else {
          dataValue.setValue(resultValue);
          dataValue.setLastUpdated(new Date());
          dataValue.setStoredBy(CaseAggregationCondition.AUTO_STORED_BY);

          dataValueService.updateDataValue(dataValue);
        }
      } else if (dataValue != null) {
        dataValueService.deleteDataValue(dataValue);
      }
    }

    return SUCCESS;
  }
  @Override
  public String execute() throws Exception {
    patient = patientService.getPatient(patientId);

    Collection<Program> programs =
        programService.getProgramsByCurrentUser(Program.MULTIPLE_EVENTS_WITH_REGISTRATION);
    programs.addAll(
        programService.getProgramsByCurrentUser(Program.SINGLE_EVENT_WITH_REGISTRATION));

    // ---------------------------------------------------------------------
    // Get relationship
    // ---------------------------------------------------------------------

    relationships = relationshipService.getRelationshipsForPatient(patient);

    Collection<ProgramInstance> programInstances = patient.getProgramInstances();

    // ---------------------------------------------------------------------
    // Get patient-attribute-values
    // ---------------------------------------------------------------------

    Collection<PatientAttributeValue> _attributeValues =
        patientAttributeValueService.getPatientAttributeValues(patient);
    attributeValues = new HashSet<PatientAttributeValue>();

    for (PatientAttributeValue attributeValue : _attributeValues) {
      String value = attributeValue.getValue();
      if (attributeValue.getPatientAttribute().getValueType().equals(PatientAttribute.TYPE_AGE)) {
        Date date = format.parseDate(value);
        value = PatientAttribute.getAgeFromDate(date) + "";
        attributeValue.setValue(value);
      }

      attributeValues.add(attributeValue);
    }

    // ---------------------------------------------------------------------
    // Get patient-identifiers
    // ---------------------------------------------------------------------

    Collection<PatientIdentifier> _identifiers = patient.getIdentifiers();
    identifiers = new HashSet<PatientIdentifier>();

    for (Program program : programs) {
      Collection<PatientIdentifierType> identifierTypes = program.getIdentifierTypes();
      for (PatientIdentifier identifier : _identifiers) {
        if (!identifierTypes.contains(identifier.getIdentifierType())) {
          identifiers.add(identifier);
        }
      }
    }
    // ---------------------------------------------------------------------
    // Get program enrollment
    // ---------------------------------------------------------------------

    activeProgramInstances = new HashSet<ProgramInstance>();

    completedProgramInstances = new HashSet<ProgramInstance>();

    for (ProgramInstance programInstance : programInstances) {
      if (programs.contains(programInstance.getProgram())) {
        if (programInstance.getStatus() == ProgramInstance.STATUS_ACTIVE) {
          activeProgramInstances.add(programInstance);

          programIndicatorsMap.putAll(
              programIndicatorService.getProgramIndicatorValues(programInstance));
        } else {
          completedProgramInstances.add(programInstance);
        }
      }
    }

    // ---------------------------------------------------------------------
    // Patient-Audit
    // ---------------------------------------------------------------------

    patientAudits = patientAuditService.getPatientAudits(patient);

    Calendar today = Calendar.getInstance();
    PeriodType.clearTimeOfDay(today);
    Date date = today.getTime();
    String visitor = currentUserService.getCurrentUsername();
    PatientAudit patientAudit =
        patientAuditService.getPatientAudit(
            patient.getId(), visitor, date, PatientAudit.MODULE_PATIENT_DASHBOARD);
    if (patientAudit == null) {
      patientAudit =
          new PatientAudit(patient, visitor, date, PatientAudit.MODULE_PATIENT_DASHBOARD);
      patientAuditService.savePatientAudit(patientAudit);
    }

    return SUCCESS;
  }
  /**
   * Return the potential number of periods of the given period type which is spanned by this
   * period.
   *
   * @param type the period type.
   * @return the potential number of periods of the given period type spanned by this period.
   */
  public int getPeriodSpan(PeriodType type) {
    double no = (double) this.getFrequencyOrder() / type.getFrequencyOrder();

    return (int) Math.floor(no);
  }
Exemplo n.º 18
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);
    }
  }
 {
   for (PeriodType periodType : PERIOD_TYPES) {
     put(periodType.getName(), periodType);
   }
 }
Exemplo n.º 20
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);
  }
Exemplo n.º 21
0
 public PeriodType getPeriodTypeByName(String name) {
   return PeriodType.getPeriodTypeByName(name);
 }
Exemplo n.º 22
0
 public List<PeriodType> getAllPeriodTypes() {
   return PeriodType.getAvailablePeriodTypes();
 }