@Override
  public JLGCollectionSheetData generateCenterCollectionSheet(
      final Long centerId, final JsonQuery query) {

    this.collectionSheetGenerateCommandFromApiJsonDeserializer.validateForGenerateCollectionSheet(
        query.json());

    final AppUser currentUser = this.context.authenticatedUser();
    final String hierarchy = currentUser.getOffice().getHierarchy();
    final String officeHierarchy = hierarchy + "%";

    final CenterData center = this.centerReadPlatformService.retrieveOne(centerId);

    final LocalDate transactionDate =
        query.localDateValueOfParameterNamed(transactionDateParamName);
    final DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
    final String dueDateStr = df.format(transactionDate.toDate());

    final JLGCollectionSheetFaltDataMapper mapper = new JLGCollectionSheetFaltDataMapper();

    StringBuilder sql = new StringBuilder(mapper.collectionSheetSchema(true));

    final SqlParameterSource namedParameters =
        new MapSqlParameterSource()
            .addValue("dueDate", dueDateStr)
            .addValue("centerId", center.getId())
            .addValue("officeHierarchy", officeHierarchy)
            .addValue("entityTypeId", CalendarEntityType.CENTERS.getValue());

    final Collection<JLGCollectionSheetFlatData> collectionSheetFlatDatas =
        this.namedParameterjdbcTemplate.query(sql.toString(), namedParameters, mapper);

    // loan data for collection sheet
    JLGCollectionSheetData collectionSheetData =
        buildJLGCollectionSheet(transactionDate, collectionSheetFlatDatas);

    // mandatory savings data for collection sheet
    Collection<JLGGroupData> groupsWithSavingsData =
        this.namedParameterjdbcTemplate.query(
            mandatorySavingsExtractor.collectionSheetSchema(true),
            namedParameters,
            mandatorySavingsExtractor);

    // merge savings data into loan data
    mergeSavingsGroupDataIntoCollectionsheetData(groupsWithSavingsData, collectionSheetData);

    collectionSheetData =
        JLGCollectionSheetData.withSavingsProducts(
            collectionSheetData, retrieveSavingsProducts(groupsWithSavingsData));

    return collectionSheetData;
  }
  @Override
  public CommandProcessingResult createLoanTaxMapping(Long entityId, JsonCommand command) {

    final JsonElement parsedQuery = this.fromJsonHelper.parse(command.json());
    final JsonQuery query = JsonQuery.from(command.json(), parsedQuery, this.fromJsonHelper);
    boolean flag = false;

    if (entityId == 1L) {
      flag = true;
    }
    String data = this.calculationPlatformService.calculateTaxLoanSchedule(query, flag);
    return new CommandProcessingResultBuilder().withResourceIdAsString(data).build();
  }
