Example usage for java.math BigDecimal divide

List of usage examples for java.math BigDecimal divide

Introduction

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

Prototype

public BigDecimal divide(BigDecimal divisor) 

Source Link

Document

Returns a BigDecimal whose value is (this / divisor) , and whose preferred scale is (this.scale() - divisor.scale()) ; if the exact quotient cannot be represented (because it has a non-terminating decimal expansion) an ArithmeticException is thrown.

Usage

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

public void search(final String src) {
    if (APP.equalsIgnoreCase(src) && abstractEstimate != null
            && abstractEstimate.getFinancialDetails().get(0) != null)
        financialDetail = abstractEstimate.getFinancialDetails().get(0);

    if (financialDetail != null && financialDetail.getFund() != null
            && financialDetail.getFund().getId() != null && financialDetail.getFund().getId() != -1)
        queryParamMap.put("fundid", financialDetail.getFund().getId());

    if (financialDetail != null && financialDetail.getFunction() != null
            && financialDetail.getFunction().getId() != null && financialDetail.getFunction().getId() != -1)
        queryParamMap.put("functionid", financialDetail.getFunction().getId());
    if (financialDetail != null && financialDetail.getBudgetGroup() != null
            && financialDetail.getBudgetGroup().getId() != null
            && financialDetail.getBudgetGroup().getId() != -1) {
        final List<BudgetGroup> budgetheadid = new ArrayList<BudgetGroup>();
        budgetheadid.add(financialDetail.getBudgetGroup());
        queryParamMap.put("budgetheadid", budgetheadid);
    }/*from   www  .  j  a va2  s.c om*/

    if (APP.equalsIgnoreCase(src) && financialDetail != null
            && financialDetail.getAbstractEstimate().getUserDepartment() != null)
        queryParamMap.put("deptid", financialDetail.getAbstractEstimate().getUserDepartment().getId());
    else if (getUserDepartment() != null && getUserDepartment() != -1)
        queryParamMap.put("deptid", getUserDepartment());

    if (APP.equalsIgnoreCase(src) && abstractEstimate != null
            && abstractEstimate.getLeastFinancialYearForEstimate() != null
            && abstractEstimate.getLeastFinancialYearForEstimate().getId() != null) {
        queryParamMap.put("financialyearid",
                financialDetail.getAbstractEstimate().getLeastFinancialYearForEstimate().getId());
        queryParamMap.put("fromDate",
                financialDetail.getAbstractEstimate().getLeastFinancialYearForEstimate().getStartingDate());
        queryParamMap.put("toDate", new Date());
    } else if (getReportDate() != null) {
        if (!DateUtils.compareDates(new Date(), getReportDate()))
            throw new ValidationException(Arrays.asList(new ValidationError(
                    "greaterthan.currentDate.reportDate", getText("greaterthan.currentDate.reportDate"))));
        CFinancialYear finyear = null;
        try {
            finyear = abstractEstimateService.getCurrentFinancialYear(getReportDate());
        } catch (final ApplicationRuntimeException noFinYearExp) {
            if (noFinYearExp.getMessage().equals("Financial Year Id does not exist."))
                throw new ValidationException(Arrays
                        .asList(new ValidationError(noFinYearExp.getMessage(), noFinYearExp.getMessage())));
            else
                throw noFinYearExp;

        }
        if (finyear != null && finyear.getId() != null)
            queryParamMap.put("financialyearid", finyear.getId());
        queryParamMap.put("toDate", getReportDate());
    }

    if (!queryParamMap.isEmpty() && getFieldErrors().isEmpty()) {
        BigDecimal planningBudgetPerc = new BigDecimal(0);
        try {
            totalGrant = budgetDetailsDAO.getBudgetedAmtForYear(queryParamMap);
            planningBudgetPerc = getPlanningBudgetPercentage(queryParamMap);
        } catch (final ValidationException valEx) {
            logger.error(valEx);
        }
        // String appValue =
        // worksService.getWorksConfigValue(PERCENTAGE_GRANT);

        if (planningBudgetPerc != null && !planningBudgetPerc.equals(0)) {
            setAppValueLabel(planningBudgetPerc.toString());
            totalGrantPerc = totalGrant.multiply(planningBudgetPerc.divide(new BigDecimal(100)));
            queryParamMap.put("totalGrantPerc", totalGrantPerc);
        }
        final Map<String, List> approvedBudgetFolioDetailsMap = abstractEstimateService
                .getApprovedAppropriationDetailsForBugetHead(queryParamMap);
        approvedBudgetFolioDetails = new ArrayList<BudgetFolioDetail>();
        if (approvedBudgetFolioDetailsMap != null && !approvedBudgetFolioDetailsMap.isEmpty()) {
            approvedBudgetFolioDetails = approvedBudgetFolioDetailsMap.get("budgetFolioList");
            setReportLatestValues(approvedBudgetFolioDetailsMap);
        }
    }
}

From source file:org.nd4j.linalg.util.BigDecimalMath.java

/**
 * Trigonometric cosine./*from w  w  w  .  j a  v a 2s. c  o m*/
 *
 * @param x The argument in radians.
 * @return cos(x) in the range -1 to 1.
 */
static public BigDecimal cos(final BigDecimal x) {
    if (x.compareTo(BigDecimal.ZERO) < 0) {
        return cos(x.negate());
    } else if (x.compareTo(BigDecimal.ZERO) == 0) {
        return BigDecimal.ONE;
    } else {
        /* reduce modulo 2pi
         */
        BigDecimal res = mod2pi(x);
        double errpi = 0.5 * Math.abs(x.ulp().doubleValue());
        int val = +err2prec(FastMath.PI, errpi);
        MathContext mc = new MathContext(val);
        BigDecimal p = pi(mc);
        mc = new MathContext(x.precision());
        if (res.compareTo(p) > 0) {
            /* pi<x<=2pi: cos(x)= - cos(x-pi)
             */
            return cos(subtractRound(res, p)).negate();
        } else if (res.multiply(new BigDecimal("2")).compareTo(p) > 0) {
            /* pi/2<x<=pi: cos(x)= -cos(pi-x)
             */
            return cos(subtractRound(p, res)).negate();
        } else {
            /* for the range 0<=x<Pi/2 one could use cos(2x)= 1-2*sin^2(x)
             * to split this further, or use the cos up to pi/4 and the sine higher up.
            throw new ProviderException("Unimplemented cosine ") ;
             */
            if (res.multiply(new BigDecimal("4")).compareTo(p) > 0) {
                /* x>pi/4: cos(x) = sin(pi/2-x)
                 */
                return sin(subtractRound(p.divide(new BigDecimal("2")), res));
            } else {
                /* Simple Taylor expansion, sum_{i=0..infinity} (-1)^(..)res^(2i)/(2i)! */
                BigDecimal resul = BigDecimal.ONE;
                /* x^i */
                BigDecimal xpowi = BigDecimal.ONE;
                /* 2i factorial */
                BigInteger ifac = BigInteger.ONE;
                /* The absolute error in the result is the error in x^2/2 which is x times the error in x.
                 */
                double xUlpDbl = 0.5 * res.ulp().doubleValue() * res.doubleValue();
                /* The error in the result is set by the error in x^2/2 itself, xUlpDbl.
                 * We need at most k terms to push x^(2k+1)/(2k+1)! below this value.
                 * x^(2k) < xUlpDbl; (2k)*log(x) < log(xUlpDbl);
                 */
                int k = (int) (Math.log(xUlpDbl) / Math.log(res.doubleValue())) / 2;
                MathContext mcTay = new MathContext(err2prec(1., xUlpDbl / k));
                for (int i = 1;; i++) {
                    /* TBD: at which precision will 2*i-1 or 2*i overflow?
                     */
                    ifac = ifac.multiply(new BigInteger("" + (2 * i - 1)));
                    ifac = ifac.multiply(new BigInteger("" + (2 * i)));
                    xpowi = xpowi.multiply(res).multiply(res).negate();
                    BigDecimal corr = xpowi.divide(new BigDecimal(ifac), mcTay);
                    resul = resul.add(corr);
                    if (corr.abs().doubleValue() < 0.5 * xUlpDbl) {
                        break;
                    }
                }
                /* The error in the result is governed by the error in x itself.
                 */
                mc = new MathContext(err2prec(resul.doubleValue(), xUlpDbl));
                return resul.round(mc);
            }
        }
    }
}

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

