@Transactional
  @Override
  public CommandProcessingResult activate(final Long savingsId, final JsonCommand command) {

    this.context.authenticatedUser();

    this.savingsAccountTransactionDataValidator.validateActivation(command);

    final SavingsAccount account =
        this.savingAccountRepository.findOneWithNotFoundDetection(savingsId);

    final Locale locale = command.extractLocale();
    final DateTimeFormatter fmt =
        DateTimeFormat.forPattern(command.dateFormat()).withLocale(locale);
    final LocalDate activationDate = command.localDateValueOfParameterNamed("activationDate");
    final List<Long> existingTransactionIds = new ArrayList<Long>();
    final List<Long> existingReversedTransactionIds = new ArrayList<Long>();

    account.activate(
        fmt, activationDate, existingReversedTransactionIds, existingReversedTransactionIds);

    this.savingAccountRepository.save(account);

    postJournalEntries(account, existingTransactionIds, existingReversedTransactionIds);

    return new CommandProcessingResultBuilder() //
        .withEntityId(savingsId) //
        .withOfficeId(account.officeId()) //
        .withClientId(account.clientId()) //
        .withGroupId(account.groupId()) //
        .withSavingsId(savingsId) //
        .build();
  }
  @Transactional
  @Override
  public CommandProcessingResult createOffice(final JsonCommand command) {

    try {
      final AppUser currentUser = context.authenticatedUser();

      this.fromApiJsonDeserializer.validateForCreate(command.json());

      Long parentId = null;
      if (command.parameterExists("parentId")) {
        parentId = command.longValueOfParameterNamed("parentId");
      }

      final Office parent = validateUserPriviledgeOnOfficeAndRetrieve(currentUser, parentId);
      final Office office = Office.fromJson(parent, command);

      // pre save to generate id for use in office hierarchy
      this.officeRepository.save(office);

      office.generateHierarchy();

      this.officeRepository.save(office);

      return new CommandProcessingResultBuilder() //
          .withCommandId(command.commandId()) //
          .withEntityId(office.getId()) //
          .withOfficeId(office.getId()) //
          .build();
    } catch (DataIntegrityViolationException dve) {
      handleOfficeDataIntegrityIssues(command, dve);
      return CommandProcessingResult.empty();
    }
  }
  @Transactional
  @Override
  public CommandProcessingResult createProspect(JsonCommand command) {

    try {
      context.authenticatedUser();
      this.clientProspectCommandFromApiJsonDeserializer.validateForCreate(command.json());

      final ClientProspect entity = ClientProspect.fromJson(fromApiJsonHelper, command);
      this.clientProspectJpaRepository.save(entity);

      return new CommandProcessingResultBuilder()
          .withCommandId(command.commandId())
          .withEntityId(entity.getId())
          .build();

    } catch (DataIntegrityViolationException dve) {
      handleDataIntegrityIssues(command, dve);
      return new CommandProcessingResult(Long.valueOf(-1));
    } catch (ParseException pe) {
      throw new PlatformDataIntegrityException(
          "invalid.date.and.time.format",
          "invalid.date.and.time.format",
          "invalid.date.and.time.format");
    }
  }
  @Transactional
  @Override
  public CommandProcessingResult followUpProspect(
      final JsonCommand command, final Long prospectId) {
    try {
      context.authenticatedUser();
      this.clientProspectCommandFromApiJsonDeserializer.validateForUpdate(command.json());

      final ProspectDetail prospectDetail = ProspectDetail.fromJson(command, prospectId);
      prospectDetailJpaRepository.save(prospectDetail);

      return new CommandProcessingResultBuilder()
          .withCommandId(command.commandId())
          .withEntityId(prospectDetail.getProspectId())
          .build();

    } catch (DataIntegrityViolationException dve) {
      handleDataIntegrityIssues(command, dve);
      return CommandProcessingResult.empty();
    } catch (ParseException e) {
      throw new PlatformDataIntegrityException(
          "invalid.date.and.time.format",
          "invalid.date.and.time.format",
          "invalid.date.and.time.format");
    }
  }
  @Override
  public CommandProcessingResult updateProspect(JsonCommand command) {

    try {
      context.authenticatedUser();
      this.clientProspectCommandFromApiJsonDeserializer.validateForCreate(command.json());

      final ClientProspect pros = retrieveCodeBy(command.entityId());
      final Map<String, Object> changes = pros.update(command);

      if (!changes.isEmpty()) {
        this.clientProspectJpaRepository.save(pros);
      }

      return new CommandProcessingResultBuilder() //
          .withCommandId(command.commandId()) //
          .withEntityId(pros.getId()) //
          .with(changes) //
          .build();

    } catch (DataIntegrityViolationException dve) {
      handleDataIntegrityIssues(command, dve);
    }
    return new CommandProcessingResultBuilder().withEntityId(-1L).build();
  }
  @Transactional
  @Override
  public CommandProcessingResult createEventOrder(JsonCommand command) {

    try {

      this.context.authenticatedUser();
      Long clientId = command.longValueOfParameterNamed("clientId");

      // Check Client Custome Validation
      this.eventValidationReadPlatformService.checkForCustomValidations(
          clientId, EventActionConstants.EVENT_EVENT_ORDER, command.json(), getUserId());
      EventOrder eventOrder = assembleEventOrderDetails(command, clientId);
      Configuration walletConfiguration =
          this.configurationRepository.findOneByName(
              ConfigurationConstants.CONFIG_PROPERTY_WALLET_ENABLE);
      boolean isBalanceAvailable =
          this.checkClientBalance(
              eventOrder.getBookedPrice(), clientId, walletConfiguration.isEnabled());
      if (!isBalanceAvailable) {
        throw new InsufficientAmountException("bookevent");
      }
      this.eventOrderRepository.save(eventOrder);

      List<OneTimeSaleData> oneTimeSaleDatas =
          eventOrderReadplatformServie.retrieveEventOrderData(eventOrder.getClientId());
      for (OneTimeSaleData oneTimeSaleData : oneTimeSaleDatas) {
        CommandProcessingResult commandProcessingResult =
            this.invoiceOneTimeSale.invoiceOneTimeSale(
                eventOrder.getClientId(), oneTimeSaleData, walletConfiguration.isEnabled());
        this.updateOneTimeSale(oneTimeSaleData);
        if (walletConfiguration.isEnabled()) {
          JournalVoucher journalVoucher =
              new JournalVoucher(
                  commandProcessingResult.resourceId(),
                  DateUtils.getDateOfTenant(),
                  "Event Sale",
                  null,
                  eventOrder.getBookedPrice(),
                  eventOrder.getClientId());
          this.journalvoucherRepository.save(journalVoucher);
        }
      }

      // Add New Action
      List<ActionDetaislData> actionDetaislDatas =
          this.actionDetailsReadPlatformService.retrieveActionDetails(
              EventActionConstants.EVENT_EVENT_ORDER);
      if (!actionDetaislDatas.isEmpty()) {
        this.actiondetailsWritePlatformService.AddNewActions(
            actionDetaislDatas, clientId, eventOrder.getId().toString(), null);
      }
      return new CommandProcessingResult(
          eventOrder.getEventOrderdetials().get(0).getMovieLink(), eventOrder.getClientId());

    } catch (DataIntegrityViolationException dve) {
      handleCodeDataIntegrityIssues(command, dve);
      return new CommandProcessingResult(Long.valueOf(-1));
    }
  }
  @Transactional
  @Override
  public EntityIdentifier disburseLoan(final Long loanId, final JsonCommand command) {

    final AppUser currentUser = context.authenticatedUser();

    final LoanStateTransitionCommand disburseLoan =
        this.loanStateTransitionCommandFromApiJsonDeserializer.commandFromApiJson(command.json());
    disburseLoan.validate();

    final Loan loan = retrieveLoanBy(loanId);

    final String noteText = command.stringValueOfParameterNamed("note");
    final LocalDate actualDisbursementDate = disburseLoan.getDisbursedOnDate();
    if (this.isBeforeToday(actualDisbursementDate) && currentUser.canNotDisburseLoanInPast()) {
      throw new NoAuthorizationException(
          "User has no authority to disburse loan with a date in the past.");
    }

    final ApplicationCurrency currency =
        this.applicationCurrencyRepository.findOneByCode(loan.getPrincpal().getCurrencyCode());

    final Map<String, Object> changes =
        loan.disburse(command, defaultLoanLifecycleStateMachine(), currency);
    this.loanRepository.save(loan);

    if (StringUtils.isNotBlank(noteText)) {
      Note note = Note.loanNote(loan, noteText);
      this.noteRepository.save(note);
    }

    return EntityIdentifier.resourceResult(loanId, command.commandId(), changes);
  }
  /*
   * Guaranteed to throw an exception no matter what the data integrity issue
   * is.
   */
  private void handleOfficeDataIntegrityIssues(
      final JsonCommand command, DataIntegrityViolationException dve) {

    Throwable realCause = dve.getMostSpecificCause();
    if (realCause.getMessage().contains("externalid_org")) {
      final String externalId = command.stringValueOfParameterNamed("externalId");
      throw new PlatformDataIntegrityException(
          "error.msg.office.duplicate.externalId",
          "Office with externalId `" + externalId + "` already exists",
          "externalId",
          externalId);
    } else if (realCause.getMessage().contains("name_org")) {
      final String name = command.stringValueOfParameterNamed("name");
      throw new PlatformDataIntegrityException(
          "error.msg.office.duplicate.name",
          "Office with name `" + name + "` already exists",
          "name",
          name);
    }

    logger.error(dve.getMessage(), dve);
    throw new PlatformDataIntegrityException(
        "error.msg.office.unknown.data.integrity.issue",
        "Unknown data integrity issue with resource.");
  }
  @Transactional
  @Override
  public CommandProcessingResult updateCharge(final Long chargeId, final JsonCommand command) {

    try {
      this.context.authenticatedUser();

      this.fromApiJsonDeserializer.validateForUpdate(command.json());

      final Charge chargeForUpdate = this.chargeRepository.findOne(chargeId);
      if (chargeForUpdate == null) {
        throw new ChargeNotFoundException(chargeId);
      }

      final Map<String, Object> changes = chargeForUpdate.update(command);

      if (!changes.isEmpty()) {
        this.chargeRepository.save(chargeForUpdate);
      }

      return new CommandProcessingResultBuilder()
          .withCommandId(command.commandId())
          .withEntityId(chargeId)
          .with(changes)
          .build();
    } catch (DataIntegrityViolationException dve) {
      handleDataIntegrityIssues(command, dve);
      return CommandProcessingResult.empty();
    }
  }
  @Transactional
  @Override
  public CommandProcessingResult rejectApplication(
      final Long savingsId, final JsonCommand command) {

    final AppUser currentUser = this.context.authenticatedUser();

    this.savingsAccountApplicationTransitionApiJsonValidator.validateRejection(command.json());

    final SavingsAccount savingsAccount = this.savingAccountAssembler.assembleFrom(savingsId);
    checkClientOrGroupActive(savingsAccount);

    final Map<String, Object> changes =
        savingsAccount.rejectApplication(currentUser, command, DateUtils.getLocalDateOfTenant());
    if (!changes.isEmpty()) {
      this.savingAccountRepository.save(savingsAccount);

      final String noteText = command.stringValueOfParameterNamed("note");
      if (StringUtils.isNotBlank(noteText)) {
        final Note note = Note.savingNote(savingsAccount, noteText);
        changes.put("note", noteText);
        this.noteRepository.save(note);
      }
    }

    return new CommandProcessingResultBuilder() //
        .withCommandId(command.commandId()) //
        .withEntityId(savingsId) //
        .withOfficeId(savingsAccount.officeId()) //
        .withClientId(savingsAccount.clientId()) //
        .withGroupId(savingsAccount.groupId()) //
        .withSavingsId(savingsId) //
        .with(changes) //
        .build();
  }
  @Transactional
  @Override
  public EntityIdentifier submitLoanApplication(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 newLoanApplication = loanAssembler.assembleFrom(command);

    this.loanRepository.save(newLoanApplication);

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

    return EntityIdentifier.resourceResult(newLoanApplication.getId(), command.commandId());
  }
  /*
   * Guaranteed to throw an exception no matter what the data integrity issue
   * is.
   */
  private void handleDataIntegrityIssues(final JsonCommand command, final DataAccessException dve) {

    final StringBuilder errorCodeBuilder =
        new StringBuilder("error.msg.").append(SavingsApiConstants.SAVINGS_ACCOUNT_RESOURCE_NAME);

    final Throwable realCause = dve.getMostSpecificCause();
    if (realCause.getMessage().contains("sa_account_no_UNIQUE")) {
      final String accountNo = command.stringValueOfParameterNamed("accountNo");
      errorCodeBuilder.append(".duplicate.accountNo");
      throw new PlatformDataIntegrityException(
          errorCodeBuilder.toString(),
          "Savings account with accountNo " + accountNo + " already exists",
          "accountNo",
          accountNo);

    } else if (realCause.getMessage().contains("sa_external_id_UNIQUE")) {

      final String externalId = command.stringValueOfParameterNamed("externalId");
      errorCodeBuilder.append(".duplicate.externalId");
      throw new PlatformDataIntegrityException(
          errorCodeBuilder.toString(),
          "Savings account with externalId " + externalId + " already exists",
          "externalId",
          externalId);
    }

    errorCodeBuilder.append(".unknown.data.integrity.issue");
    logger.error(dve.getMessage(), dve);
    throw new PlatformDataIntegrityException(
        errorCodeBuilder.toString(), "Unknown data integrity issue with savings account.");
  }
  @Transactional
  @Override
  public CommandProcessingResult submitApplication(final JsonCommand command) {
    try {
      this.savingsAccountDataValidator.validateForSubmit(command.json());
      final AppUser submittedBy = this.context.authenticatedUser();

      final SavingsAccount account = this.savingAccountAssembler.assembleFrom(command, submittedBy);
      this.savingAccountRepository.save(account);

      if (account.isAccountNumberRequiresAutoGeneration()) {
        final AccountNumberGenerator accountNoGenerator =
            this.accountIdentifierGeneratorFactory.determineSavingsAccountNoGenerator(
                account.getId());
        account.updateAccountNo(accountNoGenerator.generate());

        this.savingAccountRepository.save(account);
      }

      final Long savingsId = account.getId();
      return new CommandProcessingResultBuilder() //
          .withCommandId(command.commandId()) //
          .withEntityId(savingsId) //
          .withOfficeId(account.officeId()) //
          .withClientId(account.clientId()) //
          .withGroupId(account.groupId()) //
          .withSavingsId(savingsId) //
          .build();
    } catch (final DataAccessException dve) {
      handleDataIntegrityIssues(command, dve);
      return CommandProcessingResult.empty();
    }
  }
  @Transactional
  @Override
  public EntityIdentifier applicantWithdrawsFromLoanApplication(
      final Long loanId, final JsonCommand command) {

    final AppUser currentUser = context.authenticatedUser();

    final LoanStateTransitionCommand applicantWithdrawsFromLoanApplication =
        this.loanStateTransitionCommandFromApiJsonDeserializer.commandFromApiJson(command.json());
    applicantWithdrawsFromLoanApplication.validate();

    final Loan loan = retrieveLoanBy(loanId);

    final LocalDate eventDate = applicantWithdrawsFromLoanApplication.getWithdrawnOnDate();
    if (this.isBeforeToday(eventDate) && currentUser.canNotWithdrawByClientLoanInPast()) {
      throw new NoAuthorizationException(
          "User has no authority to mark loan as withdrawn by applicant with a date in the past.");
    }

    final Map<String, Object> changes =
        loan.loanApplicationWithdrawnByApplicant(command, defaultLoanLifecycleStateMachine());
    this.loanRepository.save(loan);

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

    return EntityIdentifier.resourceResult(loanId, command.commandId(), changes);
  }
  @Transactional
  @Override
  public CommandProcessingResult createHoliday(final JsonCommand command) {

    try {
      this.context.authenticatedUser();
      this.fromApiJsonDeserializer.validateForCreate(command.json());

      validateInputDates(command);

      final Set<Office> offices = getSelectedOffices(command);

      final Holiday holiday = Holiday.createNew(offices, command);

      this.holidayRepository.save(holiday);

      return new CommandProcessingResultBuilder()
          .withCommandId(command.commandId())
          .withEntityId(holiday.getId())
          .build();
    } catch (final DataIntegrityViolationException dve) {
      handleDataIntegrityIssues(command, dve);
      return CommandProcessingResult.empty();
    }
  }
 @Transactional
 @Override
 public CommandProcessingResult createEventPricing(JsonCommand command) {
   try {
     this.context.authenticatedUser();
     this.apiJsonDeserializer.validateForCreate(command.json());
     Long eventId = command.longValueOfParameterNamed("eventId");
     EventMaster eventMaster = this.eventMasterRepository.findOne(eventId);
     final EventPricing eventPricing = EventPricing.fromJson(command, eventMaster);
     List<EventPricingData> eventDetails =
         this.eventPricingReadPlatformService.retrieventPriceData(command.entityId());
     for (EventPricingData eventDetail : eventDetails) {
       if (eventPricing.getFormatType().equalsIgnoreCase(eventDetail.getFormatType())
           && eventPricing.getClientType() == eventDetail.getClientType()
           && eventPricing.getOptType().equalsIgnoreCase(eventDetail.getOptType())) {
         throw new DuplicatEventPrice(eventPricing.getFormatType());
       }
     }
     this.eventPricingRepository.save(eventPricing);
     return new CommandProcessingResultBuilder()
         .withCommandId(command.commandId())
         .withEntityId(eventPricing.getId())
         .build();
   } catch (DataIntegrityViolationException dve) {
     handleDataIntegrityIssues(command, dve);
     return new CommandProcessingResult(Long.valueOf(-1));
   }
 }
  @Transactional
  @Override
  public CommandProcessingResult updateGLClosure(
      final Long glClosureId, final JsonCommand command) {
    final GLClosureCommand closureCommand =
        this.fromApiJsonDeserializer.commandFromApiJson(command.json());
    closureCommand.validateForUpdate();

    // is the glClosure valid
    final GLClosure glClosure = this.glClosureRepository.findOne(glClosureId);
    if (glClosure == null) {
      throw new GLClosureNotFoundException(glClosureId);
    }

    final Map<String, Object> changesOnly = glClosure.update(command);

    if (!changesOnly.isEmpty()) {
      this.glClosureRepository.saveAndFlush(glClosure);
    }

    return new CommandProcessingResultBuilder()
        .withCommandId(command.commandId())
        .withOfficeId(glClosure.getOffice().getId())
        .withEntityId(glClosure.getId())
        .with(changesOnly)
        .build();
  }
