Example usage for java.math BigDecimal subtract

List of usage examples for java.math BigDecimal subtract

Introduction

In this page you can find the example usage for java.math BigDecimal subtract.

Prototype

public BigDecimal subtract(BigDecimal subtrahend) 

Source Link

Document

Returns a BigDecimal whose value is (this - subtrahend) , and whose scale is max(this.scale(), subtrahend.scale()) .

Usage

From source file:org.egov.works.web.actions.estimate.EstimatePDFGenerator.java

private PdfPTable createDepositAppropriationTable(final AbstractEstimate estimate,
        final String appropriationNumber) throws DocumentException {
    int isReject = -1;
    depositWorksUsageService = abstractEstimateService.getDepositWorksUsageService();
    BigDecimal totalUtilizedAmt;
    BigDecimal amtAppropriatedsofar;
    BigDecimal totalDepositAmt;/*from   w w  w  . j  av a 2  s. c o  m*/
    BigDecimal balOnHand;
    BigDecimal balanceAvailable;
    BigDecimal amtAppropriated;
    final Accountdetailtype accountdetailtype = worksService.getAccountdetailtypeByName("DEPOSITCODE");
    estimateAppropriationService = abstractEstimateService.getEstimateAppropriationService();
    abstractEstimateAppropriationList = estimateAppropriationService.findAllBy(
            "from AbstractEstimateAppropriation aea where aea.abstractEstimate.id=? and aea.depositWorksUsage.id is not null order by id, aea.depositWorksUsage.financialYearId asc",
            estimate.getId());
    final PdfPTable depositWorksAppropriationTable = new PdfPTable(2);
    depositWorksAppropriationTable.setWidthPercentage(100);
    depositWorksAppropriationTable.setWidths(new float[] { 2f, 8f });

    if (appropriationNumber != null && appropriationNumber.toUpperCase().contains("BC"))
        isReject = 1;

    if (appropriationNumber != null && estimate.getTotalAmount() != null && isReject == -1) {
        addRow(depositWorksAppropriationTable, true, centerPara("Deposit Code"),
                centerPara(estimate.getDepositCode().getCode()));
        addRow(depositWorksAppropriationTable, true, centerPara("Account Code"),
                centerPara(estimate.getFinancialDetails().get(0).getCoa().getGlcode() + "-"
                        + estimate.getFinancialDetails().get(0).getCoa().getName()));
        addRow(depositWorksAppropriationTable, true, makePara("Function Center"),
                centerPara(estimate.getFinancialDetails().get(0).getFunction().getName()));
        addRow(depositWorksAppropriationTable, true, makePara("Department"),
                centerPara(estimate.getUserDepartment().getName()));
        addRow(depositWorksAppropriationTable, true, makePara("Amount of the Estimate "),
                rightPara(toCurrency(estimate.getTotalAmount())));
        final PdfPTable appropriationDetailTable = new PdfPTable(6);
        addRow(appropriationDetailTable, true, makePara(7f, "Appropriation Number"),
                makePara(7f, "Total Deposit Amount"), makePara(7f, "Amount Appropriated so far"),
                makePara(7f, "Amount Appropriated"), makePara(7f, "Balance on Hand"),
                makePara(7f, "Balance After Appropriation"));
        for (final AbstractEstimateAppropriation abstractEstimateAppropriation : abstractEstimateAppropriationList)
            if (abstractEstimateAppropriation.getDepositWorksUsage().getConsumedAmount().doubleValue() != 0) {
                totalDepositAmt = depositWorksUsageService.getTotalDepositWorksAmount(
                        estimate.getDepositCode().getFund(),
                        abstractEstimateAppropriation.getAbstractEstimate().getFinancialDetails().get(0)
                                .getCoa(),
                        accountdetailtype, estimate.getDepositCode().getId(),
                        abstractEstimateAppropriation.getDepositWorksUsage().getAppropriationDate());
                totalUtilizedAmt = depositWorksUsageService.getTotalUtilizedAmountForDepositWorks(
                        abstractEstimateAppropriation.getAbstractEstimate().getFinancialDetails().get(0),
                        abstractEstimateAppropriation.getDepositWorksUsage().getCreatedDate());
                if (totalUtilizedAmt == null)
                    totalUtilizedAmt = BigDecimal.ZERO;
                amtAppropriatedsofar = totalUtilizedAmt
                        .subtract(abstractEstimateAppropriation.getDepositWorksUsage().getConsumedAmount());
                balOnHand = totalDepositAmt.subtract(amtAppropriatedsofar);
                amtAppropriated = abstractEstimateAppropriation.getDepositWorksUsage().getConsumedAmount();
                balanceAvailable = BigDecimal
                        .valueOf(totalDepositAmt.doubleValue() - totalUtilizedAmt.doubleValue());
                addRow(appropriationDetailTable, true,
                        makePara(7f,
                                abstractEstimateAppropriation.getDepositWorksUsage().getAppropriationNumber()),
                        rightPara(7f, toCurrency(totalDepositAmt.doubleValue())),
                        rightPara(7f, toCurrency(amtAppropriatedsofar.doubleValue())),
                        rightPara(7f, toCurrency(amtAppropriated.doubleValue())),
                        rightPara(7f, toCurrency(balOnHand.doubleValue())),
                        rightPara(7f, toCurrency(balanceAvailable.doubleValue())));
            }

        final PdfPCell appDetailpdfCell = new PdfPCell(appropriationDetailTable);
        appDetailpdfCell.setBorderWidth(0);

        final PdfPCell appDetailRightHeader = new PdfPCell(
                makePara("Financail Year Wise Appropriation Details"));
        appDetailRightHeader.setVerticalAlignment(Element.ALIGN_MIDDLE);

        depositWorksAppropriationTable.addCell(appDetailRightHeader);
        appropriationDetailTable.setWidthPercentage(100);
        depositWorksAppropriationTable.addCell(appDetailpdfCell);
    }
    return depositWorksAppropriationTable;
}

From source file:org.efaps.esjp.accounting.util.data.ImportDetails.java