/**
 * Replaces amount field with prorated tax amount in list
 *
 * @param accounts list of accounts//from   www  .  ja  v  a  2  s. c om
 * @param useTax tax to be allocated to these accounts
 * @param newSourceLines rewrites the source account lines
 */

protected void convertAmtToTax(List<PurApAccountingLine> accounts, KualiDecimal useTax,
        List<SourceAccountingLine> newSourceLines) {
    final BigDecimal HUNDRED = new BigDecimal(100);
    PurApAccountingLine purApAccountingLine;
    BigDecimal proratedAmtBD;
    KualiDecimal proratedAmt;
    // convert back to source
    KualiDecimal total = KualiDecimal.ZERO;
    int last = accounts.size() - 1;
    for (int i = 0; i < last; i++) {
        purApAccountingLine = accounts.get(i);
        BigDecimal linePercent = BigDecimal.ZERO;
        if (ObjectUtils.isNotNull(purApAccountingLine.getAccountLinePercent())) {
            linePercent = purApAccountingLine.getAccountLinePercent();
        }

        proratedAmtBD = useTax.bigDecimalValue().multiply(linePercent);
        // last object takes the rest of the amount
        // proratedAmt = (accounts.indexOf(purApAccountingLine) == last) ? useTax.subtract(total) : proratedAmt.divide(HUNDRED);
        proratedAmtBD = proratedAmtBD.divide(HUNDRED);
        proratedAmt = new KualiDecimal(proratedAmtBD);
        SourceAccountingLine acctLine = purApAccountingLine.generateSourceAccountingLine();
        acctLine.setAmount(proratedAmt);
        newSourceLines.add(acctLine);
        total = total.add(proratedAmt);
    }
    // update last object with remaining balance
    proratedAmt = useTax.subtract(total);
    purApAccountingLine = accounts.get(last);
    SourceAccountingLine acctLine = purApAccountingLine.generateSourceAccountingLine();
    acctLine.setAmount(proratedAmt);
    newSourceLines.add(acctLine);
}

From source file:org.esupportail.papercut.webportlet.EsupPapercutPortletController.java

@RequestMapping
public ModelAndView renderView(RenderRequest request, RenderResponse response) {

    ModelMap model = new ModelMap();

    model.put("htmlHeader", request.getPreferences().getValue("htmlHeader", ""));
    model.put("htmlFooter", request.getPreferences().getValue("htmlFooter", ""));
    model.put("payboxMontantMin", request.getPreferences().getValue("payboxMontantMin", "0.5"));
    model.put("payboxMontantMax", request.getPreferences().getValue("payboxMontantMax", "5.0"));
    model.put("payboxMontantStep", request.getPreferences().getValue("payboxMontantStep", "0.5"));
    model.put("payboxMontantDefaut", request.getPreferences().getValue("payboxMontantDefaut", "2.0"));

    double papercutSheetCost = Double.parseDouble(request.getPreferences().getValue("papercutSheetCost", "-1"));
    double papercutColorSheetCost = Double
            .parseDouble(request.getPreferences().getValue("papercutColorSheetCost", "-1"));

    String paperCutContext = request.getPreferences().getValue(PREF_PAPERCUT_CONTEXT, null);
    EsupPaperCutService esupPaperCutService = esupPaperCutServices.get(paperCutContext);

    String uid = getUid(request);
    String userMail = getUserMail(request);

    // check if the user can make a transaction
    int transactionNbMax = Integer.parseInt(request.getPreferences().getValue("transactionNbMax", "-1"));
    BigDecimal transactionMontantMax = new BigDecimal(
            request.getPreferences().getValue("transactionMontantMax", "-1"));
    boolean canMakeTransaction = true;

    // constraints via transactionNbMax
    if (transactionNbMax > -1) {
        long nbTransactionsNotArchived = PayboxPapercutTransactionLog
                .countFindPayboxPapercutTransactionLogsByUidEqualsAndPaperCutContextEqualsAndArchived(uid,
                        paperCutContext, false);
        if (transactionNbMax <= nbTransactionsNotArchived) {
            canMakeTransaction = false;/*www  . ja v a 2 s .c o  m*/
        }
    }

    BigDecimal payboxMontantMin = new BigDecimal(request.getPreferences().getValue("payboxMontantMin", "0.5"));
    BigDecimal payboxMontantMax = new BigDecimal(request.getPreferences().getValue("payboxMontantMax", "5.0"));
    BigDecimal payboxMontantStep = new BigDecimal(
            request.getPreferences().getValue("payboxMontantStep", "0.5"));
    BigDecimal payboxMontantDefaut = new BigDecimal(
            request.getPreferences().getValue("payboxMontantDefaut", "2.0"));
    // constraints on the slider via transactionMontantMax
    if (canMakeTransaction && transactionMontantMax.intValue() > -1) {
        List<PayboxPapercutTransactionLog> transactionsNotArchived = PayboxPapercutTransactionLog
                .findPayboxPapercutTransactionLogsByUidEqualsAndPaperCutContextEqualsAndArchived(uid,
                        paperCutContext, false)
                .getResultList();
        BigDecimal montantTotalTransactionsNotArchived = new BigDecimal("0");
        for (PayboxPapercutTransactionLog txLog : transactionsNotArchived) {
            montantTotalTransactionsNotArchived = montantTotalTransactionsNotArchived
                    .add(new BigDecimal(txLog.getMontant()));
        }
        transactionMontantMax = transactionMontantMax.multiply(new BigDecimal("100"))
                .subtract(montantTotalTransactionsNotArchived);
        if (transactionMontantMax.doubleValue() < payboxMontantMax.doubleValue() * 100) {
            payboxMontantMax = transactionMontantMax.divide(payboxMontantStep).multiply(payboxMontantStep);
            payboxMontantMax = payboxMontantMax.divide(new BigDecimal("100"));
            if (payboxMontantDefaut.compareTo(payboxMontantMax) == 1) {
                payboxMontantDefaut = payboxMontantMax;
            }
            if (payboxMontantMax.compareTo(payboxMontantMin) == -1) {
                canMakeTransaction = false;
            }
            model.put("payboxMontantMax", payboxMontantMax.doubleValue());
            model.put("payboxMontantDefaut", payboxMontantDefaut.doubleValue());
        }
    }

    // generation de l'ensemble des payboxForm :  payboxMontantMin -> payboxMontantMax par pas de payboxMontantStep
    String portletContextPath = ((RenderResponse) response).createRenderURL().toString();
    Map<Integer, PayBoxForm> payboxForms = new HashMap<Integer, PayBoxForm>();
    for (BigDecimal montant = payboxMontantMin; montant.compareTo(payboxMontantMax) <= 0; montant = montant
            .add(payboxMontantStep)) {
        PayBoxForm payBoxForm = esupPaperCutService.getPayBoxForm(uid, userMail, montant.doubleValue(),
                paperCutContext, portletContextPath);
        if (papercutSheetCost > 0) {
            int nbSheets = (int) (montant.doubleValue() / papercutSheetCost);
            payBoxForm.setNbSheets(nbSheets);
        }
        if (papercutColorSheetCost > 0) {
            int nbColorSheets = (int) (montant.doubleValue() / papercutColorSheetCost);
            payBoxForm.setNbColorSheets(nbColorSheets);
        }

        payboxForms.put(montant.multiply(new BigDecimal(100)).intValue(), payBoxForm);
    }
    Map<Integer, PayBoxForm> sortedMap = new TreeMap<Integer, PayBoxForm>(payboxForms);

    model.put("payboxForms", sortedMap);
    model.put("payboxMontantDefautCents", payboxMontantDefaut.multiply(new BigDecimal(100)).intValue());

    model.put("canMakeTransaction", canMakeTransaction);

    UserPapercutInfos userPapercutInfos = esupPaperCutService.getUserPapercutInfos(uid);
    model.put("userPapercutInfos", userPapercutInfos);

    boolean isAdmin = isAdmin(request);
    boolean isManager = isManager(request);
    model.put("isAdmin", isAdmin);
    model.put("isManager", isManager);
    model.put("active", "home");
    return new ModelAndView(getViewName(request, "index"), model);
}