Exemplo n.º 18
0
  public static Plan fromJson(JsonCommand command) {
    final String planCode = command.stringValueOfParameterNamed("planCode");
    final String planDescription = command.stringValueOfParameterNamed("planDescription");
    final LocalDate startDate = command.localDateValueOfParameterNamed("startDate");
    final LocalDate endDate = command.localDateValueOfParameterNamed("endDate");
    final Long status = command.longValueOfParameterNamed("status");
    final Long billRule = command.longValueOfParameterNamed("billRule");
    final String provisioingSystem = command.stringValueOfParameterNamed("provisioingSystem");
    boolean isPrepaid = command.booleanPrimitiveValueOfParameterNamed("isPrepaid");
    boolean allowTopup = command.booleanPrimitiveValueOfParameterNamed("allowTopup");
    boolean isHwReq = command.booleanPrimitiveValueOfParameterNamed("isHwReq");

    return new Plan(
        planCode,
        planDescription,
        startDate,
        endDate,
        billRule,
        status,
        null,
        provisioingSystem,
        isPrepaid,
        allowTopup,
        isHwReq);
  }
  private void handleDataIntegrityIssues(
      final JsonCommand command, final DataIntegrityViolationException dve) {

    Throwable realCause = dve.getMostSpecificCause();
    if (realCause.getMessage().contains("external_id")) {

      final String externalId = command.stringValueOfParameterNamed("externalId");
      throw new PlatformDataIntegrityException(
          "error.msg.client.duplicate.externalId",
          "Client with externalId `" + externalId + "` already exists",
          "externalId",
          externalId);
    } else if (realCause.getMessage().contains("account_no_UNIQUE")) {
      final String accountNo = command.stringValueOfParameterNamed("accountNo");
      throw new PlatformDataIntegrityException(
          "error.msg.client.duplicate.accountNo",
          "Client with accountNo `" + accountNo + "` already exists",
          "accountNo",
          accountNo);
    } else if (realCause.getMessage().contains("email_key")) {
      final String email = command.stringValueOfParameterNamed("email");
      throw new PlatformDataIntegrityException(
          "error.msg.client.duplicate.email",
          "Client with email `" + email + "` already exists",
          "email",
          email);
    }

    logAsErrorUnexpectedDataIntegrityException(dve);
    throw new PlatformDataIntegrityException(
        "error.msg.client.unknown.data.integrity.issue",
        "Unknown data integrity issue with resource.");
  }
