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.kuali.kpme.tklm.time.rules.overtime.weekly.service.WeeklyOvertimeRuleServiceImpl.java

/**
 * Applies overtime subtractions on the indicated TimeBlock.
 *
 * @param timeBlock The time block to reset the overtime on.
 * @param overtimeEarnCode The overtime earn code to apply overtime to.
 * @param convertFromEarnCodes The other earn codes on the time block.
 * @param overtimeHours The overtime hours to apply.
 *
 * @return the amount of overtime hours remaining to be applied.
 *///w  w  w.j a  v a 2  s .  co m
protected BigDecimal applyNegativeOvertimeOnTimeBlock(TimeBlockBo timeBlock, String overtimeEarnCode,
        Set<String> convertFromEarnCodes, BigDecimal overtimeHours) {
    BigDecimal applied = BigDecimal.ZERO;
    List<TimeHourDetailBo> timeHourDetails = timeBlock.getTimeHourDetails();
    List<TimeHourDetailBo> newTimeHourDetails = new ArrayList<TimeHourDetailBo>();

    for (TimeHourDetailBo timeHourDetail : timeHourDetails) {
        if (convertFromEarnCodes.contains(timeHourDetail.getEarnCode())) {
            TimeHourDetailBo overtimeTimeHourDetail = getTimeHourDetailByEarnCode(timeHourDetails,
                    Collections.singletonList(overtimeEarnCode));

            if (overtimeTimeHourDetail != null) { //if overtime already exists
                TimeHourDetail.Builder overtimeTimeHourDetailBuilder = TimeHourDetail.Builder
                        .create(overtimeTimeHourDetail);
                applied = overtimeTimeHourDetail.getHours().add(overtimeHours, HrConstants.MATH_CONTEXT); // add the negative number of hours of overtime to the existing OT hours
                if (applied.compareTo(BigDecimal.ZERO) >= 0) { //if the OT hours is still greater than or equal to zero, set 'applied' to this new negative number
                    applied = overtimeHours;
                } else {
                    //new OT value is now less than zero
                    applied = overtimeTimeHourDetail.getHours().negate(); //OT is now less than zer
                }

                EarnCodeContract earnCodeObj = HrServiceLocator.getEarnCodeService()
                        .getEarnCode(overtimeEarnCode, timeBlock.getEndDateTime().toLocalDate());
                BigDecimal hours = earnCodeObj.getInflateFactor().multiply(applied, HrConstants.MATH_CONTEXT)
                        .setScale(HrConstants.BIG_DECIMAL_SCALE, BigDecimal.ROUND_HALF_DOWN);

                overtimeTimeHourDetailBuilder
                        .setHours(overtimeTimeHourDetail.getHours().add(hours, HrConstants.MATH_CONTEXT));

                timeHourDetail.setHours(timeHourDetail.getHours().subtract(applied, HrConstants.MATH_CONTEXT)
                        .setScale(HrConstants.BIG_DECIMAL_SCALE, BigDecimal.ROUND_HALF_UP));
            }
        }
        newTimeHourDetails.add(timeHourDetail);
    }
    return overtimeHours.subtract(applied);
}

From source file:nl.strohalm.cyclos.services.transactions.PaymentServiceImpl.java

@Override
public List<ScheduledPaymentDTO> calculatePaymentProjection(final ProjectionDTO params) {
    getProjectionValidator().validate(params);

    final LocalSettings localSettings = settingsService.getLocalSettings();

    final int paymentCount = params.getPaymentCount();
    final TimePeriod recurrence = params.getRecurrence();
    final BigDecimal totalAmount = params.getAmount();
    final BigDecimal paymentAmount = localSettings.round(totalAmount
            .divide(CoercionHelper.coerce(BigDecimal.class, paymentCount), localSettings.getMathContext()));
    BigDecimal accumulatedAmount = BigDecimal.ZERO;
    Calendar currentDate = DateHelper.truncate(params.getFirstExpirationDate());
    final List<ScheduledPaymentDTO> payments = new ArrayList<ScheduledPaymentDTO>(paymentCount);
    for (int i = 0; i < paymentCount; i++) {
        final ScheduledPaymentDTO dto = new ScheduledPaymentDTO();
        dto.setDate(currentDate);/*ww  w .j a  v  a2s .c om*/
        dto.setAmount(i == paymentCount - 1 ? totalAmount.subtract(accumulatedAmount) : paymentAmount);
        payments.add(dto);
        accumulatedAmount = accumulatedAmount.add(dto.getAmount(), localSettings.getMathContext());
        currentDate = recurrence.add(currentDate);
    }
    return payments;
}

From source file:com.ylife.shoppingcart.service.impl.ShoppingCartServiceImpl.java

/**
 * /*  ww w.  j  a  v  a 2 s . c  o  m*/
 *
 * @param motheds
 * @param fe
 * @param num
 * @param weight
 * @return BigDecimal
 */
