public Map<String, Object> update(final JsonCommand command) { final Map<String, Object> actualChanges = new LinkedHashMap<String, Object>(9); if (command.isChangeInIntegerParameterNamed( GroupingTypesApiConstants.statusParamName, this.status)) { final Integer newValue = command.integerValueOfParameterNamed(GroupingTypesApiConstants.statusParamName); actualChanges.put( GroupingTypesApiConstants.statusParamName, GroupingTypeEnumerations.status(newValue)); this.status = GroupingTypeStatus.fromInt(newValue).getValue(); } if (command.isChangeInStringParameterNamed( GroupingTypesApiConstants.externalIdParamName, this.externalId)) { final String newValue = command.stringValueOfParameterNamed(GroupingTypesApiConstants.externalIdParamName); actualChanges.put(GroupingTypesApiConstants.externalIdParamName, newValue); this.externalId = StringUtils.defaultIfEmpty(newValue, null); } if (command.isChangeInLongParameterNamed( GroupingTypesApiConstants.officeIdParamName, this.office.getId())) { final Long newValue = command.longValueOfParameterNamed(GroupingTypesApiConstants.officeIdParamName); actualChanges.put(GroupingTypesApiConstants.officeIdParamName, newValue); } if (command.isChangeInLongParameterNamed( GroupingTypesApiConstants.staffIdParamName, staffId())) { final Long newValue = command.longValueOfParameterNamed(GroupingTypesApiConstants.staffIdParamName); actualChanges.put(GroupingTypesApiConstants.staffIdParamName, newValue); } if (command.isChangeInStringParameterNamed( GroupingTypesApiConstants.nameParamName, this.name)) { final String newValue = command.stringValueOfParameterNamed(GroupingTypesApiConstants.nameParamName); actualChanges.put(GroupingTypesApiConstants.nameParamName, newValue); this.name = StringUtils.defaultIfEmpty(newValue, null); } final String dateFormatAsInput = command.dateFormat(); final String localeAsInput = command.locale(); if (command.isChangeInLocalDateParameterNamed( GroupingTypesApiConstants.activationDateParamName, getActivationLocalDate())) { final String valueAsInput = command.stringValueOfParameterNamed(GroupingTypesApiConstants.activationDateParamName); actualChanges.put(GroupingTypesApiConstants.activationDateParamName, valueAsInput); actualChanges.put(GroupingTypesApiConstants.dateFormatParamName, dateFormatAsInput); actualChanges.put(GroupingTypesApiConstants.localeParamName, localeAsInput); final LocalDate newValue = command.localDateValueOfParameterNamed(GroupingTypesApiConstants.activationDateParamName); this.activationDate = newValue.toDate(); } return actualChanges; }
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); }
public Map<String, Object> update(JsonCommand command) { final Map<String, Object> actualChanges = new LinkedHashMap<String, Object>(1); final String businessLine = "businessLine"; final String mediaCategory = "mediaCategory"; final String revenueShareType = "revenueShareType"; if (command.isChangeInLongParameterNamed(businessLine, this.businessLine)) { final Long newValue = command.longValueOfParameterNamed(businessLine); actualChanges.put(businessLine, newValue); this.businessLine = newValue; } if (command.isChangeInLongParameterNamed(mediaCategory, this.mediaCategory)) { final Long newValue = command.longValueOfParameterNamed(mediaCategory); actualChanges.put(mediaCategory, newValue); this.mediaCategory = newValue; } if (command.isChangeInLongParameterNamed(revenueShareType, this.revenueShareType)) { final Long newValue = command.longValueOfParameterNamed(revenueShareType); actualChanges.put(revenueShareType, newValue); this.revenueShareType = newValue; } return actualChanges; }
public Map<String, Object> update(JsonCommand command) { final Map<String, Object> actualChanges = new LinkedHashMap<String, Object>(1); final String firstnameParamName = "planCode"; if (command.isChangeInStringParameterNamed(firstnameParamName, this.planCode)) { final String newValue = command.stringValueOfParameterNamed(firstnameParamName); actualChanges.put(firstnameParamName, newValue); this.planCode = StringUtils.defaultIfEmpty(newValue, null); } final String descriptionParamName = "planDescription"; if (command.isChangeInStringParameterNamed(descriptionParamName, this.description)) { final String newValue = command.stringValueOfParameterNamed(descriptionParamName); actualChanges.put(firstnameParamName, newValue); this.description = StringUtils.defaultIfEmpty(newValue, null); } final String provisioingSystem = "provisioingSystem"; if (command.isChangeInStringParameterNamed(provisioingSystem, this.provisionSystem)) { final String newValue = command.stringValueOfParameterNamed(provisioingSystem); actualChanges.put(provisioingSystem, newValue); this.provisionSystem = StringUtils.defaultIfEmpty(newValue, null); } final String startDateParamName = "startDate"; if (command.isChangeInLocalDateParameterNamed( startDateParamName, new LocalDate(this.startDate))) { final LocalDate newValue = command.localDateValueOfParameterNamed(startDateParamName); actualChanges.put(startDateParamName, newValue); this.startDate = newValue.toDate(); } final String endDateParamName = "endDate"; if (command.isChangeInLocalDateParameterNamed(endDateParamName, new LocalDate(this.endDate))) { final LocalDate newValue = command.localDateValueOfParameterNamed(endDateParamName); actualChanges.put(endDateParamName, newValue); if (newValue != null) this.endDate = newValue.toDate(); } final String billRuleParamName = "billRule"; if (command.isChangeInLongParameterNamed(billRuleParamName, this.billRule)) { final Long newValue = command.longValueOfParameterNamed(billRuleParamName); actualChanges.put(billRuleParamName, newValue); this.billRule = newValue; } final String statusParamName = "status"; if (command.isChangeInLongParameterNamed(statusParamName, this.status)) { final Long newValue = command.longValueOfParameterNamed(statusParamName); actualChanges.put(statusParamName, newValue); this.status = newValue; } final boolean isPrepaid = command.booleanPrimitiveValueOfParameterNamed("isPrepaid"); final char isPrepaidParamName = isPrepaid ? 'Y' : 'N'; this.isPrepaid = isPrepaidParamName; final boolean allowTopupParamName = command.booleanPrimitiveValueOfParameterNamed("allowTopup"); this.allowTopup = allowTopupParamName ? 'Y' : 'N'; final boolean isHwReqParamName = command.booleanPrimitiveValueOfParameterNamed("isHwReq"); this.isHwReq = isHwReqParamName ? 'Y' : 'N'; return actualChanges; }
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()); }
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); }
@Transactional @Override public CommandProcessingResult officeTransaction(final JsonCommand command) { context.authenticatedUser(); this.moneyTransferCommandFromApiJsonDeserializer.validateOfficeTransfer(command.json()); Long officeId = null; Office fromOffice = null; final Long fromOfficeId = command.longValueOfParameterNamed("fromOfficeId"); if (fromOfficeId != null) { fromOffice = this.officeRepository.findOne(fromOfficeId); officeId = fromOffice.getId(); } Office toOffice = null; final Long toOfficeId = command.longValueOfParameterNamed("toOfficeId"); if (toOfficeId != null) { toOffice = this.officeRepository.findOne(toOfficeId); officeId = toOffice.getId(); } if (fromOffice == null && toOffice == null) { throw new OfficeNotFoundException(toOfficeId); } final String currencyCode = command.stringValueOfParameterNamed("currencyCode"); final ApplicationCurrency appCurrency = this.applicationCurrencyRepository.findOneByCode(currencyCode); if (appCurrency == null) { throw new CurrencyNotFoundException(currencyCode); } final MonetaryCurrency currency = new MonetaryCurrency(appCurrency.getCode(), appCurrency.getDecimalPlaces()); final Money amount = Money.of(currency, command.bigDecimalValueOfParameterNamed("transactionAmount")); final OfficeTransaction entity = OfficeTransaction.fromJson(fromOffice, toOffice, amount, command); this.officeTransactionRepository.save(entity); return new CommandProcessingResultBuilder() // .withCommandId(command.commandId()) // .withEntityId(entity.getId()) // .withOfficeId(officeId) // .build(); }
@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 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 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 @CacheEvict(value = "hooks", allEntries = true) public CommandProcessingResult updateHook(final Long hookId, final JsonCommand command) { try { this.context.authenticatedUser(); this.fromApiJsonDeserializer.validateForUpdate(command.json()); final Hook hook = retrieveHookBy(hookId); final HookTemplate template = hook.getHookTemplate(); final Map<String, Object> changes = hook.update(command); if (!changes.isEmpty()) { if (changes.containsKey(templateIdParamName)) { final Long ugdTemplateId = command.longValueOfParameterNamed(templateIdParamName); final Template ugdTemplate = this.ugdTemplateRepository.findOne(ugdTemplateId); if (ugdTemplate == null) { changes.remove(templateIdParamName); throw new TemplateNotFoundException(ugdTemplateId); } hook.updateUgdTemplate(ugdTemplate); } if (changes.containsKey(eventsParamName)) { final Set<HookResource> events = assembleSetOfEvents(command.arrayOfParameterNamed(eventsParamName)); final boolean updated = hook.updateEvents(events); if (!updated) { changes.remove(eventsParamName); } } if (changes.containsKey(configParamName)) { final String configJson = command.jsonFragment(configParamName); final Set<HookConfiguration> config = assembleConfig(command.mapValueOfParameterNamed(configJson), template); final boolean updated = hook.updateConfig(config); if (!updated) { changes.remove(configParamName); } } this.hookRepository.saveAndFlush(hook); } return new CommandProcessingResultBuilder() // .withCommandId(command.commandId()) // .withEntityId(hookId) // .with(changes) // .build(); } catch (final DataIntegrityViolationException dve) { handleHookDataIntegrityIssues(command, dve); return null; } }
@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(); } }
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 @CacheEvict(value = "usersByUsername", allEntries = true) public CommandProcessingResult createUser(final JsonCommand command) { try { this.context.authenticatedUser(); this.fromApiJsonDeserializer.validateForCreate(command.json()); final String officeIdParamName = "officeId"; final Long officeId = command.longValueOfParameterNamed(officeIdParamName); final Office userOffice = this.officeRepository.findOne(officeId); if (userOffice == null) { throw new OfficeNotFoundException(officeId); } final String[] roles = command.arrayValueOfParameterNamed("roles"); final Set<Role> allRoles = assembleSetOfRoles(roles); final AppUser appUser = AppUser.fromJson(userOffice, allRoles, command); final Boolean sendPasswordToEmail = command.booleanObjectValueOfParameterNamed("sendPasswordToEmail"); this.userDomainService.create(appUser, sendPasswordToEmail); return new CommandProcessingResultBuilder() // .withCommandId(command.commandId()) // .withEntityId(appUser.getId()) // .withOfficeId(userOffice.getId()) // .build(); } catch (final DataIntegrityViolationException dve) { handleDataIntegrityIssues(command, dve); return CommandProcessingResult.empty(); } catch (final PlatformEmailSendException e) { final List<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>(); final String email = command.stringValueOfParameterNamed("email"); final ApiParameterError error = ApiParameterError.parameterError( "error.msg.user.email.invalid", "The parameter email is invalid.", "email", email); dataValidationErrors.add(error); throw new PlatformApiDataValidationException( "validation.msg.validation.errors.exist", "Validation errors exist.", dataValidationErrors); } }
/** * @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()); }
@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(); }
@Transactional @Override public CommandProcessingResult createGLClosure(final JsonCommand command) { try { final GLClosureCommand closureCommand = this.fromApiJsonDeserializer.commandFromApiJson(command.json()); closureCommand.validateForCreate(); // check office is valid final Long officeId = command.longValueOfParameterNamed(GLClosureJsonInputParams.OFFICE_ID.getValue()); final Office office = this.officeRepository.findOne(officeId); if (office == null) { throw new OfficeNotFoundException(officeId); } // TODO: Get Tenant specific date // ensure closure date is not in the future final Date todaysDate = DateUtils.getDateOfTenant(); final Date closureDate = command.DateValueOfParameterNamed(GLClosureJsonInputParams.CLOSING_DATE.getValue()); if (closureDate.after(todaysDate)) { throw new GLClosureInvalidException(GL_CLOSURE_INVALID_REASON.FUTURE_DATE, closureDate); } // shouldn't be before an existing accounting closure final GLClosure latestGLClosure = this.glClosureRepository.getLatestGLClosureByBranch(officeId); if (latestGLClosure != null) { if (latestGLClosure.getClosingDate().after(closureDate)) { throw new GLClosureInvalidException( GL_CLOSURE_INVALID_REASON.ACCOUNTING_CLOSED, latestGLClosure.getClosingDate()); } } final GLClosure glClosure = GLClosure.fromJson(office, command); this.glClosureRepository.saveAndFlush(glClosure); return new CommandProcessingResultBuilder() .withCommandId(command.commandId()) .withOfficeId(officeId) .withEntityId(glClosure.getId()) .build(); } catch (final DataIntegrityViolationException dve) { handleGLClosureIntegrityIssues(command, dve); return CommandProcessingResult.empty(); } }
@Transactional @Override @CacheEvict(value = "hooks", allEntries = true) public CommandProcessingResult createHook(final JsonCommand command) { try { this.context.authenticatedUser(); this.fromApiJsonDeserializer.validateForCreate(command.json()); final HookTemplate template = retrieveHookTemplateBy(command.stringValueOfParameterNamed(nameParamName)); final String configJson = command.jsonFragment(configParamName); final Set<HookConfiguration> config = assembleConfig(command.mapValueOfParameterNamed(configJson), template); final JsonArray events = command.arrayOfParameterNamed(eventsParamName); final Set<HookResource> allEvents = assembleSetOfEvents(events); Template ugdTemplate = null; if (command.hasParameter(templateIdParamName)) { final Long ugdTemplateId = command.longValueOfParameterNamed(templateIdParamName); ugdTemplate = this.ugdTemplateRepository.findOne(ugdTemplateId); if (ugdTemplate == null) { throw new TemplateNotFoundException(ugdTemplateId); } } final Hook hook = Hook.fromJson(command, template, config, allEvents, ugdTemplate); validateHookRules(template, config, allEvents); this.hookRepository.save(hook); return new CommandProcessingResultBuilder() .withCommandId(command.commandId()) .withEntityId(hook.getId()) .build(); } catch (final DataIntegrityViolationException dve) { handleHookDataIntegrityIssues(command, dve); return CommandProcessingResult.empty(); } }
@Transactional @Override 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(); } }
@Transactional @Override public CommandProcessingResult create(final JsonCommand command) { this.accountTransfersDataValidator.validate(command); final LocalDate transactionDate = command.localDateValueOfParameterNamed(transferDateParamName); final BigDecimal transactionAmount = command.bigDecimalValueOfParameterNamed(transferAmountParamName); final Locale locale = command.extractLocale(); final DateTimeFormatter fmt = DateTimeFormat.forPattern(command.dateFormat()).withLocale(locale); final Integer fromAccountTypeId = command.integerValueSansLocaleOfParameterNamed(fromAccountTypeParamName); final PortfolioAccountType fromAccountType = PortfolioAccountType.fromInt(fromAccountTypeId); final Integer toAccountTypeId = command.integerValueSansLocaleOfParameterNamed(toAccountTypeParamName); final PortfolioAccountType toAccountType = PortfolioAccountType.fromInt(toAccountTypeId); final PaymentDetail paymentDetail = null; Long fromSavingsAccountId = null; Long transferTransactionId = null; if (isSavingsToSavingsAccountTransfer(fromAccountType, toAccountType)) { fromSavingsAccountId = command.longValueOfParameterNamed(fromAccountIdParamName); final SavingsAccount fromSavingsAccount = this.savingsAccountAssembler.assembleFrom(fromSavingsAccountId); final SavingsAccountTransaction withdrawal = this.savingsAccountDomainService.handleWithdrawal( fromSavingsAccount, fmt, transactionDate, transactionAmount, paymentDetail, fromSavingsAccount.isWithdrawalFeeApplicableForTransfer()); final Long toSavingsId = command.longValueOfParameterNamed(toAccountIdParamName); final SavingsAccount toSavingsAccount = this.savingsAccountAssembler.assembleFrom(toSavingsId); final SavingsAccountTransaction deposit = this.savingsAccountDomainService.handleDeposit( toSavingsAccount, fmt, transactionDate, transactionAmount, paymentDetail); final AccountTransfer transferTransaction = this.accountTransferAssembler.assembleSavingsToSavingsTransfer( command, withdrawal, deposit); this.accountTransferRepository.saveAndFlush(transferTransaction); transferTransactionId = transferTransaction.getId(); } else if (isSavingsToLoanAccountTransfer(fromAccountType, toAccountType)) { // fromSavingsAccountId = command.longValueOfParameterNamed(fromAccountIdParamName); final SavingsAccount fromSavingsAccount = this.savingsAccountAssembler.assembleFrom(fromSavingsAccountId); final SavingsAccountTransaction withdrawal = this.savingsAccountDomainService.handleWithdrawal( fromSavingsAccount, fmt, transactionDate, transactionAmount, paymentDetail, fromSavingsAccount.isWithdrawalFeeApplicableForTransfer()); final Long toLoanAccountId = command.longValueOfParameterNamed(toAccountIdParamName); final Loan toLoanAccount = this.loanAccountAssembler.assembleFrom(toLoanAccountId); final LoanTransaction loanRepaymentTransaction = this.loanAccountDomainService.makeRepayment( toLoanAccount, new CommandProcessingResultBuilder(), transactionDate, transactionAmount, paymentDetail, null, null); final AccountTransfer transferTransaction = this.accountTransferAssembler.assembleSavingsToLoanTransfer( command, fromSavingsAccount, toLoanAccount, withdrawal, loanRepaymentTransaction); this.accountTransferRepository.saveAndFlush(transferTransaction); transferTransactionId = transferTransaction.getId(); } else if (isLoanToSavingsAccountTransfer(fromAccountType, toAccountType)) { // FIXME - kw - ADD overpaid loan to savings account transfer // support. // final Long fromLoanAccountId = command.longValueOfParameterNamed(fromAccountIdParamName); final Loan fromLoanAccount = this.loanAccountAssembler.assembleFrom(fromLoanAccountId); final LoanTransaction loanRefundTransaction = this.loanAccountDomainService.makeRefund( fromLoanAccountId, new CommandProcessingResultBuilder(), transactionDate, transactionAmount, paymentDetail, null, null); final Long toSavingsAccountId = command.longValueOfParameterNamed(toAccountIdParamName); final SavingsAccount toSavingsAccount = this.savingsAccountAssembler.assembleFrom(toSavingsAccountId); final SavingsAccountTransaction deposit = this.savingsAccountDomainService.handleDeposit( toSavingsAccount, fmt, transactionDate, transactionAmount, paymentDetail); final AccountTransfer transferTransaction = this.accountTransferAssembler.assembleLoanToSavingsTransfer( command, fromLoanAccount, toSavingsAccount, deposit, loanRefundTransaction); this.accountTransferRepository.saveAndFlush(transferTransaction); transferTransactionId = transferTransaction.getId(); } else { } final CommandProcessingResultBuilder builder = new CommandProcessingResultBuilder().withEntityId(transferTransactionId); if (fromAccountType.isSavingsAccount()) { builder.withSavingsId(fromSavingsAccountId); } return builder.build(); }
public Map<String, Object> update( final JsonCommand command, final PlatformPasswordEncoder platformPasswordEncoder) { final Map<String, Object> actualChanges = new LinkedHashMap<String, Object>(7); // unencoded password provided final String passwordParamName = "password"; final String passwordEncodedParamName = "passwordEncoded"; if (command.hasParameter(passwordParamName)) { if (command.isChangeInPasswordParameterNamed( passwordParamName, this.password, platformPasswordEncoder, this.getId())) { final String passwordEncodedValue = command.passwordValueOfParameterNamed( passwordParamName, platformPasswordEncoder, this.getId()); actualChanges.put(passwordEncodedParamName, passwordEncodedValue); updatePassword(passwordEncodedValue); } } if (command.hasParameter(passwordEncodedParamName)) { if (command.isChangeInStringParameterNamed(passwordEncodedParamName, this.password)) { final String newValue = command.stringValueOfParameterNamed(passwordEncodedParamName); actualChanges.put(passwordEncodedParamName, newValue); updatePassword(newValue); } } final String officeIdParamName = "officeId"; if (command.isChangeInLongParameterNamed(officeIdParamName, this.office.getId())) { final Long newValue = command.longValueOfParameterNamed(officeIdParamName); actualChanges.put(officeIdParamName, newValue); } final String rolesParamName = "roles"; if (command.isChangeInArrayParameterNamed(rolesParamName, getRolesAsIdStringArray())) { final String[] newValue = command.arrayValueOfParameterNamed(rolesParamName); actualChanges.put(rolesParamName, newValue); } final String usernameParamName = "username"; if (command.isChangeInStringParameterNamed(usernameParamName, this.username)) { final String newValue = command.stringValueOfParameterNamed(usernameParamName); actualChanges.put(usernameParamName, newValue); this.username = newValue; } final String firstnameParamName = "firstname"; if (command.isChangeInStringParameterNamed(firstnameParamName, this.firstname)) { final String newValue = command.stringValueOfParameterNamed(firstnameParamName); actualChanges.put(firstnameParamName, newValue); this.firstname = newValue; } final String lastnameParamName = "lastname"; if (command.isChangeInStringParameterNamed(lastnameParamName, this.lastname)) { final String newValue = command.stringValueOfParameterNamed(lastnameParamName); actualChanges.put(lastnameParamName, newValue); this.lastname = newValue; } final String emailParamName = "email"; if (command.isChangeInStringParameterNamed(emailParamName, this.email)) { final String newValue = command.stringValueOfParameterNamed(emailParamName); actualChanges.put(emailParamName, newValue); this.email = newValue; } return actualChanges; }
@Transactional @Override public CommandProcessingResult updateSavingAccount( final Long savingsId, final JsonCommand command) { try { this.context.authenticatedUser(); this.savingsAccountDataValidator.validateForUpdate(command.json()); final Map<String, Object> changes = new LinkedHashMap<String, Object>(20); final SavingsAccount account = this.savingAccountRepository.findOneWithNotFoundDetection(savingsId); account.update(command, changes); if (!changes.isEmpty()) { if (changes.containsKey(SavingsApiConstants.clientIdParamName)) { final Long clientId = command.longValueOfParameterNamed(SavingsApiConstants.clientIdParamName); if (clientId != null) { final Client client = this.clientRepository.findOneWithNotFoundDetection(clientId); account.update(client); } else { final Client client = null; account.update(client); } } if (changes.containsKey(SavingsApiConstants.groupIdParamName)) { final Long groupId = command.longValueOfParameterNamed(SavingsApiConstants.groupIdParamName); if (groupId != null) { final Group group = this.groupRepository.findOne(groupId); if (group == null) { throw new GroupNotFoundException(groupId); } account.update(group); } else { final Group group = null; account.update(group); } } if (changes.containsKey(SavingsApiConstants.productIdParamName)) { final Long productId = command.longValueOfParameterNamed(SavingsApiConstants.productIdParamName); final SavingsProduct product = this.savingsProductRepository.findOne(productId); if (product == null) { throw new SavingsProductNotFoundException(productId); } account.update(product); } this.savingAccountRepository.saveAndFlush(account); } return new CommandProcessingResultBuilder() // .withCommandId(command.commandId()) // .withEntityId(savingsId) // .withOfficeId(account.officeId()) // .withClientId(account.clientId()) // .withGroupId(account.groupId()) // .withSavingsId(savingsId) // .with(changes) // .build(); } catch (DataAccessException dve) { handleDataIntegrityIssues(command, dve); return new CommandProcessingResult(Long.valueOf(-1)); } }
// @SuppressWarnings("unused") @Override public CommandProcessingResult selfRegistrationProcess(JsonCommand command) { try { context.authenticatedUser(); Configuration deviceStatusConfiguration = configurationRepository.findOneByName( ConfigurationConstants.CONFIR_PROPERTY_REGISTRATION_DEVICE); commandFromApiJsonDeserializer.validateForCreate( command.json(), deviceStatusConfiguration.isEnabled()); Long id = new Long(1); CommandProcessingResult resultClient = null; CommandProcessingResult resultSale = null; CommandProcessingResult resultOrder = null; String device = null; String dateFormat = "dd MMMM yyyy"; String activationDate = new SimpleDateFormat(dateFormat).format(DateUtils.getDateOfTenant()); String fullname = command.stringValueOfParameterNamed("fullname"); String firstName = command.stringValueOfParameterNamed("firstname"); String city = command.stringValueOfParameterNamed("city"); String address = command.stringValueOfParameterNamed("address"); Long phone = command.longValueOfParameterNamed("phone"); Long homePhoneNumber = command.longValueOfParameterNamed("homePhoneNumber"); String email = command.stringValueOfParameterNamed("email"); String nationalId = command.stringValueOfParameterNamed("nationalId"); String deviceId = command.stringValueOfParameterNamed("device"); String deviceAgreementType = command.stringValueOfParameterNamed("deviceAgreementType"); String password = command.stringValueOfParameterNamed("password"); String isMailCheck = command.stringValueOfParameterNamed("isMailCheck"); String passport = command.stringValueOfParameterNamed("passport"); SelfCareTemporary temporary = null; if (isMailCheck == null || isMailCheck.isEmpty()) { temporary = selfCareTemporaryRepository.findOneByEmailId(email); if (temporary == null) { throw new SelfCareTemporaryEmailIdNotFoundException(email); } else if (temporary.getStatus().equalsIgnoreCase("ACTIVE")) { throw new ClientAlreadyCreatedException(); } else if (temporary.getStatus().equalsIgnoreCase("INACTIVE")) { throw new SelfCareNotVerifiedException(email); } } // if (temporary.getStatus().equalsIgnoreCase("PENDING")){ String zipCode = command.stringValueOfParameterNamed("zipCode"); // client creation AddressData addressData = this.addressReadPlatformService.retrieveAdressBy(city); CodeValue codeValue = this.codeValueRepository.findOneByCodeValue("Normal"); JSONObject clientcreation = new JSONObject(); clientcreation.put("officeId", new Long(1)); clientcreation.put("clientCategory", codeValue.getId()); clientcreation.put("firstname", firstName); clientcreation.put("lastname", fullname); clientcreation.put("phone", phone); clientcreation.put("homePhoneNumber", homePhoneNumber); clientcreation.put("entryType", "IND"); // new Long(1)); clientcreation.put("addressNo", address); clientcreation.put("city", addressData.getCity()); clientcreation.put("state", addressData.getState()); clientcreation.put("country", addressData.getCountry()); clientcreation.put("email", email); clientcreation.put("locale", "en"); clientcreation.put("active", true); clientcreation.put("dateFormat", dateFormat); clientcreation.put("activationDate", activationDate); clientcreation.put("flag", false); clientcreation.put("zipCode", zipCode); clientcreation.put("device", deviceId); clientcreation.put("password", password); if (nationalId != null && !nationalId.equalsIgnoreCase("")) { clientcreation.put("externalId", nationalId); } final JsonElement element = fromJsonHelper.parse(clientcreation.toString()); JsonCommand clientCommand = new JsonCommand( null, clientcreation.toString(), element, fromJsonHelper, null, null, null, null, null, null, null, null, null, null, null, null); resultClient = this.clientWritePlatformService.createClient(clientCommand); if (resultClient == null) { throw new PlatformDataIntegrityException( "error.msg.client.creation.failed", "Client Creation Failed", "Client Creation Failed"); } if (passport != null && !passport.equalsIgnoreCase("")) { CodeValue passportcodeValue = this.codeValueRepository.findOneByCodeValue("Passport"); JSONObject clientIdentifierJson = new JSONObject(); clientIdentifierJson.put("documentTypeId", passportcodeValue.getId()); clientIdentifierJson.put("documentKey", passport); final JsonElement idenfierJsonEement = fromJsonHelper.parse(clientIdentifierJson.toString()); JsonCommand idenfierJsonCommand = new JsonCommand( null, clientIdentifierJson.toString(), idenfierJsonEement, fromJsonHelper, null, null, null, null, null, null, null, null, null, null, null, null); this.clientIdentifierWritePlatformService.addClientIdentifier( resultClient.getClientId(), idenfierJsonCommand); } if (temporary != null) { temporary.setStatus("ACTIVE"); this.selfCareTemporaryRepository.saveAndFlush(temporary); } // book device if (deviceStatusConfiguration != null) { if (deviceStatusConfiguration.isEnabled()) { JSONObject bookDevice = new JSONObject(); /*deviceStatusConfiguration = configurationRepository .findOneByName(ConfigurationConstants.CONFIG_PROPERTY_DEVICE_AGREMENT_TYPE);*/ /*if (deviceStatusConfiguration != null&& deviceStatusConfiguration.isEnabled() && deviceStatusConfiguration.getValue().equalsIgnoreCase(ConfigurationConstants.CONFIR_PROPERTY_SALE)) {*/ if (deviceAgreementType.equalsIgnoreCase(ConfigurationConstants.CONFIR_PROPERTY_SALE)) { device = command.stringValueOfParameterNamed("device"); ItemDetails detail = itemDetailsRepository.getInventoryItemDetailBySerialNum(device); if (detail == null) { throw new SerialNumberNotFoundException(device); } ItemMaster itemMaster = this.itemRepository.findOne(detail.getItemMasterId()); if (itemMaster == null) { throw new ItemNotFoundException(deviceId); } if (detail != null && detail.getStatus().equalsIgnoreCase("Used")) { throw new SerialNumberAlreadyExistException(device); } JSONObject serialNumberObject = new JSONObject(); serialNumberObject.put("serialNumber", device); serialNumberObject.put("clientId", resultClient.getClientId()); serialNumberObject.put("status", "allocated"); serialNumberObject.put("itemMasterId", detail.getItemMasterId()); serialNumberObject.put("isNewHw", "Y"); JSONArray serialNumber = new JSONArray(); serialNumber.put(0, serialNumberObject); bookDevice.put("chargeCode", itemMaster.getChargeCode()); bookDevice.put("unitPrice", itemMaster.getUnitPrice()); bookDevice.put("itemId", itemMaster.getId()); bookDevice.put("discountId", id); bookDevice.put("officeId", detail.getOfficeId()); bookDevice.put("totalPrice", itemMaster.getUnitPrice()); bookDevice.put("quantity", id); bookDevice.put("locale", "en"); bookDevice.put("dateFormat", dateFormat); bookDevice.put("saleType", "NEWSALE"); bookDevice.put("saleDate", activationDate); bookDevice.put("serialNumber", serialNumber); final JsonElement deviceElement = fromJsonHelper.parse(bookDevice.toString()); JsonCommand comm = new JsonCommand( null, bookDevice.toString(), deviceElement, fromJsonHelper, null, null, null, null, null, null, null, null, null, null, null, null); resultSale = this.oneTimeSaleWritePlatformService.createOneTimeSale( comm, resultClient.getClientId()); if (resultSale == null) { throw new PlatformDataIntegrityException( "error.msg.client.device.assign.failed", "Device Assign Failed for ClientId :" + resultClient.getClientId(), "Device Assign Failed"); } } else if (deviceAgreementType.equalsIgnoreCase( ConfigurationConstants.CONFIR_PROPERTY_OWN)) { List<ItemMaster> itemMaster = this.itemRepository.findAll(); bookDevice.put("locale", "en"); bookDevice.put("dateFormat", dateFormat); bookDevice.put("allocationDate", activationDate); bookDevice.put("provisioningSerialNumber", deviceId); bookDevice.put("itemType", itemMaster.get(0).getId()); bookDevice.put("serialNumber", deviceId); bookDevice.put("status", "ACTIVE"); CommandWrapper commandWrapper = new CommandWrapperBuilder() .createOwnedHardware(resultClient.getClientId()) .withJson(bookDevice.toString()) .build(); final CommandProcessingResult result = portfolioCommandSourceWritePlatformService.logCommandSource(commandWrapper); if (result == null) { throw new PlatformDataIntegrityException( "error.msg.client.device.assign.failed", "Device Assign Failed for ClientId :" + resultClient.getClientId(), "Device Assign Failed"); } } else { } } } // book order Configuration selfregistrationconfiguration = configurationRepository.findOneByName( ConfigurationConstants.CONFIR_PROPERTY_SELF_REGISTRATION); if (selfregistrationconfiguration != null && selfregistrationconfiguration.isEnabled()) { if (selfregistrationconfiguration.getValue() != null) { JSONObject ordeJson = new JSONObject(selfregistrationconfiguration.getValue()); ordeJson.put("locale", "en"); ordeJson.put("isNewplan", true); ordeJson.put("dateFormat", dateFormat); ordeJson.put("start_date", activationDate); CommandWrapper commandRequest = new CommandWrapperBuilder() .createOrder(resultClient.getClientId()) .withJson(ordeJson.toString()) .build(); resultOrder = this.portfolioCommandSourceWritePlatformService.logCommandSource(commandRequest); if (resultOrder == null) { throw new PlatformDataIntegrityException( "error.msg.client.order.creation", "Book Order Failed for ClientId:" + resultClient.getClientId(), "Book Order Failed"); } } else { String paytermCode = command.stringValueOfParameterNamed("paytermCode"); Long contractPeriod = command.longValueOfParameterNamed("contractPeriod"); Long planCode = command.longValueOfParameterNamed("planCode"); JSONObject ordeJson = new JSONObject(); ordeJson.put("planCode", planCode); ordeJson.put("contractPeriod", contractPeriod); ordeJson.put("paytermCode", paytermCode); ordeJson.put("billAlign", false); ordeJson.put("locale", "en"); ordeJson.put("isNewplan", true); ordeJson.put("dateFormat", dateFormat); ordeJson.put("start_date", activationDate); CommandWrapper commandRequest = new CommandWrapperBuilder() .createOrder(resultClient.getClientId()) .withJson(ordeJson.toString()) .build(); resultOrder = this.portfolioCommandSourceWritePlatformService.logCommandSource(commandRequest); if (resultOrder == null) { throw new PlatformDataIntegrityException( "error.msg.client.order.creation", "Book Order Failed for ClientId:" + resultClient.getClientId(), "Book Order Failed"); } } } return resultClient; /*} else { return new CommandProcessingResult(Long.valueOf(-1)); }*/ } catch (DataIntegrityViolationException dve) { handleDataIntegrityIssues(command, dve); return new CommandProcessingResult(Long.valueOf(-1)); } catch (JSONException e) { return new CommandProcessingResult(Long.valueOf(-1)); } }
@Transactional @Override public CommandProcessingResult modifyApplication( final Long savingsId, final JsonCommand command) { try { this.savingsAccountDataValidator.validateForUpdate(command.json()); final Map<String, Object> changes = new LinkedHashMap<String, Object>(20); final SavingsAccount account = this.savingAccountAssembler.assembleFrom(savingsId); checkClientOrGroupActive(account); account.modifyApplication(command, changes); account.validateNewApplicationState(DateUtils.getLocalDateOfTenant()); account.validateAccountValuesWithProduct(); if (!changes.isEmpty()) { if (changes.containsKey(SavingsApiConstants.clientIdParamName)) { final Long clientId = command.longValueOfParameterNamed(SavingsApiConstants.clientIdParamName); if (clientId != null) { final Client client = this.clientRepository.findOneWithNotFoundDetection(clientId); if (client.isNotActive()) { throw new ClientNotActiveException(clientId); } account.update(client); } else { final Client client = null; account.update(client); } } if (changes.containsKey(SavingsApiConstants.groupIdParamName)) { final Long groupId = command.longValueOfParameterNamed(SavingsApiConstants.groupIdParamName); if (groupId != null) { final Group group = this.groupRepository.findOne(groupId); if (group == null) { throw new GroupNotFoundException(groupId); } if (group.isNotActive()) { if (group.isCenter()) { throw new CenterNotActiveException(groupId); } throw new GroupNotActiveException(groupId); } account.update(group); } else { final Group group = null; account.update(group); } } if (changes.containsKey(SavingsApiConstants.productIdParamName)) { final Long productId = command.longValueOfParameterNamed(SavingsApiConstants.productIdParamName); final SavingsProduct product = this.savingsProductRepository.findOne(productId); if (product == null) { throw new SavingsProductNotFoundException(productId); } account.update(product); } if (changes.containsKey(SavingsApiConstants.fieldOfficerIdParamName)) { final Long fieldOfficerId = command.longValueOfParameterNamed(SavingsApiConstants.fieldOfficerIdParamName); Staff fieldOfficer = null; if (fieldOfficerId != null) { fieldOfficer = this.staffRepository.findOneWithNotFoundDetection(fieldOfficerId); } else { changes.put(SavingsApiConstants.fieldOfficerIdParamName, ""); } account.update(fieldOfficer); } if (changes.containsKey("charges")) { final Set<SavingsAccountCharge> charges = this.savingsAccountChargeAssembler.fromParsedJson( command.parsedJson(), account.getCurrency().getCode()); final boolean updated = account.update(charges); if (!updated) { changes.remove("charges"); } } this.savingAccountRepository.saveAndFlush(account); } return new CommandProcessingResultBuilder() // .withCommandId(command.commandId()) // .withEntityId(savingsId) // .withOfficeId(account.officeId()) // .withClientId(account.clientId()) // .withGroupId(account.groupId()) // .withSavingsId(savingsId) // .with(changes) // .build(); } catch (final DataAccessException dve) { handleDataIntegrityIssues(command, dve); return new CommandProcessingResult(Long.valueOf(-1)); } }
@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); }