From source file:com.mg.merp.planning.support.MPSProcessorServiceBean.java

private void calculateProductionPlan(short lowLevelCode) {
    //?  PlanningItem, BucketOffset desc
    Collections.sort(generatedMPSLines, new Comparator<MpsLine>() {

        public int compare(MpsLine o1, MpsLine o2) {
            if (o1.getPlanningItem().getId() < o2.getPlanningItem().getId())
                return 1;
            else if (o1.getPlanningItem().getId() > o2.getPlanningItem().getId())
                return -1;
            else {
                if (o1.getBucketOffset() < o2.getBucketOffset())
                    return 1;
                else if (o1.getBucketOffset() > o2.getBucketOffset())
                    return -1;
                else
                    return 0;
            }/*from  ww  w . ja v a  2s .  c  om*/
        }

    });

    BigDecimal availableOnBeginBucket = BigDecimal.ZERO;
    GenericItem currentPlanningItem = null;
    for (MpsLine mpsLine : generatedMPSLines) {
        if (MathUtils.compareToZero(mpsLine.getProductionDemandQty()) <= 0
                && mpsLine.getLevelCode() == lowLevelCode) {
            if (currentPlanningItem == null
                    || currentPlanningItem.getId() != mpsLine.getPlanningItem().getId()) {
                currentPlanningItem = mpsLine.getPlanningItem();
                availableOnBeginBucket = BigDecimal.ZERO;
            }

            BigDecimal plannedQty = mpsLine.calculatePlannedQuantity(availableOnBeginBucket);

            Bom bom = bomService.findCurrentBOM(currentPlanningItem.getCatalog().getId());
            if (bom != null) {
                BigDecimal MaxQty = bom.getMaxLotQty(), MinQty = bom.getMinLotQty(),
                        Increment = bom.getLotIncrementQty(), Remainder, RemInc;
                if (!(MathUtils.compareToZeroOrNull(MaxQty) == 0 || MathUtils.compareToZeroOrNull(MinQty) == 0
                        || MathUtils.compareToZeroOrNull(Increment) == 0)) {
                    //?  ?  ?  
                    if (bom.getCatalog().getMeasure1().getId() != mpsLine.getMeasure().getId()) {
                        MaxQty = getMeasureConversionService().conversion(bom.getCatalog().getMeasure1(),
                                mpsLine.getMeasure(), bom.getCatalog(), mpsLine.getBucketOffsetDate(), MaxQty);
                        MinQty = getMeasureConversionService().conversion(bom.getCatalog().getMeasure1(),
                                mpsLine.getMeasure(), bom.getCatalog(), mpsLine.getBucketOffsetDate(), MinQty);
                        Increment = getMeasureConversionService().conversion(bom.getCatalog().getMeasure1(),
                                mpsLine.getMeasure(), bom.getCatalog(), mpsLine.getBucketOffsetDate(),
                                Increment);
                    }

                    long NumOfMax = plannedQty.divide(MaxQty).longValue();
                    Remainder = plannedQty.subtract(MaxQty.multiply(new BigDecimal(NumOfMax)));
                    plannedQty = MaxQty.multiply(new BigDecimal(NumOfMax));
                    if (MathUtils.compareToZero(Remainder) != 0) {
                        if (Remainder.compareTo(MinQty) == -1)
                            plannedQty = plannedQty.add(MinQty);
                        else {
                            long NumOfInc = Remainder.subtract(MinQty).divide(Increment).longValue();
                            RemInc = Remainder.subtract(MinQty)
                                    .subtract(Increment.multiply(new BigDecimal(NumOfInc)));
                            if (MathUtils.compareToZero(RemInc) != 0)
                                plannedQty = plannedQty.add(MinQty)
                                        .add(Increment.multiply(new BigDecimal(NumOfInc))).add(Increment);
                            else
                                plannedQty = plannedQty.add(Remainder);
                        }
                    }
                }
            }
            availableOnBeginBucket = mpsLine.calculateAvailableQuantityOnEndBucket(plannedQty,
                    availableOnBeginBucket);

            if (MathUtils.compareToZero(plannedQty) < 0)
                plannedQty = BigDecimal.ZERO;
            mpsLine.setPlannedQty(plannedQty);
        }
    }
}

From source file:com.mg.merp.planning.support.MPSProcessorServiceBean.java