public BigDecimal computeFreight(String motheds, FreightExpress fe, Integer num, BigDecimal weight) {
    BigDecimal price = new BigDecimal(0);
    if (num == 0) {
        return price;
    }
    // 
    if ("0".equals(motheds)) {
        // ?
        if (num < Integer.parseInt(fe.getExpressStart().toString())) {
            //  =  +   -*
            int a = 0;
            BigDecimal temp = fe.getExpressPostageplus().multiply(new BigDecimal(a));
            price = fe.getExpressPostage().add(temp);
        } else {
            //  =  +   -*
            int a = num - Integer.parseInt(fe.getExpressStart().toString());
            BigDecimal temp = fe.getExpressPostageplus().multiply(
                    (new BigDecimal(a)).divide(new BigDecimal(fe.getExpressPlusN1()), 0, BigDecimal.ROUND_UP));
            price = fe.getExpressPostage().add(temp);
        }

        return price;
    } else {
        // ??
        if (weight.compareTo(new BigDecimal(fe.getExpressStart())) == -1) {
            // ? = ? + ?-?*?
            BigDecimal a = new BigDecimal(0);
            BigDecimal temp = fe.getExpressPostageplus().multiply(a);
            price = fe.getExpressPostage().add(temp);
        } else {
            // ? = ? + ?-?*?
            BigDecimal a = weight.subtract(new BigDecimal(fe.getExpressStart()));
            BigDecimal temp = fe.getExpressPostageplus()
                    .multiply(a.divide(new BigDecimal(fe.getExpressPlusN1()), 0, BigDecimal.ROUND_UP));
            price = fe.getExpressPostage().add(temp);
        }

        return price;
    }
}

From source file:org.kuali.ole.select.document.OleInvoiceDocument.java

/**
 * This method calculates the grand Total
 *
 * @param includeBelowTheLine/*from   ww w  .j  a v a 2 s .  com*/
 * @param itemsForTotal
 * @return
 */
protected KualiDecimal getInvoicedTotalWithAllItems(boolean includeBelowTheLine,
        List<OleInvoiceItem> itemsForTotal) {

    BigDecimal total = BigDecimal.ZERO;
    for (OleInvoiceItem item : itemsForTotal) {
        item.refreshReferenceObject(PurapPropertyConstants.ITEM_TYPE);
        ItemType it = item.getItemType();
        if (includeBelowTheLine || it.isLineItemIndicator()) {
            BigDecimal totalAmount = item.getTotalAmount().bigDecimalValue();
            BigDecimal itemTotal = (totalAmount != null) ? totalAmount : BigDecimal.ZERO;
            if (item.isDebitItem()) {
                total = total.add(itemTotal);
            } else {
                total = total.subtract(itemTotal);
            }
            /*if (item.getItemDiscount() != null) {
            total = total.subtract(item.getItemDiscount());
            }*/
        }
    }
    return new KualiDecimal(total);
}

From source file:com.ylife.shoppingcart.service.impl.ShoppingCartServiceImpl.java

/**
 * //from ww w  .  j a v a  2  s  .  co m
 *
 * @param motheds
 * @param frall
 * @param num
 * @param weight
 * @return BigDecimal
 */
public BigDecimal computeFreightAll(String motheds, FreightExpressAll frall, Integer num, BigDecimal weight) {
    BigDecimal price = new BigDecimal(0);
    if (num == 0) {
        return price;
    }
    // 
    if ("0".equals(motheds)) {
        // ?
        if (num < Integer.parseInt(frall.getExpressStart().toString())) {
            //  =  +   -*
            int a = 0;
            BigDecimal temp = frall.getExpressPostageplus().multiply(new BigDecimal(a));
            price = frall.getExpressPostage().add(temp);
        } else {
            //  =  +   -*
            int a = num - Integer.parseInt(frall.getExpressStart().toString());
            BigDecimal temp = frall.getExpressPostageplus().multiply((new BigDecimal(a))
                    .divide(new BigDecimal(frall.getExpressPlusN1()), 0, BigDecimal.ROUND_UP));
            price = frall.getExpressPostage().add(temp);
        }

        return price;
    } else {
        // ??
        if (weight.compareTo(new BigDecimal(frall.getExpressStart())) == -1) {
            // ? = ? + ?-?*?
            BigDecimal a = new BigDecimal(0);
            BigDecimal temp = frall.getExpressPostageplus().multiply(a);
            price = frall.getExpressPostage().add(temp);
        } else {
            // ? = ? + ?-?*?
            BigDecimal a = weight.subtract(new BigDecimal(frall.getExpressStart()));
            BigDecimal temp = frall.getExpressPostageplus()
                    .multiply(a.divide(new BigDecimal(frall.getExpressPlusN1()), 0, BigDecimal.ROUND_UP));
            price = frall.getExpressPostage().add(temp);
        }

        return price;
    }

}

From source file:org.openbravo.costing.CostingMigrationProcess.java

