Search in sources :

Example 31 with BusinessRuleException

use of org.mifos.service.BusinessRuleException in project head by mifos.

the class ImportTransactionsServiceFacadeWebTier method undoFullImport.

@Override
public void undoFullImport(String importTransactionsFileName) {
    MifosUser mifosUser = (MifosUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    UserContext userContext = new UserContextFactory().create(mifosUser);
    TreeSet<String> accountsWithAdjustedPayments = new TreeSet<String>();
    try {
        ImportedFilesEntity filesEntity = this.importedFilesService.getImportedFileByName(importTransactionsFileName);
        List<AccountTrxnEntity> trxUndo = new ArrayList<AccountTrxnEntity>(filesEntity.getImportedTrxn());
        List<ImportedAccPaymentDto> accPaymentList = new ArrayList<ImportedAccPaymentDto>();
        for (AccountTrxnEntity trxn : trxUndo) {
            try {
                validateForAdjustedPayments(trxn, accountsWithAdjustedPayments);
                accPaymentList.add(new ImportedAccPaymentDto(trxn.getAccount().getGlobalAccountNum(), trxn.getAccountPayment().getPaymentId()));
            } catch (BusinessRuleException e) {
            //nothing to do   
            }
        }
        for (ImportedAccPaymentDto accDto : accPaymentList) {
            try {
                this.accountServiceFacade.applyHistoricalAdjustment(accDto.getGlobalNum(), accDto.getPaymentId(), IMPORT_UNDONE, userContext.getId(), null);
            } catch (MifosRuntimeException e) {
            // TODO: validation will be added with MIFOS-5779
            }
        }
        this.importedFilesService.saveImportedFileName(filesEntity.getFileName(), filesEntity.getSubmittedBy(), null, Boolean.TRUE, filesEntity.getUndoable());
    } catch (Exception e) {
        throw new MifosRuntimeException(e);
    }
}
Also used : UserContext(org.mifos.security.util.UserContext) ArrayList(java.util.ArrayList) MifosUser(org.mifos.security.MifosUser) UserContextFactory(org.mifos.accounts.servicefacade.UserContextFactory) ImportedFilesEntity(org.mifos.application.importexport.business.ImportedFilesEntity) BusinessRuleException(org.mifos.service.BusinessRuleException) MifosRuntimeException(org.mifos.core.MifosRuntimeException) AccountTrxnEntity(org.mifos.accounts.business.AccountTrxnEntity) BusinessRuleException(org.mifos.service.BusinessRuleException) TreeSet(java.util.TreeSet) MifosRuntimeException(org.mifos.core.MifosRuntimeException)

Example 32 with BusinessRuleException

use of org.mifos.service.BusinessRuleException in project head by mifos.

the class ImportTransactionsServiceFacadeWebTier method validateForAdjustedPayments.

private void validateForAdjustedPayments(AccountTrxnEntity trxn, TreeSet<String> accountsWithAdjustedPayments) {
    if (accountsWithAdjustedPayments.contains(trxn.getAccount().getGlobalAccountNum())) {
        throw new BusinessRuleException("errors.paymentsWereAdjusted");
    }
    Query query = StaticHibernateUtil.getSessionTL().getNamedQuery("countRelatedTransactions");
    query.setParameter("trxn_id", trxn.getAccountTrxnId().intValue());
    if (((BigInteger) query.uniqueResult()).intValue() > 0) {
        accountsWithAdjustedPayments.add(trxn.getAccount().getGlobalAccountNum());
        throw new BusinessRuleException("errors.paymentsWereAdjusted");
    }
}
Also used : BusinessRuleException(org.mifos.service.BusinessRuleException) Query(org.hibernate.Query)

Example 33 with BusinessRuleException

use of org.mifos.service.BusinessRuleException in project head by mifos.

the class WebTierAccountServiceFacade method applyGroupCharge.

@Override
public void applyGroupCharge(Map<Integer, String> idsAndValues, Short chargeId, boolean isPenaltyType) {
    MifosUser user = (MifosUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    UserContext userContext = toUserContext(user);
    TreeMap<Integer, String> idsAndValueAsTreeMap = new TreeMap<Integer, String>(idsAndValues);
    try {
        AccountBO parentAccount = ((LoanBO) legacyAccountDao.getAccount(new AccountBusinessService().getAccount(idsAndValueAsTreeMap.firstKey()).getAccountId())).getParentAccount();
        BigDecimal parentAmount = ((LoanBO) parentAccount).getLoanAmount().getAmount();
        BigDecimal membersAmount = BigDecimal.ZERO;
        for (Map.Entry<Integer, String> entry : idsAndValues.entrySet()) {
            LoanBO individual = loanDao.findById(entry.getKey());
            Double chargeAmount = Double.valueOf(entry.getValue());
            if (chargeAmount.equals(0.0)) {
                continue;
            }
            membersAmount = membersAmount.add(individual.getLoanAmount().getAmount());
            individual.updateDetails(userContext);
            if (isPenaltyType && !chargeId.equals(Short.valueOf(AccountConstants.MISC_PENALTY))) {
                PenaltyBO penalty = this.penaltyDao.findPenaltyById(chargeId.intValue());
                individual.addAccountPenalty(new AccountPenaltiesEntity(individual, penalty, chargeAmount));
            } else {
                individual.applyCharge(chargeId, chargeAmount);
            }
        }
        boolean isRateCharge = false;
        if (!chargeId.equals(Short.valueOf(AccountConstants.MISC_FEES)) && !chargeId.equals(Short.valueOf(AccountConstants.MISC_PENALTY))) {
            if (isPenaltyType) {
                PenaltyBO penalty = this.penaltyDao.findPenaltyById(chargeId.intValue());
                if (penalty instanceof RatePenaltyBO) {
                    isRateCharge = true;
                }
            } else {
                FeeBO fee = feeDao.findById(chargeId);
                if (fee.getFeeType().equals(RateAmountFlag.RATE)) {
                    isRateCharge = true;
                }
            }
        }
        Double chargeAmount = null;
        if (!isRateCharge) {
            chargeAmount = sumCharge(idsAndValues);
        } else {
            chargeAmount = Double.valueOf(idsAndValueAsTreeMap.firstEntry().getValue());
            BigDecimal chargeAmountBig = new BigDecimal(chargeAmount);
            membersAmount = membersAmount.multiply(chargeAmountBig);
            int scale = Money.getInternalPrecision();
            chargeAmountBig = membersAmount.divide(parentAmount, scale, RoundingMode.HALF_EVEN);
            chargeAmount = chargeAmountBig.doubleValue();
        }
        parentAccount.updateDetails(userContext);
        CustomerLevel customerLevel = null;
        if (parentAccount.isCustomerAccount()) {
            customerLevel = parentAccount.getCustomer().getLevel();
        }
        if (parentAccount.getPersonnel() != null) {
            checkPermissionForApplyCharges(parentAccount.getType(), customerLevel, userContext, parentAccount.getOffice().getOfficeId(), parentAccount.getPersonnel().getPersonnelId());
        } else {
            checkPermissionForApplyCharges(parentAccount.getType(), customerLevel, userContext, parentAccount.getOffice().getOfficeId(), userContext.getId());
        }
        this.transactionHelper.startTransaction();
        if (isPenaltyType && parentAccount instanceof LoanBO) {
            PenaltyBO penalty = this.penaltyDao.findPenaltyById(chargeId.intValue());
            ((LoanBO) parentAccount).addAccountPenalty(new AccountPenaltiesEntity(parentAccount, penalty, chargeAmount));
        } else {
            parentAccount.applyCharge(chargeId, chargeAmount);
        }
        this.transactionHelper.commitTransaction();
    } catch (ServiceException e) {
        this.transactionHelper.rollbackTransaction();
        throw new MifosRuntimeException(e);
    } catch (ApplicationException e) {
        this.transactionHelper.rollbackTransaction();
        throw new BusinessRuleException(e.getKey(), e);
    }
}
Also used : AccountPenaltiesEntity(org.mifos.accounts.business.AccountPenaltiesEntity) RatePenaltyBO(org.mifos.accounts.penalties.business.RatePenaltyBO) CustomerLevel(org.mifos.customers.api.CustomerLevel) PenaltyBO(org.mifos.accounts.penalties.business.PenaltyBO) RatePenaltyBO(org.mifos.accounts.penalties.business.RatePenaltyBO) UserContext(org.mifos.security.util.UserContext) LoanBO(org.mifos.accounts.loan.business.LoanBO) MifosUser(org.mifos.security.MifosUser) TreeMap(java.util.TreeMap) BigDecimal(java.math.BigDecimal) AccountBO(org.mifos.accounts.business.AccountBO) BusinessRuleException(org.mifos.service.BusinessRuleException) AccountBusinessService(org.mifos.accounts.business.service.AccountBusinessService) ApplicationException(org.mifos.framework.exceptions.ApplicationException) ServiceException(org.mifos.framework.exceptions.ServiceException) FeeBO(org.mifos.accounts.fees.business.FeeBO) RateFeeBO(org.mifos.accounts.fees.business.RateFeeBO) Map(java.util.Map) HashMap(java.util.HashMap) TreeMap(java.util.TreeMap) MifosRuntimeException(org.mifos.core.MifosRuntimeException)

Example 34 with BusinessRuleException

use of org.mifos.service.BusinessRuleException in project head by mifos.

the class SavingsServiceFacadeWebTier method postInterestForAccount.

private void postInterestForAccount(Integer savingsId, UserContext userContext, PersonnelBO createdBy, boolean inTransaction) {
    SavingsBO savingsAccount = this.savingsDao.findById(Long.valueOf(savingsId));
    savingsAccount.updateDetails(userContext);
    List<EndOfDayDetail> allEndOfDayDetailsForAccount = savingsDao.retrieveAllEndOfDayDetailsFor(savingsAccount.getCurrency(), Long.valueOf(savingsId));
    LocalDate interestPostingDate = new LocalDate(savingsAccount.getNextIntPostDate());
    InterestScheduledEvent postingSchedule = savingsInterestScheduledEventFactory.createScheduledEventFrom(savingsAccount.getInterestPostingMeeting());
    LocalDate startOfPeriod = postingSchedule.findFirstDateOfPeriodForMatchingDate(interestPostingDate);
    CalendarPeriod lastInterestPostingPeriod = new CalendarPeriod(startOfPeriod, interestPostingDate);
    InterestPostingPeriodResult interestPostingPeriodResult = determinePostingPeriodResult(lastInterestPostingPeriod, savingsAccount, allEndOfDayDetailsForAccount);
    savingsAccount.postInterest(postingSchedule, interestPostingPeriodResult, createdBy);
    StringBuilder postingInfoMessage = new StringBuilder().append("account id: ").append(savingsAccount.getAccountId()).append("posting interest: ").append(interestPostingPeriodResult);
    logger.info(postingInfoMessage.toString());
    try {
        if (!inTransaction) {
            this.transactionHelper.startTransaction();
        }
        this.savingsDao.save(savingsAccount);
        if (!inTransaction) {
            this.transactionHelper.commitTransaction();
        }
    } catch (Exception e) {
        if (!inTransaction) {
            this.transactionHelper.rollbackTransaction();
        }
        throw new BusinessRuleException(savingsAccount.getAccountId().toString(), e);
    } finally {
        if (!inTransaction) {
            this.transactionHelper.closeSession();
        }
    }
}
Also used : InterestPostingPeriodResult(org.mifos.accounts.savings.interest.InterestPostingPeriodResult) BusinessRuleException(org.mifos.service.BusinessRuleException) InterestScheduledEvent(org.mifos.accounts.savings.interest.schedule.InterestScheduledEvent) EndOfDayDetail(org.mifos.accounts.savings.interest.EndOfDayDetail) CalendarPeriod(org.mifos.accounts.savings.interest.CalendarPeriod) SavingsBO(org.mifos.accounts.savings.business.SavingsBO) LocalDate(org.joda.time.LocalDate) InvalidDateException(org.mifos.application.admin.servicefacade.InvalidDateException) MifosRuntimeException(org.mifos.core.MifosRuntimeException) StatesInitializationException(org.mifos.framework.exceptions.StatesInitializationException) AccountException(org.mifos.accounts.exceptions.AccountException) BusinessRuleException(org.mifos.service.BusinessRuleException) PersistenceException(org.mifos.framework.exceptions.PersistenceException) ServiceException(org.mifos.framework.exceptions.ServiceException) HibernateSearchException(org.mifos.framework.exceptions.HibernateSearchException) PageExpiredException(org.mifos.framework.exceptions.PageExpiredException)

Example 35 with BusinessRuleException

use of org.mifos.service.BusinessRuleException in project head by mifos.

the class SavingsServiceFacadeWebTier method adjustTransaction.

@Override
public PaymentDto adjustTransaction(SavingsAdjustmentDto savingsAdjustment, boolean inTransaction) {
    MifosUser user = (MifosUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    UserContext userContext = toUserContext(user);
    SavingsBO savingsAccount = this.savingsDao.findById(savingsAdjustment.getSavingsId());
    try {
        personnelDao.checkAccessPermission(userContext, savingsAccount.getOfficeId(), savingsAccount.getCustomer().getLoanOfficerId());
    } catch (AccountException e) {
        throw new MifosRuntimeException(e.getMessage(), e);
    }
    PersonnelBO updatedBy = this.personnelDao.findPersonnelById(userContext.getId());
    savingsAccount.updateDetails(userContext);
    Money amountAdjustedTo = new Money(savingsAccount.getCurrency(), BigDecimal.valueOf(savingsAdjustment.getAdjustedAmount()));
    AccountPaymentEntity adjustedPayment = savingsAccount.findPaymentById(savingsAdjustment.getPaymentId());
    PaymentDto otherTransferPayment = adjustedPayment.getOtherTransferPaymentDto();
    Money originalAmount = adjustedPayment.getAmount();
    LocalDate dateOfWithdrawal = savingsAdjustment.getTrxnDate();
    if (adjustedPayment.isSavingsWithdrawal() && originalAmount.isLessThan(amountAdjustedTo)) {
        Money addedWithdrawalAmount = amountAdjustedTo.subtract(originalAmount);
        if (withdrawalMakesBalanceNegative(savingsAccount, addedWithdrawalAmount, dateOfWithdrawal)) {
            throw new BusinessRuleException("errors.insufficentbalance", new String[] { savingsAccount.getGlobalAccountNum() });
        }
    } else if (adjustedPayment.isSavingsDeposit() && originalAmount.isGreaterThan(amountAdjustedTo)) {
        Money substractedAmount = originalAmount.subtract(amountAdjustedTo);
        if (withdrawalMakesBalanceNegative(savingsAccount, substractedAmount, dateOfWithdrawal)) {
            throw new BusinessRuleException("errors.insufficentbalance", new String[] { savingsAccount.getGlobalAccountNum() });
        }
    }
    try {
        if (!inTransaction) {
            this.transactionHelper.startTransaction();
        }
        this.transactionHelper.beginAuditLoggingFor(savingsAccount);
        AccountPaymentEntity newPayment = savingsAccount.adjustUserAction(amountAdjustedTo, savingsAdjustment.getNote(), savingsAdjustment.getTrxnDate(), updatedBy, savingsAdjustment.getPaymentId());
        recalculateInterestPostings(savingsAccount.getAccountId(), new LocalDate(adjustedPayment.getPaymentDate()));
        if (hasAccountNegativeBalance(savingsAccount)) {
            throw new BusinessRuleException("errors.insufficentbalance", new String[] { savingsAccount.getGlobalAccountNum() });
        }
        this.savingsDao.save(savingsAccount);
        // savings-savings transfer adjustment
        if (otherTransferPayment != null && otherTransferPayment.isSavingsPayment()) {
            this.transactionHelper.flushAndClearSession();
            SavingsBO otherSavingsAccount = this.savingsDao.findById(otherTransferPayment.getAccountId());
            otherSavingsAccount.updateDetails(userContext);
            AccountPaymentEntity newOtherTransferPayment = otherSavingsAccount.adjustUserAction(amountAdjustedTo, savingsAdjustment.getNote(), savingsAdjustment.getTrxnDate(), updatedBy, otherTransferPayment.getPaymentId());
            recalculateInterestPostings(savingsAccount.getAccountId(), new LocalDate(adjustedPayment.getPaymentDate()));
            if (hasAccountNegativeBalance(otherSavingsAccount)) {
                throw new BusinessRuleException("errors.insufficentbalance", new String[] { savingsAccount.getGlobalAccountNum() });
            }
            transactionHelper.flushAndClearSession();
            if (newPayment != null) {
                newPayment = savingsAccount.findPaymentById(newPayment.getPaymentId());
                newPayment.setOtherTransferPayment(newOtherTransferPayment);
                newOtherTransferPayment.setOtherTransferPayment(newPayment);
                legacyAcccountDao.updatePayment(newPayment);
            }
            this.savingsDao.save(otherSavingsAccount);
        }
        if (!inTransaction) {
            this.transactionHelper.commitTransaction();
        }
        return (newPayment == null) ? null : newPayment.toDto();
    } catch (BusinessRuleException e) {
        if (!inTransaction) {
            this.transactionHelper.rollbackTransaction();
        }
        throw new BusinessRuleException(e.getMessageKey(), e);
    } catch (Exception e) {
        if (!inTransaction) {
            this.transactionHelper.rollbackTransaction();
        }
        throw new MifosRuntimeException(e.getMessage(), e);
    } finally {
        if (!inTransaction) {
            this.transactionHelper.closeSession();
        }
    }
}
Also used : UserContext(org.mifos.security.util.UserContext) AccountPaymentEntity(org.mifos.accounts.business.AccountPaymentEntity) MifosUser(org.mifos.security.MifosUser) SavingsBO(org.mifos.accounts.savings.business.SavingsBO) AdjustableSavingsPaymentDto(org.mifos.dto.screen.AdjustableSavingsPaymentDto) PaymentDto(org.mifos.dto.domain.PaymentDto) LocalDate(org.joda.time.LocalDate) InvalidDateException(org.mifos.application.admin.servicefacade.InvalidDateException) MifosRuntimeException(org.mifos.core.MifosRuntimeException) StatesInitializationException(org.mifos.framework.exceptions.StatesInitializationException) AccountException(org.mifos.accounts.exceptions.AccountException) BusinessRuleException(org.mifos.service.BusinessRuleException) PersistenceException(org.mifos.framework.exceptions.PersistenceException) ServiceException(org.mifos.framework.exceptions.ServiceException) HibernateSearchException(org.mifos.framework.exceptions.HibernateSearchException) PageExpiredException(org.mifos.framework.exceptions.PageExpiredException) Money(org.mifos.framework.util.helpers.Money) BusinessRuleException(org.mifos.service.BusinessRuleException) AccountException(org.mifos.accounts.exceptions.AccountException) PersonnelBO(org.mifos.customers.personnel.business.PersonnelBO) MifosRuntimeException(org.mifos.core.MifosRuntimeException)

Aggregations

BusinessRuleException (org.mifos.service.BusinessRuleException)140 MifosRuntimeException (org.mifos.core.MifosRuntimeException)68 UserContext (org.mifos.security.util.UserContext)63 MifosUser (org.mifos.security.MifosUser)61 AccountException (org.mifos.accounts.exceptions.AccountException)46 PersistenceException (org.mifos.framework.exceptions.PersistenceException)43 ApplicationException (org.mifos.framework.exceptions.ApplicationException)33 LocalDate (org.joda.time.LocalDate)31 ServiceException (org.mifos.framework.exceptions.ServiceException)30 PersonnelBO (org.mifos.customers.personnel.business.PersonnelBO)26 ArrayList (java.util.ArrayList)23 CustomerBO (org.mifos.customers.business.CustomerBO)22 Money (org.mifos.framework.util.helpers.Money)22 UserContextFactory (org.mifos.accounts.servicefacade.UserContextFactory)20 CustomerException (org.mifos.customers.exceptions.CustomerException)19 LoanBO (org.mifos.accounts.loan.business.LoanBO)18 SavingsBO (org.mifos.accounts.savings.business.SavingsBO)16 InvalidDateException (org.mifos.application.admin.servicefacade.InvalidDateException)16 MeetingException (org.mifos.application.meeting.exceptions.MeetingException)16 PageExpiredException (org.mifos.framework.exceptions.PageExpiredException)16