private RollUpMPSResult rollUpMPS(Mps mpsDst, MpsLine srcMpsLine, BigDecimal quan, Date countDay,
        int mpsSequence) {
    BigDecimal roundedQty = quan;
    if (srcMpsLine.getPlanningItem().getCatalog() != null) {
        Bom bom = bomService.findCurrentBOM(srcMpsLine.getPlanningItem().getCatalog().getId());
        if (bom != null) {
            BigDecimal maxQty = bom.getMaxLotQty();
            BigDecimal minQty = bom.getMinLotQty();
            BigDecimal increment = bom.getLotIncrementQty();

            if (!(MathUtils.compareToZeroOrNull(maxQty) == 0 || MathUtils.compareToZeroOrNull(minQty) == 0
                    || MathUtils.compareToZeroOrNull(increment) == 0)) {
                if (bom.getCatalog().getMeasure1().getId() != srcMpsLine.getPlanningItem().getMeasure()
                        .getId()) {//from   w ww  .j a  v  a  2 s  .com
                    maxQty = getMeasureConversionService().conversion(bom.getCatalog().getMeasure1(),
                            srcMpsLine.getPlanningItem().getMeasure(), bom.getCatalog(),
                            srcMpsLine.getBucketOffsetDate(), maxQty);
                    minQty = getMeasureConversionService().conversion(bom.getCatalog().getMeasure1(),
                            srcMpsLine.getPlanningItem().getMeasure(), bom.getCatalog(),
                            srcMpsLine.getBucketOffsetDate(), minQty);
                    increment = getMeasureConversionService().conversion(bom.getCatalog().getMeasure1(),
                            srcMpsLine.getPlanningItem().getMeasure(), bom.getCatalog(),
                            srcMpsLine.getBucketOffsetDate(), increment);
                }

                long numOfMax = roundedQty.divide(maxQty).longValue();
                roundedQty = maxQty.multiply(new BigDecimal(numOfMax));
                BigDecimal remainder = roundedQty.add(roundedQty);

                if (MathUtils.compareToZero(remainder) != 0) {
                    if (remainder.compareTo(minQty) < 0) {
                        roundedQty = roundedQty.add(minQty);
                    } else {
                        long numOfInc = remainder.subtract(minQty).divide(increment).longValue();
                        BigDecimal remInc = remainder.subtract(minQty)
                                .subtract(increment.multiply(new BigDecimal(numOfInc)));
                        if (MathUtils.compareToZero(remInc) != 0)
                            roundedQty = roundedQty.add(minQty)
                                    .add(increment.multiply(new BigDecimal(numOfInc))).add(increment);
                        else
                            roundedQty = roundedQty.add(remainder);

                    }
                }
            }
        }
    }

    short bucket = MfUtils.determineBucketOffset(mpsDst.getPlanningLevel().getId(), countDay);
    MpsLine mpsLine = null;
    for (MpsLine line : generatedMPSLines) {
        if (MathUtils.compareToZero(line.getProductionDemandQty()) <= 0
                && line.getPlanningItem().getId() == srcMpsLine.getPlanningItem().getId()
                && line.getBucketOffset() == bucket) {
            mpsLine = line;
            break;
        }
    }
    if (mpsLine == null) {
        mpsLine = mpsLineService.initialize();
        mpsLine.setPlanningItem(srcMpsLine.getPlanningItem());
        mpsLine.setLevelCode(srcMpsLine.getPlanningItem().getLowLevelCode());
        mpsLine.setMps(mpsDst);
        mpsLine.setBucketOffset(bucket);
        BucketRange bucketRange = MfUtils.determineBucketRange(mpsDst.getPlanningLevel().getId(), bucket);
        mpsLine.setBucketOffsetDate(bucketRange.getBucketStart());
        mpsLine.setDemandFenceDate(srcMpsLine.getDemandFenceDate());
        mpsLine.setMpsSequence(mpsSequence);
        mpsLine.setOutputMpsSequence(null);
        mpsLine.setMeasure(srcMpsLine.getMeasure());
        mpsLine.setPlannedQty(roundedQty);

        generatedMPSLines.add(mpsLine);
        //    ? MPS
        return new RollUpMPSResult(roundedQty, mpsSequence + 1);
    } else {
        mpsLine.setPlannedQty(mpsLine.getPlannedQty().add(roundedQty));
        return new RollUpMPSResult(roundedQty, mpsSequence);
    }
}

From source file:org.libreplan.business.orders.entities.OrderElement.java

public BigDecimal calculateBudgetFromCriteriaAndCostCategories() {
    BigDecimal totalBudget = new BigDecimal(0);

    Configuration configuration = Registry.getConfigurationDAO().getConfiguration();
    TypeOfWorkHours typeofWorkHours = configuration.getBudgetDefaultTypeOfWorkHours();

    if (!configuration.isEnabledAutomaticBudget()
            || (configuration.getBudgetDefaultTypeOfWorkHours() == null)) {
        return totalBudget;
    }//from   w ww  . j  a v a2 s  . c  o  m

    BigDecimal costPerHour = new BigDecimal(0);
    BigDecimal hours;

    for (HoursGroup hoursGroup : getHoursGroups()) {
        hours = new BigDecimal(hoursGroup.getWorkingHours());

        for (CriterionRequirement crit : hoursGroup.getCriterionRequirements()) {
            CostCategory costcat = crit.getCriterion().getCostCategory();

            if (costcat != null) {

                IHourCostDAO hourCostDAO = Registry.getHourCostDAO();
                costPerHour = hourCostDAO.getPriceCostFromCriterionAndType(costcat, typeofWorkHours);

            }
            totalBudget = totalBudget.add(costPerHour.multiply(hours));
        }
        if (hoursGroup.getCriterionRequirements().size() > 1) {
            totalBudget = totalBudget.divide(new BigDecimal(hoursGroup.getCriterionRequirements().size()));
        }
    }

    return totalBudget;
}

From source file:com.ugam.collage.plus.service.people_count.impl.PeopleAccountingServiceImpl.java