protected List<Document> checkAccounts(final Parameter _parameter, final File _file,
        final Map<String, Instance> _docMap, final DateTime _date, final Boolean _inverse)
        throws IOException, EFapsException {
    final List<Document> ret = new ArrayList<>();
    final CSVReader reader = new CSVReader(new InputStreamReader(new FileInputStream(_file), "UTF-8"));
    final List<String[]> entries = reader.readAll();
    reader.close();/*from  w  ww .  j  av a  2s .c o  m*/
    entries.remove(0);
    int i = 1;
    final Map<String, Document> map = new HashMap<>();
    for (final String[] row : entries) {
        i++;
        final String docNumber = row[0];
        final String ruc = row[1];
        final String dateStr = row[2];
        final String accountStr = row[5];
        final String accountDesc = row[4];
        final DecimalFormat formater = (DecimalFormat) NumberFormat.getInstance(Locale.GERMAN);
        formater.setParseBigDecimal(true);
        final String amountMEStr = row[6];
        final String amountMNStr = row[7];

        final QueryBuilder queryBldr = new QueryBuilder(CIAccounting.AccountAbstract);
        queryBldr.addWhereAttrEqValue(CIAccounting.AccountAbstract.Name, accountStr.trim());
        final InstanceQuery query = queryBldr.getQuery();
        query.executeWithoutAccessCheck();
        if (query.next()) {
            ImportDetails.LOG.info("Found account: '{}' ", accountStr);
            final String[] docSplit = docNumber.split("-");
            if (docSplit.length != 2 && _docMap != null) {
                ImportDetails.LOG.warn(
                        "Document '{}'  - Line: {} has no '-' to distinguish SerialNumber and No.", docNumber,
                        i);
            } else {
                try {
                    final Formatter criteria = new Formatter();
                    String name = docNumber;
                    if (_docMap != null) {
                        final String serialNo = docSplit[0];
                        final String docNo = docSplit[1];
                        final int serial = Integer.parseInt(serialNo.trim().replaceAll("\\D", ""));
                        final int no = Integer.parseInt(docNo.trim().replaceAll("\\D", ""));
                        criteria.format("%03d-%06d", serial, no);
                        name = criteria.toString();
                    }

                    Document doc;
                    if (map.containsKey(name)) {
                        doc = map.get(name);
                    } else {
                        if (_docMap != null && _docMap.containsKey(name)) {
                            doc = new Document(name, _docMap.get(name), ruc, dateStr, accountDesc);
                        } else {
                            doc = new Document(name, null, ruc, dateStr, accountDesc);
                        }
                    }

                    BigDecimal amountME = (BigDecimal) formater.parse(amountMEStr);
                    BigDecimal amountMN = (BigDecimal) formater.parse(amountMNStr);

                    if (_inverse) {
                        amountME = amountME.negate();
                        amountMN = amountMN.negate();
                    }

                    if (amountMN.compareTo(BigDecimal.ZERO) >= 0) {
                        doc.addAmountMECredit(amountME);
                        doc.addAmountMNCredit(amountMN);
                    } else {
                        doc.addAmountMEDebit(amountME);
                        doc.addAmountMNDebit(amountMN);
                    }

                    final Map<String, Account> accounts = doc.getAccounts();
                    Account acc;
                    if (accounts.containsKey(accountStr)) {
                        acc = accounts.get(accountStr);
                    } else {
                        acc = new Account(accountStr, accountDesc);
                        accounts.put(accountStr, acc);
                    }
                    acc.addAmountME(amountME);
                    acc.addAmountMN(amountMN);
                    acc.setInstance(query.getCurrentValue());

                    map.put(name, doc);

                    criteria.close();
                } catch (final NumberFormatException e) {
                    ImportDetails.LOG.error("wrong format for document '{}'", docNumber);
                } catch (final ParseException e) {
                    ImportDetails.LOG.error("wrong format for amounts '{}' - '{}'", amountMEStr, amountMNStr);
                }
            }
        } else {
            ImportDetails.LOG.error("Not found account: {}", accountStr);
        }
    }

    final Instance periodInst = getPeriodInstance();
    for (final Document doc : map.values()) {
        final BigDecimal amountCreditMN = doc.getAmountMNCredit() != null ? doc.getAmountMNCredit()
                : BigDecimal.ZERO;
        final BigDecimal amountDebitMN = doc.getAmountMNDebit() != null ? doc.getAmountMNDebit()
                : BigDecimal.ZERO;
        final BigDecimal amountMN = amountCreditMN.add(amountDebitMN);
        final BigDecimal amountCreditME = doc.getAmountMECredit() != null ? doc.getAmountMECredit()
                : BigDecimal.ZERO;
        final BigDecimal amountDebitME = doc.getAmountMEDebit() != null ? doc.getAmountMEDebit()
                : BigDecimal.ZERO;
        final BigDecimal amountME = amountCreditME.add(amountDebitME);
        if (BigDecimal.ZERO.compareTo(amountMN) == 0 && BigDecimal.ZERO.compareTo(amountME) == 0) {
            ImportDetails.LOG.info(
                    "For Document: '{}'. Sum of Credit with Debit Amount (ME): '{}' + '{}' and Credit with Debit Amount (MN): '{}' + '{}' are Zero (0)",
                    doc.getName(), amountCreditME, amountDebitME, amountCreditMN, amountDebitMN);
        } else {
            ImportDetails.LOG.error(
                    "For Document: '{}'. Sum of Credit with Debit Amount (ME): '{}' + '{}' = '{}' and Credit with Debit Amount (MN): '{}' + '{}' = '{}'",
                    doc.getName(), amountCreditME, amountDebitME, amountME, amountCreditMN, amountDebitMN,
                    amountMN);
        }

        final Insert insert = new Insert(CIAccounting.TransactionOpeningBalance);
        insert.add(CIAccounting.TransactionOpeningBalance.Date, _date);
        final StringBuilder descBldr = new StringBuilder()
                .append(doc.getInstance() != null ? doc.getInstance().getType().getLabel() : "Sin Documento")
                .append(": ").append(doc.getName()).append(" - RUC: ").append(doc.getRuc()).append(" - ")
                .append(doc.getDate()).append(" - ").append(doc.getDesc());

        insert.add(CIAccounting.TransactionOpeningBalance.Description, descBldr.toString());
        insert.add(CIAccounting.TransactionOpeningBalance.Status,
                Status.find(CIAccounting.TransactionStatus.Open));
        insert.add(CIAccounting.TransactionOpeningBalance.PeriodLink, periodInst);
        insert.executeWithoutAccessCheck();

        if (_docMap != null) {
            final Instance instance = insert.getInstance();
            new Create().connectDocs2Transaction(_parameter, instance, doc.getInstance());
        }

        final Map<String, Account> accounts = doc.getAccounts();
        final Instance basCur = Currency.getBaseCurrency();
        for (final Account acc : accounts.values()) {
            final Insert insertpos = new Insert(
                    acc.getAmountMN().compareTo(BigDecimal.ZERO) > 0 ? CIAccounting.TransactionPositionCredit
                            : CIAccounting.TransactionPositionDebit);
            insertpos.add(CIAccounting.TransactionPositionAbstract.AccountLink, acc.getInstance());
            insertpos.add(CIAccounting.TransactionPositionAbstract.Amount, acc.getAmountMN());
            insertpos.add(CIAccounting.TransactionPositionAbstract.CurrencyLink, basCur);
            insertpos.add(CIAccounting.TransactionPositionAbstract.Rate, acc.getRateObject());
            insertpos.add(CIAccounting.TransactionPositionAbstract.RateAmount, acc.getAmountME());
            insertpos.add(CIAccounting.TransactionPositionAbstract.RateCurrencyLink, 1);
            insertpos.add(CIAccounting.TransactionPositionAbstract.TransactionLink, insert.getInstance());
            insertpos.executeWithoutAccessCheck();
        }

        if (amountCreditMN.compareTo(amountDebitMN.abs()) != 0
                && amountCreditMN.subtract(amountDebitMN.abs()).abs().compareTo(new BigDecimal("0.05")) <= 0) {
            Insert insertpos = null;
            Account acc = null;
            if (amountCreditMN.compareTo(amountDebitMN.abs()) > 0) {
                acc = getRoundingAccount(AccountingSettings.PERIOD_ROUNDINGDEBIT);
                acc.addAmountMN(amountCreditMN.subtract(amountDebitMN.abs()).negate());
                acc.addAmountME(amountCreditME.subtract(amountDebitME.abs()).negate());
                insertpos = new Insert(CIAccounting.TransactionPositionDebit);
            } else {
                acc = getRoundingAccount(AccountingSettings.PERIOD_ROUNDINGCREDIT);
                acc.addAmountMN(amountDebitMN.abs().subtract(amountCreditMN));
                acc.addAmountME(amountDebitME.abs().subtract(amountCreditME));
                insertpos = new Insert(CIAccounting.TransactionPositionCredit);
            }
            insertpos.add(CIAccounting.TransactionPositionAbstract.AccountLink, acc.getInstance());
            insertpos.add(CIAccounting.TransactionPositionAbstract.Amount, acc.getAmountMN());
            insertpos.add(CIAccounting.TransactionPositionAbstract.CurrencyLink, basCur);
            insertpos.add(CIAccounting.TransactionPositionAbstract.Rate, acc.getRateObject());
            insertpos.add(CIAccounting.TransactionPositionAbstract.RateAmount, acc.getAmountME());
            insertpos.add(CIAccounting.TransactionPositionAbstract.RateCurrencyLink, 1);
            insertpos.add(CIAccounting.TransactionPositionAbstract.TransactionLink, insert.getInstance());
            insertpos.executeWithoutAccessCheck();
        } else if (amountCreditMN.compareTo(amountDebitMN.abs()) != 0
                && amountCreditMN.subtract(amountDebitMN.abs()).abs().compareTo(new BigDecimal("0.05")) > 0) {
            Insert insertpos = null;
            final Account acc = getRoundingAccount(AccountingSettings.PERIOD_TRANSFERACCOUNT);
            ;
            if (amountCreditMN.compareTo(amountDebitMN.abs()) > 0) {
                acc.addAmountMN(amountCreditMN.subtract(amountDebitMN.abs()).negate());
                acc.addAmountME(amountCreditME.subtract(amountDebitME.abs()).negate());
                insertpos = new Insert(CIAccounting.TransactionPositionDebit);
            } else {
                acc.addAmountMN(amountDebitMN.abs().subtract(amountCreditMN));
                acc.addAmountME(amountDebitME.abs().subtract(amountCreditME));
                insertpos = new Insert(CIAccounting.TransactionPositionCredit);
            }
            insertpos.add(CIAccounting.TransactionPositionAbstract.AccountLink, acc.getInstance());
            insertpos.add(CIAccounting.TransactionPositionAbstract.Amount, acc.getAmountMN());
            insertpos.add(CIAccounting.TransactionPositionAbstract.CurrencyLink, basCur);
            insertpos.add(CIAccounting.TransactionPositionAbstract.Rate, acc.getRateObject());
            insertpos.add(CIAccounting.TransactionPositionAbstract.RateAmount, acc.getAmountME());
            insertpos.add(CIAccounting.TransactionPositionAbstract.RateCurrencyLink, 1);
            insertpos.add(CIAccounting.TransactionPositionAbstract.TransactionLink, insert.getInstance());
            insertpos.executeWithoutAccessCheck();
        }
    }

    return ret;
}

From source file:com.lp.server.lieferschein.ejbfac.LieferscheinFacBean.java