Example #3
0
  @POST
  @Path("{groupId}")
  @Consumes({MediaType.APPLICATION_JSON})
  @Produces({MediaType.APPLICATION_JSON})
  public String activateOrGenerateCollectionSheet(
      @PathParam("groupId") final Long groupId,
      @QueryParam("command") final String commandParam,
      @QueryParam("roleId") final Long roleId,
      final String apiRequestBodyAsJson,
      @Context final UriInfo uriInfo) {
    final CommandWrapperBuilder builder =
        new CommandWrapperBuilder().withJson(apiRequestBodyAsJson);

    CommandProcessingResult result = null;
    if (is(commandParam, "activate")) {
      final CommandWrapper commandRequest = builder.activateGroup(groupId).build();
      result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest);
      return this.toApiJsonSerializer.serialize(result);
    } else if (is(commandParam, "associateClients")) {
      final CommandWrapper commandRequest = builder.associateClientsToGroup(groupId).build();
      result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest);
      return this.toApiJsonSerializer.serialize(result);
    } else if (is(commandParam, "disassociateClients")) {
      final CommandWrapper commandRequest = builder.disassociateClientsFromGroup(groupId).build();
      result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest);
      return this.toApiJsonSerializer.serialize(result);
    } else if (is(commandParam, "generateCollectionSheet")) {
      final JsonElement parsedQuery = this.fromJsonHelper.parse(apiRequestBodyAsJson);
      final JsonQuery query =
          JsonQuery.from(apiRequestBodyAsJson, parsedQuery, this.fromJsonHelper);
      final JLGCollectionSheetData collectionSheet =
          this.collectionSheetReadPlatformService.generateGroupCollectionSheet(groupId, query);
      final ApiRequestJsonSerializationSettings settings =
          this.apiRequestParameterHelper.process(uriInfo.getQueryParameters());
      return this.toApiJsonSerializer.serialize(
          settings, collectionSheet, GroupingTypesApiConstants.COLLECTIONSHEET_DATA_PARAMETERS);
    } else if (is(commandParam, "saveCollectionSheet")) {
      final CommandWrapper commandRequest = builder.saveGroupCollectionSheet(groupId).build();
      result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest);
      return this.toApiJsonSerializer.serialize(result);
    } else if (is(commandParam, "unassignStaff")) {
      final CommandWrapper commandRequest = builder.unassignGroupStaff(groupId).build();
      result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest);
      return this.toApiJsonSerializer.serialize(result);
    } else if (is(commandParam, "assignStaff")) {
      final CommandWrapper commandRequest = builder.assignGroupStaff(groupId).build();
      result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest);
      return this.toApiJsonSerializer.serialize(result);
    } else if (is(commandParam, "assignRole")) {
      final CommandWrapper commandRequest = builder.assignRole(groupId).build();
      result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest);
      return this.toApiJsonSerializer.serialize(result);
    } else if (is(commandParam, "unassignRole")) {
      final CommandWrapper commandRequest = builder.unassignRole(groupId, roleId).build();
      result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest);
      return this.toApiJsonSerializer.serialize(result);
    } else if (is(commandParam, "updateRole")) {
      final CommandWrapper commandRequest = builder.updateRole(groupId, roleId).build();
      result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest);
      return this.toApiJsonSerializer.serialize(result);
    } else if (is(commandParam, "transferClients")) {
      final CommandWrapper commandRequest = builder.transferClientsBetweenGroups(groupId).build();
      result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest);
      return this.toApiJsonSerializer.serialize(result);
    } else {
      throw new UnrecognizedQueryParamException(
          "command",
          commandParam,
          new Object[] {
            "activate",
            "generateCollectionSheet",
            "saveCollectionSheet",
            "unassignStaff",
            "assignRole",
            "unassignRole",
            "updateassignRole"
          });
    }
  }
  @Override
  public JLGCollectionSheetData generateGroupCollectionSheet(
      final Long groupId, final JsonQuery query) {

    this.collectionSheetGenerateCommandFromApiJsonDeserializer.validateForGenerateCollectionSheet(
        query.json());

    final Long calendarId = query.longValueOfParameterNamed(calendarIdParamName);
    final LocalDate transactionDate =
        query.localDateValueOfParameterNamed(transactionDateParamName);
    final DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
    final String transactionDateStr = df.format(transactionDate.toDate());

    final Calendar calendar =
        this.calendarRepositoryWrapper.findOneWithNotFoundDetection(calendarId);
    // check if transaction against calendar effective from date

    if (!calendar.isValidRecurringDate(transactionDate)) {
      throw new NotValidRecurringDateException(
          "collectionsheet",
          "The date '" + transactionDate + "' is not a valid meeting date.",
          transactionDate);
    }

    final AppUser currentUser = this.context.authenticatedUser();
    final String hierarchy = currentUser.getOffice().getHierarchy();
    final String officeHierarchy = hierarchy + "%";

    final GroupGeneralData group = this.groupReadPlatformService.retrieveOne(groupId);

    final JLGCollectionSheetFaltDataMapper mapper = new JLGCollectionSheetFaltDataMapper();

    // entityType should be center if it's within a center
    final CalendarEntityType entityType =
        (group.isChildGroup()) ? CalendarEntityType.CENTERS : CalendarEntityType.GROUPS;

    final SqlParameterSource namedParameters =
        new MapSqlParameterSource()
            .addValue("dueDate", transactionDateStr)
            .addValue("groupId", group.getId())
            .addValue("officeHierarchy", officeHierarchy)
            .addValue("entityTypeId", entityType.getValue());

    final Collection<JLGCollectionSheetFlatData> collectionSheetFlatDatas =
        this.namedParameterjdbcTemplate.query(
            mapper.collectionSheetSchema(false), namedParameters, mapper);

    // loan data for collection sheet
    JLGCollectionSheetData collectionSheetData =
        buildJLGCollectionSheet(transactionDate, collectionSheetFlatDatas);

    // mandatory savings data for collection sheet
    Collection<JLGGroupData> groupsWithSavingsData =
        this.namedParameterjdbcTemplate.query(
            mandatorySavingsExtractor.collectionSheetSchema(false),
            namedParameters,
            mandatorySavingsExtractor);

    // merge savings data into loan data
    mergeSavingsGroupDataIntoCollectionsheetData(groupsWithSavingsData, collectionSheetData);

    collectionSheetData =
        JLGCollectionSheetData.withSavingsProducts(
            collectionSheetData, retrieveSavingsProducts(groupsWithSavingsData));

    return collectionSheetData;
  }
  @Transactional
  @Override
  public EntityIdentifier modifyLoanApplication(final Long loanId, final JsonCommand command) {

    context.authenticatedUser();

    LoanApplicationCommand loanApplicationCommand =
        this.fromApiJsonDeserializer.commandFromApiJson(command.json());
    loanApplicationCommand.validate();

    CalculateLoanScheduleQuery calculateLoanScheduleQuery =
        this.calculateLoanScheduleQueryFromApiJsonDeserializer.commandFromApiJson(command.json());
    calculateLoanScheduleQuery.validate();

    final Loan existingLoanApplication = retrieveLoanBy(loanId);

    final Map<String, Object> changes =
        existingLoanApplication.modifyLoanApplication(
            command, loanApplicationCommand.getCharges(), this.aprCalculator);

    final String clientIdParamName = "clientId";
    if (changes.containsKey(clientIdParamName)) {
      final Long clientId = command.longValueOfParameterNamed(clientIdParamName);
      final Client client = this.clientRepository.findOne(clientId);
      if (client == null || client.isDeleted()) {
        throw new ClientNotFoundException(clientId);
      }

      existingLoanApplication.updateClient(client);
    }

    final String productIdParamName = "productId";
    if (changes.containsKey(productIdParamName)) {
      final Long productId = command.longValueOfParameterNamed(productIdParamName);
      final LoanProduct loanProduct = this.loanProductRepository.findOne(productId);
      if (loanProduct == null) {
        throw new LoanProductNotFoundException(productId);
      }

      existingLoanApplication.updateLoanProduct(loanProduct);
    }

    final String fundIdParamName = "fundId";
    if (changes.containsKey(fundIdParamName)) {
      final Long fundId = command.longValueOfParameterNamed(fundIdParamName);
      final Fund fund = this.loanAssembler.findFundByIdIfProvided(fundId);

      existingLoanApplication.updateFund(fund);
    }

    final String strategyIdParamName = "transactionProcessingStrategyId";
    if (changes.containsKey(strategyIdParamName)) {
      final Long strategyId = command.longValueOfParameterNamed(strategyIdParamName);
      final LoanTransactionProcessingStrategy strategy =
          this.loanAssembler.findStrategyByIdIfProvided(strategyId);

      existingLoanApplication.updateTransactionProcessingStrategy(strategy);
    }

    final String chargesParamName = "charges";
    if (changes.containsKey(chargesParamName)) {
      final Set<LoanCharge> loanCharges =
          this.loanChargeAssembler.fromParsedJson(command.parsedJson());
      existingLoanApplication.updateLoanCharges(loanCharges);
    }

    if (changes.containsKey("recalculateLoanSchedule")) {
      changes.remove("recalculateLoanSchedule");

      final JsonElement parsedQuery = this.fromJsonHelper.parse(command.json());
      final JsonQuery query = JsonQuery.from(command.json(), parsedQuery, this.fromJsonHelper);

      final LoanScheduleData loanSchedule =
          this.calculationPlatformService.calculateLoanSchedule(query);
      existingLoanApplication.updateLoanSchedule(loanSchedule);
      existingLoanApplication.updateLoanScheduleDependentDerivedFields();
    }

    this.loanRepository.save(existingLoanApplication);

    final String submittedOnNote = command.stringValueOfParameterNamed("submittedOnNote");
    if (StringUtils.isNotBlank(submittedOnNote)) {
      Note note = Note.loanNote(existingLoanApplication, submittedOnNote);
      this.noteRepository.save(note);
    }

    return EntityIdentifier.resourceResult(loanId, command.commandId(), changes);
  }