@Override
public List<EmpcntClientProjectDataVo> generateEmployeeSummary(Integer yearId, Integer monthId,
        String costCentreId) {//w  w w  . jav a2s . c  om

    List<EmpcntClientProjectDataVo> empcntClientProjectDataVoList = new ArrayList<EmpcntClientProjectDataVo>();
    List<EmpcntClientProjectData> empcntClientProjectDataList = new ArrayList<EmpcntClientProjectData>();
    List<EmpcntClientProjectData> empOpenCntClientProjectDataList = new ArrayList<EmpcntClientProjectData>();
    List<EmpcntClientProjectData> empCloseCntClientProjectDataList = new ArrayList<EmpcntClientProjectData>();
    List<EmpcntClientProjectData> empAverageCntClientProjectDataList = new ArrayList<EmpcntClientProjectData>();
    List<EmpcntProjectActivityData> empcntProjectActivityDataList = new ArrayList<EmpcntProjectActivityData>();
    Map<String, EmployeePcTagsTeamStruct> employeePcTagsTeamStructMap = new HashMap<String, EmployeePcTagsTeamStruct>();
    // Get opening count loop
    List<EmployeeMonthlyAssignment> openCountList = employeeMonthlyAssignmentDao.findByOpeningCount(yearId,
            monthId, costCentreId);

    // Get closing count loop
    List<EmployeeMonthlyAssignment> closingCountList = employeeMonthlyAssignmentDao.findByClosingCount(yearId,
            monthId, costCentreId);

    Integer openCountTypeId = Constants.COUNT_CLASSIFICATION_TYPE_OPENING;
    Integer closeCountTypeId = 2;
    // logger.debug("{Opening Count }===>openCountList.size()}:" +
    // openCountList.size());
    // logger.debug("{Close Count }===>closingCountList.size()}:" +
    // closingCountList.size());
    // Check For Opening Count Rule
    for (EmployeeMonthlyAssignment openCount : openCountList) {

        List<Integer> employeeIdList = new ArrayList<Integer>();
        employeeIdList.add(openCount.getEmployeeMaster().getEmployeeId());

        Integer ruleId = openCount.getEmployeeCntRulesByOpeningRuleId().getId();
        // logger.debug("Rule Id:===========================>" +ruleId);
        switch (ruleId) {
        case 1:
            // logger.debug("{Opening Count EmployeeMonthlyAssignment}===>getEmployeeMaster}:"
            // + openCount.getEmployeeMaster());
            defaultRule(yearId, monthId, costCentreId, empcntClientProjectDataVoList,
                    empOpenCntClientProjectDataList, empAverageCntClientProjectDataList,
                    empCloseCntClientProjectDataList, employeeIdList, openCount, openCountTypeId,
                    employeePcTagsTeamStructMap);

            break;
        case 2:
            ruleOne(yearId, monthId, costCentreId, empOpenCntClientProjectDataList,
                    empAverageCntClientProjectDataList, empCloseCntClientProjectDataList, employeeIdList,
                    openCount, openCountTypeId, employeePcTagsTeamStructMap);
            break;
        case 3:
            ruleTwo(yearId, monthId, costCentreId, empOpenCntClientProjectDataList,
                    empAverageCntClientProjectDataList, empCloseCntClientProjectDataList, employeeIdList,
                    openCount, openCountTypeId, employeePcTagsTeamStructMap);
            break;
        case 4:
            ruleThree(yearId, monthId, costCentreId, empOpenCntClientProjectDataList,
                    empAverageCntClientProjectDataList, empCloseCntClientProjectDataList, employeeIdList,
                    openCount, openCountTypeId, employeePcTagsTeamStructMap);
            break;
        case 5:
            ruleFour(yearId, monthId, costCentreId, empOpenCntClientProjectDataList,
                    empAverageCntClientProjectDataList, empCloseCntClientProjectDataList, employeeIdList,
                    openCount, openCountTypeId, employeePcTagsTeamStructMap);
            break;
        case 6:
            ruleFive(yearId, monthId, costCentreId, empOpenCntClientProjectDataList,
                    empAverageCntClientProjectDataList, empCloseCntClientProjectDataList, employeeIdList,
                    openCount, openCountTypeId, employeePcTagsTeamStructMap);
            break;
        case 7:
            ruleSix(yearId, monthId, costCentreId, empOpenCntClientProjectDataList,
                    empAverageCntClientProjectDataList, empCloseCntClientProjectDataList, employeeIdList,
                    openCount, openCountTypeId, employeePcTagsTeamStructMap);
            break;
        }
    }
    // logger.debug("{Clossing Count }===>openCountList.size()}:" +
    // closingCountList.size());
    // Check For Clossing Count Rule
    for (EmployeeMonthlyAssignment closingCount : closingCountList) {
        List<Integer> employeeIdList = new ArrayList<Integer>();
        employeeIdList.add(closingCount.getEmployeeMaster().getEmployeeId());

        Integer ruleId = closingCount.getEmployeeCntRulesByOpeningRuleId().getId();
        switch (ruleId) {
        case 1:
            defaultRule(yearId, monthId, costCentreId, empcntClientProjectDataVoList,
                    empOpenCntClientProjectDataList, empCloseCntClientProjectDataList,
                    empAverageCntClientProjectDataList, employeeIdList, closingCount, closeCountTypeId,
                    employeePcTagsTeamStructMap);

            break;
        case 2:
            ruleOne(yearId, monthId, costCentreId, empOpenCntClientProjectDataList,
                    empAverageCntClientProjectDataList, empCloseCntClientProjectDataList, employeeIdList,
                    closingCount, closeCountTypeId, employeePcTagsTeamStructMap);
            break;
        case 3:
            ruleTwo(yearId, monthId, costCentreId, empOpenCntClientProjectDataList,
                    empAverageCntClientProjectDataList, empCloseCntClientProjectDataList, employeeIdList,
                    closingCount, closeCountTypeId, employeePcTagsTeamStructMap);
            break;
        case 4:
            ruleThree(yearId, monthId, costCentreId, empOpenCntClientProjectDataList,
                    empAverageCntClientProjectDataList, empCloseCntClientProjectDataList, employeeIdList,
                    closingCount, closeCountTypeId, employeePcTagsTeamStructMap);
            break;
        case 5:
            ruleFour(yearId, monthId, costCentreId, empOpenCntClientProjectDataList,
                    empAverageCntClientProjectDataList, empCloseCntClientProjectDataList, employeeIdList,
                    closingCount, closeCountTypeId, employeePcTagsTeamStructMap);
            break;
        case 6:
            ruleFive(yearId, monthId, costCentreId, empOpenCntClientProjectDataList,
                    empAverageCntClientProjectDataList, empCloseCntClientProjectDataList, employeeIdList,
                    closingCount, closeCountTypeId, employeePcTagsTeamStructMap);
            break;
        case 7:
            ruleSix(yearId, monthId, costCentreId, empOpenCntClientProjectDataList,
                    empAverageCntClientProjectDataList, empCloseCntClientProjectDataList, employeeIdList,
                    closingCount, closeCountTypeId, employeePcTagsTeamStructMap);
            break;
        }
    }
    // Need to implement for Cost centre CI

    if (costCentreId.equalsIgnoreCase("CI")) {
        for (EmpcntClientProjectData empcntClientProjectData : empcntClientProjectDataList) {
            // Get Data Id for given Employee Id
            List<CustomGroupTab3FieldsData> customGroupTab3FieldsDataList = customGroupTab3FieldsDataDao
                    .findByYearIdMonthIdDataId(yearId, monthId,
                            empcntClientProjectData.getEmployeeMaster().getEmployeeId());
            if (customGroupTab3FieldsDataList.isEmpty()) {
                ActivityFinanceMaster activityFinanceMaster = new ActivityFinanceMaster();
                activityFinanceMaster.setActFinId(4);
                EmpcntProjectActivityData empcntProjectActivityData = new EmpcntProjectActivityData(
                        empcntClientProjectData.getEmployeeMaster(), activityFinanceMaster,
                        empcntClientProjectData.getCountClassification(), empcntClientProjectData.getTabMonth(),
                        empcntClientProjectData.getProjectMaster(), empcntClientProjectData.getTabYear(),
                        empcntClientProjectData.getCostCentre(), empcntClientProjectData.getAssignedCnt(),
                        empcntClientProjectData.getAssistedCnt(), empcntClientProjectData.getApportionedCnt(),
                        empcntClientProjectData.getTotalCnt());
                empcntProjectActivityDataList.add(empcntProjectActivityData);
            } else {
                ActivityFinanceMaster activityFinanceMaster = new ActivityFinanceMaster();
                activityFinanceMaster.setActFinId(customGroupTab3FieldsDataList.get(0).getDataId());
                EmpcntProjectActivityData empcntProjectActivityData = new EmpcntProjectActivityData(
                        empcntClientProjectData.getEmployeeMaster(), activityFinanceMaster,
                        empcntClientProjectData.getCountClassification(), empcntClientProjectData.getTabMonth(),
                        empcntClientProjectData.getProjectMaster(), empcntClientProjectData.getTabYear(),
                        empcntClientProjectData.getCostCentre(), empcntClientProjectData.getAssignedCnt(),
                        empcntClientProjectData.getAssistedCnt(), empcntClientProjectData.getApportionedCnt(),
                        empcntClientProjectData.getTotalCnt());
                empcntProjectActivityDataList.add(empcntProjectActivityData);
            }
        }
    }

    // Calcuate Average count
    Map<String, EmpcntClientProjectData> openDataMap = new HashMap<String, EmpcntClientProjectData>();
    Map<String, EmpcntClientProjectData> closeDataMap = new HashMap<String, EmpcntClientProjectData>();

    if (!empOpenCntClientProjectDataList.isEmpty() && !empCloseCntClientProjectDataList.isEmpty()) {
        // y_m_e_c_p_c_

        for (EmpcntClientProjectData openData : empOpenCntClientProjectDataList) {
            Integer empId = openData.getEmployeeMaster().getEmployeeId();
            Integer compId = openData.getCompanyMaster().getCompanyId();
            Integer proId = openData.getProjectMaster().getProjectId();
            String key = yearId + "-" + monthId + "-" + empId + "-" + compId + "-" + proId + "-" + 1;
            // logger.debug("Open Map key:"+key);
            openDataMap.put(key, openData);
        }
        for (EmpcntClientProjectData closedata : empCloseCntClientProjectDataList) {
            Integer empId = closedata.getEmployeeMaster().getEmployeeId();
            Integer compId = closedata.getCompanyMaster().getCompanyId();
            Integer proId = closedata.getProjectMaster().getProjectId();
            String key = yearId + "-" + monthId + "-" + empId + "-" + compId + "-" + proId + "-" + 2;
            // logger.debug("Close Map key:"+key);
            closeDataMap.put(key, closedata);
        }
    }

    // Calcuate Average count
    Map<String, EmpcntClientProjectData> openDatas = new HashMap<String, EmpcntClientProjectData>();
    Map<String, EmpcntClientProjectData> closeDatas = new HashMap<String, EmpcntClientProjectData>();
    if (empOpenCntClientProjectDataList.isEmpty() || empCloseCntClientProjectDataList.isEmpty()) {
        // logger.debug("List is empty");
        return null;
    } else if (!openDataMap.isEmpty() && !closeDataMap.isEmpty()) {
        // y_m_e_c_p_c_
        Integer openCount = openDataMap.size();
        Integer closeCount = closeDataMap.size();
        BigDecimal averageCount = new BigDecimal(2);
        for (String keyVal : openDataMap.keySet()) {
            EmpcntClientProjectData openData = openDataMap.get(keyVal);
            Integer empId = openData.getEmployeeMaster().getEmployeeId();
            Integer compId = openData.getCompanyMaster().getCompanyId();
            Integer proId = openData.getProjectMaster().getProjectId();
            String key = yearId + "-" + monthId + "-" + empId + "-" + compId + "-" + proId + "-" + 2;
            // logger.debug("Average key:"+key);
            openDatas.put(key, openData);
        }
        for (String keyVal : closeDataMap.keySet()) {
            logger.debug("Close Map key:" + keyVal);
            EmpcntClientProjectData closedata = closeDataMap.get(keyVal);
            Integer empId = closedata.getEmployeeMaster().getEmployeeId();
            Integer compId = closedata.getCompanyMaster().getCompanyId();
            Integer proId = closedata.getProjectMaster().getProjectId();
            String key = yearId + "-" + monthId + "-" + empId + "-" + compId + "-" + proId + "-" + 2;
            logger.debug("Average key:" + key);
            closeDatas.put(key, closedata);
        }
        if (openCount == closeCount) {
            for (String key : openDatas.keySet()) {
                EmpcntClientProjectData avgData = openDatas.get(key);
                CountClassification avgCount = new CountClassification();
                avgCount.setId(3);
                EmployeeMaster employee = avgData.getEmployeeMaster();
                TabMonth month = avgData.getTabMonth();
                TabYear year = avgData.getTabYear();
                CostCentre costCentre = avgData.getCostCentre();
                EmpcntClientProjectData averageEmpcntClientProjectData = new EmpcntClientProjectData(employee,
                        avgData.getCompanyMaster(), avgCount, month, avgData.getProjectMaster(), year,
                        costCentre, avgData.getAssignedCnt(), avgData.getAssistedCnt(),
                        avgData.getApportionedCnt(), avgData.getTotalCnt());

                empAverageCntClientProjectDataList.add(averageEmpcntClientProjectData);
            }
        }
        if (openCount < closeCount) {
            for (String key : closeDatas.keySet()) {
                if (openDatas.containsKey(key)) {
                    EmpcntClientProjectData avgData = openDatas.get(key);
                    CountClassification avgCount = new CountClassification();
                    avgCount.setId(3);
                    EmployeeMaster employee = avgData.getEmployeeMaster();
                    TabMonth month = avgData.getTabMonth();
                    TabYear year = avgData.getTabYear();
                    CostCentre costCentre = avgData.getCostCentre();

                    EmpcntClientProjectData averageEmpcntClientProjectData = new EmpcntClientProjectData(
                            employee, avgData.getCompanyMaster(), avgCount, month, avgData.getProjectMaster(),
                            year, costCentre, avgData.getAssignedCnt(), avgData.getAssistedCnt(),
                            avgData.getApportionedCnt(), avgData.getTotalCnt());

                    empAverageCntClientProjectDataList.add(averageEmpcntClientProjectData);
                } else {
                    EmpcntClientProjectData avgData = closeDatas.get(key);
                    CountClassification avgCount = new CountClassification();
                    avgCount.setId(3);
                    EmployeeMaster employee = avgData.getEmployeeMaster();
                    TabMonth month = avgData.getTabMonth();
                    TabYear year = avgData.getTabYear();
                    CostCentre costCentre = avgData.getCostCentre();
                    ProjectMaster projectMaster = avgData.getProjectMaster();
                    CompanyMaster companyMaster = avgData.getCompanyMaster();

                    BigDecimal assignedCnt = avgData.getAssignedCnt();
                    assignedCnt = assignedCnt.divide(averageCount);

                    BigDecimal asssistedCnt = avgData.getAssistedCnt();
                    asssistedCnt = asssistedCnt.divide(averageCount);

                    BigDecimal apportionedCnt = avgData.getApportionedCnt();
                    apportionedCnt = apportionedCnt.divide(averageCount);

                    BigDecimal totalCnt = avgData.getTotalCnt();
                    totalCnt = totalCnt.divide(averageCount);

                    EmpcntClientProjectData averageEmpcntClientProjectData = new EmpcntClientProjectData(
                            employee, companyMaster, avgCount, month, projectMaster, year, costCentre,
                            assignedCnt, asssistedCnt, apportionedCnt, totalCnt);

                    empAverageCntClientProjectDataList.add(averageEmpcntClientProjectData);
                }

            }
        }
        if (openCount > closeCount) {
            for (String key : openDatas.keySet()) {
                if (closeDatas.containsKey(key)) {
                    EmpcntClientProjectData avgData = openDatas.get(key);
                    CountClassification avgCount = new CountClassification();
                    avgCount.setId(3);
                    EmployeeMaster employee = avgData.getEmployeeMaster();
                    TabMonth month = avgData.getTabMonth();
                    TabYear year = avgData.getTabYear();
                    CostCentre costCentre = avgData.getCostCentre();

                    EmpcntClientProjectData averageEmpcntClientProjectData = new EmpcntClientProjectData(
                            employee, avgData.getCompanyMaster(), avgCount, month, avgData.getProjectMaster(),
                            year, costCentre, avgData.getAssignedCnt(), avgData.getAssistedCnt(),
                            avgData.getApportionedCnt(), avgData.getTotalCnt());

                    empAverageCntClientProjectDataList.add(averageEmpcntClientProjectData);
                } else {
                    EmpcntClientProjectData avgData = openDatas.get(key);
                    CountClassification avgCount = new CountClassification();
                    avgCount.setId(3);
                    EmployeeMaster employee = avgData.getEmployeeMaster();
                    TabMonth month = avgData.getTabMonth();
                    TabYear year = avgData.getTabYear();
                    CostCentre costCentre = avgData.getCostCentre();
                    ProjectMaster projectMaster = avgData.getProjectMaster();
                    CompanyMaster companyMaster = avgData.getCompanyMaster();

                    BigDecimal assignedCnt = avgData.getAssignedCnt();
                    assignedCnt = assignedCnt.divide(averageCount);

                    BigDecimal asssistedCnt = avgData.getAssistedCnt();
                    asssistedCnt = asssistedCnt.divide(averageCount);

                    BigDecimal apportionedCnt = avgData.getApportionedCnt();
                    apportionedCnt = apportionedCnt.divide(averageCount);

                    BigDecimal totalCnt = avgData.getTotalCnt();
                    totalCnt = totalCnt.divide(averageCount);

                    EmpcntClientProjectData averageEmpcntClientProjectData = new EmpcntClientProjectData(
                            employee, companyMaster, avgCount, month, projectMaster, year, costCentre,
                            assignedCnt, asssistedCnt, apportionedCnt, totalCnt);

                    empAverageCntClientProjectDataList.add(averageEmpcntClientProjectData);
                }

            }
        }
    }

    // Delete old values
    if (!empOpenCntClientProjectDataList.isEmpty() && !empCloseCntClientProjectDataList.isEmpty()) {
        logger.debug("********************IN DELETE*****************************");
        List<EmpcntClientProjectData> empCountClientProjectDataList = empcntClientProjectDataDao
                .findByYearIdMonthIdCostCentreId(yearId, monthId, costCentreId);
        logger.debug("empCountClientProjectDataList size ===>" + empCountClientProjectDataList.size());
        for (EmpcntClientProjectData empcntClientProjectData : empCountClientProjectDataList) {

            empcntClientProjectDataDao.delete(empcntClientProjectData);
        }
    }
    logger.debug("----------------------------->Open Map size:" + openDataMap.size());
    logger.debug("----------------------------->Close Map size:" + closeDataMap.size());
    if (!openDataMap.isEmpty() && !empCloseCntClientProjectDataList.isEmpty()) {

        logger.debug("**************************************************");
        for (String keyVal : openDataMap.keySet()) {
            EmpcntClientProjectData empcntClientProjectData = openDataMap.get(keyVal);
            empcntClientProjectDataDao.create(empcntClientProjectData);
        }
        for (String keyVal : closeDataMap.keySet()) {
            EmpcntClientProjectData empcntClientProjectData = closeDataMap.get(keyVal);
            empcntClientProjectDataDao.create(empcntClientProjectData);
        }
        // Save Average count list data
        if (!empAverageCntClientProjectDataList.isEmpty()) {
            for (EmpcntClientProjectData empcntClientProjectData : empAverageCntClientProjectDataList) {
                empcntClientProjectDataDao.create(empcntClientProjectData);
            }
        }

        for (EmpcntProjectActivityData empcntProjectActivityData : empcntProjectActivityDataList) {
            empcntProjectActivityDataDao.create(empcntProjectActivityData);
        }
    }
    if (!employeePcTagsTeamStructMap.isEmpty()) {
        for (String key : employeePcTagsTeamStructMap.keySet()) {
            EmployeePcTagsTeamStruct employeePcTagsTeamStruct = employeePcTagsTeamStructMap.get(key);
            employeePcTagsTeamStructDao.saveOrUpdate(employeePcTagsTeamStruct);
        }
    } else {
        logger.debug("===>Somthing wrong happen. Please run again");
    }
    Integer typeId = 1;
    empcntClientProjectDataList = new ArrayList<EmpcntClientProjectData>();
    empcntClientProjectDataList = empcntClientProjectDataDao.findByYearIdMonthIdCostCentreIdTypeId(yearId,
            monthId, costCentreId, typeId);
    for (EmpcntClientProjectData empcntClientProjectData : empcntClientProjectDataList) {
        EmpcntClientProjectDataVo empcntClientProjectDataVo = new EmpcntClientProjectDataVo(
                empcntClientProjectData.getTabYear().getYearId(),
                empcntClientProjectData.getTabMonth().getMonthId(),
                empcntClientProjectData.getEmployeeMaster().getEmployeeId(),
                empcntClientProjectData.getCountClassification().getId(),
                empcntClientProjectData.getProjectMaster().getProjectName(),
                empcntClientProjectData.getCompanyMaster().getCompanyName(),
                empcntClientProjectData.getAssignedCnt(), empcntClientProjectData.getAssistedCnt(),
                empcntClientProjectData.getApportionedCnt(), empcntClientProjectData.getTotalCnt());
        empcntClientProjectDataVo.setId(empcntClientProjectData.getId());
        empcntClientProjectDataVoList.add(empcntClientProjectDataVo);
    }
    List<BigDecimal> apportionCount = employeePcTagsTeamStructDao.findByYearIdMonthIdCostCentreId(yearId,
            monthId, costCentreId);
    logger.debug("*************************************===>" + apportionCount.size());
    if (!apportionCount.isEmpty()) {
        BigDecimal count = apportionCount.get(0);
        EmpcntClientProjectDataVo apportionCountVo = new EmpcntClientProjectDataVo(yearId, monthId, 0, 0,
                "No-Client", "No-Project", BigDecimal.ZERO, BigDecimal.ZERO, count, count);
        empcntClientProjectDataVoList.add(apportionCountVo);
    }

    return empcntClientProjectDataVoList;
}

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