private void calculateCosts(Organization org) {
    Currency cur = FinancialUtils.getLegalEntityCurrency(org);
    String curId = cur.getId();/*from w  w  w . j  ava2 s. c o  m*/
    Set<String> orgs = OBContext.getOBContext().getOrganizationStructureProvider(org.getClient().getId())
            .getChildTree(org.getId(), true);
    String orgId = org.getId();

    int costPrecision = cur.getCostingPrecision().intValue();
    int stdPrecision = cur.getStandardPrecision().intValue();
    CostingRuleProcess crp = new CostingRuleProcess();
    // Update cost of inventories and process starting physical inventories.
    ScrollableResults icls = getCloseInventoryLines(orgs);
    String productId = "";
    BigDecimal totalCost = BigDecimal.ZERO;
    BigDecimal totalStock = BigDecimal.ZERO;
    int i = 0;
    try {
        while (icls.next()) {
            InventoryCountLine icl = (InventoryCountLine) icls.get(0);
            if (!productId.equals(icl.getProduct().getId())) {
                productId = icl.getProduct().getId();
                HashMap<String, BigDecimal> stock = getCurrentValuedStock(productId, curId, orgs, orgId);
                totalCost = stock.get("cost");
                totalStock = stock.get("stock");
            }

            MaterialTransaction trx = crp.getInventoryLineTransaction(icl);
            trx.setTransactionProcessDate(DateUtils.addSeconds(trx.getTransactionProcessDate(), -1));
            trx.setCurrency(OBDal.getInstance().get(Currency.class, curId));

            BigDecimal trxCost = BigDecimal.ZERO;
            if (totalStock.compareTo(BigDecimal.ZERO) != 0) {
                trxCost = totalCost.multiply(trx.getMovementQuantity().abs()).divide(totalStock, stdPrecision,
                        BigDecimal.ROUND_HALF_UP);
            }
            if (trx.getMovementQuantity().compareTo(totalStock) == 0) {
                // Last transaction adjusts remaining cost amount.
                trxCost = totalCost;
            }
            trx.setTransactionCost(trxCost);
            trx.setCostCalculated(true);
            trx.setCostingStatus("CC");
            OBDal.getInstance().save(trx);
            Currency legalEntityCur = FinancialUtils.getLegalEntityCurrency(trx.getOrganization());
            BigDecimal cost = BigDecimal.ZERO;
            if (BigDecimal.ZERO.compareTo(trx.getMovementQuantity()) != 0) {
                cost = trxCost.divide(trx.getMovementQuantity().abs(), costPrecision, BigDecimal.ROUND_HALF_UP);
            }
            if (!legalEntityCur.equals(cur)) {
                cost = FinancialUtils.getConvertedAmount(cost, cur, legalEntityCur, new Date(),
                        icl.getOrganization(), FinancialUtils.PRECISION_COSTING);
            }

            InventoryCountLine initICL = icl.getRelatedInventory();
            initICL.setCost(cost);
            OBDal.getInstance().save(initICL);

            totalCost = totalCost.subtract(trxCost);
            // MovementQty is already negative so add to totalStock to decrease it.
            totalStock = totalStock.add(trx.getMovementQuantity());

            if ((i % 100) == 0) {
                OBDal.getInstance().flush();
                OBDal.getInstance().getSession().clear();
                cur = OBDal.getInstance().get(Currency.class, curId);
            }
            i++;
        }
    } finally {
        icls.close();
    }

    OBDal.getInstance().flush();
    insertTrxCosts();

}