private BigDecimal berechneWertMitZuUndAbschlaegenAusKonditionen(BigDecimal bdWertI, Integer iIdLieferscheinI,
        TheClientDto theClientDto) throws EJBExceptionLP {
    LieferscheinDto oDto = lieferscheinFindByPrimaryKey(iIdLieferscheinI, theClientDto);

    // zuerst den versteckten Aufschlag aufschlagen ...
    if (oDto.getFVersteckterAufschlag().doubleValue() != (double) 0) {
        BigDecimal versteckterAufschlag = bdWertI
                .multiply(new BigDecimal(oDto.getFVersteckterAufschlag().doubleValue()).movePointLeft(2));
        versteckterAufschlag = Helper.rundeKaufmaennisch(versteckterAufschlag, 4);
        bdWertI = bdWertI.add(versteckterAufschlag);
    }/* ww w . j  ava 2 s  .  c  om*/

    // dann den rabatt beruecksichtigen ...
    if (oDto.getFAllgemeinerRabattsatz().doubleValue() != (double) 0) {
        BigDecimal allgRabatt = bdWertI
                .multiply(new BigDecimal(oDto.getFAllgemeinerRabattsatz().doubleValue()).movePointLeft(2));
        allgRabatt = Helper.rundeKaufmaennisch(allgRabatt, 4);
        bdWertI = bdWertI.subtract(allgRabatt);
    }

    return bdWertI;
}

From source file:com.lp.server.auftrag.ejbfac.AuftragFacBean.java

@Override
public void berechneBeleg(Integer iIdAuftragI, TheClientDto theClientDto)
        throws EJBExceptionLP, RemoteException {
    Auftrag oAuftrag = em.find(Auftrag.class, iIdAuftragI);
    myLogger.entry();/*from   www  .j  a va2 s. c om*/

    if (oAuftrag.getAuftragstatusCNr().equals(AuftragServiceFac.AUFTRAGSTATUS_ANGELEGT)) {

        BigDecimal bdAuftragswertInAuftragswaehrung = berechneNettowertGesamt(oAuftrag.getIId(), theClientDto); // Berechnung in
        // Auftragswaehrung

        if (oAuftrag.getNKorrekturbetrag() != null) {
            bdAuftragswertInAuftragswaehrung = bdAuftragswertInAuftragswaehrung
                    .add(oAuftrag.getNKorrekturbetrag());
        }

        BigDecimal bdWechselkurs = Helper.getKehrwert(
                new BigDecimal(oAuftrag.getFWechselkursmandantwaehrungzuauftragswaehrung().doubleValue()));
        BigDecimal bdAuftragswertInMandantenwaehrung = bdAuftragswertInAuftragswaehrung.multiply(bdWechselkurs);
        bdAuftragswertInMandantenwaehrung = Helper.rundeKaufmaennisch(bdAuftragswertInMandantenwaehrung, 4);
        checkNumberFormat(bdAuftragswertInMandantenwaehrung);

        BigDecimal bdMaterialwertInMandantenwaehrung = berechneMaterialwertGesamt(oAuftrag.getIId(),
                theClientDto); // in
        // Mandantenwaehrung

        oAuftrag.setNGesamtauftragswertinauftragswaehrung(bdAuftragswertInAuftragswaehrung);
        oAuftrag.setNMaterialwertinmandantenwaehrung(bdMaterialwertInMandantenwaehrung);

        BigDecimal bdRohdeckungInMandantenwaehrung = bdAuftragswertInMandantenwaehrung
                .subtract(bdMaterialwertInMandantenwaehrung);

        bdRohdeckungInMandantenwaehrung = Helper.rundeKaufmaennisch(bdRohdeckungInMandantenwaehrung, 4);
        checkNumberFormat(bdRohdeckungInMandantenwaehrung);
        if (oAuftrag.getNRohdeckungaltinmandantenwaehrung() == null) {
            oAuftrag.setNRohdeckunginmandantenwaehrung(bdRohdeckungInMandantenwaehrung);
            oAuftrag.setNRohdeckungaltinmandantenwaehrung(bdRohdeckungInMandantenwaehrung);
        }
        em.merge(oAuftrag);
        em.flush();

    }
}

From source file:org.kuali.ole.module.purap.service.impl.PurapAccountingServiceImpl.java

/**
 * @see org.kuali.ole.module.purap.service.PurapAccountingService#generateAccountDistributionForProration(java.util.List,
 *      org.kuali.rice.kns.util.KualiDecimal, java.lang.Integer)
 *//*w  ww . j  a va  2 s .co  m*/
@Override
public List<PurApAccountingLine> generateAccountDistributionForProration(List<SourceAccountingLine> accounts,
        KualiDecimal totalAmount, Integer percentScale, Class clazz) {
    String methodName = "generateAccountDistributionForProration()";
    if (LOG.isDebugEnabled()) {
        LOG.debug(methodName + " started");
    }
    List<PurApAccountingLine> newAccounts = new ArrayList();

    if (totalAmount.isZero()) {
        throwRuntimeException(methodName,
                "Purchasing/Accounts Payable account distribution for proration does not allow zero dollar total.");
    }

    BigDecimal percentTotal = BigDecimal.ZERO;
    BigDecimal totalAmountBigDecimal = totalAmount.bigDecimalValue();
    for (SourceAccountingLine accountingLine : accounts) {
        KualiDecimal amt = KualiDecimal.ZERO;
        if (ObjectUtils.isNotNull(accountingLine.getAmount())) {
            amt = accountingLine.getAmount();
        }

        if (LOG.isDebugEnabled()) {
            LOG.debug(methodName + " " + accountingLine.getAccountNumber() + " " + amt + "/"
                    + totalAmountBigDecimal);
        }
        BigDecimal pct = amt.bigDecimalValue().divide(totalAmountBigDecimal, percentScale,
                BIG_DECIMAL_ROUNDING_MODE);
        pct = pct.stripTrailingZeros().multiply(ONE_HUNDRED);

        if (LOG.isDebugEnabled()) {
            LOG.debug(methodName + " pct = " + pct + "  (trailing zeros removed)");
        }

        BigDecimal lowestPossible = this.getLowestPossibleRoundUpNumber();
        if (lowestPossible.compareTo(pct) <= 0) {
            PurApAccountingLine newAccountingLine;
            newAccountingLine = null;

            try {
                newAccountingLine = (PurApAccountingLine) clazz.newInstance();
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }

            PurApObjectUtils.populateFromBaseClass(AccountingLineBase.class, accountingLine, newAccountingLine);
            newAccountingLine.setAccountLinePercent(pct);
            if (LOG.isDebugEnabled()) {
                LOG.debug(methodName + " adding " + newAccountingLine.getAccountLinePercent());
            }
            newAccounts.add(newAccountingLine);
            percentTotal = percentTotal.add(newAccountingLine.getAccountLinePercent());
            if (LOG.isDebugEnabled()) {
                LOG.debug(methodName + " total = " + percentTotal);
            }
        }
    }

    if ((percentTotal.compareTo(BigDecimal.ZERO)) == 0) {
        /*
         * This means there are so many accounts or so strange a distribution that we can't round properly... not sure of viable
         * solution
         */
        throwRuntimeException(methodName, "Can't round properly due to number of accounts");
    }

    // Now deal with rounding
    if ((ONE_HUNDRED.compareTo(percentTotal)) < 0) {
        /*
         * The total percent is greater than one hundred Here we find the account that occurs latest in our list with a percent
         * that is higher than the difference and we subtract off the difference
         */
        BigDecimal difference = percentTotal.subtract(ONE_HUNDRED);
        if (LOG.isDebugEnabled()) {
            LOG.debug(methodName + " Rounding up by " + difference);
        }

        boolean foundAccountToUse = false;
        int currentNbr = newAccounts.size() - 1;
        while (currentNbr >= 0) {
            PurApAccountingLine potentialSlushAccount = newAccounts.get(currentNbr);

            BigDecimal linePercent = BigDecimal.ZERO;
            if (ObjectUtils.isNotNull(potentialSlushAccount.getAccountLinePercent())) {
                linePercent = potentialSlushAccount.getAccountLinePercent();
            }

            if ((difference.compareTo(linePercent)) < 0) {
                // the difference amount is less than the current accounts percent... use this account
                // the 'potentialSlushAccount' technically is now the true 'Slush Account'
                potentialSlushAccount.setAccountLinePercent(linePercent.subtract(difference).movePointLeft(2)
                        .stripTrailingZeros().movePointRight(2));
                foundAccountToUse = true;
                break;
            }
            currentNbr--;
        }

        if (!foundAccountToUse) {
            /*
             * We could not find any account in our list where the percent of that account was greater than that of the
             * difference... doing so on just any account could result in a negative percent value
             */
            throwRuntimeException(methodName, "Can't round properly due to math calculation error");
        }

    } else if ((ONE_HUNDRED.compareTo(percentTotal)) > 0) {
        /*
         * The total percent is less than one hundred Here we find the last account in our list and add the remaining required
         * percent to its already calculated percent
         */
        BigDecimal difference = ONE_HUNDRED.subtract(percentTotal);
        if (LOG.isDebugEnabled()) {
            LOG.debug(methodName + " Rounding down by " + difference);
        }
        PurApAccountingLine slushAccount = newAccounts.get(newAccounts.size() - 1);

        BigDecimal slushLinePercent = BigDecimal.ZERO;
        if (ObjectUtils.isNotNull(slushAccount.getAccountLinePercent())) {
            slushLinePercent = slushAccount.getAccountLinePercent();
        }

        slushAccount.setAccountLinePercent(
                slushLinePercent.add(difference).movePointLeft(2).stripTrailingZeros().movePointRight(2));
    }
    if (LOG.isDebugEnabled()) {
        LOG.debug(methodName + " ended");
    }
    return newAccounts;
}