/**
 * Calculates the discount item for this invoice.
 *
 * @param invoiceDocument The payment request document whose discount to be calculated.
 *//*from w  w w  .ja v  a  2  s  . c om*/
protected void calculateDiscount(InvoiceDocument invoiceDocument) {
    InvoiceItem discountItem = findDiscountItem(invoiceDocument);
    // find out if we really need the discount item
    PaymentTermType pt = invoiceDocument.getVendorPaymentTerms();
    if ((pt != null) && (pt.getVendorPaymentTermsPercent() != null)
            && (BigDecimal.ZERO.compareTo(pt.getVendorPaymentTermsPercent()) != 0)) {
        if (discountItem == null) {
            // set discountItem and add to items
            // this is probably not the best way of doing it but should work for now if we start excluding discount from below
            // we will need to manually add
            purapService.addBelowLineItems(invoiceDocument);

            // fix up below the line items
            removeIneligibleAdditionalCharges(invoiceDocument);

            discountItem = findDiscountItem(invoiceDocument);
        }

        // Deleted the discountItem.getExtendedPrice() null and isZero
        InvoiceItem fullOrderItem = findFullOrderDiscountItem(invoiceDocument);
        KualiDecimal fullOrderAmount = KualiDecimal.ZERO;
        KualiDecimal fullOrderTaxAmount = KualiDecimal.ZERO;

        if (fullOrderItem != null) {
            fullOrderAmount = (ObjectUtils.isNotNull(fullOrderItem.getExtendedPrice()))
                    ? fullOrderItem.getExtendedPrice()
                    : KualiDecimal.ZERO;
            fullOrderTaxAmount = (ObjectUtils.isNotNull(fullOrderItem.getItemTaxAmount()))
                    ? fullOrderItem.getItemTaxAmount()
                    : KualiDecimal.ZERO;
        }
        KualiDecimal totalCost = invoiceDocument.getTotalPreTaxDollarAmountAboveLineItems()
                .add(fullOrderAmount);
        PurApItem tradeInItem = invoiceDocument.getTradeInItem();
        if (ObjectUtils.isNotNull(tradeInItem)) {
            totalCost = totalCost.subtract(tradeInItem.getTotalAmount());
        }
        BigDecimal discountAmount = pt.getVendorPaymentTermsPercent().multiply(totalCost.bigDecimalValue())
                .multiply(new BigDecimal(PurapConstants.PRQS_DISCOUNT_MULT));

        // do we really need to set both, not positive, but probably won't hurt
        discountItem.setItemUnitPrice(discountAmount.setScale(4, KualiDecimal.ROUND_BEHAVIOR));
        discountItem.setExtendedPrice(new KualiDecimal(discountAmount));

        // set tax amount
        boolean salesTaxInd = parameterService.getParameterValueAsBoolean(
                OleParameterConstants.PURCHASING_DOCUMENT.class, PurapParameterConstants.ENABLE_SALES_TAX_IND);
        boolean useTaxIndicator = invoiceDocument.isUseTaxIndicator();

        if (salesTaxInd == true && useTaxIndicator == false) {
            KualiDecimal totalTax = invoiceDocument.getTotalTaxAmountAboveLineItems().add(fullOrderTaxAmount);
            BigDecimal discountTaxAmount = null;
            if (totalCost.isNonZero()) {
                discountTaxAmount = discountAmount.divide(totalCost.bigDecimalValue())
                        .multiply(totalTax.bigDecimalValue());
            } else {
                discountTaxAmount = BigDecimal.ZERO;
            }

            discountItem.setItemTaxAmount(new KualiDecimal(
                    discountTaxAmount.setScale(KualiDecimal.SCALE, KualiDecimal.ROUND_BEHAVIOR)));
        }

        // set document
        discountItem.setPurapDocument(invoiceDocument);
    } else { // no discount
        if (discountItem != null) {
            invoiceDocument.getItems().remove(discountItem);
        }
    }

}

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