From source file:org.openbravo.advpaymentmngt.ad_actionbutton.ProcessInvoice.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    VariablesSecureApp vars = new VariablesSecureApp(request);

    if (vars.commandIn("DEFAULT")) {
        final String strWindowId = vars.getGlobalVariable("inpwindowId", "ProcessInvoice|Window_ID",
                IsIDFilter.instance);/*from   ww w .j av  a 2 s  . c  o  m*/
        final String strTabId = vars.getGlobalVariable("inpTabId", "ProcessInvoice|Tab_ID",
                IsIDFilter.instance);

        final String strC_Invoice_ID = vars.getGlobalVariable("inpcInvoiceId", strWindowId + "|C_Invoice_ID",
                "", IsIDFilter.instance);

        final String strdocaction = vars.getStringParameter("inpdocaction");
        final String strProcessing = vars.getStringParameter("inpprocessing", "Y");
        final String strOrg = vars.getRequestGlobalVariable("inpadOrgId", "ProcessInvoice|Org_ID",
                IsIDFilter.instance);
        final String strClient = vars.getStringParameter("inpadClientId", IsIDFilter.instance);

        final String strdocstatus = vars.getRequiredStringParameter("inpdocstatus");
        final String stradTableId = "318";
        final int accesslevel = 1;

        if ((org.openbravo.erpCommon.utility.WindowAccessData.hasReadOnlyAccess(this, vars.getRole(), strTabId))
                || !(Utility.isElementInList(
                        Utility.getContext(this, vars, "#User_Client", strWindowId, accesslevel), strClient)
                        && Utility.isElementInList(
                                Utility.getContext(this, vars, "#User_Org", strWindowId, accesslevel),
                                strOrg))) {
            OBError myError = Utility.translateError(this, vars, vars.getLanguage(),
                    Utility.messageBD(this, "NoWriteAccess", vars.getLanguage()));
            vars.setMessage(strTabId, myError);
            printPageClosePopUp(response, vars);
        } else {
            printPageDocAction(response, vars, strC_Invoice_ID, strdocaction, strProcessing, strdocstatus,
                    stradTableId, strWindowId);
        }
    } else if (vars.commandIn("SAVE_BUTTONDocAction111")) {
        final String strWindowId = vars.getGlobalVariable("inpwindowId", "ProcessInvoice|Window_ID",
                IsIDFilter.instance);
        final String strTabId = vars.getGlobalVariable("inpTabId", "ProcessInvoice|Tab_ID",
                IsIDFilter.instance);
        final String strC_Invoice_ID = vars.getGlobalVariable("inpKey", strWindowId + "|C_Invoice_ID", "");
        final String strdocaction = vars.getStringParameter("inpdocaction");
        final String strVoidInvoiceDate = vars.getStringParameter("inpVoidedDocumentDate");
        final String strVoidInvoiceAcctDate = vars.getStringParameter("inpVoidedDocumentAcctDate");
        final String strOrg = vars.getGlobalVariable("inpadOrgId", "ProcessInvoice|Org_ID",
                IsIDFilter.instance);

        OBError myMessage = null;
        try {

            Invoice invoice = dao.getObject(Invoice.class, strC_Invoice_ID);
            invoice.setDocumentAction(strdocaction);
            OBDal.getInstance().save(invoice);
            OBDal.getInstance().flush();

            OBError msg = null;
            for (ProcessInvoiceHook hook : hooks) {
                msg = hook.preProcess(invoice, strdocaction);
                if (msg != null && "Error".equals(msg.getType())) {
                    vars.setMessage(strTabId, msg);
                    String strWindowPath = Utility.getTabURL(strTabId, "R", true);
                    if (strWindowPath.equals(""))
                        strWindowPath = strDefaultServlet;
                    printPageClosePopUp(response, vars, strWindowPath);
                    return;
                }
            }
            // check BP currency
            if ("CO".equals(strdocaction)) {
                // check BP currency
                if (invoice.getBusinessPartner().getCurrency() == null) {
                    String errorMSG = Utility.messageBD(this, "InitBPCurrencyLnk", vars.getLanguage(), false);
                    msg = new OBError();
                    msg.setType("Error");
                    msg.setTitle(Utility.messageBD(this, "Error", vars.getLanguage()));
                    msg.setMessage(String.format(errorMSG, invoice.getBusinessPartner().getId(),
                            invoice.getBusinessPartner().getName()));

                    vars.setMessage(strTabId, msg);
                    printPageClosePopUp(response, vars, Utility.getTabURL(strTabId, "R", true));
                    return;
                }
            }

            OBContext.setAdminMode(true);
            Process process = null;
            try {
                process = dao.getObject(Process.class, "111");
            } finally {
                OBContext.restorePreviousMode();
            }

            Map<String, String> parameters = null;
            if (!strVoidInvoiceDate.isEmpty() && !strVoidInvoiceAcctDate.isEmpty()) {
                Date voidDate = null;
                Date voidAcctDate = null;
                try {
                    voidDate = OBDateUtils.getDate(strVoidInvoiceDate);
                    voidAcctDate = OBDateUtils.getDate(strVoidInvoiceAcctDate);
                } catch (ParseException pe) {
                    voidDate = new Date();
                    voidAcctDate = new Date();
                    log4j.error("Not possible to parse the following date: " + strVoidInvoiceDate, pe);
                    log4j.error("Not possible to parse the following date: " + strVoidInvoiceAcctDate, pe);
                }
                parameters = new HashMap<String, String>();
                parameters.put("voidedDocumentDate", OBDateUtils.formatDate(voidDate, "yyyy-MM-dd"));
                parameters.put("voidedDocumentAcctDate", OBDateUtils.formatDate(voidAcctDate, "yyyy-MM-dd"));
            }

            final ProcessInstance pinstance = CallProcess.getInstance().call(process, strC_Invoice_ID,
                    parameters);

            OBDal.getInstance().getSession().refresh(invoice);
            invoice.setAPRMProcessinvoice(invoice.getDocumentAction());
            // Remove invoice's used credit description
            if ("RE".equals(strdocaction) && pinstance.getResult() != 0L) {
                final String invDesc = invoice.getDescription();
                if (invDesc != null) {
                    final String creditMsg = Utility.messageBD(this, "APRM_InvoiceDescUsedCredit",
                            vars.getLanguage());
                    if (creditMsg != null) {
                        final StringBuffer newDesc = new StringBuffer();
                        for (final String line : invDesc.split("\n")) {
                            if (!line.startsWith(creditMsg.substring(0, creditMsg.lastIndexOf("%s")))) {
                                newDesc.append(line);
                                if (!"".equals(line))
                                    newDesc.append("\n");
                            }
                        }
                        invoice.setDescription(newDesc.toString());
                    }
                }
            }
            OBDal.getInstance().save(invoice);
            OBDal.getInstance().flush();

            OBContext.setAdminMode();
            try {
                // on error close popup
                if (pinstance.getResult() == 0L) {
                    OBDal.getInstance().commitAndClose();
                    final PInstanceProcessData[] pinstanceData = PInstanceProcessData.select(this,
                            pinstance.getId());
                    myMessage = Utility.getProcessInstanceMessage(this, vars, pinstanceData);
                    log4j.debug(myMessage.getMessage());
                    vars.setMessage(strTabId, myMessage);

                    String strWindowPath = Utility.getTabURL(strTabId, "R", true);
                    if (strWindowPath.equals(""))
                        strWindowPath = strDefaultServlet;
                    printPageClosePopUp(response, vars, strWindowPath);
                    return;
                }
            } finally {
                OBContext.restorePreviousMode();
            }

            for (ProcessInvoiceHook hook : hooks) {
                msg = hook.postProcess(invoice, strdocaction);
                if (msg != null && "Error".equals(msg.getType())) {
                    vars.setMessage(strTabId, msg);
                    String strWindowPath = Utility.getTabURL(strTabId, "R", true);
                    if (strWindowPath.equals(""))
                        strWindowPath = strDefaultServlet;
                    printPageClosePopUp(response, vars, strWindowPath);
                    OBDal.getInstance().rollbackAndClose();
                    return;
                }
            }

            OBDal.getInstance().commitAndClose();
            final PInstanceProcessData[] pinstanceData = PInstanceProcessData.select(this, pinstance.getId());
            myMessage = Utility.getProcessInstanceMessage(this, vars, pinstanceData);
            log4j.debug(myMessage.getMessage());
            vars.setMessage(strTabId, myMessage);

            OBContext.setAdminMode();
            try {
                if (!"CO".equals(strdocaction)) {
                    String strWindowPath = Utility.getTabURL(strTabId, "R", true);
                    if (strWindowPath.equals(""))
                        strWindowPath = strDefaultServlet;
                    printPageClosePopUp(response, vars, strWindowPath);
                    return;
                }
            } finally {
                OBContext.restorePreviousMode();
            }

            if ("CO".equals(strdocaction)) {
                // Need to refresh the invoice again from the db
                invoice = dao.getObject(Invoice.class, strC_Invoice_ID);
                OBContext.setAdminMode(false);
                String invoiceDocCategory = "";
                try {
                    invoiceDocCategory = invoice.getDocumentType().getDocumentCategory();

                    /*
                     * Print a grid popup in case of credit payment
                     */
                    // If the invoice grand total is ZERO or already has payments (due to
                    // payment method automation) or the business partner does not have a default financial
                    // account defined or invoice's payment method is not inside BP's financial
                    // account do not cancel credit
                    if (BigDecimal.ZERO.compareTo(invoice.getGrandTotalAmount()) != 0
                            && isPaymentMethodConfigured(invoice) && !isInvoiceWithPayments(invoice)
                            && (AcctServer.DOCTYPE_ARInvoice.equals(invoiceDocCategory)
                                    || AcctServer.DOCTYPE_APInvoice.equals(invoiceDocCategory))) {
                        creditPayments = dao.getCustomerPaymentsWithCredit(invoice.getOrganization(),
                                invoice.getBusinessPartner(), invoice.isSalesTransaction());
                        if (creditPayments != null && !creditPayments.isEmpty()) {
                            printPageCreditPaymentGrid(response, vars, strC_Invoice_ID, strdocaction, strTabId,
                                    strC_Invoice_ID, strdocaction, strWindowId, strTabId,
                                    invoice.getInvoiceDate(), strOrg);
                        }
                    }
                } finally {
                    OBContext.restorePreviousMode();
                }

                executePayments(response, vars, strWindowId, strTabId, strC_Invoice_ID, strOrg);
            }

        } catch (ServletException ex) {
            myMessage = Utility.translateError(this, vars, vars.getLanguage(), ex.getMessage());
            if (!myMessage.isConnectionAvailable()) {
                bdErrorConnection(response);
                return;
            } else
                vars.setMessage(strTabId, myMessage);
        }

    } else if (vars.commandIn("GRIDLIST")) {
        final String strWindowId = vars.getGlobalVariable("inpwindowId", "ProcessInvoice|Window_ID",
                IsIDFilter.instance);
        final String strC_Invoice_ID = vars.getGlobalVariable("inpKey", strWindowId + "|C_Invoice_ID", "",
                IsIDFilter.instance);

        printGrid(response, vars, strC_Invoice_ID);
    } else if (vars.commandIn("USECREDITPAYMENTS") || vars.commandIn("CANCEL_USECREDITPAYMENTS")) {
        final String strWindowId = vars.getGlobalVariable("inpwindowId", "ProcessInvoice|Window_ID",
                IsIDFilter.instance);
        final String strTabId = vars.getGlobalVariable("inpTabId", "ProcessInvoice|Tab_ID",
                IsIDFilter.instance);
        final String strC_Invoice_ID = vars.getGlobalVariable("inpKey", strWindowId + "|C_Invoice_ID", "");
        final String strPaymentDate = vars.getRequiredStringParameter("inpPaymentDate");
        final String strOrg = vars.getGlobalVariable("inpadOrgId", "ProcessInvoice|Org_ID",
                IsIDFilter.instance);

        final String strCreditPaymentIds;
        if (vars.commandIn("CANCEL_USECREDITPAYMENTS")) {
            strCreditPaymentIds = null;
        } else {
            strCreditPaymentIds = vars.getInParameter("inpCreditPaymentId", IsIDFilter.instance);
        }

        /*
         * Use credit logic
         */
        if (strCreditPaymentIds != null && !strCreditPaymentIds.isEmpty()) {
            List<FIN_Payment> selectedCreditPayment = FIN_Utility.getOBObjectList(FIN_Payment.class,
                    strCreditPaymentIds);
            HashMap<String, BigDecimal> selectedCreditPaymentAmounts = FIN_AddPayment
                    .getSelectedBaseOBObjectAmount(vars, selectedCreditPayment, "inpPaymentAmount");
            try {
                OBContext.setAdminMode(true);
                final Invoice invoice = OBDal.getInstance().get(Invoice.class, strC_Invoice_ID);

                final StringBuffer creditPaymentsIdentifiers = new StringBuffer();
                BigDecimal totalUsedCreditAmt = BigDecimal.ZERO;
                for (final FIN_Payment creditPayment : selectedCreditPayment) {
                    final BigDecimal usedCreditAmt = selectedCreditPaymentAmounts.get(creditPayment.getId());
                    // Set Used Credit = Amount + Previous used credit introduced by the user
                    creditPayment.setUsedCredit(usedCreditAmt.add(creditPayment.getUsedCredit()));
                    final StringBuffer description = new StringBuffer();
                    if (creditPayment.getDescription() != null && !creditPayment.getDescription().equals(""))
                        description.append(creditPayment.getDescription()).append("\n");
                    description.append(String.format(
                            Utility.messageBD(this, "APRM_CreditUsedinInvoice", vars.getLanguage()),
                            invoice.getDocumentNo()));
                    String truncateDescription = (description.length() > 255)
                            ? description.substring(0, 251).concat("...").toString()
                            : description.toString();
                    creditPayment.setDescription(truncateDescription);
                    totalUsedCreditAmt = totalUsedCreditAmt.add(usedCreditAmt);
                    creditPaymentsIdentifiers.append(creditPayment.getDocumentNo());
                    creditPaymentsIdentifiers.append(", ");
                }
                creditPaymentsIdentifiers.delete(creditPaymentsIdentifiers.length() - 2,
                        creditPaymentsIdentifiers.length());
                creditPaymentsIdentifiers.append("\n");

                final List<FIN_PaymentScheduleDetail> paymentScheduleDetails = new ArrayList<FIN_PaymentScheduleDetail>();
                final HashMap<String, BigDecimal> paymentScheduleDetailsAmounts = new HashMap<String, BigDecimal>();
                BigDecimal allocatedAmt = BigDecimal.ZERO;
                for (final FIN_PaymentScheduleDetail paymentScheduleDetail : dao
                        .getInvoicePendingScheduledPaymentDetails(invoice)) {
                    if (totalUsedCreditAmt.compareTo(allocatedAmt) > 0) {
                        final BigDecimal pendingToAllocate = totalUsedCreditAmt.subtract(allocatedAmt);
                        paymentScheduleDetails.add(paymentScheduleDetail);

                        final BigDecimal psdAmt = paymentScheduleDetail.getAmount();
                        if (psdAmt.compareTo(pendingToAllocate) <= 0) {
                            paymentScheduleDetailsAmounts.put(paymentScheduleDetail.getId(), psdAmt);
                            allocatedAmt = allocatedAmt.add(psdAmt);
                        } else {
                            paymentScheduleDetailsAmounts.put(paymentScheduleDetail.getId(), pendingToAllocate);
                            allocatedAmt = allocatedAmt.add(pendingToAllocate);
                        }
                    }
                }

                // Create new Payment
                final boolean isSalesTransaction = invoice.isSalesTransaction();
                final DocumentType docType = FIN_Utility.getDocumentType(invoice.getOrganization(),
                        isSalesTransaction ? AcctServer.DOCTYPE_ARReceipt : AcctServer.DOCTYPE_APPayment);
                final String strPaymentDocumentNo = FIN_Utility.getDocumentNo(docType,
                        docType.getTable() != null ? docType.getTable().getDBTableName() : "");
                final FIN_FinancialAccount bpFinAccount = isSalesTransaction
                        ? invoice.getBusinessPartner().getAccount()
                        : invoice.getBusinessPartner().getPOFinancialAccount();
                // Calculate Conversion Rate
                final ConversionRate conversionRate = StringUtils.equals(invoice.getCurrency().getId(),
                        bpFinAccount.getCurrency().getId())
                                ? null
                                : FinancialUtils.getConversionRate(FIN_Utility.getDate(strPaymentDate),
                                        invoice.getCurrency(), bpFinAccount.getCurrency(),
                                        invoice.getOrganization(), invoice.getClient());
                final FIN_Payment newPayment = FIN_AddPayment.savePayment(null, isSalesTransaction, docType,
                        strPaymentDocumentNo, invoice.getBusinessPartner(), invoice.getPaymentMethod(),
                        bpFinAccount, "0", FIN_Utility.getDate(strPaymentDate), invoice.getOrganization(),
                        invoice.getDocumentNo(), paymentScheduleDetails, paymentScheduleDetailsAmounts, false,
                        false, invoice.getCurrency(),
                        conversionRate != null ? conversionRate.getMultipleRateBy() : null, null);
                newPayment.setAmount(BigDecimal.ZERO);
                newPayment.setGeneratedCredit(BigDecimal.ZERO);
                newPayment.setUsedCredit(totalUsedCreditAmt);

                // Link new Payment with the credit payments used
                for (final FIN_Payment creditPayment : selectedCreditPayment) {
                    final BigDecimal usedCreditAmt = selectedCreditPaymentAmounts.get(creditPayment.getId());
                    FIN_PaymentProcess.linkCreditPayment(newPayment, usedCreditAmt, creditPayment);
                }

                // Process the new payment
                OBError message = FIN_AddPayment.processPayment(vars, this, "P", newPayment);
                if ("Success".equals(message.getType())) {
                    // Update Invoice's description
                    final StringBuffer invDesc = new StringBuffer();
                    if (invoice.getDescription() != null) {
                        invDesc.append(invoice.getDescription());
                        invDesc.append("\n");
                    }
                    invDesc.append(String.format(
                            Utility.messageBD(this, "APRM_InvoiceDescUsedCredit", vars.getLanguage()),
                            creditPaymentsIdentifiers.toString()));
                    invoice.setDescription(invDesc.toString());
                } else {
                    message.setMessage(OBMessageUtils.messageBD("PaymentError") + " " + message.getMessage());
                    vars.setMessage(strTabId, message);
                }

            } catch (final Exception e) {
                log4j.error("Exception while canceling the credit in the invoice: " + strC_Invoice_ID);
                e.printStackTrace();
            } finally {
                OBContext.restorePreviousMode();
            }
        }
        executePayments(response, vars, strWindowId, strTabId, strC_Invoice_ID, strOrg);
    }
}