From source file:org.egov.ptis.domain.service.property.PropertyExternalService.java

public ReceiptDetails payPropertyTax(final PayPropertyTaxDetails payPropertyTaxDetails, String propertyType) {
    ReceiptDetails receiptDetails = null;
    ErrorDetails errorDetails;/*w  w  w.  j  ava 2s  . c o m*/
    BigDecimal totalAmountToBePaid = BigDecimal.ZERO;
    final BasicProperty basicProperty = basicPropertyDAO
            .getBasicPropertyByPropertyID(payPropertyTaxDetails.getAssessmentNo());
    if (propertyType.equalsIgnoreCase(OWNERSHIP_TYPE_VAC_LAND))
        propertyTaxBillable.setVacantLandTaxPayment(true);

    propertyTaxBillable.setBasicProperty(basicProperty);
    propertyTaxBillable.setReferenceNumber(propertyTaxNumberGenerator
            .generateBillNumber(basicProperty.getPropertyID().getWard().getBoundaryNum().toString()));
    propertyTaxBillable.setBillType(egBillDAO.getBillTypeByCode(BILLTYPE_AUTO));
    propertyTaxBillable.setLevyPenalty(Boolean.TRUE);
    propertyTaxBillable.setTransanctionReferenceNumber(payPropertyTaxDetails.getTransactionId());
    final EgBill egBill = ptBillServiceImpl.generateBill(propertyTaxBillable);

    for (EgBillDetails billDetails : egBill.getEgBillDetails()) {
        if (!(billDetails.getDescription().contains(PropertyTaxConstants.DEMANDRSN_STR_ADVANCE)
                || billDetails.getDescription().contains(PropertyTaxConstants.DEMANDRSN_CODE_REBATE))
                && billDetails.getCrAmount().compareTo(BigDecimal.ZERO) > 0) {
            totalAmountToBePaid = totalAmountToBePaid.add(billDetails.getCrAmount());
        } else if (billDetails.getDescription().contains(PropertyTaxConstants.DEMANDRSN_CODE_REBATE)) {
            totalAmountToBePaid = totalAmountToBePaid.subtract(billDetails.getDrAmount());
        }
    }

    final CollectionHelper collectionHelper = new CollectionHelper(egBill);
    final Map<String, String> paymentDetailsMap = new HashMap<>();
    paymentDetailsMap.put(TOTAL_AMOUNT, payPropertyTaxDetails.getPaymentAmount().toString());
    paymentDetailsMap.put(PAID_BY, payPropertyTaxDetails.getPaidBy());
    if (THIRD_PARTY_PAYMENT_MODE_CHEQUE.equalsIgnoreCase(payPropertyTaxDetails.getPaymentMode().toLowerCase())
            || THIRD_PARTY_PAYMENT_MODE_DD
                    .equalsIgnoreCase(payPropertyTaxDetails.getPaymentMode().toLowerCase())) {
        paymentDetailsMap.put(ChequePayment.INSTRUMENTNUMBER, payPropertyTaxDetails.getChqddNo());
        paymentDetailsMap.put(ChequePayment.INSTRUMENTDATE,
                ChequePayment.CHEQUE_DATE_FORMAT.format(payPropertyTaxDetails.getChqddDate()));
        paymentDetailsMap.put(ChequePayment.BRANCHNAME, payPropertyTaxDetails.getBranchName());
        final Long validatesBankId = validateBank(payPropertyTaxDetails.getBankName());
        paymentDetailsMap.put(ChequePayment.BANKID, validatesBankId.toString());
    }
    final Payment payment = Payment.create(payPropertyTaxDetails.getPaymentMode().toLowerCase(),
            paymentDetailsMap);
    final BillReceiptInfo billReceiptInfo = collectionHelper.executeCollection(payment,
            payPropertyTaxDetails.getSource());

    if (null != billReceiptInfo) {
        receiptDetails = new ReceiptDetails();
        receiptDetails.setReceiptNo(billReceiptInfo.getReceiptNum());
        receiptDetails.setReceiptDate(formatDate(billReceiptInfo.getReceiptDate()));
        receiptDetails.setPayeeName(billReceiptInfo.getPayeeName());
        receiptDetails.setPayeeAddress(billReceiptInfo.getPayeeAddress());
        receiptDetails.setBillReferenceNo(billReceiptInfo.getBillReferenceNum());
        receiptDetails.setServiceName(billReceiptInfo.getServiceName());
        receiptDetails.setDescription(billReceiptInfo.getDescription());
        receiptDetails.setPaidBy(billReceiptInfo.getPaidBy());
        receiptDetails.setPaymentAmount(billReceiptInfo.getTotalAmount());
        receiptDetails.setPaymentMode(payPropertyTaxDetails.getPaymentMode());
        receiptDetails.setTransactionId(billReceiptInfo.getManualReceiptNumber());

        String[] paidFrom = null;
        String[] paidTo = null;
        Installment fromInstallment = null;
        Installment toInstallment = null;
        if (totalAmountToBePaid.compareTo(BigDecimal.ZERO) > 0) {
            List<ReceiptAccountInfo> receiptAccountsList = new ArrayList<>(billReceiptInfo.getAccountDetails());
            Collections.sort(receiptAccountsList, new Comparator<ReceiptAccountInfo>() {
                @Override
                public int compare(ReceiptAccountInfo rcptAcctInfo1, ReceiptAccountInfo rcptAcctInfo2) {
                    if (rcptAcctInfo1.getOrderNumber() != null && rcptAcctInfo2.getOrderNumber() != null)
                        return rcptAcctInfo1.getOrderNumber().compareTo(rcptAcctInfo2.getOrderNumber());
                    return 0;
                }
            });
            for (ReceiptAccountInfo rcptAcctInfo : receiptAccountsList) {
                if (rcptAcctInfo.getCrAmount().compareTo(ZERO) > 0 && !rcptAcctInfo.getDescription()
                        .contains(PropertyTaxConstants.DEMANDRSN_STR_ADVANCE)) {
                    if (paidFrom == null)
                        paidFrom = rcptAcctInfo.getDescription().split("-", 2);
                    paidTo = rcptAcctInfo.getDescription().split("-", 2);
                }
            }
            Module module = moduleService.getModuleByName(PropertyTaxConstants.PTMODULENAME);
            if (paidFrom != null)
                fromInstallment = installmentDao.getInsatllmentByModuleAndDescription(module, paidFrom[1]);
            if (paidTo != null)
                toInstallment = installmentDao.getInsatllmentByModuleAndDescription(module, paidTo[1]);
        }
        /**
         * If collection is done for complete current financial year only, todate shown is last date of current financial year
         * and payment type is 'Fully'. In case, collection is done for complete current financial year with advance, todate
         * shown is last date of current financial year and payment type is 'Advance'. In case, collection is only for
         * advance, collection period will be blank and payment type is 'Advance'
         */
        if (totalAmountToBePaid.compareTo(BigDecimal.ZERO) == 0) {
            receiptDetails.setPaymentPeriod(StringUtils.EMPTY);
            receiptDetails.setPaymentType(PAYMENT_TYPE_ADVANCE);
        } else
            receiptDetails.setPaymentPeriod(DateUtils.getDefaultFormattedDate(fromInstallment.getFromDate())
                    .concat(" to ").concat(DateUtils.getDefaultFormattedDate(toInstallment.getToDate())));

        if (payPropertyTaxDetails.getPaymentAmount().compareTo(totalAmountToBePaid) > 0)
            receiptDetails.setPaymentType(PAYMENT_TYPE_ADVANCE);
        else if (totalAmountToBePaid.compareTo(payPropertyTaxDetails.getPaymentAmount()) > 0)
            receiptDetails.setPaymentType(PAYMENT_TYPE_PARTIALLY);
        else
            receiptDetails.setPaymentType(PAYMENT_TYPE_FULLY);

        basicPropertyService.update(basicProperty);
        errorDetails = new ErrorDetails();
        errorDetails.setErrorCode(THIRD_PARTY_ERR_CODE_SUCCESS);
        errorDetails.setErrorMessage(THIRD_PARTY_ERR_MSG_SUCCESS);

        receiptDetails.setErrorDetails(errorDetails);
    }
    return receiptDetails;
}