Exemplo n.º 20
0
  public static RevenueMaster fromJson(final JsonCommand command) {

    final Long businessLine = command.longValueOfParameterNamed("businessLine");
    final Long mediaCategory = command.longValueOfParameterNamed("mediaCategory");
    final Long revenueShareType = command.longValueOfParameterNamed("revenueShareType");
    /*final Long clientId = command.longValueOfParameterNamed("clientId");*/
    return new RevenueMaster(businessLine, mediaCategory, revenueShareType, command.entityId());
  }
 private void validateInputDates(final JsonCommand command) {
   final LocalDate fromDate =
       command.localDateValueOfParameterNamed(HolidayApiConstants.fromDateParamName);
   final LocalDate toDate =
       command.localDateValueOfParameterNamed(HolidayApiConstants.toDateParamName);
   final LocalDate repaymentsRescheduledTo =
       command.localDateValueOfParameterNamed(
           HolidayApiConstants.repaymentsRescheduledToParamName);
   this.validateInputDates(fromDate, toDate, repaymentsRescheduledTo);
 }
  @Override
  public CommandProcessingResult createGameMediaAsset(JsonCommand command) {

    MediaAsset mediaAsset = null;
    try {
      this.context.authenticatedUser();
      fromApiJsonDeserializer.validateForCreateGame(command.json());
      mediaAsset = MediaAsset.fromGameMediaJsonForm(command);

      PartnerAccountData contentProvider =
          mediaSettlementReadPlatformService.retrieveContentProviderPartnerId(
              mediaAsset.getContentProvider());
      if (!command.stringValueOfParameterNamed("mediaCategory").equalsIgnoreCase("Games")) {
        throw new NotaContentProviderException(
            "This game category is not available", "this game category is not available");
      }
      if (contentProvider == null) {
        throw new NotaContentProviderException();
      } else if (contentProvider != null) {
        if (!contentProvider.getPartnerName().equalsIgnoreCase("Content Provider")) {
          throw new NotaContentProviderException();
        }
      }
      mediaAsset.setContentProvider(contentProvider.getId().toString());
      assetRepository.save(mediaAsset);

      /*final JsonArray gameData = command.arrayOfParameterNamed("gameMediaData").getAsJsonArray();
      for(int i=0; i<gameData.size();i++){
      	String currentData = gameData.get(i).toString();
      	final JsonElement element = fromApiJsonHelper.parse(currentData);

      	 final BigDecimal amount = fromApiJsonHelper.extractBigDecimalWithLocaleNamed("amount", element);
        final String category = fromApiJsonHelper.extractStringNamed("category", element);
        final String mediaContentProvider = fromApiJsonHelper.extractStringNamed("mediaContentProvider", element);
        final String mt = fromApiJsonHelper.extractStringNamed("mediaType", element);
        final Character mediaType = mt.equals("Flat")?'F':'P';
        final Long sequence = fromApiJsonHelper.extractLongNamed("sequence", element);
        final String source = fromApiJsonHelper.extractStringNamed("source", element);


        Settlement settlement = Settlement.fromJson(mediaAsset.getId(),amount,category,mediaContentProvider,mediaType,sequence,source);
        settlementJpaRepository.save(settlement);
      }*/

    } catch (EmptyResultDataAccessException e) {
      throw new PlatformDataIntegrityException(
          "not.a.valid.content.provider", "not.a.valid.content.provider", "ContentProvider");
    } catch (DataIntegrityViolationException dve) {
      handleCodeDataIntegrityIssues(command, dve);
      throw new DataIntegrityViolationException(dve.toString());
    } catch (Exception e) {
      throw new DataIntegrityViolationException(e.toString());
    }
    return new CommandProcessingResult(mediaAsset.getId());
  }
  @Transactional
  @Override
  @Caching(
      evict = {
        @CacheEvict(
            value = "offices",
            key =
                "T(org.mifosplatform.infrastructure.core.service.ThreadLocalContextUtil).getTenant().getTenantIdentifier().concat(#root.target.context.authenticatedUser().getOffice().getHierarchy()+'of')"),
        @CacheEvict(
            value = "officesForDropdown",
            key =
                "T(org.mifosplatform.infrastructure.core.service.ThreadLocalContextUtil).getTenant().getTenantIdentifier().concat(#root.target.context.authenticatedUser().getOffice().getHierarchy()+'ofd')"),
        @CacheEvict(
            value = "officesById",
            key =
                "T(org.mifosplatform.infrastructure.core.service.ThreadLocalContextUtil).getTenant().getTenantIdentifier().concat(#officeId)")
      })
  public CommandProcessingResult updateOffice(final Long officeId, final JsonCommand command) {

    try {
      final AppUser currentUser = context.authenticatedUser();

      this.fromApiJsonDeserializer.validateForUpdate(command.json());

      Long parentId = null;
      if (command.parameterExists("parentId")) {
        parentId = command.longValueOfParameterNamed("parentId");
      }

      final Office office = validateUserPriviledgeOnOfficeAndRetrieve(currentUser, officeId);

      final Map<String, Object> changes = office.update(command);

      if (changes.containsKey("parentId")) {
        final Office parent = validateUserPriviledgeOnOfficeAndRetrieve(currentUser, parentId);
        office.update(parent);
      }

      if (!changes.isEmpty()) {
        this.officeRepository.saveAndFlush(office);
      }

      return new CommandProcessingResultBuilder() //
          .withCommandId(command.commandId()) //
          .withEntityId(office.getId()) //
          .withOfficeId(office.getId()) //
          .with(changes) //
          .build();
    } catch (DataIntegrityViolationException dve) {
      handleOfficeDataIntegrityIssues(command, dve);
      return CommandProcessingResult.empty();
    }
  }
  @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();
  }