/**
 * Calculates the discount item for this paymentRequest.
 *
 * @param paymentRequestDocument The payment request document whose discount to be calculated.
 *///w ww .ja va 2  s.  co  m
protected void calculateDiscount(PaymentRequestDocument paymentRequestDocument) {
    PaymentRequestItem discountItem = findDiscountItem(paymentRequestDocument);
    // find out if we really need the discount item
    PaymentTermType pt = paymentRequestDocument.getVendorPaymentTerms();
    if ((pt != null) && (pt.getVendorPaymentTermsPercent() != null)
            && (BigDecimal.ZERO.compareTo(pt.getVendorPaymentTermsPercent()) != 0)) {
        if (discountItem == null) {
            // set discountItem and add to items
            // this is probably not the best way of doing it but should work for now if we start excluding discount from below
            // we will need to manually add
            purapService.addBelowLineItems(paymentRequestDocument);

            // fix up below the line items
            removeIneligibleAdditionalCharges(paymentRequestDocument);

            discountItem = findDiscountItem(paymentRequestDocument);
        }

        // Deleted the discountItem.getExtendedPrice() null and isZero
        PaymentRequestItem fullOrderItem = findFullOrderDiscountItem(paymentRequestDocument);
        KualiDecimal fullOrderAmount = KualiDecimal.ZERO;
        KualiDecimal fullOrderTaxAmount = KualiDecimal.ZERO;

        if (fullOrderItem != null) {
            fullOrderAmount = (ObjectUtils.isNotNull(fullOrderItem.getExtendedPrice()))
                    ? fullOrderItem.getExtendedPrice()
                    : KualiDecimal.ZERO;
            fullOrderTaxAmount = (ObjectUtils.isNotNull(fullOrderItem.getItemTaxAmount()))
                    ? fullOrderItem.getItemTaxAmount()
                    : KualiDecimal.ZERO;
        }
        KualiDecimal totalCost = paymentRequestDocument.getTotalPreTaxDollarAmountAboveLineItems()
                .add(fullOrderAmount);
        PurApItem tradeInItem = paymentRequestDocument.getTradeInItem();
        if (ObjectUtils.isNotNull(tradeInItem)) {
            totalCost = totalCost.subtract(tradeInItem.getTotalAmount());
        }
        BigDecimal discountAmount = pt.getVendorPaymentTermsPercent().multiply(totalCost.bigDecimalValue())
                .multiply(new BigDecimal(PurapConstants.PREQ_DISCOUNT_MULT));

        // do we really need to set both, not positive, but probably won't hurt
        discountItem.setItemUnitPrice(discountAmount.setScale(2, KualiDecimal.ROUND_BEHAVIOR));
        discountItem.setExtendedPrice(new KualiDecimal(discountAmount));

        // set tax amount
        boolean salesTaxInd = parameterService.getParameterValueAsBoolean(
                OleParameterConstants.PURCHASING_DOCUMENT.class, PurapParameterConstants.ENABLE_SALES_TAX_IND);
        boolean useTaxIndicator = paymentRequestDocument.isUseTaxIndicator();

        if (salesTaxInd == true && useTaxIndicator == false) {
            KualiDecimal totalTax = paymentRequestDocument.getTotalTaxAmountAboveLineItems()
                    .add(fullOrderTaxAmount);
            BigDecimal discountTaxAmount = null;
            if (totalCost.isNonZero()) {
                discountTaxAmount = discountAmount.divide(totalCost.bigDecimalValue())
                        .multiply(totalTax.bigDecimalValue());
            } else {
                discountTaxAmount = BigDecimal.ZERO;
            }

            discountItem.setItemTaxAmount(new KualiDecimal(
                    discountTaxAmount.setScale(KualiDecimal.SCALE, KualiDecimal.ROUND_BEHAVIOR)));
        }

        // set document
        discountItem.setPurapDocument(paymentRequestDocument);
    } else { // no discount
        if (discountItem != null) {
            paymentRequestDocument.getItems().remove(discountItem);
        }
    }

}