From source file:org.egov.adtax.service.AdvertisementDemandService.java

public EgDemand updateDemand(final AdvertisementPermitDetail advertisementPermitDetail, EgDemand demand) {
    final Installment installment = getCurrentInstallment();
    BigDecimal totalDemandAmount = BigDecimal.ZERO;

    // Boolean calculateTax=true;
    Boolean enchroachmentFeeAlreadyExistInDemand = false;
    final List<EgDemandDetails> removableDemandDetailList = new ArrayList<>();

    // EgDemand demand = advertisement.getDemandId();
    if (demand == null)
        demand = createDemand(advertisementPermitDetail);
    else {/*from w ww .jav  a 2 s.co  m*/
        final EgDemandReason pendingTaxReason = getDemandReasonByCodeAndInstallment(
                AdvertisementTaxConstants.DEMANDREASON_ARREAR_ADVERTISEMENTTAX, installment);
        final EgDemandReason encroachmentFeeReason = getDemandReasonByCodeAndInstallment(
                AdvertisementTaxConstants.DEMANDREASON_ENCROCHMENTFEE, installment);
        final EgDemandReason taxReason = getDemandReasonByCodeAndInstallment(
                AdvertisementTaxConstants.DEMANDREASON_ADVERTISEMENTTAX, installment);
        /*
         * if (advertisementPermitDetail.getTaxAmount() != null ||
         * advertisementPermitDetail.getAdvertisement().getPendingTax() != null) { if
         * (advertisementPermitDetail.getAdvertisement().getPendingTax() != null) taxAmount =
         * taxAmount.add(advertisementPermitDetail.getAdvertisement().getPendingTax()); if
         * (advertisementPermitDetail.getTaxAmount() != null) taxAmount =
         * taxAmount.add(advertisementPermitDetail.getTaxAmount()); }
         */
        for (final EgDemandDetails dmdDtl : demand.getEgDemandDetails()) {
            // Assumption: tax amount is mandatory.
            if (dmdDtl.getEgDemandReason().getId() == taxReason.getId()
                    && advertisementPermitDetail.getTaxAmount().compareTo(BigDecimal.ZERO) > 0) {
                // TODO: Also check whether fully collected ?
                totalDemandAmount = totalDemandAmount
                        .add(advertisementPermitDetail.getTaxAmount().subtract(dmdDtl.getAmount()));
                dmdDtl.setAmount(
                        advertisementPermitDetail.getTaxAmount().setScale(0, BigDecimal.ROUND_HALF_UP));
            }
            if (dmdDtl.getEgDemandReason().getId() == pendingTaxReason.getId()
                    && advertisementPermitDetail.getAdvertisement().getPendingTax() != null
                    && advertisementPermitDetail.getAdvertisement().getPendingTax()
                            .compareTo(BigDecimal.ZERO) > 0) {
                // TODO: Also check whether fully collected ?
                totalDemandAmount = totalDemandAmount.add(advertisementPermitDetail.getAdvertisement()
                        .getPendingTax().subtract(dmdDtl.getAmount()));
                dmdDtl.setAmount(advertisementPermitDetail.getAdvertisement().getPendingTax().setScale(0,
                        BigDecimal.ROUND_HALF_UP));

            }
            // Encroachment fee may not mandatory. If already part of demand
            // then
            if (dmdDtl.getEgDemandReason().getId() == encroachmentFeeReason.getId()) {
                enchroachmentFeeAlreadyExistInDemand = true;
                if (advertisementPermitDetail.getEncroachmentFee() != null
                        && advertisementPermitDetail.getEncroachmentFee().compareTo(BigDecimal.ZERO) > 0) {
                    totalDemandAmount = totalDemandAmount
                            .add(advertisementPermitDetail.getEncroachmentFee().subtract(dmdDtl.getAmount()));
                    dmdDtl.setAmount(advertisementPermitDetail.getEncroachmentFee().setScale(0,
                            BigDecimal.ROUND_HALF_UP));

                    // update encroachment fee..
                } else {
                    totalDemandAmount = totalDemandAmount.subtract(dmdDtl.getAmount());
                    // demand.removeEgDemandDetails(dmdDtl);
                    removableDemandDetailList.add(dmdDtl);
                    // delete demand detail
                }

            }
        }
        for (final EgDemandDetails removableDmdDtl : removableDemandDetailList)
            demand.removeEgDemandDetails(removableDmdDtl);
        if (!enchroachmentFeeAlreadyExistInDemand && advertisementPermitDetail.getEncroachmentFee() != null
                && advertisementPermitDetail.getEncroachmentFee().compareTo(BigDecimal.ZERO) > 0) {
            demand.addEgDemandDetails(
                    createDemandDetails(advertisementPermitDetail.getEncroachmentFee(),
                            getDemandReasonByCodeAndInstallment(
                                    AdvertisementTaxConstants.DEMANDREASON_ENCROCHMENTFEE, installment),
                            BigDecimal.ZERO));
            totalDemandAmount = totalDemandAmount.add(advertisementPermitDetail.getEncroachmentFee());
            // TODO: CHECK WHETHER FULLY PAID IN LEGACY HANDLED.
        }
        demand.addBaseDemand(totalDemandAmount.setScale(0, BigDecimal.ROUND_HALF_UP));

    }
    return demand;

}

From source file:org.kuali.kpme.tklm.leave.transfer.service.BalanceTransferServiceImpl.java