From source file:org.egov.services.payment.PaymentService.java

public List<PaymentBean> getCSList(final List<EgBillregister> billList,
        final Map<Long, BigDecimal> deductionAmtMap, final Map<Long, BigDecimal> paidAmtMap) {
    if (LOGGER.isDebugEnabled())
        LOGGER.debug("Starting getCSList...");
    final List<PaymentBean> contractorList = new ArrayList<PaymentBean>();
    PaymentBean paymentBean = null;//ww  w . j av a 2  s  . c o m
    if (billList != null && !billList.isEmpty())
        for (final EgBillregister billregister : billList) {
            paymentBean = new PaymentBean();
            paymentBean.setCsBillId(billregister.getId());
            paymentBean.setBillNumber(billregister.getBillnumber());
            paymentBean.setBillDate(billregister.getBilldate());
            paymentBean.setExpType(billregister.getExpendituretype());

            if (billregister.getExpendituretype()
                    .equals(FinancialConstants.STANDARD_EXPENDITURETYPE_CONTINGENT)) {
                if (billregister.getEgBillregistermis().getEgBillSubType() != null) {
                    if (billregister.getEgBillregistermis().getEgBillSubType().getName()
                            .equalsIgnoreCase("TNEB"))
                        paymentBean.setPayTo(billregister.getEgBillregistermis().getPayto());
                    else
                        paymentBean.setPayTo(getPayeeNameForCBill(billregister));
                } else
                    paymentBean.setPayTo(getPayeeNameForCBill(billregister));
            } else
                paymentBean.setPayTo(billregister.getEgBillregistermis().getPayto());
            paymentBean.setDeductionAmt(deductionAmtMap.get(paymentBean.getCsBillId()) == null ? BigDecimal.ZERO
                    : deductionAmtMap.get(paymentBean.getCsBillId()));
            final BigDecimal passedamount = billregister.getPassedamount() == null ? BigDecimal.ZERO
                    : billregister.getPassedamount().setScale(2, BigDecimal.ROUND_HALF_EVEN);
            paymentBean.setNetAmt(passedamount.subtract(
                    paymentBean.getDeductionAmt() == null ? BigDecimal.ZERO : paymentBean.getDeductionAmt()));
            paymentBean.setEarlierPaymentAmt(paidAmtMap.get(paymentBean.getCsBillId()) == null ? BigDecimal.ZERO
                    : paidAmtMap.get(paymentBean.getCsBillId()));
            paymentBean.setPayableAmt(paymentBean.getNetAmt().subtract(paymentBean.getEarlierPaymentAmt()));
            paymentBean.setPaymentAmt(paymentBean.getPayableAmt());
            if (paymentBean.getPaymentAmt().compareTo(BigDecimal.ZERO) == 0)
                continue;
            if (billregister.getEgBillregistermis().getFund() != null)
                paymentBean.setFundName(billregister.getEgBillregistermis().getFund().getName());
            if (billregister.getEgBillregistermis().getEgDepartment() != null)
                paymentBean.setDeptName(billregister.getEgBillregistermis().getEgDepartment().getName());
            if (billregister.getEgBillregistermis().getScheme() != null)
                paymentBean.setSchemeName(billregister.getEgBillregistermis().getScheme().getName());
            if (billregister.getEgBillregistermis().getSubScheme() != null)
                paymentBean.setSubschemeName(billregister.getEgBillregistermis().getSubScheme().getName());
            if (billregister.getEgBillregistermis().getFunctionaryid() != null)
                paymentBean
                        .setFunctionaryName(billregister.getEgBillregistermis().getFunctionaryid().getName());
            if (billregister.getEgBillregistermis().getFunction() != null)
                paymentBean.setFunctionName(billregister.getEgBillregistermis().getFunction().getName());
            if (billregister.getEgBillregistermis().getFundsource() != null)
                paymentBean.setFundsourceName(billregister.getEgBillregistermis().getFundsource().getName());
            if (billregister.getEgBillregistermis().getFieldid() != null)
                paymentBean.setFieldName(billregister.getEgBillregistermis().getFieldid().getName());
            if (billregister.getEgBillregistermis().getVoucherHeader() != null) {
                paymentBean.setBillVoucherNumber(
                        billregister.getEgBillregistermis().getVoucherHeader().getVoucherNumber());
                paymentBean.setBillVoucherDate(
                        billregister.getEgBillregistermis().getVoucherHeader().getVoucherDate());
                paymentBean.setBillVoucherId(billregister.getEgBillregistermis().getVoucherHeader().getId());
            }
            if (billregister.getEgBillregistermis().getEgBillSubType() != null)
                if (billregister.getEgBillregistermis().getEgBillSubType().getName().equalsIgnoreCase("TNEB")) {
                    final String region = (String) persistenceService.find(
                            "select region from EBDetails where egBillregister.id = ?", billregister.getId());

                    if (region != null)
                        paymentBean.setRegion(region);
                }

            contractorList.add(paymentBean);
        }
    if (LOGGER.isDebugEnabled())
        LOGGER.debug("Completed getCSList.");
    return contractorList;
}