Exemplo n.º 25
0
  public static EventOrder fromJson(
      JsonCommand command,
      EventMaster eventMaster,
      MediaDeviceData details,
      final Long cType,
      final Long eventId) {

    final Long clientId = command.longValueOfParameterNamed("cId"); // details.getClientId();
    final LocalDate eventBookedDate = command.localDateValueOfParameterNamed("eventBookedDate");
    Long clientType =
        command.longValueOfParameterNamed("categoryType"); // details.getClientTypeId();
    if (clientType == null) {
      clientType = cType;
    }
    final String optType = command.stringValueOfParameterNamed("optType");
    final String formatType = command.stringValueOfParameterNamed("formatType");
    final Date eventValidtill = eventMaster.getEventValidity();

    if (eventMaster.getEventPricings() == null || eventMaster.getEventPricings().isEmpty()) {
      throw new NoEventPriceFoundException();
    }

    final Long eventPriceId = eventMaster.getEventPricings().get(0).getId();
    Double bookedPrice = 0D;
    List<EventPricing> eventPricings = eventMaster.getEventPricings();

    for (EventPricing eventPricing : eventPricings) {
      if (eventPricing.getClientType().longValue() == clientType.longValue()
          && eventPricing.getFormatType().equalsIgnoreCase(formatType)
          && eventPricing.getOptType().equalsIgnoreCase(optType)) {
        bookedPrice = eventPricing.getPrice();
      }
    }
    if (bookedPrice == null) {

      throw new NoPricesFoundException();
    }

    final int status = eventMaster.getStatus();
    final String chargeCode = eventMaster.getChargeCode();

    return new EventOrder(
        eventId,
        eventBookedDate,
        eventValidtill,
        eventPriceId,
        bookedPrice,
        clientId,
        status,
        chargeCode);
  }
  private EventOrder assembleEventOrderDetails(JsonCommand command, Long clientId) {

    Configuration configuration =
        this.configurationRepository.findOneByName(
            ConfigurationConstants.CONFIR_PROPERTY_REGISTRATION_DEVICE);
    this.apiJsonDeserializer.validateForCreate(command.json(), configuration.isEnabled());
    final Long eventId = command.longValueOfParameterNamed("eventId");
    final String deviceId = command.stringValueOfParameterNamed("deviceId");
    Long clientType = Long.valueOf(0);

    if (configuration != null && configuration.isEnabled()) {
      MediaDeviceData deviceData = this.deviceReadPlatformService.retrieveDeviceDetails(deviceId);
      if (deviceData == null) {
        throw new NoMediaDeviceFoundException();
      }
      clientId = deviceData.getClientId();
      clientType = deviceData.getClientTypeId();

    } else if (clientId != null) {
      Client client = this.clientRepository.findOne(clientId);
      clientType = client.getCategoryType();
    }

    final String formatType = command.stringValueOfParameterNamed("formatType");
    final String optType = command.stringValueOfParameterNamed("optType");
    EventMaster eventMaster = this.eventMasterRepository.findOne(eventId);
    if (eventMaster == null) {
      throw new NoEventMasterFoundException();
    }
    List<EventDetails> eventDetails = eventMaster.getEventDetails();
    EventOrder eventOrder = EventOrder.fromJson(command, eventMaster, clientType);
    for (EventDetails detail : eventDetails) {
      EventDetails eventDetail = this.eventDetailsRepository.findOne(detail.getId());
      MediaAsset mediaAsset = this.mediaAssetRepository.findOne(eventDetail.getMediaId());
      List<MediaassetLocation> mediaassetLocations = mediaAsset.getMediaassetLocations();
      String movieLink = "";
      for (MediaassetLocation location : mediaassetLocations) {
        if (location.getFormatType().equalsIgnoreCase(formatType)) {
          movieLink = location.getLocation();
        }
      }
      EventOrderdetials eventOrderdetials =
          new EventOrderdetials(eventDetail, movieLink, formatType, optType);
      eventOrder.addEventOrderDetails(eventOrderdetials);
      if (movieLink.isEmpty()) {
        throw new NoMoviesFoundException();
      }
    }
    return eventOrder;
  }
  @Transactional
  @Override
  public CommandProcessingResult deleteProspect(JsonCommand command) {

    context.authenticatedUser();
    final ClientProspect clientProspect = retrieveCodeBy(command.entityId());
    clientProspect.setIsDeleted('Y');
    clientProspect.setStatus("Canceled");
    clientProspect.setStatusRemark(command.stringValueOfParameterNamed("statusRemark"));

    this.clientProspectJpaRepository.saveAndFlush(clientProspect);

    return new CommandProcessingResultBuilder().withEntityId(clientProspect.getId()).build();
  }
  @Override
  public CommandProcessingResult updateEventOrderPrice(JsonCommand command) {

    Long id =
        eventOrderReadplatformServie.getCurrentRow(
            command.stringValueOfParameterNamed("formatType"),
            command.stringValueOfParameterNamed("optType"),
            command.longValueOfParameterNamed("clientId"));
    EventPrice eventPricing = eventPricingRepository.findOne(id);
    eventPricing.setPrice(Double.valueOf(command.stringValueOfParameterNamed("price")));
    eventPricingRepository.save(eventPricing);
    return new CommandProcessingResultBuilder()
        .withResourceIdAsString(eventPricing.getPrice().toString())
        .build();
  }
  /**
   * @param command
   * @param dve
   */
  private void handleGLClosureIntegrityIssues(
      final JsonCommand command, final DataIntegrityViolationException dve) {
    final Throwable realCause = dve.getMostSpecificCause();
    if (realCause.getMessage().contains("office_id_closing_date")) {
      throw new GLClosureDuplicateException(
          command.longValueOfParameterNamed(GLClosureJsonInputParams.OFFICE_ID.getValue()),
          new LocalDate(
              command.DateValueOfParameterNamed(GLClosureJsonInputParams.CLOSING_DATE.getValue())));
    }

    logger.error(dve.getMessage(), dve);
    throw new PlatformDataIntegrityException(
        "error.msg.glClosure.unknown.data.integrity.issue",
        "Unknown data integrity issue with resource GL Closure: " + realCause.getMessage());
  }
  @Transactional
  @Override
  public CommandProcessingResult deposit(final Long savingsId, final JsonCommand command) {

    this.context.authenticatedUser();

    this.savingsAccountTransactionDataValidator.validate(command);

    final SavingsAccount account =
        this.savingAccountRepository.findOneWithNotFoundDetection(savingsId);

    final Locale locale = command.extractLocale();
    final DateTimeFormatter fmt =
        DateTimeFormat.forPattern(command.dateFormat()).withLocale(locale);

    final LocalDate transactionDate = command.localDateValueOfParameterNamed("transactionDate");
    final BigDecimal transactionAmount =
        command.bigDecimalValueOfParameterNamed("transactionAmount");

    final List<Long> existingTransactionIds = new ArrayList<Long>();
    final List<Long> existingReversedTransactionIds = new ArrayList<Long>();
    final Map<String, Object> changes = new LinkedHashMap<String, Object>();
    PaymentDetail paymentDetail =
        paymentDetailWritePlatformService.createAndPersistPaymentDetail(command, changes);

    final SavingsAccountTransaction deposit =
        account.deposit(
            fmt,
            transactionDate,
            transactionAmount,
            existingTransactionIds,
            existingReversedTransactionIds,
            paymentDetail);
    final Long transactionId = saveTransactionToGenerateTransactionId(deposit);

    this.savingAccountRepository.save(account);

    postJournalEntries(account, existingTransactionIds, existingReversedTransactionIds);

    return new CommandProcessingResultBuilder() //
        .withEntityId(transactionId) //
        .withOfficeId(account.officeId()) //
        .withClientId(account.clientId()) //
        .withGroupId(account.groupId()) //
        .withSavingsId(savingsId) //
        .with(changes) //
        .build();
  }