@Override
public BalanceTransfer initializeTransfer(String principalId, String accrualCategoryRule,
        BigDecimal accruedBalance, LocalDate effectiveDate) {
    //Initially, principals may be allowed to edit the transfer amount when prompted to submit this balance transfer, however,
    //a base transfer amount together with a forfeited amount is calculated to bring the balance back to its limit in accordance
    //with transfer limits. This "default" transfer object is used to adjust forfeiture when the user changes the transfer amount.
    BalanceTransfer bt = null;/*from   w w  w . ja v a  2 s.com*/
    AccrualCategoryRule accrualRule = HrServiceLocator.getAccrualCategoryRuleService()
            .getAccrualCategoryRule(accrualCategoryRule);

    if (ObjectUtils.isNotNull(accrualRule) && ObjectUtils.isNotNull(accruedBalance)) {
        bt = new BalanceTransfer();
        //These two objects are essential to balance transfers triggered when the employee submits their leave calendar for approval.
        //Neither of these objects should be null, otherwise this method could not have been called.
        AccrualCategory fromAccrualCategory = HrServiceLocator.getAccrualCategoryService()
                .getAccrualCategory(accrualRule.getLmAccrualCategoryId());
        AccrualCategory toAccrualCategory = HrServiceLocator.getAccrualCategoryService()
                .getAccrualCategory(accrualRule.getMaxBalanceTransferToAccrualCategory(), effectiveDate);
        BigDecimal fullTimeEngagement = HrServiceLocator.getJobService()
                .getFteSumForAllActiveLeaveEligibleJobs(principalId, effectiveDate);

        BigDecimal transferConversionFactor = null;
        if (ObjectUtils.isNotNull(accrualRule.getMaxBalanceTransferConversionFactor()))
            transferConversionFactor = accrualRule.getMaxBalanceTransferConversionFactor();

        // AccrualRule.maxBalance == null -> no balance limit. No balance limit -> no accrual triggered transfer / payout / lose.
        // execution point should not be here if max balance on accrualRule is null, unless there exists an employee override.
        BigDecimal maxBalance = accrualRule.getMaxBalance();
        BigDecimal adjustedMaxBalance = maxBalance.multiply(fullTimeEngagement).setScale(2);

        BigDecimal maxTransferAmount = null;
        BigDecimal adjustedMaxTransferAmount = null;
        if (ObjectUtils.isNotNull(accrualRule.getMaxTransferAmount())) {
            maxTransferAmount = new BigDecimal(accrualRule.getMaxTransferAmount());
            adjustedMaxTransferAmount = maxTransferAmount.multiply(fullTimeEngagement).setScale(2);
        } else {
            // no limit on transfer amount
            maxTransferAmount = new BigDecimal(Long.MAX_VALUE);
            adjustedMaxTransferAmount = maxTransferAmount;
        }

        BigDecimal maxCarryOver = null;
        BigDecimal adjustedMaxCarryOver = null;
        if (ObjectUtils.isNotNull(accrualRule.getMaxCarryOver())) {
            maxCarryOver = new BigDecimal(accrualRule.getMaxCarryOver());
            adjustedMaxCarryOver = maxCarryOver.multiply(fullTimeEngagement).setScale(2);
        } else {
            //no limit to carry over.
            maxCarryOver = new BigDecimal(Long.MAX_VALUE);
            adjustedMaxCarryOver = maxCarryOver;
        }

        List<? extends EmployeeOverrideContract> overrides = LmServiceLocator.getEmployeeOverrideService()
                .getEmployeeOverrides(principalId, effectiveDate);
        for (EmployeeOverrideContract override : overrides) {
            if (StringUtils.equals(override.getAccrualCategory(), fromAccrualCategory.getAccrualCategory())) {
                //Do not pro-rate override values for FTE.
                if (StringUtils.equals(override.getOverrideType(), "MB"))
                    adjustedMaxBalance = new BigDecimal(override.getOverrideValue());
                if (StringUtils.equals(override.getOverrideType(), "MTA"))
                    adjustedMaxTransferAmount = new BigDecimal(override.getOverrideValue());
                if (StringUtils.equals(override.getOverrideType(), "MAC"))
                    adjustedMaxCarryOver = new BigDecimal(override.getOverrideValue());
            }
        }

        BigDecimal transferAmount = accruedBalance.subtract(adjustedMaxBalance);
        if (StringUtils.equals(accrualRule.getActionAtMaxBalance(), HrConstants.ACTION_AT_MAX_BALANCE.LOSE)) {
            //Move all time in excess of employee's fte adjusted max balance to forfeiture.
            bt.setForfeitedAmount(transferAmount);
            //There is no transfer to another accrual category.
            bt.setTransferAmount(BigDecimal.ZERO);
            bt.setAmountTransferred(BigDecimal.ZERO);
            // to accrual category is a required field on maintenance document. Set as from accrual category
            // to remove validation errors when routing, approving, etc.
            bt.setToAccrualCategory(fromAccrualCategory.getAccrualCategory());
        } else {
            // ACTION_AT_MAX_BALANCE = TRANSFER
            bt.setToAccrualCategory(toAccrualCategory.getAccrualCategory());
            if (transferAmount.compareTo(adjustedMaxTransferAmount) > 0) {
                //there's forfeiture.
                //bring transfer amount down to the adjusted maximum transfer amount, and place excess in forfeiture.
                //accruedBalance - adjustedMaxTransferAmount - adjustedMaxBalance = forfeiture.
                //transferAmount = accruedBalance - adjustedMaxBalance; forfeiture = transferAmount - adjustedMaxTransferAmount.
                BigDecimal forfeiture = transferAmount.subtract(adjustedMaxTransferAmount).setScale(2);
                forfeiture = forfeiture.stripTrailingZeros();
                bt.setForfeitedAmount(forfeiture);
                bt.setTransferAmount(adjustedMaxTransferAmount);
            } else {
                bt.setTransferAmount(transferAmount);
                bt.setForfeitedAmount(BigDecimal.ZERO);
            }
        }

        //assert(adjustedMaxBalance.compareTo(accruedBalance.subtract(bt.getTransferAmount().add(bt.getForfeitedAmount()))) == 0);

        // Max Carry Over logic for Year End transfers.
        if (StringUtils.equals(accrualRule.getMaxBalanceActionFrequency(),
                HrConstants.MAX_BAL_ACTION_FREQ.YEAR_END)) {

            //At this point, transfer amount and forfeiture have been set so that the new accrued balance will be the
            //adjusted max balance, so this amount is used to check against carry over.
            if (adjustedMaxBalance.compareTo(adjustedMaxCarryOver) > 0) {
                BigDecimal carryOverDiff = adjustedMaxBalance.subtract(adjustedMaxCarryOver);

                if (StringUtils.equals(accrualRule.getActionAtMaxBalance(),
                        HrConstants.ACTION_AT_MAX_BALANCE.LOSE)) {
                    //add carry over excess to forfeiture.
                    bt.setForfeitedAmount(bt.getForfeitedAmount().add(carryOverDiff));
                } else {
                    //maximize the transfer amount.
                    BigDecimal potentialTransferAmount = bt.getTransferAmount().add(carryOverDiff);

                    //Can this amount be added to the transfer amount without exceeding adjusted max transfer amount??
                    if (potentialTransferAmount.compareTo(adjustedMaxTransferAmount) <= 0) {
                        //yes
                        bt.setTransferAmount(bt.getTransferAmount().add(carryOverDiff));
                    } else {
                        //no
                        BigDecimal carryOverExcess = potentialTransferAmount
                                .subtract(adjustedMaxTransferAmount);
                        //move excess to forfeiture
                        bt.setForfeitedAmount(bt.getForfeitedAmount().add(carryOverExcess));
                        //the remainder (if any) can be added to the transfer amount.
                        bt.setTransferAmount(
                                bt.getTransferAmount().add(carryOverDiff.subtract(carryOverExcess)));

                        assert (bt.getTransferAmount().compareTo(adjustedMaxTransferAmount) == 0);
                        // assert that the new balance will be equal to the adjusted max carry over < adjusted max balance.
                    }
                }
                assert (adjustedMaxCarryOver.compareTo(
                        accruedBalance.subtract(bt.getTransferAmount().add(bt.getForfeitedAmount()))) == 0);
            }
            //otherwise, given balance will be at or under the max annual carry over.
        }

        bt.setEffectiveLocalDate(effectiveDate);
        bt.setAccrualCategoryRule(accrualCategoryRule);
        bt.setFromAccrualCategory(fromAccrualCategory.getAccrualCategory());
        bt.setPrincipalId(principalId);
        bt.setUserPrincipalId(HrContext.getPrincipalId());
        if (ObjectUtils.isNotNull(transferConversionFactor)) {
            bt.setAmountTransferred(bt.getTransferAmount().multiply(transferConversionFactor).setScale(2,
                    RoundingMode.HALF_UP));
        } else {
            bt.setAmountTransferred(bt.getTransferAmount());
        }
    }
    return bt;
}

From source file:org.kuali.kpme.tklm.leave.payout.service.LeavePayoutServiceImpl.java