From source file:och.front.service.FrontAppTest.java

private String getDeltaVal(BigDecimal newVal, BigDecimal oldVal) throws Exception {
     return round(newVal.subtract(oldVal)).toString();
 }

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

public EgDemand updateDemandForLegacyEntry(final AdvertisementPermitDetail advertisementPermitDetail,
        EgDemand demand) {/*  w  w  w.j av a 2s .co  m*/
    final Installment installment = getCurrentInstallment();
    BigDecimal totalDemandAmount = BigDecimal.ZERO;

    Boolean taxFullyPaidForCurrentYear = false;

    if (advertisementPermitDetail.getAdvertisement() != null
            && advertisementPermitDetail.getAdvertisement().getLegacy()
            && advertisementPermitDetail.getAdvertisement().getTaxPaidForCurrentYear())
        taxFullyPaidForCurrentYear = true;

    Boolean enchroachmentFeeAlreadyExistInDemand = false;
    Boolean arrearsTaxalreadyExistInDemand = false;
    Boolean taxalreadyExistInDemand = false;
    final List<EgDemandDetails> deleteDmdDtl = new ArrayList<>();
    if (demand == null)
        demand = createDemand(advertisementPermitDetail);
    else {
        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);

        for (final EgDemandDetails dmdDtl : demand.getEgDemandDetails())
            if (dmdDtl.getEgDemandReason().getId() == taxReason.getId()) {
                taxalreadyExistInDemand = true;
                if (advertisementPermitDetail.getTaxAmount().compareTo(BigDecimal.ZERO) > 0) {

                    totalDemandAmount = totalDemandAmount
                            .add(advertisementPermitDetail.getTaxAmount().subtract(dmdDtl.getAmount()));
                    dmdDtl.setAmount(
                            advertisementPermitDetail.getTaxAmount().setScale(0, BigDecimal.ROUND_HALF_UP));

                    if (taxFullyPaidForCurrentYear)
                        dmdDtl.setAmtCollected(advertisementPermitDetail.getTaxAmount() != null
                                ? advertisementPermitDetail.getTaxAmount()
                                : BigDecimal.ZERO);
                    else
                        dmdDtl.setAmtCollected(BigDecimal.ZERO);
                } else {
                    totalDemandAmount = totalDemandAmount.subtract(dmdDtl.getAmount());
                    deleteDmdDtl.add(dmdDtl);
                    // demand.removeEgDemandDetails(dmdDtl);
                }
            } else if (dmdDtl.getEgDemandReason().getId() == pendingTaxReason.getId()) {
                arrearsTaxalreadyExistInDemand = true;
                if (advertisementPermitDetail.getAdvertisement().getPendingTax() != null
                        && advertisementPermitDetail.getAdvertisement().getPendingTax()
                                .compareTo(BigDecimal.ZERO) > 0) {

                    totalDemandAmount = totalDemandAmount.add(advertisementPermitDetail.getAdvertisement()
                            .getPendingTax().subtract(dmdDtl.getAmount()));
                    dmdDtl.setAmount(advertisementPermitDetail.getAdvertisement().getPendingTax().setScale(0,
                            BigDecimal.ROUND_HALF_UP));

                    /*
                     * if (taxFullyPaidForCurrentYear) {
                     * dmdDtl.setAmtCollected((advertisementPermitDetail.getAdvertisement().getPendingTax() != null ?
                     * (advertisementPermitDetail .getAdvertisement().getPendingTax()) : BigDecimal.ZERO)); } else
                     */
                    dmdDtl.setAmtCollected(BigDecimal.ZERO);
                } else {
                    totalDemandAmount = totalDemandAmount.subtract(dmdDtl.getAmount());
                    deleteDmdDtl.add(dmdDtl);
                }
            } else 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));

                    if (taxFullyPaidForCurrentYear)
                        dmdDtl.setAmtCollected(advertisementPermitDetail.getEncroachmentFee() != null
                                ? advertisementPermitDetail.getEncroachmentFee()
                                : BigDecimal.ZERO);
                    else
                        dmdDtl.setAmtCollected(BigDecimal.ZERO);

                    // update encroachment fee.. // Encroachment fee may not mandatory. If already part of demand
                } else {
                    totalDemandAmount = totalDemandAmount.subtract(dmdDtl.getAmount());
                    deleteDmdDtl.add(dmdDtl);
                    // delete demand detail
                }

            }

        for (final EgDemandDetails dmdDtls : deleteDmdDtl)
            demand.removeEgDemandDetails(dmdDtls);

        if (!enchroachmentFeeAlreadyExistInDemand && advertisementPermitDetail.getEncroachmentFee() != null
                && advertisementPermitDetail.getEncroachmentFee().compareTo(BigDecimal.ZERO) > 0) {
            demand.addEgDemandDetails(createDemandDetails(advertisementPermitDetail.getEncroachmentFee(),
                    getDemandReasonByCodeAndInstallment(AdvertisementTaxConstants.DEMANDREASON_ENCROCHMENTFEE,
                            installment),
                    taxFullyPaidForCurrentYear ? advertisementPermitDetail.getEncroachmentFee()
                            : BigDecimal.ZERO));
            totalDemandAmount = totalDemandAmount.add(advertisementPermitDetail.getEncroachmentFee());
            demand.setEgInstallmentMaster(installment);
        }
        if (!arrearsTaxalreadyExistInDemand
                && advertisementPermitDetail.getAdvertisement().getPendingTax() != null
                && advertisementPermitDetail.getAdvertisement().getPendingTax()
                        .compareTo(BigDecimal.ZERO) > 0) {
            demand.addEgDemandDetails(createDemandDetails(
                    advertisementPermitDetail.getAdvertisement().getPendingTax(),
                    getDemandReasonByCodeAndInstallment(
                            AdvertisementTaxConstants.DEMANDREASON_ARREAR_ADVERTISEMENTTAX, installment),
                    BigDecimal.ZERO));
            totalDemandAmount = totalDemandAmount
                    .add(advertisementPermitDetail.getAdvertisement().getPendingTax());
            demand.setEgInstallmentMaster(installment);
        }
        if (!taxalreadyExistInDemand && advertisementPermitDetail.getTaxAmount() != null
                && advertisementPermitDetail.getTaxAmount().compareTo(BigDecimal.ZERO) > 0) {
            demand.addEgDemandDetails(createDemandDetails(advertisementPermitDetail.getTaxAmount(),
                    getDemandReasonByCodeAndInstallment(AdvertisementTaxConstants.DEMANDREASON_ADVERTISEMENTTAX,
                            installment),
                    taxFullyPaidForCurrentYear ? advertisementPermitDetail.getTaxAmount() : BigDecimal.ZERO));
            totalDemandAmount = totalDemandAmount.add(advertisementPermitDetail.getTaxAmount());
            demand.setEgInstallmentMaster(installment);
        }
        demand.addBaseDemand(totalDemandAmount.setScale(0, BigDecimal.ROUND_HALF_UP));

    }
    return demand;

}