List of usage examples for java.math BigDecimal compareTo
@Override public int compareTo(BigDecimal val)
From source file:com.gst.portfolio.loanaccount.service.LoanApplicationWritePlatformServiceJpaRepositoryImpl.java
@Transactional @Override/* w w w . j av a 2s . c o m*/ public CommandProcessingResult approveApplication(final Long loanId, final JsonCommand command) { final AppUser currentUser = getAppUserIfPresent(); LocalDate expectedDisbursementDate = null; this.loanApplicationTransitionApiJsonValidator.validateApproval(command.json()); final Loan loan = retrieveLoanBy(loanId); final JsonArray disbursementDataArray = command .arrayOfParameterNamed(LoanApiConstants.disbursementDataParameterName); expectedDisbursementDate = command .localDateValueOfParameterNamed(LoanApiConstants.disbursementDateParameterName); if (expectedDisbursementDate == null) { expectedDisbursementDate = loan.getExpectedDisbursedOnLocalDate(); } if (loan.loanProduct().isMultiDisburseLoan()) { this.validateMultiDisbursementData(command, expectedDisbursementDate); } checkClientOrGroupActive(loan); Boolean isSkipRepaymentOnFirstMonth = false; Integer numberOfDays = 0; // validate expected disbursement date against meeting date if (loan.isSyncDisbursementWithMeeting() && (loan.isGroupLoan() || loan.isJLGLoan())) { final CalendarInstance calendarInstance = this.calendarInstanceRepository .findCalendarInstaneByEntityId(loan.getId(), CalendarEntityType.LOANS.getValue()); final Calendar calendar = calendarInstance.getCalendar(); boolean isSkipRepaymentOnFirstMonthEnabled = this.configurationDomainService .isSkippingMeetingOnFirstDayOfMonthEnabled(); if (isSkipRepaymentOnFirstMonthEnabled) { isSkipRepaymentOnFirstMonth = this.loanUtilService.isLoanRepaymentsSyncWithMeeting(loan.group(), calendar); if (isSkipRepaymentOnFirstMonth) { numberOfDays = configurationDomainService.retreivePeroidInNumberOfDaysForSkipMeetingDate() .intValue(); } } this.loanScheduleAssembler.validateDisbursementDateWithMeetingDates(expectedDisbursementDate, calendar, isSkipRepaymentOnFirstMonth, numberOfDays); } final Map<String, Object> changes = loan.loanApplicationApproval(currentUser, command, disbursementDataArray, defaultLoanLifecycleStateMachine()); entityDatatableChecksWritePlatformService.runTheCheckForProduct(loanId, EntityTables.LOAN.getName(), StatusEnum.APPROVE.getCode().longValue(), EntityTables.LOAN.getForeignKeyColumnNameOnDatatable(), loan.productId()); if (!changes.isEmpty()) { // If loan approved amount less than loan demanded amount, then need // to recompute the schedule if (changes.containsKey(LoanApiConstants.approvedLoanAmountParameterName) || changes.containsKey("recalculateLoanSchedule") || changes.containsKey("expectedDisbursementDate")) { LocalDate recalculateFrom = null; ScheduleGeneratorDTO scheduleGeneratorDTO = this.loanUtilService.buildScheduleGeneratorDTO(loan, recalculateFrom); loan.regenerateRepaymentSchedule(scheduleGeneratorDTO, currentUser); } if (loan.isTopup() && loan.getClientId() != null) { final Long loanIdToClose = loan.getTopupLoanDetails().getLoanIdToClose(); final Loan loanToClose = this.loanRepositoryWrapper .findNonClosedLoanThatBelongsToClient(loanIdToClose, loan.getClientId()); if (loanToClose == null) { throw new GeneralPlatformDomainRuleException( "error.msg.loan.to.be.closed.with.topup.is.not.active", "Loan to be closed with this topup is not active."); } final LocalDate lastUserTransactionOnLoanToClose = loanToClose.getLastUserTransactionDate(); if (!loan.getDisbursementDate().isAfter(lastUserTransactionOnLoanToClose)) { throw new GeneralPlatformDomainRuleException( "error.msg.loan.disbursal.date.should.be.after.last.transaction.date.of.loan.to.be.closed", "Disbursal date of this loan application " + loan.getDisbursementDate() + " should be after last transaction date of loan to be closed " + lastUserTransactionOnLoanToClose); } BigDecimal loanOutstanding = this.loanReadPlatformService .retrieveLoanPrePaymentTemplate(loanIdToClose, expectedDisbursementDate).getAmount(); final BigDecimal firstDisbursalAmount = loan.getFirstDisbursalAmount(); if (loanOutstanding.compareTo(firstDisbursalAmount) > 0) { throw new GeneralPlatformDomainRuleException( "error.msg.loan.amount.less.than.outstanding.of.loan.to.be.closed", "Topup loan amount should be greater than outstanding amount of loan to be closed."); } } saveAndFlushLoanWithDataIntegrityViolationChecks(loan); final String noteText = command.stringValueOfParameterNamed("note"); if (StringUtils.isNotBlank(noteText)) { final Note note = Note.loanNote(loan, noteText); changes.put("note", noteText); this.noteRepository.save(note); } this.businessEventNotifierService.notifyBusinessEventWasExecuted(BUSINESS_EVENTS.LOAN_APPROVED, constructEntityMap(BUSINESS_ENTITY.LOAN, loan)); } return new CommandProcessingResultBuilder() // .withCommandId(command.commandId()) // .withEntityId(loan.getId()) // .withOfficeId(loan.getOfficeId()) // .withClientId(loan.getClientId()) // .withGroupId(loan.getGroupId()) // .withLoanId(loanId) // .with(changes) // .build(); }
From source file:nl.strohalm.cyclos.services.accounts.AccountStatusHandlerImpl.java
/** * adds or substracts an amount to the status balance. Call this in stead of directly increasing credits or debits, as it takes care for rate * balance correction field too. Only updates the real credits and debits, not the pending debits and credits. * /*from w w w . j a va 2 s .co m*/ * @param status The status to be updated. Nothing is saved; the status fields are just updated. * @param transfer the transfer being processed. */ private void updateBalanceWithTransfer(final PendingAccountStatus pendingStatus, final AccountStatus status, final Transfer transfer) { if (pendingStatus.getTransferStatus() != Payment.Status.PROCESSED) { // method only deals with real debits and credits; not with pendings... return; } final BigDecimal amount = transfer.getAmount(); final boolean isDebit = status.getAccount().equals(transfer.getFrom()); final boolean isRoot = transfer.isRoot(); final Currency currency = status.getAccount().getType().getCurrency(); final Calendar date = transfer.getProcessDate(); final boolean rated = (currency.isEnableARate(date) || currency.isEnableDRate(date)); if (isDebit) { // call this first, before the balance is updated. if (rated) { aRateService.updateRateBalanceCorrectionOnFromAccount(status, amount); } if (isRoot) { status.setRootDebits(status.getRootDebits().add(amount)); } else { status.setNestedDebits(status.getNestedDebits().add(amount)); } } else { // call this first, before the balance is updated. if (rated && amount.compareTo(BigDecimal.ZERO) < 0) { // special case for chargebacks (having negative transfer amounts) aRateService.updateRateBalanceCorrectionOnFromAccount(status, amount.negate()); } if (isRoot) { status.setRootCredits(status.getRootCredits().add(amount)); } else { status.setNestedCredits(status.getNestedCredits().add(amount)); } } }
From source file:com.app.jdy.ui.CashAdvanceActivity.java
private void addEvents() { button.setOnClickListener(new OnClickListener() { @Override/* ww w . jav a 2s .c o m*/ public void onClick(View v) { // ???? if (HttpUtils.isNetworkConnected(CashAdvanceActivity.this)) { if (editText.getText().toString().length() == 0) { Toast.makeText(CashAdvanceActivity.this, "?", Toast.LENGTH_SHORT).show(); } else { // ? int count = 0, start = 0; while ((start = editText.getText().toString().indexOf(".", start)) >= 0) { start += ".".length(); count++; } if (count > 1 || editText.getText().toString().indexOf(".") == 0) { Toast.makeText(CashAdvanceActivity.this, "", Toast.LENGTH_SHORT) .show(); } else { // ????? BigDecimal judgemoney = null; try { judgemoney = new BigDecimal(editText.getText().toString()); } catch (NumberFormatException e) { Toast.makeText(CashAdvanceActivity.this, "", Toast.LENGTH_SHORT).show(); return; } judgemoney = judgemoney.setScale(2, BigDecimal.ROUND_HALF_UP); // ????? String judgecanWithdCash = textView2.getText().toString(); if (textView4.getText().toString().equals("?") || textView4.getText().toString().length() == 0 || textView3.getText().toString().length() == 0) { Toast.makeText(CashAdvanceActivity.this, "?", Toast.LENGTH_SHORT) .show(); } else if (judgemoney.toString() == "0.00") { Toast.makeText(CashAdvanceActivity.this, "?0?", Toast.LENGTH_SHORT).show(); } else if (judgemoney .compareTo(BigDecimal.valueOf(Double.valueOf(judgecanWithdCash))) == 1) { // BigDecimalcompareTo-1 ? 0 // 1 Toast.makeText(CashAdvanceActivity.this, "??????", Toast.LENGTH_LONG).show(); } else { editText.setText(judgemoney.toString()); withdrawCashDialog = new WithdrawCashDialog(CashAdvanceActivity.this, R.style.ForwardDialog, judgemoney.toString()); withdrawCashDialog.show(); } } } } else { // ?? Toast.makeText(CashAdvanceActivity.this, Constants.NO_INTENT_TIPS, Toast.LENGTH_LONG).show(); } } }); // ?????? findViewById(R.id.cash_textView5).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(CashAdvanceActivity.this, BankCardActivity.class); Bundle bundle = new Bundle(); bundle.putBoolean("isOk", true); intent.putExtras(bundle); startActivity(intent); finish(); } }); }
From source file:org.efaps.esjp.accounting.transaction.Recalculate_Base.java
/** * Method to recalculate rate./*from ww w. ja va2 s .c om*/ * * @param _parameter Parameter as passed from the eFaps API. * @return new Return. * @throws EFapsException on error. */ public Return recalculateRate(final Parameter _parameter) throws EFapsException { final Instance docInst = Instance.get(_parameter.getParameterValue("docInst")); final PrintQuery print = new PrintQuery(docInst); print.addAttribute(CISales.DocumentSumAbstract.RateCrossTotal, CISales.DocumentSumAbstract.CrossTotal, CISales.DocumentSumAbstract.RateCurrencyId, CISales.DocumentSumAbstract.CurrencyId, CISales.DocumentSumAbstract.Date, CISales.DocumentSumAbstract.Name); print.execute(); final BigDecimal rateCross = print.<BigDecimal>getAttribute(CISales.DocumentSumAbstract.RateCrossTotal); final BigDecimal crossTotal = print.<BigDecimal>getAttribute(CISales.DocumentSumAbstract.CrossTotal); final DateTime dateDoc = print.<DateTime>getAttribute(CISales.DocumentSumAbstract.Date); final String nameDoc = print.<String>getAttribute(CISales.DocumentSumAbstract.Name); final Instance targetCurrInst = Instance.get(CIERP.Currency.getType(), print.<Long>getAttribute(CISales.DocumentSumAbstract.RateCurrencyId)); final Instance currentInst = Instance.get(CIERP.Currency.getType(), print.<Long>getAttribute(CISales.DocumentSumAbstract.CurrencyId)); final CurrencyInst tarCurr = new CurrencyInst(targetCurrInst); final CurrencyInst curr = new CurrencyInst(currentInst); final PriceUtil priceUtil = new PriceUtil(); final BigDecimal[] rates = priceUtil.getRates(_parameter, targetCurrInst, currentInst); final BigDecimal rate = rates[2]; final BigDecimal newCrossTotal = rateCross.compareTo(BigDecimal.ZERO) == 0 ? BigDecimal.ZERO : rateCross.divide(rate, BigDecimal.ROUND_HALF_UP); final BigDecimal gainloss = newCrossTotal.subtract(crossTotal); final Map<String, String[]> map = validateInfo(_parameter, gainloss); final String[] accs = map.get("accs"); final String[] check = map.get("check"); if (checkAccounts(accs, 0, check).length() > 0 && checkAccounts(accs, 1, check).length() > 0) { if (gainloss.compareTo(BigDecimal.ZERO) != 0) { if (!tarCurr.equals(curr)) { final String[] accOids = map.get("accountOids"); final Insert insert = new Insert(CIAccounting.Transaction); final StringBuilder description = new StringBuilder(); final DateTimeFormatter formater = DateTimeFormat.mediumDate(); final String dateStr = dateDoc.withChronology(Context.getThreadContext().getChronology()) .toString(formater.withLocale(Context.getThreadContext().getLocale())); description .append(DBProperties .getProperty("Accounting_TransactionRecalculateForm.TxnRecalculate.Label")) .append(" ").append(nameDoc).append(" ").append(dateStr); insert.add(CIAccounting.Transaction.Description, description); insert.add(CIAccounting.Transaction.Date, _parameter.getParameterValue("date")); insert.add(CIAccounting.Transaction.PeriodLink, _parameter.getInstance().getId()); insert.add(CIAccounting.Transaction.Status, Status.find(CIAccounting.TransactionStatus.uuid, "Open").getId()); insert.execute(); final Instance instance = insert.getInstance(); new Create().connectDocs2Transaction(_parameter, instance, docInst); final Insert insert2 = new Insert(CIAccounting.TransactionPositionCredit); insert2.add(CIAccounting.TransactionPositionCredit.TransactionLink, instance.getId()); insert2.add(CIAccounting.TransactionPositionCredit.AccountLink, Instance.get(accOids[1]).getId()); insert2.add(CIAccounting.TransactionPositionCredit.CurrencyLink, curr.getInstance().getId()); insert2.add(CIAccounting.TransactionPositionCredit.RateCurrencyLink, curr.getInstance().getId()); insert2.add(CIAccounting.TransactionPositionCredit.Rate, new Object[] { 1, 1 }); insert2.add(CIAccounting.TransactionPositionCredit.RateAmount, gainloss.abs()); insert2.add(CIAccounting.TransactionPositionCredit.Amount, gainloss.abs()); insert2.execute(); final Insert insert3 = new Insert(CIAccounting.TransactionPositionDebit); insert3.add(CIAccounting.TransactionPositionDebit.TransactionLink, instance.getId()); insert3.add(CIAccounting.TransactionPositionDebit.AccountLink, Instance.get(accOids[0]).getId()); insert3.add(CIAccounting.TransactionPositionDebit.CurrencyLink, curr.getInstance().getId()); insert3.add(CIAccounting.TransactionPositionDebit.RateCurrencyLink, curr.getInstance().getId()); insert3.add(CIAccounting.TransactionPositionDebit.Rate, new Object[] { 1, 1 }); insert3.add(CIAccounting.TransactionPositionDebit.RateAmount, gainloss.abs().negate()); insert3.add(CIAccounting.TransactionPositionDebit.Amount, gainloss.abs().negate()); insert3.execute(); _parameter.put(ParameterValues.INSTANCE, docInst); new Accounting4DocSum().recalculateRate(_parameter); } } } return new Return(); }
From source file:nl.strohalm.cyclos.services.elements.MemberImportServiceImpl.java
private void importMember(final MemberImport memberImport, final MemberGroupAccountSettings accountSettings, final int lineNumber, final Map<String, CustomField> customFieldMap, final Map<String, MemberRecordType> recordTypeMap, final Map<MemberRecordType, Map<String, CustomField>> recordTypeFieldsMap, final LocalSettings localSettings, final AccessSettings accessSettings, final List<String> headers, final List<String> values, final Set<String> importedUsernames) { final Map<MemberRecordType, ImportedMemberRecord> records = new HashMap<MemberRecordType, ImportedMemberRecord>(); final Map<String, String> customFieldValues = new HashMap<String, String>(); final Map<MemberRecordType, Map<String, String>> recordFieldValues = new HashMap<MemberRecordType, Map<String, String>>(); // Insert the member ImportedMember member = new ImportedMember(); member.setSalt(hashHandler.newSalt()); member.setLineNumber(lineNumber);/*from w ww . ja va2 s. c o m*/ member.setImport(memberImport); member.setStatus(ImportedMember.Status.SUCCESS); member = importedMemberDao.insert(member); final Calendar today = DateHelper.truncate(Calendar.getInstance()); try { member.setCustomValues(new ArrayList<MemberCustomFieldValue>()); final CalendarConverter dateConverter = localSettings.getRawDateConverter(); // Process each field. Field names are lowercased to ignore case for (int i = 0; i < headers.size() && i < values.size(); i++) { final String field = StringUtils.trimToEmpty(headers.get(i)).toLowerCase(); final String value = StringUtils.trimToNull(values.get(i)); if ("name".equals(field)) { member.setName(value); } else if ("username".equals(field)) { member.setUsername(value); } else if ("password".equals(field)) { member.setPassword(hashHandler.hash(member.getSalt(), value)); } else if ("email".equals(field)) { member.setEmail(value); } else if ("creationdate".equals(field)) { try { final Calendar creationDate = dateConverter.valueOf(value); if (creationDate != null) { if (creationDate.after(today) || creationDate.get(Calendar.YEAR) < 1950) { throw new Exception(); } member.setCreationDate(creationDate); } } catch (final Exception e) { member.setStatus(ImportedMember.Status.INVALID_CREATION_DATE); member.setErrorArgument1(value); break; } } else if ("balance".equals(field)) { try { member.setInitialBalance(localSettings.getNumberConverter().valueOf(value)); } catch (final Exception e) { member.setStatus(ImportedMember.Status.INVALID_BALANCE); member.setErrorArgument1(value); break; } } else if ("creditlimit".equals(field)) { try { BigDecimal limit = localSettings.getNumberConverter().valueOf(value); // Ensure the limit is positive if (limit != null) { limit = limit.abs(); } member.setCreditLimit(limit); } catch (final Exception e) { member.setStatus(ImportedMember.Status.INVALID_CREDIT_LIMIT); member.setErrorArgument1(value); break; } } else if ("uppercreditlimit".equals(field)) { try { member.setUpperCreditLimit(localSettings.getNumberConverter().valueOf(value)); } catch (final Exception e) { member.setStatus(ImportedMember.Status.INVALID_UPPER_CREDIT_LIMIT); member.setErrorArgument1(value); break; } } else if (customFieldMap.containsKey(field)) { // Create a custom field value CustomField customField = customFieldMap.get(field); final MemberCustomFieldValue fieldValue = new MemberCustomFieldValue(); fieldValue.setField(customField); fieldValue.setValue(preprocessCustomFieldValue(customField, value)); member.getCustomValues().add(fieldValue); customFieldValues.put(field, value); } else if (field.contains(".")) { // A record type value final String[] parts = field.split("\\."); // Find the record type final String recordTypeName = parts[0]; final MemberRecordType recordType = recordTypeMap.get(recordTypeName); if (recordType == null) { member.setStatus(ImportedMember.Status.INVALID_RECORD_TYPE); member.setErrorArgument1(recordTypeName); break; } // Find the custom field final String recordTypeField = parts[1]; final Map<String, CustomField> fieldsMap = recordTypeFieldsMap.get(recordType); final CustomField customField = fieldsMap.get(recordTypeField); if (customField == null) { member.setStatus(ImportedMember.Status.INVALID_RECORD_TYPE_FIELD); member.setErrorArgument1(recordTypeName); member.setErrorArgument2(recordTypeField); break; } // Find the imported member record ImportedMemberRecord record = records.get(recordType); if (record == null) { // None yet - create a new one record = new ImportedMemberRecord(); record.setMember(member); record.setType(recordType); record = importedMemberRecordDao.insert(record); record.setCustomValues(new ArrayList<ImportedMemberRecordCustomFieldValue>()); records.put(recordType, record); } // Set the custom field final ImportedMemberRecordCustomFieldValue fieldValue = new ImportedMemberRecordCustomFieldValue(); fieldValue.setField(customField); fieldValue.setValue(preprocessCustomFieldValue(customField, value)); record.getCustomValues().add(fieldValue); // Store the field value in a map Map<String, String> fieldValues = recordFieldValues.get(recordType); if (fieldValues == null) { fieldValues = new HashMap<String, String>(); recordFieldValues.put(recordType, fieldValues); } fieldValues.put(recordTypeField, value); } else { throw new UnknownColumnException(field); } } // When there was an error, stop processing if (member.getStatus() != ImportedMember.Status.SUCCESS) { return; } // Validate some data if (member.getName() == null) { // Name is always required member.setStatus(ImportedMember.Status.MISSING_NAME); return; } final String username = member.getUsername(); if (accessSettings.getUsernameGeneration() == UsernameGeneration.NONE && username == null) { // Username is required when it's not generated member.setStatus(ImportedMember.Status.MISSING_USERNAME); return; } // Validate the username if (username != null) { // Check the username format ValidationError error = new RegexValidation(accessSettings.getUsernameRegex()).validate(null, null, username); if (error == null) { // Check the username length error = new LengthValidation(accessSettings.getUsernameLength()).validate(null, null, username); } if (error != null) { member.setStatus(ImportedMember.Status.INVALID_USERNAME); member.setErrorArgument1(username); return; } // Check if username is duplicated in this import if (!importedUsernames.add(username)) { member.setStatus(ImportedMember.Status.USERNAME_ALREADY_IN_USE); member.setErrorArgument1(username); return; } // Check if username is already used by another member in cyclos try { elementService.loadUser(username); // If an user could be loaded, it means that the username is already in use member.setStatus(ImportedMember.Status.USERNAME_ALREADY_IN_USE); member.setErrorArgument1(username); return; } catch (final EntityNotFoundException e) { // Ok - not used yet } } if (member.getEmail() == null && localSettings.isEmailRequired()) { // Mail is required member.setStatus(ImportedMember.Status.MISSING_EMAIL); return; } if (EmailValidation.instance().validate(null, null, member.getEmail()) != null) { // Mail format is invalid member.setStatus(ImportedMember.Status.INVALID_EMAIL); member.setErrorArgument1(member.getEmail()); return; } if (memberImport.getAccountType() == null) { // Nothing related to accounts will be imported member.setInitialBalance(null); member.setCreditLimit(null); member.setUpperCreditLimit(null); } else { if (member.getCreditLimit() == null) { // Get the default group credit limit member.setCreditLimit(accountSettings.getDefaultCreditLimit()); } if (member.getUpperCreditLimit() == null) { // Get the default group upper credit limit member.setUpperCreditLimit(accountSettings.getDefaultUpperCreditLimit()); } final BigDecimal balance = member.getInitialBalance(); if (balance != null) { double balanceValue = balance.doubleValue(); if (balanceValue > 0 && memberImport.getInitialCreditTransferType() == null) { // There was an initial credit, but no TT for it: ignore member.setInitialBalance(null); balanceValue = 0; } else if (balanceValue < 0 && memberImport.getInitialDebitTransferType() == null) { // There was an initial debit, but no TT for it: ignore member.setInitialBalance(null); balanceValue = 0; } final BigDecimal creditLimit = member.getCreditLimit(); if (creditLimit != null && balanceValue < 0 && balance.compareTo(creditLimit.negate()) < 0) { // When the initial balance is negative, ensure the credit limit accommodates it member.setStatus(ImportedMember.Status.BALANCE_LOWER_THAN_CREDIT_LIMIT); return; } final BigDecimal upperCreditLimit = member.getUpperCreditLimit(); if (upperCreditLimit != null && balanceValue > 0 && balance.compareTo(upperCreditLimit) > 0) { // When the initial balance is positive, ensure the credit limit accommodates it member.setStatus(ImportedMember.Status.BALANCE_UPPER_THAN_CREDIT_LIMIT); return; } } } // Save the custom field values try { memberCustomFieldService.saveValues(member); } catch (final Exception e) { member.setStatus(ImportedMember.Status.INVALID_CUSTOM_FIELD); if (e instanceof ValidationException) { final ValidationException vex = (ValidationException) e; final Map<String, Collection<ValidationError>> errorsByProperty = vex.getErrorsByProperty(); if (MapUtils.isNotEmpty(errorsByProperty)) { final String fieldName = errorsByProperty.keySet().iterator().next(); final String displayName = vex.getDisplayNameByProperty().get(fieldName); member.setErrorArgument1(StringUtils.isEmpty(displayName) ? fieldName : displayName); final String fieldValue = StringUtils .trimToNull(customFieldValues.get(fieldName.toLowerCase())); if (CollectionUtils.isNotEmpty(errorsByProperty.get(fieldName))) { ValidationError ve = errorsByProperty.get(fieldName).iterator().next(); if (ve instanceof UniqueError) { member.setStatus(ImportedMember.Status.INVALID_CUSTOM_FIELD_VALUE_UNIQUE); member.setErrorArgument2(ve.getArguments().iterator().next().toString()); } else if (ve instanceof RequiredError) { member.setStatus(ImportedMember.Status.MISSING_CUSTOM_FIELD); } else if (ve instanceof MaxLengthError) { member.setStatus(ImportedMember.Status.INVALID_CUSTOM_FIELD_VALUE_MAX_LENGTH); member.setErrorArgument2(ve.getArguments().iterator().next().toString()); } else if (ve instanceof MinLengthError) { member.setStatus(ImportedMember.Status.INVALID_CUSTOM_FIELD_VALUE_MIN_LENGTH); member.setErrorArgument2(ve.getArguments().iterator().next().toString()); } } if (StringUtils.isEmpty(member.getErrorArgument2()) && fieldValue != null) { member.setErrorArgument2(fieldValue); } } } return; } // Save each record field values for (final ImportedMemberRecord record : records.values()) { final MemberRecordType recordType = record.getType(); final Map<String, String> fieldValues = recordFieldValues.get(recordType); // Check if the record is not empty boolean empty = true; for (final String value : fieldValues.values()) { if (StringUtils.isNotEmpty(value)) { empty = false; break; } } if (empty) { // There are no fields for this record: remove the record itself importedMemberRecordDao.delete(record.getId()); continue; } try { memberRecordCustomFieldService.saveValues(record); } catch (final Exception e) { member.setStatus(ImportedMember.Status.INVALID_RECORD_FIELD); if (e instanceof ValidationException) { final ValidationException vex = (ValidationException) e; final Map<String, Collection<ValidationError>> errorsByProperty = vex.getErrorsByProperty(); if (MapUtils.isNotEmpty(errorsByProperty)) { final String fieldName = errorsByProperty.keySet().iterator().next(); member.setErrorArgument1(recordType.getName() + "." + fieldName); final String fieldValue = StringUtils.trimToNull(fieldValues.get(fieldName)); if (fieldValue == null) { // When validation failed and the field is null, it's actually missing member.setStatus(ImportedMember.Status.MISSING_RECORD_FIELD); } else { member.setErrorArgument2(fieldValue); } } } return; } } } catch (final UnknownColumnException e) { throw e; } catch (final Exception e) { member.setStatus(ImportedMember.Status.UNKNOWN_ERROR); member.setErrorArgument1(e.toString()); } finally { importedMemberDao.update(member); } }
From source file:org.apache.fineract.portfolio.loanaccount.domain.LoanCharge.java
public void update(final BigDecimal amount, final LocalDate dueDate, final BigDecimal loanPrincipal, Integer numberOfRepayments, BigDecimal loanCharge) { if (dueDate != null) { this.dueDate = dueDate.toDate(); }//from w ww . j a v a 2 s . co m if (amount != null) { switch (ChargeCalculationType.fromInt(this.chargeCalculation)) { case INVALID: break; case FLAT: if (isInstalmentFee()) { if (numberOfRepayments == null) { numberOfRepayments = this.loan.fetchNumberOfInstallmensAfterExceptions(); } this.amount = amount.multiply(BigDecimal.valueOf(numberOfRepayments)); } else { this.amount = amount; } break; case PERCENT_OF_AMOUNT: case PERCENT_OF_AMOUNT_AND_INTEREST: case PERCENT_OF_INTEREST: case PERCENT_OF_DISBURSEMENT_AMOUNT: this.percentage = amount; this.amountPercentageAppliedTo = loanPrincipal; if (loanCharge.compareTo(BigDecimal.ZERO) == 0) { loanCharge = percentageOf(this.amountPercentageAppliedTo); } this.amount = minimumAndMaximumCap(loanCharge); break; } this.amountOrPercentage = amount; this.amountOutstanding = calculateOutstanding(); if (this.loan != null && isInstalmentFee()) { updateInstallmentCharges(); } } }
From source file:com.ssbusy.controller.checkout.CheckoutController.java
@RequestMapping(value = "/checkout/alipaySucessOrFailed") public String alipayCheckout(HttpServletRequest request, HttpServletResponse response, Model model, MyBillingInfoForm billingForm, BindingResult result, String orderNum, String returnInfo, String total_fee) {/*from w w w . j a v a2 s.co m*/ LOG.info("this is our alipayCheckout function:"); /* * String orderNum = (String) request.getAttribute("order_id"); String * returnInfo = (String) request.getAttribute("return_info"); String * total_fee = (String) request.getAttribute("total_fee"); */ BigDecimal alipay = null; if ("".equals(total_fee) || total_fee == null) { LOG.error("total_fee is null"); } else { alipay = new BigDecimal(total_fee); } if (orderNum == null || returnInfo == null || alipay == null || orderNum.length() < 13 || !"success".equals(returnInfo)) { LOG.error("orderNum or retutnInfo or alipay is error"); return getCartPageRedirect(); } Long orderId; try { orderId = Long.parseLong(orderNum.substring(12)); } catch (NumberFormatException e) { LOG.error("substring orderNum throws an exception" + orderNum, e); return getCartPageRedirect(); } Order cart = orderService.findOrderById(orderId); if (cart != null && OrderStatus.IN_PROCESS.equals(cart.getStatus())) { if (alipay.compareTo(cart.getTotal().getAmount()) < 0) { billingForm.setAlipay(alipay); LOG.info("a part of the order is used alipay"); String ret = ""; try { ret = complexCheckout(request, response, model, billingForm, result, MyPaymentInfoType.Payment_Alipay, orderId); } catch (CheckoutException e) { if (e.getCause() instanceof InventoryUnavailableException) { LOG.info("InventoryUnavailableException so we pay balance to the customer"); return aplipayFailedRollBack2Banlance(alipay, cart); } else { LOG.info("not know exception", e); } } if (OrderStatus.IN_PROCESS.equals(cart.getStatus())) { return aplipayFailedRollBack2Banlance(alipay, cart); } else { LOG.info("alipay pay the part of the order is success"); return ret; } } copyShippingAddressToBillingAddress(cart, billingForm); billingInfoFormValidator.validate(billingForm, result); if (result.hasErrors()) { LOG.error("result.hasErrors() orderid=" + orderId); populateModelWithShippingReferenceData(request, model); return getCheckoutView(); } // ?? cart.getPaymentInfos().clear(); PaymentInfo alipayInfo = alipayPaymentInfoFactory.constructPaymentInfo(cart); alipayInfo.setAddress(billingForm.getMyAddress()); cart.getPaymentInfos().add(alipayInfo); AlipayPaymentInfo alipayReference = (AlipayPaymentInfo) alipaySecurePaymentInfoService .create(MyPaymentInfoType.Payment_Alipay); alipayReference.setMessage("success"); alipayReference.setReferenceNumber("try"); Map<PaymentInfo, Referenced> payments = new HashMap<PaymentInfo, Referenced>(1); payments.put(alipayInfo, alipayReference); CheckoutResponse checkoutResponse = null; try { checkoutResponse = checkoutService.performCheckout(cart, payments); } catch (CheckoutException e) { if (e.getCause() instanceof InventoryUnavailableException) { LOG.info("InventoryUnavailableException in all pay by alipay"); return aplipayFailedRollBack2Banlance(alipay, cart); } else { LOG.info("not know exception in all pay by alipay", e); } } if (!checkoutResponse.getPaymentResponse().getResponseItems().get(alipayInfo).getTransactionSuccess()) { LOG.error("alipay is finished but the order is not success because some problems"); // ???????? return aplipayFailedRollBack2Banlance(alipay, cart); } LOG.info("alipay success, the order is success order id=" + orderId); return getConfirmationView(cart.getOrderNumber()); } else { LOG.error("alipay failed, the order is not normal order invalid: id=" + orderId); if (cart != null) { LOG.error("alipay failed OrderStatus is " + cart.getStatus()); } } return getCartPageRedirect(); }
From source file:com.visionet.platform.cooperation.service.OrderService.java
public void payNotify(String orderNo, BigDecimal amount) { if (orderNo == null) { throw new BizException("?orderNo"); }//from w w w. ja va 2 s . c o m if (amount == null) { throw new BizException("?amount"); } if (amount.compareTo(BigDecimal.valueOf(0)) != 1) {//-1? 0 1 ???0?? throw new BizException("??0"); } Order order = orderMapper.selectByPrimaryKey(orderNo); if (order == null) { throw new BizException("??"); } String customerPhone = order.getCustomerPhone(); if (customerPhone != null) { Customer customer = customerMapper.selectByPrimaryKey(customerPhone); if (customer == null) { throw new BizException("?"); } Map<String, Object> map = new HashMap<>(); map.put("phone", customerPhone); map.put("userType", "2"); List<PushDes> pushDesList = pushDesMapper.selectByPhoneAndUserType(map); if (pushDesList == null || pushDesList.isEmpty()) { throw new BizException("?"); } PushDes pushDes = pushDesList.get(0); if (pushDes == null || StringUtils.isBlank(pushDes.getChannelId())) { throw new BizException("?"); } String channelId = pushDes.getChannelId(); BaseJson<JPushDto> JPushDtoJson = new BaseJson<JPushDto>(); JPushDto jPushdto = new JPushDto(); JSONObject contentJson = new JSONObject(); contentJson.put("type", "orderNeedPay"); contentJson.put("content", car_order_pay_with_app); contentJson.put("orderId", orderNo); contentJson.put("money", amount); jPushdto.setContent(contentJson); List<String> desList = new ArrayList<String>(); desList.add(channelId); jPushdto.setDes(desList); jPushdto.setAlert(car_order_pay_with_app); jPushdto.setTimeToLive(6000); jPushdto.setType(1);// 12? jPushdto.setUserType(2);// 1:?23:? jPushdto.setPushType(1);// 0?1?2tag? JPushDtoJson.setBody(jPushdto); push2socket(JPushDtoJson);// socket? } }
From source file:com.gst.portfolio.loanaccount.service.LoanApplicationWritePlatformServiceJpaRepositoryImpl.java
@Transactional @Override//w ww. j a va 2 s . c o m public CommandProcessingResult submitApplication(final JsonCommand command) { try { final AppUser currentUser = getAppUserIfPresent(); boolean isMeetingMandatoryForJLGLoans = configurationDomainService.isMeetingMandatoryForJLGLoans(); final Long productId = this.fromJsonHelper.extractLongNamed("productId", command.parsedJson()); final LoanProduct loanProduct = this.loanProductRepository.findOne(productId); if (loanProduct == null) { throw new LoanProductNotFoundException(productId); } final Long clientId = this.fromJsonHelper.extractLongNamed("clientId", command.parsedJson()); if (clientId != null) { Client client = this.clientRepository.findOneWithNotFoundDetection(clientId); officeSpecificLoanProductValidation(productId, client.getOffice().getId()); } final Long groupId = this.fromJsonHelper.extractLongNamed("groupId", command.parsedJson()); if (groupId != null) { Group group = this.groupRepository.findOneWithNotFoundDetection(groupId); officeSpecificLoanProductValidation(productId, group.getOffice().getId()); } this.fromApiJsonDeserializer.validateForCreate(command.json(), isMeetingMandatoryForJLGLoans, loanProduct); final List<ApiParameterError> dataValidationErrors = new ArrayList<>(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) .resource("loan"); if (loanProduct.useBorrowerCycle()) { Integer cycleNumber = 0; if (clientId != null) { cycleNumber = this.loanReadPlatformService.retriveLoanCounter(clientId, loanProduct.getId()); } else if (groupId != null) { cycleNumber = this.loanReadPlatformService.retriveLoanCounter(groupId, AccountType.GROUP.getValue(), loanProduct.getId()); } this.loanProductCommandFromApiJsonDeserializer.validateMinMaxConstraints(command.parsedJson(), baseDataValidator, loanProduct, cycleNumber); } else { this.loanProductCommandFromApiJsonDeserializer.validateMinMaxConstraints(command.parsedJson(), baseDataValidator, loanProduct); } if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } final Loan newLoanApplication = this.loanAssembler.assembleFrom(command, currentUser); validateSubmittedOnDate(newLoanApplication); final LoanProductRelatedDetail productRelatedDetail = newLoanApplication.repaymentScheduleDetail(); if (loanProduct.getLoanProductConfigurableAttributes() != null) { updateProductRelatedDetails(productRelatedDetail, newLoanApplication); } this.fromApiJsonDeserializer.validateLoanTermAndRepaidEveryValues(newLoanApplication.getTermFrequency(), newLoanApplication.getTermPeriodFrequencyType(), productRelatedDetail.getNumberOfRepayments(), productRelatedDetail.getRepayEvery(), productRelatedDetail.getRepaymentPeriodFrequencyType().getValue(), newLoanApplication); if (loanProduct.canUseForTopup() && clientId != null) { final Boolean isTopup = command.booleanObjectValueOfParameterNamed(LoanApiConstants.isTopup); if (null == isTopup) { newLoanApplication.setIsTopup(false); } else { newLoanApplication.setIsTopup(isTopup); } if (newLoanApplication.isTopup()) { final Long loanIdToClose = command.longValueOfParameterNamed(LoanApiConstants.loanIdToClose); final Loan loanToClose = this.loanRepositoryWrapper .findNonClosedLoanThatBelongsToClient(loanIdToClose, clientId); if (loanToClose == null) { throw new GeneralPlatformDomainRuleException( "error.msg.loan.loanIdToClose.no.active.loan.associated.to.client.found", "loanIdToClose is invalid, No Active Loan associated with the given Client ID found."); } if (loanToClose.isMultiDisburmentLoan() && !loanToClose.isInterestRecalculationEnabledForProduct()) { throw new GeneralPlatformDomainRuleException( "error.msg.loan.topup.on.multi.tranche.loan.without.interest.recalculation.not.supported", "Topup on loan with multi-tranche disbursal and without interest recalculation is not supported."); } final LocalDate disbursalDateOfLoanToClose = loanToClose.getDisbursementDate(); if (!newLoanApplication.getSubmittedOnDate().isAfter(disbursalDateOfLoanToClose)) { throw new GeneralPlatformDomainRuleException( "error.msg.loan.submitted.date.should.be.after.topup.loan.disbursal.date", "Submitted date of this loan application " + newLoanApplication.getSubmittedOnDate() + " should be after the disbursed date of loan to be closed " + disbursalDateOfLoanToClose); } if (!loanToClose.getCurrencyCode().equals(newLoanApplication.getCurrencyCode())) { throw new GeneralPlatformDomainRuleException( "error.msg.loan.to.be.closed.has.different.currency", "loanIdToClose is invalid, Currency code is different."); } final LocalDate lastUserTransactionOnLoanToClose = loanToClose.getLastUserTransactionDate(); if (!newLoanApplication.getDisbursementDate().isAfter(lastUserTransactionOnLoanToClose)) { throw new GeneralPlatformDomainRuleException( "error.msg.loan.disbursal.date.should.be.after.last.transaction.date.of.loan.to.be.closed", "Disbursal date of this loan application " + newLoanApplication.getDisbursementDate() + " should be after last transaction date of loan to be closed " + lastUserTransactionOnLoanToClose); } BigDecimal loanOutstanding = this.loanReadPlatformService .retrieveLoanPrePaymentTemplate(loanIdToClose, newLoanApplication.getDisbursementDate()) .getAmount(); final BigDecimal firstDisbursalAmount = newLoanApplication.getFirstDisbursalAmount(); if (loanOutstanding.compareTo(firstDisbursalAmount) > 0) { throw new GeneralPlatformDomainRuleException( "error.msg.loan.amount.less.than.outstanding.of.loan.to.be.closed", "Topup loan amount should be greater than outstanding amount of loan to be closed."); } final LoanTopupDetails topupDetails = new LoanTopupDetails(newLoanApplication, loanIdToClose); newLoanApplication.setTopupLoanDetails(topupDetails); } } this.loanRepositoryWrapper.save(newLoanApplication); if (loanProduct.isInterestRecalculationEnabled()) { this.fromApiJsonDeserializer.validateLoanForInterestRecalculation(newLoanApplication); createAndPersistCalendarInstanceForInterestRecalculation(newLoanApplication); } if (newLoanApplication.isAccountNumberRequiresAutoGeneration()) { final AccountNumberFormat accountNumberFormat = this.accountNumberFormatRepository .findByAccountType(EntityAccountType.LOAN); newLoanApplication.updateAccountNo( this.accountNumberGenerator.generate(newLoanApplication, accountNumberFormat)); this.loanRepositoryWrapper.save(newLoanApplication); } final String submittedOnNote = command.stringValueOfParameterNamed("submittedOnNote"); if (StringUtils.isNotBlank(submittedOnNote)) { final Note note = Note.loanNote(newLoanApplication, submittedOnNote); this.noteRepository.save(note); } // Save calendar instance final Long calendarId = command.longValueOfParameterNamed("calendarId"); Calendar calendar = null; if (calendarId != null && calendarId != 0) { calendar = this.calendarRepository.findOne(calendarId); if (calendar == null) { throw new CalendarNotFoundException(calendarId); } final CalendarInstance calendarInstance = new CalendarInstance(calendar, newLoanApplication.getId(), CalendarEntityType.LOANS.getValue()); this.calendarInstanceRepository.save(calendarInstance); } else { final LoanApplicationTerms loanApplicationTerms = this.loanScheduleAssembler .assembleLoanTerms(command.parsedJson()); final Integer repaymentFrequencyNthDayType = command .integerValueOfParameterNamed("repaymentFrequencyNthDayType"); if (loanApplicationTerms.getRepaymentPeriodFrequencyType() == PeriodFrequencyType.MONTHS && repaymentFrequencyNthDayType != null) { final String title = "loan_schedule_" + newLoanApplication.getId(); LocalDate calendarStartDate = loanApplicationTerms.getRepaymentsStartingFromLocalDate(); if (calendarStartDate == null) calendarStartDate = loanApplicationTerms.getExpectedDisbursementDate(); final CalendarFrequencyType calendarFrequencyType = CalendarFrequencyType.MONTHLY; final Integer frequency = loanApplicationTerms.getRepaymentEvery(); final Integer repeatsOnDay = loanApplicationTerms.getWeekDayType().getValue(); final Integer repeatsOnNthDayOfMonth = loanApplicationTerms.getNthDay(); final Integer calendarEntityType = CalendarEntityType.LOANS.getValue(); final Calendar loanCalendar = Calendar.createRepeatingCalendar(title, calendarStartDate, CalendarType.COLLECTION.getValue(), calendarFrequencyType, frequency, repeatsOnDay, repeatsOnNthDayOfMonth); this.calendarRepository.save(loanCalendar); final CalendarInstance calendarInstance = CalendarInstance.from(loanCalendar, newLoanApplication.getId(), calendarEntityType); this.calendarInstanceRepository.save(calendarInstance); } } // Save linked account information final Long savingsAccountId = command.longValueOfParameterNamed("linkAccountId"); if (savingsAccountId != null) { final SavingsAccount savingsAccount = this.savingsAccountAssembler.assembleFrom(savingsAccountId); this.fromApiJsonDeserializer.validatelinkedSavingsAccount(savingsAccount, newLoanApplication); boolean isActive = true; final AccountAssociations accountAssociations = AccountAssociations.associateSavingsAccount( newLoanApplication, savingsAccount, AccountAssociationType.LINKED_ACCOUNT_ASSOCIATION.getValue(), isActive); this.accountAssociationsRepository.save(accountAssociations); } if (command.parameterExists(LoanApiConstants.datatables)) { this.entityDatatableChecksWritePlatformService.saveDatatables( StatusEnum.CREATE.getCode().longValue(), EntityTables.LOAN.getName(), newLoanApplication.getId(), newLoanApplication.productId(), command.arrayOfParameterNamed(LoanApiConstants.datatables)); } this.entityDatatableChecksWritePlatformService.runTheCheckForProduct(newLoanApplication.getId(), EntityTables.LOAN.getName(), StatusEnum.CREATE.getCode().longValue(), EntityTables.LOAN.getForeignKeyColumnNameOnDatatable(), newLoanApplication.productId()); return new CommandProcessingResultBuilder() // .withCommandId(command.commandId()) // .withEntityId(newLoanApplication.getId()) // .withOfficeId(newLoanApplication.getOfficeId()) // .withClientId(newLoanApplication.getClientId()) // .withGroupId(newLoanApplication.getGroupId()) // .withLoanId(newLoanApplication.getId()) // .build(); } catch (final DataIntegrityViolationException dve) { handleDataIntegrityIssues(command, dve.getMostSpecificCause(), dve); return CommandProcessingResult.empty(); } catch (final PersistenceException dve) { Throwable throwable = ExceptionUtils.getRootCause(dve.getCause()); handleDataIntegrityIssues(command, throwable, dve); return CommandProcessingResult.empty(); } }
From source file:com.streamsets.pipeline.stage.origin.jdbc.cdc.oracle.OracleCDCSource.java
/** * Refresh the schema for the table if the last update of this table was before the given SCN. * Returns true if it was updated, else returns false. *///www. j av a 2 s. c o m private boolean refreshSchema(BigDecimal scnDecimal, SchemaAndTable schemaAndTable) throws SQLException { try { if (!tableSchemaLastUpdate.containsKey(schemaAndTable) || scnDecimal.compareTo(tableSchemaLastUpdate.get(schemaAndTable)) > 0) { if (containerized) { try (Statement switchToPdb = connection.createStatement()) { switchToPdb.execute("ALTER SESSION SET CONTAINER = " + configBean.pdb); } } tableSchemas.put(schemaAndTable, getTableSchema(schemaAndTable)); tableSchemaLastUpdate.put(schemaAndTable, scnDecimal); return true; } return false; } finally { alterSession(); } }