@Override
public LeavePayout initializePayout(String principalId, String accrualCategoryRule, BigDecimal accruedBalance,
        LocalDate effectiveDate) {
    //Initially, principals may be allowed to edit the transfer amount when prompted to submit this balance transfer, however,
    //a base transfer amount together with a forfeited amount is calculated to bring the balance back to its limit in accordance
    //with transfer limits.
    LeavePayout leavePayout = null;//from   w  w w  . j  a v a2  s . c  o  m
    AccrualCategoryRule accrualRule = HrServiceLocator.getAccrualCategoryRuleService()
            .getAccrualCategoryRule(accrualCategoryRule);

    if (ObjectUtils.isNotNull(accrualRule) && ObjectUtils.isNotNull(accruedBalance)) {
        leavePayout = new LeavePayout();
        //Leave summary is not a requirement, per se, but the information it contains is.
        //The only thing that is obtained from leave summary is the accrued balance of the leave summary row matching the
        //passed accrualCategoryRules accrual category.
        //These two objects are essential to balance transfers triggered when the employee submits their leave calendar for approval.
        //Neither of these objects should be null, otherwise this method could not have been called.
        AccrualCategory fromAccrualCategory = HrServiceLocator.getAccrualCategoryService()
                .getAccrualCategory(accrualRule.getLmAccrualCategoryId());
        BigDecimal fullTimeEngagement = HrServiceLocator.getJobService()
                .getFteSumForAllActiveLeaveEligibleJobs(principalId, effectiveDate);

        // AccrualRule.maxBalance == null -> no balance limit. No balance limit -> no accrual triggered transfer / payout / lose.
        // execution point should not be here if max balance on accrualRule is null, unless there exists an employee override.
        BigDecimal maxBalance = accrualRule.getMaxBalance();
        BigDecimal adjustedMaxBalance = maxBalance.multiply(fullTimeEngagement).setScale(2);

        BigDecimal maxPayoutAmount = null;
        BigDecimal adjustedMaxPayoutAmount = null;
        if (ObjectUtils.isNotNull(accrualRule.getMaxPayoutAmount())) {
            maxPayoutAmount = new BigDecimal(accrualRule.getMaxPayoutAmount());
            adjustedMaxPayoutAmount = maxPayoutAmount.multiply(fullTimeEngagement).setScale(2);
        } else {
            // no limit on transfer amount
            maxPayoutAmount = new BigDecimal(Long.MAX_VALUE);
            adjustedMaxPayoutAmount = maxPayoutAmount;
        }

        BigDecimal maxCarryOver = null;
        BigDecimal adjustedMaxCarryOver = null;
        if (ObjectUtils.isNotNull(accrualRule.getMaxCarryOver())) {
            maxCarryOver = new BigDecimal(accrualRule.getMaxCarryOver());
            adjustedMaxCarryOver = maxCarryOver.multiply(fullTimeEngagement).setScale(2);
        } else {
            //no limit to carry over.
            maxCarryOver = new BigDecimal(Long.MAX_VALUE);
            adjustedMaxCarryOver = maxCarryOver;
        }

        EmployeeOverrideContract maxBalanceOverride = LmServiceLocator.getEmployeeOverrideService()
                .getEmployeeOverride(principalId, fromAccrualCategory.getLeavePlan(),
                        fromAccrualCategory.getAccrualCategory(), "MB", effectiveDate);
        EmployeeOverrideContract maxPayoutAmountOverride = LmServiceLocator.getEmployeeOverrideService()
                .getEmployeeOverride(principalId, fromAccrualCategory.getLeavePlan(),
                        fromAccrualCategory.getAccrualCategory(), "MPA", effectiveDate);
        EmployeeOverrideContract maxAnnualCarryOverOverride = LmServiceLocator.getEmployeeOverrideService()
                .getEmployeeOverride(principalId, fromAccrualCategory.getLeavePlan(),
                        fromAccrualCategory.getAccrualCategory(), "MAC", effectiveDate);
        //Do not pro-rate override values for FTE.
        if (maxBalanceOverride != null)
            adjustedMaxBalance = new BigDecimal(maxBalanceOverride.getOverrideValue());
        if (maxPayoutAmountOverride != null)
            adjustedMaxPayoutAmount = new BigDecimal(maxPayoutAmountOverride.getOverrideValue());
        if (maxAnnualCarryOverOverride != null)
            adjustedMaxCarryOver = new BigDecimal(maxAnnualCarryOverOverride.getOverrideValue());

        BigDecimal transferAmount = accruedBalance.subtract(adjustedMaxBalance);
        if (transferAmount.compareTo(adjustedMaxPayoutAmount) > 0) {
            //there's forfeiture.
            //bring transfer amount down to the adjusted maximum transfer amount, and place excess in forfeiture.
            //accruedBalance - adjustedMaxPayoutAmount - adjustedMaxBalance = forfeiture.
            //transferAmount = accruedBalance - adjustedMaxBalance; forfeiture = transferAmount - adjustedMaxPayoutAmount.
            BigDecimal forfeiture = transferAmount.subtract(adjustedMaxPayoutAmount).setScale(2);
            forfeiture = forfeiture.stripTrailingZeros();
            leavePayout.setForfeitedAmount(forfeiture);
            leavePayout.setPayoutAmount(adjustedMaxPayoutAmount);
        } else {
            leavePayout.setPayoutAmount(transferAmount);
            leavePayout.setForfeitedAmount(BigDecimal.ZERO);
        }

        assert (adjustedMaxBalance.compareTo(accruedBalance
                .subtract(leavePayout.getPayoutAmount().add(leavePayout.getForfeitedAmount()))) == 0);

        // Max Carry Over logic for Year End transfers.
        if (StringUtils.equals(accrualRule.getMaxBalanceActionFrequency(),
                HrConstants.MAX_BAL_ACTION_FREQ.YEAR_END)) {
            if (ObjectUtils.isNotNull(maxCarryOver)) {

                if (ObjectUtils.isNull(adjustedMaxCarryOver))
                    adjustedMaxCarryOver = maxCarryOver.multiply(fullTimeEngagement).setScale(2);
                //otherwise, adjustedMaxCarryOver has an employee override value, which trumps accrual rule defined MAC.
                //At this point, transfer amount and forfeiture have been set so that the new accrued balance will be the
                //adjusted max balance, so this amount is used to check against carry over.
                if (adjustedMaxBalance.compareTo(adjustedMaxCarryOver) > 0) {
                    BigDecimal carryOverDiff = adjustedMaxBalance.subtract(adjustedMaxCarryOver);

                    if (StringUtils.equals(accrualRule.getActionAtMaxBalance(),
                            HrConstants.ACTION_AT_MAX_BALANCE.LOSE)) {
                        //add carry over excess to forfeiture.
                        leavePayout.setForfeitedAmount(leavePayout.getForfeitedAmount().add(carryOverDiff));
                    } else {
                        //maximize the transfer amount.
                        BigDecimal potentialPayoutAmount = leavePayout.getPayoutAmount().add(carryOverDiff);

                        //Can this entire amount be added to the transfer amount??
                        if (potentialPayoutAmount.compareTo(adjustedMaxPayoutAmount) <= 0) {
                            //yes
                            leavePayout.setPayoutAmount(leavePayout.getPayoutAmount().add(carryOverDiff));
                        } else {
                            //no
                            BigDecimal carryOverExcess = potentialPayoutAmount
                                    .subtract(adjustedMaxPayoutAmount);
                            //move excess to forfeiture
                            leavePayout
                                    .setForfeitedAmount(leavePayout.getForfeitedAmount().add(carryOverExcess));
                            //the remainder (if any) can be added to the transfer amount ( unless action is LOSE ).
                            leavePayout.setPayoutAmount(
                                    leavePayout.getPayoutAmount().add(carryOverDiff.subtract(carryOverExcess)));

                            assert (adjustedMaxCarryOver.compareTo(accruedBalance.subtract(
                                    leavePayout.getPayoutAmount().add(leavePayout.getForfeitedAmount()))) == 0);
                        }
                    }
                }
                //otherwise, given balance will be at or under the max annual carry over.
            }
        }

        leavePayout.setEffectiveLocalDate(effectiveDate);
        leavePayout.setAccrualCategoryRule(accrualCategoryRule);
        leavePayout.setFromAccrualCategory(fromAccrualCategory.getAccrualCategory());
        leavePayout.setPrincipalId(principalId);
        leavePayout.setUserPrincipalId(HrContext.getPrincipalId());
        leavePayout.setEarnCode(accrualRule.getMaxPayoutEarnCode());

    }
    return leavePayout;
}

From source file:org.kuali.ole.select.document.service.impl.OleInvoiceServiceImpl.java

/**
 * @see org.kuali.ole.select.document.service.OleInvoiceService#calculateProrateItemSurcharge(org.kuali.ole.select.document.OleInvoiceDocument)
 *//*from   w  w  w  .  j  av a 2s  . c  o  m*/
@Override
public void calculateProrateItemSurcharge(OleInvoiceDocument invoiceDocument) {
    LOG.debug("Inside Calculation for ProrateItemSurcharge");
    //  KualiDecimal addChargeItem = invoiceDocument.getGrandPreTaxTotalExcludingDiscount().subtract(invoiceDocument.getLineItemPreTaxTotal());
    BigDecimal addChargeItem = BigDecimal.ZERO;
    List<OleInvoiceItem> item = invoiceDocument.getItems();
    for (OleInvoiceItem items : item) {
        if (items.getItemType().isAdditionalChargeIndicator() && items.getExtendedPrice() != null) {
            addChargeItem = addChargeItem.add(items.getExtendedPrice().bigDecimalValue());
        }
    }
    List<PurApItem> items = new ArrayList<>();
    /*List<OlePurchaseOrderDocument> olePurchaseOrderDocuments = invoiceDocument.getPurchaseOrderDocuments();
    for (OlePurchaseOrderDocument olePurchaseOrderDocument : olePurchaseOrderDocuments) {
    for (OlePurchaseOrderItem purItem : (List<OlePurchaseOrderItem>) olePurchaseOrderDocument.getItems()) {
        purItem.setItemListPrice(new KualiDecimal(purItem.getInvoiceItemListPrice()));
        if (purItem.isItemForInvoice() && purItem.getItemListPrice().compareTo(KualiDecimal.ZERO) >= 0) {
            items.add(purItem);
        } else {
            purItem.setItemSurcharge(BigDecimal.ZERO);
        }
        if (purItem.getItemListPrice().compareTo(KualiDecimal.ZERO) < 0) {
            purItem.setItemUnitPrice(SpringContext.getBean(OlePurapService.class).calculateDiscount(purItem));
        }
    }
            
    }
    if (items.size() == 0) {*/
    for (OleInvoiceItem invoiceItem : (List<OleInvoiceItem>) invoiceDocument.getItems()) {
        /* if(invoiceItem.getItemType().isQuantityBasedGeneralLedgerIndicator() && invoiceItem.getRelatedViews() != null) {
            invoiceItem.setRelatedViews(null);
        }*/
        items.add(invoiceItem);
    }
    /* }
     else {
    for (OleInvoiceItem invoiceItem : (List<OleInvoiceItem>) invoiceDocument.getItems()) {
        if (!(invoiceItem.getItemType().isQuantityBasedGeneralLedgerIndicator())) {
            items.add(invoiceItem);
        }
    }
     }*/
    List<BigDecimal> newUnitPriceList = new ArrayList<>();
    BigDecimal totalExtPrice = new BigDecimal(0);
    BigDecimal newUnitPrice = new BigDecimal(0);
    BigDecimal extPrice = new BigDecimal(0);
    BigDecimal unitPricePercent = new BigDecimal(0);
    BigDecimal hundred = new BigDecimal(100);
    BigDecimal one = new BigDecimal(1);
    BigDecimal totalSurCharge = new BigDecimal(0);
    BigDecimal totalItemQuantity = new BigDecimal(0);
    BigDecimal itemSurchargeCons = new BigDecimal(0);
    for (PurApItem purItem : items) {
        if (purItem instanceof OlePurchaseOrderItem) {
            OlePurchaseOrderItem poItem = (OlePurchaseOrderItem) purItem;
            //  purItem.setItemListPrice(new KualiDecimal(purItem.getInvoiceItemListPrice()));
            if ((poItem.getItemType().isQuantityBasedGeneralLedgerIndicator())
                    && !ObjectUtils.isNull(poItem.getNoOfCopiesInvoiced())
                    && poItem.getItemListPrice().compareTo(KualiDecimal.ZERO) >= 0) {
                if (invoiceDocument.getProrateBy().equals(OLEConstants.PRORATE_BY_QTY)) {
                    totalItemQuantity = totalItemQuantity.add(poItem.getNoOfCopiesInvoiced().bigDecimalValue());
                }
                if (invoiceDocument.getProrateBy().equals(OLEConstants.PRORATE_BY_DOLLAR)
                        || invoiceDocument.getProrateBy().equals(OLEConstants.MANUAL_PRORATE)
                        || invoiceDocument.getProrateBy().equals(OLEConstants.PRORATE_BY_QTY)) {
                    if (poItem.getItemDiscount() == null) {
                        poItem.setItemDiscount(KualiDecimal.ZERO);
                    }
                    if (poItem.getItemDiscountType() != null && poItem.getItemDiscountType()
                            .equalsIgnoreCase(OleSelectConstant.DISCOUNT_TYPE_PERCENTAGE)) {
                        newUnitPrice = (hundred.subtract(poItem.getItemDiscount().bigDecimalValue()))
                                .divide(hundred).multiply(poItem.getItemListPrice().bigDecimalValue());
                    } else {
                        newUnitPrice = poItem.getItemListPrice().bigDecimalValue()
                                .subtract(poItem.getItemDiscount().bigDecimalValue());
                    }
                    newUnitPriceList.add(newUnitPrice);
                    extPrice = newUnitPrice.multiply(poItem.getNoOfCopiesInvoiced().bigDecimalValue());
                    totalExtPrice = totalExtPrice.add(extPrice);
                }
                if (invoiceDocument.getProrateBy().equals(OLEConstants.MANUAL_PRORATE)) {
                    if (poItem.getItemSurcharge() == null) {
                        poItem.setItemSurcharge(BigDecimal.ZERO);
                    }
                    totalSurCharge = totalSurCharge.add(poItem.getNoOfCopiesInvoiced().bigDecimalValue()
                            .multiply(poItem.getItemSurcharge()));
                }
            }
        }

        else if (purItem instanceof OleInvoiceItem) {
            OleInvoiceItem invItem = (OleInvoiceItem) purItem;
            if ((invItem.getItemType().isQuantityBasedGeneralLedgerIndicator())
                    && !ObjectUtils.isNull(invItem.getItemQuantity())
                    && invItem.getItemListPrice().compareTo(KualiDecimal.ZERO) >= 0) {
                if (invoiceDocument.getProrateBy().equals(OLEConstants.PRORATE_BY_QTY)) {
                    totalItemQuantity = totalItemQuantity.add(invItem.getItemQuantity().bigDecimalValue());
                }
                if (invoiceDocument.getProrateBy().equals(OLEConstants.PRORATE_BY_DOLLAR)
                        || invoiceDocument.getProrateBy().equals(OLEConstants.MANUAL_PRORATE)
                        || invoiceDocument.getProrateBy().equals(OLEConstants.PRORATE_BY_QTY)) {
                    if (invItem.getItemDiscount() == null) {
                        invItem.setItemDiscount(KualiDecimal.ZERO);
                    }
                    if (invItem.getItemDiscountType() != null && invItem.getItemDiscountType()
                            .equalsIgnoreCase(OleSelectConstant.DISCOUNT_TYPE_PERCENTAGE)) {
                        newUnitPrice = (hundred.subtract(invItem.getItemDiscount().bigDecimalValue()))
                                .divide(hundred).multiply(invItem.getItemListPrice().bigDecimalValue());
                    } else {
                        newUnitPrice = invItem.getItemListPrice().bigDecimalValue()
                                .subtract(invItem.getItemDiscount().bigDecimalValue());
                    }
                    newUnitPriceList.add(newUnitPrice);
                    extPrice = newUnitPrice.multiply(invItem.getItemQuantity().bigDecimalValue());
                    totalExtPrice = totalExtPrice.add(extPrice);
                }
                if (invoiceDocument.getProrateBy().equals(OLEConstants.MANUAL_PRORATE)) {
                    if (invItem.getItemSurcharge() == null) {
                        invItem.setItemSurcharge(BigDecimal.ZERO);
                    }
                    totalSurCharge = totalSurCharge.add(
                            invItem.getItemQuantity().bigDecimalValue().multiply(invItem.getItemSurcharge()));
                }
            }
        }
    }

    if (invoiceDocument.getProrateBy().equals(OLEConstants.PRORATE_BY_QTY)) {
        if (totalItemQuantity.compareTo(BigDecimal.ZERO) != 0) {
            itemSurchargeCons = one.divide(totalItemQuantity, 8, RoundingMode.HALF_UP);
        }
    }
    for (int i = 0, j = 0; items.size() > i; i++) {
        PurApItem purItem = items.get(i);
        if (purItem instanceof OlePurchaseOrderItem) {
            OlePurchaseOrderItem poItem = (OlePurchaseOrderItem) purItem;

            if (poItem.getItemType().isQuantityBasedGeneralLedgerIndicator() && newUnitPriceList.size() > j
                    && !ObjectUtils.isNull(poItem.getNoOfCopiesInvoiced())) {
                if (invoiceDocument.getProrateBy().equals(OLEConstants.PRORATE_BY_DOLLAR)) {
                    if (totalExtPrice.compareTo(BigDecimal.ZERO) != 0) {
                        unitPricePercent = newUnitPriceList.get(j).divide(totalExtPrice, 8,
                                RoundingMode.HALF_UP);
                    }
                    poItem.setItemSurcharge(
                            unitPricePercent.multiply(addChargeItem).setScale(4, RoundingMode.HALF_UP));
                    poItem.setItemUnitPrice(newUnitPriceList.get(j).add(poItem.getItemSurcharge()));
                }
                if (invoiceDocument.getProrateBy().equals(OLEConstants.PRORATE_BY_QTY)) {
                    poItem.setItemSurcharge(
                            itemSurchargeCons.multiply(addChargeItem).setScale(4, RoundingMode.HALF_UP));
                    poItem.setItemUnitPrice(newUnitPriceList.get(j).add(poItem.getItemSurcharge()));
                }
                if (invoiceDocument.getProrateBy().equals(OLEConstants.MANUAL_PRORATE)
                        && poItem.getItemSurcharge() != null) {
                    poItem.setItemUnitPrice(newUnitPriceList.get(j).add(poItem.getItemSurcharge()));
                }
                j++;
            }
        } else if (purItem instanceof OleInvoiceItem) {
            OleInvoiceItem invItem = (OleInvoiceItem) purItem;
            if (invItem.getItemType().isQuantityBasedGeneralLedgerIndicator() && newUnitPriceList.size() > j
                    && !ObjectUtils.isNull(invItem.getItemQuantity())) {
                if (invoiceDocument.getProrateBy().equals(OLEConstants.PRORATE_BY_DOLLAR)) {
                    if (totalExtPrice.compareTo(BigDecimal.ZERO) != 0) {
                        unitPricePercent = newUnitPriceList.get(j).divide(totalExtPrice, 8,
                                RoundingMode.HALF_UP);
                    }
                    invItem.setItemSurcharge(
                            unitPricePercent.multiply(addChargeItem).setScale(4, RoundingMode.HALF_UP));
                    invItem.setItemUnitPrice(newUnitPriceList.get(j).add(invItem.getItemSurcharge()));
                }
                if (invoiceDocument.getProrateBy().equals(OLEConstants.PRORATE_BY_QTY)) {
                    invItem.setItemSurcharge(
                            itemSurchargeCons.multiply(addChargeItem).setScale(4, RoundingMode.HALF_UP));
                    invItem.setItemUnitPrice(newUnitPriceList.get(j).add(invItem.getItemSurcharge()));
                }
                if (invoiceDocument.getProrateBy().equals(OLEConstants.MANUAL_PRORATE)
                        && invItem.getItemSurcharge() != null) {
                    invItem.setItemUnitPrice(newUnitPriceList.get(j).add(invItem.getItemSurcharge()));
                }
                j++;
            }

        }
    }
    if (invoiceDocument.getProrateBy().equals(OLEConstants.MANUAL_PRORATE)) {
        if (totalSurCharge.compareTo(addChargeItem) != 0) {
            GlobalVariables.getMessageMap().putError(PurapConstants.ITEM_TAB_ERROR_PROPERTY,
                    OLEKeyConstants.ERROR_PAYMENT_REQUEST_TOTAL_MISMATCH);
        }
    }
    LOG.debug("Leaving Calculation for ProrateItemSurcharge");
}