Example usage for java.math RoundingMode HALF_UP

List of usage examples for java.math RoundingMode HALF_UP

Introduction

In this page you can find the example usage for java.math RoundingMode HALF_UP.

Prototype

RoundingMode HALF_UP

To view the source code for java.math RoundingMode HALF_UP.

Click Source Link

Document

Rounding mode to round towards "nearest neighbor" unless both neighbors are equidistant, in which case round up.

Usage

From source file:org.kuali.ole.module.purap.document.web.struts.OleRequisitionAction.java

/**
 * Add a new item to the document./* w w  w .  j  a  v a  2s  .c  om*/
 *
 * @param mapping  An ActionMapping
 * @param form     An ActionForm
 * @param request  The HttpServletRequest
 * @param response The HttpServletResponse
 * @return An ActionForward
 * @throws Exception
 */
@Override
public ActionForward addItem(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    LOG.debug("###########Inside AddItem in oleRequisitionAction ###########");
    PurchasingFormBase purchasingForm = (PurchasingFormBase) form;
    OleRequisitionItem item = (OleRequisitionItem) purchasingForm.getNewPurchasingItemLine();
    OleRequisitionDocument document = (OleRequisitionDocument) purchasingForm.getDocument();
    OleRequisitionForm oleForm = (OleRequisitionForm) form;
    OleRequisitionDocument doc = (OleRequisitionDocument) oleForm.getDocument();
    Iterator itemIterator = doc.getItems().iterator();
    int itemCounter = 0;
    while (itemIterator.hasNext()) {
        OleRequisitionItem tempItem = (OleRequisitionItem) itemIterator.next();
        if (tempItem.getItemTypeCode().equals(PurapConstants.ItemTypeCodes.ITEM_TYPE_ITEM_CODE)) {
            itemCounter++;
        }
    }
    String itemNo = String.valueOf(itemCounter);
    BibInfoBean xmlBibInfoBean = new BibInfoBean();
    if (item.getBibInfoBean() == null) {
        item.setBibInfoBean(xmlBibInfoBean);
        if (item.getBibInfoBean().getDocStoreOperation() == null) {
            item.getBibInfoBean().setDocStoreOperation(OleSelectConstant.DOCSTORE_OPERATION_STAFF);
        }
    } else {
        if (item.getBibInfoBean().getDocStoreOperation() == null) {
            item.getBibInfoBean().setDocStoreOperation(OleSelectConstant.DOCSTORE_OPERATION_STAFF);
        }
    }
    String fileName = document.getDocumentNumber() + "_" + itemNo;
    // Modified for jira OLE - 2437 starts

    setItemDescription(item, fileName);
    if (document.getVendorDetail().getVendorHeader().getVendorForeignIndicator() != null) {
        if ((document.getVendorDetail() == null) || (document.getVendorDetail().getVendorName() != null
                && !document.getVendorDetail().getVendorHeader().getVendorForeignIndicator())) {
            purchasingForm.getNewPurchasingItemLine()
                    .setItemUnitPrice(SpringContext.getBean(OlePurapService.class).calculateDiscount(item)
                            .setScale(2, BigDecimal.ROUND_HALF_UP));
            super.addItem(mapping, purchasingForm, request, response);
            //}
        } else {
            LOG.debug("###########Foreign Currency Field Calculation for requisition###########");
            SpringContext.getBean(OlePurapService.class).calculateForeignCurrency(item);
            Long currencyTypeId = document.getVendorDetail().getCurrencyType().getCurrencyTypeId();
            Map documentNumberMap = new HashMap();
            documentNumberMap.put(OleSelectConstant.CURRENCY_TYPE_ID, currencyTypeId);
            BusinessObjectService businessObjectService = SpringContext.getBean(BusinessObjectService.class);
            List<OleExchangeRate> exchangeRateList = (List) businessObjectService.findMatchingOrderBy(
                    OleExchangeRate.class, documentNumberMap, OleSelectConstant.EXCHANGE_RATE_DATE, false);
            Iterator iterator = exchangeRateList.iterator();
            if (iterator.hasNext()) {
                OleExchangeRate tempOleExchangeRate = (OleExchangeRate) iterator.next();
                item.setItemExchangeRate(new KualiDecimal(tempOleExchangeRate.getExchangeRate()));
            }
            if (item.getItemExchangeRate() != null && item.getItemForeignUnitCost() != null) {
                item.setItemUnitCostUSD(new KualiDecimal(item.getItemForeignUnitCost().bigDecimalValue()
                        .divide(item.getItemExchangeRate().bigDecimalValue(), 4, RoundingMode.HALF_UP)));
                item.setItemUnitPrice(
                        item.getItemUnitCostUSD().bigDecimalValue().setScale(2, BigDecimal.ROUND_HALF_UP));
                item.setItemListPrice(item.getItemUnitCostUSD());
            }
            super.addItem(mapping, purchasingForm, request, response);
        }
    } else {
        purchasingForm.getNewPurchasingItemLine().setItemUnitPrice(SpringContext.getBean(OlePurapService.class)
                .calculateDiscount(item).setScale(2, BigDecimal.ROUND_HALF_UP));
        super.addItem(mapping, purchasingForm, request, response);
    }
    if (item.getClaimDate() == null) {
        getOlePurapService().setClaimDateForReq(item, document.getVendorDetail());
    }
    return mapping.findForward(OLEConstants.MAPPING_BASIC);
}

From source file:net.sourceforge.entrainer.gui.socket.EntrainerSocketConnector.java

private void setAutoFrequency(double value) {
    int val = new BigDecimal(value).divide(BigDecimal.ONE, 0, RoundingMode.HALF_UP).intValue();
    if (frequency.getValue() == val)
        return;//from   www .  ja  va  2  s .  c om
    isEntrainerFrequencyMessage = true;
    frequency.setValue(val);
}

From source file:net.sourceforge.fenixedu.domain.Lesson.java

public BigDecimal getUnitHours() {
    return BigDecimal.valueOf(getUnitMinutes()).divide(BigDecimal.valueOf(NUMBER_OF_MINUTES_IN_HOUR), 2,
            RoundingMode.HALF_UP);
}

From source file:net.sourceforge.entrainer.gui.socket.EntrainerSocketConnector.java

private void setAutoEntrainment(double value) {
    double val = new BigDecimal(value * 100).divide(BigDecimal.ONE, 0, RoundingMode.HALF_UP).doubleValue();
    if (entrainmentFrequency.getValue() == val)
        return;/*ww  w. ja v  a  2 s . c  o m*/
    isEntrainerEntrainmentFrequencyMessage = true;
    entrainmentFrequency.setValue((int) val);
}

From source file:jp.furplag.util.commons.NumberUtils.java

public static BigDecimal cos(final BigDecimal angle, MathContext mc, boolean isRadians) {
    if (angle == null)
        return null;
    BigDecimal cos = BigDecimal.ONE;
    BigDecimal radians = isRadians ? angle : valueOf(toRadians(angle), BigDecimal.class);
    BigDecimal nSquare = radians.pow(2);
    int index = 0;
    for (BigDecimal factor : COSINE_FACTOR_DECIMAL128) {
        BigDecimal temporary = factor.multiply(nSquare);
        if (index % 2 == 0)
            temporary = temporary.negate();
        cos = cos.add(temporary);// w  w w .  j a  v  a2s  . c  o  m
        nSquare = nSquare.multiply(radians.pow(2)).setScale(
                ((mc == null ? MathContext.DECIMAL128 : mc).getPrecision() + 2), RoundingMode.HALF_UP);
        index++;
    }

    return cos.setScale((mc == null ? MathContext.DECIMAL128 : mc).getPrecision(), RoundingMode.HALF_UP);
}

From source file:net.sourceforge.fenixedu.domain.Lesson.java

public double hoursAfter(int hour) {

    HourMinuteSecond afterHour = new HourMinuteSecond(hour, 0, 0);

    if (!getBeginHourMinuteSecond().isBefore(afterHour)) {
        return getUnitHours().doubleValue();

    } else if (getEndHourMinuteSecond().isAfter(afterHour)) {
        return BigDecimal.valueOf(Minutes.minutesBetween(afterHour, getEndHourMinuteSecond()).getMinutes())
                .divide(BigDecimal.valueOf(NUMBER_OF_MINUTES_IN_HOUR), 2, RoundingMode.HALF_UP).doubleValue();
    }//  w w w.j a  v a2s. c  om

    return 0.0;
}

From source file:ch.elexis.data.TarmedOptifier.java

/**
 * Get double as int rounded half up./*  ww  w . j a va2s . com*/
 * 
 * @param value
 * @return
 */
private int doubleToInt(double value) {
    BigDecimal bd = new BigDecimal(value);
    bd = bd.setScale(0, RoundingMode.HALF_UP);
    return bd.intValue();
}

From source file:org.openbravo.erpCommon.ad_forms.DocInvoice.java

/**
 * Create Facts (the accounting logic) for ARI, ARC, ARF, API, APC.
 * //from www.  jav  a 2s. co  m
 * <pre>
 *  ARI, ARF
 *      Receivables     DR
 *      Charge                  CR
 *      TaxDue                  CR
 *      Revenue                 CR
 *  ARC
 *      Receivables             CR
 *      Charge          DR
 *      TaxDue          DR
 *      Revenue         RR
 *  API
 *      Payables                CR
 *      Charge          DR
 *      TaxCredit       DR
 *      Expense         DR
 *  APC
 *      Payables        DR
 *      Charge                  CR
 *      TaxCredit               CR
 *      Expense                 CR
 * </pre>
 * 
 * @param as
 *          accounting schema
 * @return Fact
 */
public Fact createFact(AcctSchema as, ConnectionProvider conn, Connection con, VariablesSecureApp vars)
        throws ServletException {
    // Select specific definition
    String strClassname = AcctServerData.selectTemplateDoc(conn, as.m_C_AcctSchema_ID, DocumentType);
    if (strClassname.equals(""))
        strClassname = AcctServerData.selectTemplate(conn, as.m_C_AcctSchema_ID, AD_Table_ID);
    if (!strClassname.equals("")) {
        try {
            DocInvoiceTemplate newTemplate = (DocInvoiceTemplate) Class.forName(strClassname).newInstance();
            return newTemplate.createFact(this, as, conn, con, vars);
        } catch (Exception e) {
            log4j.error("Error while creating new instance for DocInvoiceTemplate - " + e);
        }
    }
    log4jDocInvoice.debug("Starting create fact");
    // create Fact Header
    Fact fact = new Fact(this, as, Fact.POST_Actual);
    String Fact_Acct_Group_ID = SequenceIdData.getUUID();
    // Cash based accounting
    if (!as.isAccrual())
        return null;

    /** @todo Assumes TaxIncluded = N */

    // ARI, ARF, ARI_RM
    if (DocumentType.equals(AcctServer.DOCTYPE_ARInvoice) || DocumentType.equals(AcctServer.DOCTYPE_ARProForma)
            || DocumentType.equals(AcctServer.DOCTYPE_RMSalesInvoice)) {
        log4jDocInvoice.debug("Point 1");
        // Receivables DR
        if (m_payments == null || m_payments.length == 0)
            for (int i = 0; m_debt_payments != null && i < m_debt_payments.length; i++) {
                if (m_debt_payments[i].isReceipt.equals("Y"))
                    fact.createLine(m_debt_payments[i],
                            getAccountBPartner(C_BPartner_ID, as, true, m_debt_payments[i].dpStatus, conn),
                            this.C_Currency_ID,
                            getConvertedAmt(m_debt_payments[i].Amount, m_debt_payments[i].C_Currency_ID_From,
                                    this.C_Currency_ID, DateAcct, "", AD_Client_ID, AD_Org_ID, conn),
                            "", Fact_Acct_Group_ID, nextSeqNo(SeqNo), DocumentType, conn);
                else
                    fact.createLine(m_debt_payments[i],
                            getAccountBPartner(C_BPartner_ID, as, false, m_debt_payments[i].dpStatus, conn),
                            this.C_Currency_ID, "",
                            getConvertedAmt(m_debt_payments[i].Amount, m_debt_payments[i].C_Currency_ID_From,
                                    this.C_Currency_ID, DateAcct, "", AD_Client_ID, AD_Org_ID, conn),
                            Fact_Acct_Group_ID, nextSeqNo(SeqNo), DocumentType, conn);
            }
        else
            for (int i = 0; m_payments != null && i < m_payments.length; i++) {
                fact.createLine(m_payments[i], getAccountBPartner(C_BPartner_ID, as, true, false, conn),
                        this.C_Currency_ID, m_payments[i].Amount, "", Fact_Acct_Group_ID, nextSeqNo(SeqNo),
                        DocumentType, conn);
                if (m_payments[i].C_Currency_ID_From.equals(as.m_C_Currency_ID)
                        && new BigDecimal(m_payments[i].PrepaidAmount).compareTo(ZERO) != 0) {
                    fact.createLine(m_payments[i], getAccountBPartner(C_BPartner_ID, as, true, true, conn),
                            this.C_Currency_ID, m_payments[i].PrepaidAmount, "", Fact_Acct_Group_ID,
                            nextSeqNo(SeqNo), DocumentType, conn);
                } else if (!m_payments[i].C_Currency_ID_From.equals(as.m_C_Currency_ID)) {
                    try {
                        DocInvoiceData[] prepayments = DocInvoiceData.selectPrepayments(connectionProvider,
                                m_payments[i].Line_ID);
                        for (int j = 0; j < prepayments.length; j++) {
                            BigDecimal prePaymentAmt = convertAmount(new BigDecimal(prepayments[j].prepaidamt),
                                    true, DateAcct, TABLEID_Payment, prepayments[j].finPaymentId,
                                    m_payments[i].C_Currency_ID_From, as.m_C_Currency_ID, m_payments[i], as,
                                    fact, Fact_Acct_Group_ID, nextSeqNo(SeqNo), conn);
                            fact.createLine(m_payments[i],
                                    getAccountBPartner(C_BPartner_ID, as, true, true, conn),
                                    m_payments[i].C_Currency_ID_From, prePaymentAmt.toString(), "",
                                    Fact_Acct_Group_ID, nextSeqNo(SeqNo), DocumentType, conn);
                        }
                    } catch (ServletException e) {
                        log4jDocInvoice.warn(e);
                    }
                }
            }
        if ((m_payments == null || m_payments.length == 0)
                && (m_debt_payments == null || m_debt_payments.length == 0)) {
            BigDecimal grossamt = new BigDecimal(Amounts[AMTTYPE_Gross]);
            BigDecimal prepayment = new BigDecimal(prepaymentamt);
            BigDecimal difference = grossamt.abs().subtract(prepayment.abs());
            if (!prepaymentamt.equals("0")) {
                if (grossamt.abs().compareTo(prepayment.abs()) > 0) {
                    if (IsReturn.equals("Y")) {
                        fact.createLine(null, getAccountBPartner(C_BPartner_ID, as, true, true, conn),
                                this.C_Currency_ID, "", prepaymentamt, Fact_Acct_Group_ID, nextSeqNo(SeqNo),
                                DocumentType, conn);
                        fact.createLine(null, getAccountBPartner(C_BPartner_ID, as, true, false, conn),
                                this.C_Currency_ID, "", difference.toString(), Fact_Acct_Group_ID,
                                nextSeqNo(SeqNo), DocumentType, conn);
                    } else {
                        fact.createLine(null, getAccountBPartner(C_BPartner_ID, as, true, true, conn),
                                this.C_Currency_ID, prepaymentamt, "", Fact_Acct_Group_ID, nextSeqNo(SeqNo),
                                DocumentType, conn);
                        fact.createLine(null, getAccountBPartner(C_BPartner_ID, as, true, false, conn),
                                this.C_Currency_ID, difference.toString(), "", Fact_Acct_Group_ID,
                                nextSeqNo(SeqNo), DocumentType, conn);
                    }
                } else {
                    if (IsReturn.equals("Y")) {
                        fact.createLine(null, getAccountBPartner(C_BPartner_ID, as, true, true, conn),
                                this.C_Currency_ID, "", prepaymentamt, Fact_Acct_Group_ID, nextSeqNo(SeqNo),
                                DocumentType, conn);
                    } else {
                        fact.createLine(null, getAccountBPartner(C_BPartner_ID, as, true, true, conn),
                                this.C_Currency_ID, prepaymentamt, "", Fact_Acct_Group_ID, nextSeqNo(SeqNo),
                                DocumentType, conn);
                    }
                }
            } else {
                fact.createLine(null, getAccountBPartner(C_BPartner_ID, as, true, false, conn),
                        this.C_Currency_ID, Amounts[AMTTYPE_Gross], "", Fact_Acct_Group_ID, nextSeqNo(SeqNo),
                        DocumentType, conn);
            }

        }
        // Charge CR
        log4jDocInvoice.debug("The first create line");
        fact.createLine(null, getAccount(AcctServer.ACCTTYPE_Charge, as, conn), C_Currency_ID, "",
                getAmount(AcctServer.AMTTYPE_Charge), Fact_Acct_Group_ID, nextSeqNo(SeqNo), DocumentType, conn);
        // TaxDue CR
        log4jDocInvoice.debug("m_taxes.length: " + m_taxes);
        BigDecimal grossamt = new BigDecimal(Amounts[AMTTYPE_Gross]);
        BigDecimal prepayment = new BigDecimal(prepaymentamt);

        for (int i = 0; m_taxes != null && i < m_taxes.length; i++) {
            // New docLine created to assign C_Tax_ID value to the entry
            DocLine docLine = new DocLine(DocumentType, Record_ID, "");
            docLine.m_C_Tax_ID = m_taxes[i].m_C_Tax_ID;

            BigDecimal percentageFinalAccount = CashVATUtil._100;
            final BigDecimal taxesAmountTotal = new BigDecimal(
                    StringUtils.isBlank(m_taxes[i].m_amount) ? "0" : m_taxes[i].m_amount);
            BigDecimal taxToTransAccount = BigDecimal.ZERO;
            int precission = 0;
            OBContext.setAdminMode(true);
            try {
                Currency currency = OBDal.getInstance().get(Currency.class, C_Currency_ID);
                precission = currency.getStandardPrecision().intValue();
            } finally {
                OBContext.restorePreviousMode();
            }
            if (IsReversal.equals("Y")) {
                if (isCashVAT && m_taxes[i].m_isCashVAT) {
                    if ((m_payments == null || m_payments.length == 0)
                            && (m_debt_payments == null || m_debt_payments.length == 0)
                            && (!prepaymentamt.equals("0"))) {
                        percentageFinalAccount = ((prepayment.multiply(new BigDecimal(100)))
                                .divide(grossamt.abs(), precission, RoundingMode.HALF_UP));
                        taxToTransAccount = CashVATUtil.calculatePercentageAmount(
                                CashVATUtil._100.subtract(percentageFinalAccount), taxesAmountTotal,
                                C_Currency_ID);
                    } else {
                        percentageFinalAccount = CashVATUtil
                                .calculatePrepaidPercentageForCashVATTax(m_taxes[i].m_C_Tax_ID, Record_ID);
                        taxToTransAccount = CashVATUtil.calculatePercentageAmount(
                                CashVATUtil._100.subtract(percentageFinalAccount), taxesAmountTotal,
                                C_Currency_ID);
                    }
                    fact.createLine(docLine, m_taxes[i].getAccount(DocTax.ACCTTYPE_TaxDue_Trans, as, conn),
                            C_Currency_ID, taxToTransAccount.toString(), "", Fact_Acct_Group_ID,
                            nextSeqNo(SeqNo), DocumentType, conn);
                }
                final BigDecimal taxToFinalAccount = taxesAmountTotal.subtract(taxToTransAccount);
                fact.createLine(docLine, m_taxes[i].getAccount(DocTax.ACCTTYPE_TaxDue, as, conn), C_Currency_ID,
                        taxToFinalAccount.toString(), "", Fact_Acct_Group_ID, nextSeqNo(SeqNo), DocumentType,
                        conn);
            } else {
                if (isCashVAT && m_taxes[i].m_isCashVAT) {
                    if ((m_payments == null || m_payments.length == 0)
                            && (m_debt_payments == null || m_debt_payments.length == 0)
                            && (!prepaymentamt.equals("0"))) {
                        percentageFinalAccount = ((prepayment.multiply(new BigDecimal(100)))
                                .divide(grossamt.abs(), precission, RoundingMode.HALF_UP));
                        taxToTransAccount = CashVATUtil.calculatePercentageAmount(
                                CashVATUtil._100.subtract(percentageFinalAccount), taxesAmountTotal,
                                C_Currency_ID);
                    } else {
                        percentageFinalAccount = CashVATUtil
                                .calculatePrepaidPercentageForCashVATTax(m_taxes[i].m_C_Tax_ID, Record_ID);
                        taxToTransAccount = CashVATUtil.calculatePercentageAmount(
                                CashVATUtil._100.subtract(percentageFinalAccount), taxesAmountTotal,
                                C_Currency_ID);
                    }
                    fact.createLine(docLine, m_taxes[i].getAccount(DocTax.ACCTTYPE_TaxDue_Trans, as, conn),
                            C_Currency_ID, "", taxToTransAccount.toString(), Fact_Acct_Group_ID,
                            nextSeqNo(SeqNo), DocumentType, conn);
                }
                final BigDecimal taxToFinalAccount = taxesAmountTotal.subtract(taxToTransAccount);
                fact.createLine(docLine, m_taxes[i].getAccount(DocTax.ACCTTYPE_TaxDue, as, conn), C_Currency_ID,
                        "", taxToFinalAccount.toString(), Fact_Acct_Group_ID, nextSeqNo(SeqNo), DocumentType,
                        conn);
            }
        }
        // Revenue CR
        if (p_lines != null && p_lines.length > 0) {
            for (int i = 0; i < p_lines.length; i++) {
                Account account = ((DocLine_Invoice) p_lines[i]).getAccount(ProductInfo.ACCTTYPE_P_Revenue, as,
                        conn);
                if (DocumentType.equals(AcctServer.DOCTYPE_RMSalesInvoice)) {
                    Account accountReturnMaterial = ((DocLine_Invoice) p_lines[i])
                            .getAccount(ProductInfo.ACCTTYPE_P_RevenueReturn, as, conn);
                    if (accountReturnMaterial != null) {
                        account = accountReturnMaterial;
                    }
                }
                String amount = p_lines[i].getAmount();
                String amountConverted = "";
                ConversionRateDoc conversionRateCurrentDoc = getConversionRateDoc(TABLEID_Invoice, Record_ID,
                        C_Currency_ID, as.m_C_Currency_ID);
                if (conversionRateCurrentDoc != null) {
                    amountConverted = applyRate(new BigDecimal(p_lines[i].getAmount()),
                            conversionRateCurrentDoc, true).setScale(2, BigDecimal.ROUND_HALF_UP).toString();
                } else {
                    amountConverted = getConvertedAmt(p_lines[i].getAmount(), C_Currency_ID, as.m_C_Currency_ID,
                            DateAcct, "", AD_Client_ID, AD_Org_ID, conn);
                }
                if (((DocLine_Invoice) p_lines[i]).isDeferred()) {
                    amount = createAccDefRevenueFact(
                            fact, (DocLine_Invoice) p_lines[i], account, ((DocLine_Invoice) p_lines[i])
                                    .getAccount(ProductInfo.ACCTTYPE_P_DefRevenue, as, conn),
                            amountConverted, as.m_C_Currency_ID, conn);
                    if (IsReversal.equals("Y")) {
                        fact.createLine(p_lines[i], account, as.m_C_Currency_ID, amount, "", Fact_Acct_Group_ID,
                                nextSeqNo(SeqNo), DocumentType, conn);
                    } else {
                        fact.createLine(p_lines[i], account, as.m_C_Currency_ID, "", amount, Fact_Acct_Group_ID,
                                nextSeqNo(SeqNo), DocumentType, conn);
                    }
                } else {
                    if (IsReversal.equals("Y")) {
                        fact.createLine(p_lines[i], account, this.C_Currency_ID, amount, "", Fact_Acct_Group_ID,
                                nextSeqNo(SeqNo), DocumentType, conn);
                    } else {
                        fact.createLine(p_lines[i], account, this.C_Currency_ID, "", amount, Fact_Acct_Group_ID,
                                nextSeqNo(SeqNo), DocumentType, conn);
                    }
                }
                // If revenue has been deferred
                if (((DocLine_Invoice) p_lines[i]).isDeferred() && !amount.equals(amountConverted)) {
                    amount = new BigDecimal(amountConverted).subtract(new BigDecimal(amount)).toString();
                    if (IsReversal.equals("Y")) {
                        fact.createLine(p_lines[i],
                                ((DocLine_Invoice) p_lines[i]).getAccount(ProductInfo.ACCTTYPE_P_DefRevenue, as,
                                        conn),
                                as.m_C_Currency_ID, amount, "", Fact_Acct_Group_ID, nextSeqNo(SeqNo),
                                DocumentType, conn);
                    } else {
                        fact.createLine(p_lines[i],
                                ((DocLine_Invoice) p_lines[i]).getAccount(ProductInfo.ACCTTYPE_P_DefRevenue, as,
                                        conn),
                                as.m_C_Currency_ID, "", amount, Fact_Acct_Group_ID, nextSeqNo(SeqNo),
                                DocumentType, conn);
                    }
                }
            }
        }
        // Set Locations
        FactLine[] fLines = fact.getLines();
        for (int i = 0; i < fLines.length; i++) {
            if (fLines[i] != null) {
                fLines[i].setLocationFromOrg(fLines[i].getAD_Org_ID(conn), true, conn); // from Loc
                fLines[i].setLocationFromBPartner(C_BPartner_Location_ID, false, conn); // to Loc
            }
        }
    }
    // ARC
    else if (this.DocumentType.equals(AcctServer.DOCTYPE_ARCredit)) {
        log4jDocInvoice.debug("Point 2");
        // Receivables CR
        if (m_payments == null || m_payments.length == 0)
            for (int i = 0; m_debt_payments != null && i < m_debt_payments.length; i++) {
                BigDecimal amount = new BigDecimal(m_debt_payments[i].Amount);
                // BigDecimal ZERO = BigDecimal.ZERO;
                fact.createLine(m_debt_payments[i],
                        getAccountBPartner(C_BPartner_ID, as, true, m_debt_payments[i].dpStatus, conn),
                        this.C_Currency_ID, "",
                        getConvertedAmt(((amount.negate())).toPlainString(),
                                m_debt_payments[i].C_Currency_ID_From, this.C_Currency_ID, DateAcct, "",
                                AD_Client_ID, AD_Org_ID, conn),
                        Fact_Acct_Group_ID, nextSeqNo(SeqNo), DocumentType, conn);
            }
        else
            for (int i = 0; m_payments != null && i < m_payments.length; i++) {
                BigDecimal amount = new BigDecimal(m_payments[i].Amount);
                BigDecimal prepaidAmount = new BigDecimal(m_payments[i].PrepaidAmount);
                fact.createLine(m_payments[i], getAccountBPartner(C_BPartner_ID, as, true, false, conn),
                        this.C_Currency_ID, "", amount.negate().toString(), Fact_Acct_Group_ID,
                        nextSeqNo(SeqNo), DocumentType, conn);
                // Pre-payment: Probably not needed as at this point we can not generate pre-payments
                // against ARC. Amount is negated
                if (m_payments[i].C_Currency_ID_From.equals(as.m_C_Currency_ID)
                        && prepaidAmount.compareTo(ZERO) != 0) {
                    fact.createLine(m_payments[i], getAccountBPartner(C_BPartner_ID, as, true, true, conn),
                            this.C_Currency_ID, "", prepaidAmount.negate().toString(), Fact_Acct_Group_ID,
                            nextSeqNo(SeqNo), DocumentType, conn);
                } else if (!m_payments[i].C_Currency_ID_From.equals(as.m_C_Currency_ID)) {
                    try {
                        DocInvoiceData[] prepayments = DocInvoiceData.selectPrepayments(connectionProvider,
                                m_payments[i].Line_ID);
                        for (int j = 0; j < prepayments.length; j++) {
                            BigDecimal prePaymentAmt = convertAmount(
                                    new BigDecimal(prepayments[j].prepaidamt).negate(), true, DateAcct,
                                    TABLEID_Payment, prepayments[j].finPaymentId,
                                    m_payments[i].C_Currency_ID_From, as.m_C_Currency_ID, m_payments[i], as,
                                    fact, Fact_Acct_Group_ID, nextSeqNo(SeqNo), conn);
                            fact.createLine(m_payments[i],
                                    getAccountBPartner(C_BPartner_ID, as, true, true, conn),
                                    m_payments[i].C_Currency_ID_From, "", prePaymentAmt.toString(),
                                    Fact_Acct_Group_ID, nextSeqNo(SeqNo), DocumentType, conn);
                        }
                    } catch (ServletException e) {
                        log4jDocInvoice.warn(e);
                    }
                }
            }
        if ((m_payments == null || m_payments.length == 0)
                && (m_debt_payments == null || m_debt_payments.length == 0)) {
            fact.createLine(null, getAccountBPartner(C_BPartner_ID, as, true, false, conn), this.C_Currency_ID,
                    "", Amounts[AMTTYPE_Gross], Fact_Acct_Group_ID, nextSeqNo(SeqNo), DocumentType, conn);
        }
        // Charge DR
        fact.createLine(null, getAccount(AcctServer.ACCTTYPE_Charge, as, conn), this.C_Currency_ID,
                getAmount(AcctServer.AMTTYPE_Charge), "", Fact_Acct_Group_ID, nextSeqNo(SeqNo), DocumentType,
                conn);
        // TaxDue DR
        for (int i = 0; m_taxes != null && i < m_taxes.length; i++) {
            // New docLine created to assign C_Tax_ID value to the entry
            DocLine docLine = new DocLine(DocumentType, Record_ID, "");
            docLine.m_C_Tax_ID = m_taxes[i].m_C_Tax_ID;

            BigDecimal percentageFinalAccount = CashVATUtil._100;
            final BigDecimal taxesAmountTotal = new BigDecimal(
                    StringUtils.isBlank(m_taxes[i].getAmount()) ? "0" : m_taxes[i].getAmount());
            BigDecimal taxToTransAccount = BigDecimal.ZERO;
            if (isCashVAT && m_taxes[i].m_isCashVAT) {
                percentageFinalAccount = CashVATUtil
                        .calculatePrepaidPercentageForCashVATTax(m_taxes[i].m_C_Tax_ID, Record_ID);
                taxToTransAccount = CashVATUtil.calculatePercentageAmount(
                        CashVATUtil._100.subtract(percentageFinalAccount), taxesAmountTotal, C_Currency_ID);
                fact.createLine(docLine, m_taxes[i].getAccount(DocTax.ACCTTYPE_TaxDue_Trans, as, conn),
                        this.C_Currency_ID, taxToTransAccount.toString(), "", Fact_Acct_Group_ID,
                        nextSeqNo(SeqNo), DocumentType, conn);
            }
            final BigDecimal taxToFinalAccount = taxesAmountTotal.subtract(taxToTransAccount);
            fact.createLine(docLine, m_taxes[i].getAccount(DocTax.ACCTTYPE_TaxDue, as, conn),
                    this.C_Currency_ID, taxToFinalAccount.toString(), "", Fact_Acct_Group_ID, nextSeqNo(SeqNo),
                    DocumentType, conn);
        }
        // Revenue CR
        for (int i = 0; p_lines != null && i < p_lines.length; i++) {
            String amount = p_lines[i].getAmount();
            String amountCoverted = "";
            ConversionRateDoc conversionRateCurrentDoc = getConversionRateDoc(TABLEID_Invoice, Record_ID,
                    C_Currency_ID, as.m_C_Currency_ID);
            if (conversionRateCurrentDoc != null) {
                amountCoverted = applyRate(new BigDecimal(p_lines[i].getAmount()), conversionRateCurrentDoc,
                        true).setScale(2, BigDecimal.ROUND_HALF_UP).toString();
            } else {
                amountCoverted = getConvertedAmt(p_lines[i].getAmount(), C_Currency_ID, as.m_C_Currency_ID,
                        DateAcct, "", AD_Client_ID, AD_Org_ID, conn);
            }
            Account account = ((DocLine_Invoice) p_lines[i]).getAccount(ProductInfo.ACCTTYPE_P_Revenue, as,
                    conn);
            if (((DocLine_Invoice) p_lines[i]).isDeferred()) {
                amount = createAccDefRevenueFact(fact, (DocLine_Invoice) p_lines[i], account,
                        ((DocLine_Invoice) p_lines[i]).getAccount(ProductInfo.ACCTTYPE_P_DefRevenue, as, conn),
                        amountCoverted, as.m_C_Currency_ID, conn);
                fact.createLine(p_lines[i], account, as.m_C_Currency_ID, amount, "", Fact_Acct_Group_ID,
                        nextSeqNo(SeqNo), DocumentType, conn);
            } else {
                fact.createLine(p_lines[i], account, this.C_Currency_ID, amount, "", Fact_Acct_Group_ID,
                        nextSeqNo(SeqNo), DocumentType, conn);
            }
            // If revenue has been deferred
            if (((DocLine_Invoice) p_lines[i]).isDeferred() && !amount.equals(amountCoverted)) {
                amount = new BigDecimal(amountCoverted).subtract(new BigDecimal(amount)).toString();
                fact.createLine(p_lines[i],
                        ((DocLine_Invoice) p_lines[i]).getAccount(ProductInfo.ACCTTYPE_P_DefRevenue, as, conn),
                        as.m_C_Currency_ID, amount, "", Fact_Acct_Group_ID, nextSeqNo(SeqNo), DocumentType,
                        conn);
            }
        }
        // Set Locations
        FactLine[] fLines = fact.getLines();
        for (int i = 0; fLines != null && i < fLines.length; i++) {
            if (fLines[i] != null) {
                fLines[i].setLocationFromOrg(fLines[i].getAD_Org_ID(conn), true, conn); // from Loc
                fLines[i].setLocationFromBPartner(C_BPartner_Location_ID, false, conn); // to Loc
            }
        }
    }
    // API
    else if (this.DocumentType.equals(AcctServer.DOCTYPE_APInvoice)) {
        log4jDocInvoice.debug("Point 3");
        // Liability CR
        if (m_payments == null || m_payments.length == 0)
            for (int i = 0; m_debt_payments != null && i < m_debt_payments.length; i++) {
                if (m_debt_payments[i].isReceipt.equals("Y"))
                    fact.createLine(m_debt_payments[i],
                            getAccountBPartner(C_BPartner_ID, as, true, m_debt_payments[i].dpStatus, conn),
                            this.C_Currency_ID,
                            getConvertedAmt(m_debt_payments[i].Amount, m_debt_payments[i].C_Currency_ID_From,
                                    this.C_Currency_ID, DateAcct, "", AD_Client_ID, AD_Org_ID, conn),
                            "", Fact_Acct_Group_ID, nextSeqNo(SeqNo), DocumentType, conn);
                else
                    fact.createLine(m_debt_payments[i],
                            getAccountBPartner(C_BPartner_ID, as, false, m_debt_payments[i].dpStatus, conn),
                            this.C_Currency_ID, "",
                            getConvertedAmt(m_debt_payments[i].Amount, m_debt_payments[i].C_Currency_ID_From,
                                    this.C_Currency_ID, DateAcct, "", AD_Client_ID, AD_Org_ID, conn),
                            Fact_Acct_Group_ID, nextSeqNo(SeqNo), DocumentType, conn);
            }
        else
            for (int i = 0; m_payments != null && i < m_payments.length; i++) {
                fact.createLine(m_payments[i], getAccountBPartner(C_BPartner_ID, as, false, false, conn),
                        this.C_Currency_ID, "", m_payments[i].Amount, Fact_Acct_Group_ID, nextSeqNo(SeqNo),
                        DocumentType, conn);
                if (m_payments[i].C_Currency_ID_From.equals(as.m_C_Currency_ID)
                        && new BigDecimal(m_payments[i].PrepaidAmount).compareTo(ZERO) != 0) {
                    fact.createLine(m_payments[i], getAccountBPartner(C_BPartner_ID, as, false, true, conn),
                            this.C_Currency_ID, "", m_payments[i].PrepaidAmount, Fact_Acct_Group_ID,
                            nextSeqNo(SeqNo), DocumentType, conn);
                } else if (!m_payments[i].C_Currency_ID_From.equals(as.m_C_Currency_ID)) {
                    try {
                        DocInvoiceData[] prepayments = DocInvoiceData.selectPrepayments(connectionProvider,
                                m_payments[i].Line_ID);
                        for (int j = 0; j < prepayments.length; j++) {
                            BigDecimal prePaymentAmt = convertAmount(new BigDecimal(prepayments[j].prepaidamt),
                                    false, DateAcct, TABLEID_Payment, prepayments[j].finPaymentId,
                                    m_payments[i].C_Currency_ID_From, as.m_C_Currency_ID, m_payments[i], as,
                                    fact, Fact_Acct_Group_ID, nextSeqNo(SeqNo), conn);
                            fact.createLine(m_payments[i],
                                    getAccountBPartner(C_BPartner_ID, as, false, true, conn),
                                    m_payments[i].C_Currency_ID_From, "", prePaymentAmt.toString(),
                                    Fact_Acct_Group_ID, nextSeqNo(SeqNo), DocumentType, conn);
                        }
                    } catch (ServletException e) {
                        log4jDocInvoice.warn(e);
                    }
                }
            }
        if ((m_payments == null || m_payments.length == 0)
                && (m_debt_payments == null || m_debt_payments.length == 0)) {
            BigDecimal grossamt = new BigDecimal(Amounts[AMTTYPE_Gross]);
            BigDecimal prepayment = new BigDecimal(prepaymentamt);
            BigDecimal difference = grossamt.abs().subtract(prepayment.abs());
            if (!prepaymentamt.equals("0")) {
                if (grossamt.abs().compareTo(prepayment.abs()) > 0) {
                    if (IsReturn.equals("Y")) {
                        fact.createLine(null, getAccountBPartner(C_BPartner_ID, as, false, true, conn),
                                this.C_Currency_ID, prepaymentamt, "", Fact_Acct_Group_ID, nextSeqNo(SeqNo),
                                DocumentType, conn);
                        fact.createLine(null, getAccountBPartner(C_BPartner_ID, as, false, false, conn),
                                this.C_Currency_ID, difference.toString(), "", Fact_Acct_Group_ID,
                                nextSeqNo(SeqNo), DocumentType, conn);
                    } else {
                        fact.createLine(null, getAccountBPartner(C_BPartner_ID, as, false, true, conn),
                                this.C_Currency_ID, "", prepaymentamt, Fact_Acct_Group_ID, nextSeqNo(SeqNo),
                                DocumentType, conn);
                        fact.createLine(null, getAccountBPartner(C_BPartner_ID, as, false, false, conn),
                                this.C_Currency_ID, "", difference.toString(), Fact_Acct_Group_ID,
                                nextSeqNo(SeqNo), DocumentType, conn);
                    }
                } else {
                    if (IsReturn.equals("Y")) {
                        fact.createLine(null, getAccountBPartner(C_BPartner_ID, as, false, true, conn),
                                this.C_Currency_ID, prepaymentamt, "", Fact_Acct_Group_ID, nextSeqNo(SeqNo),
                                DocumentType, conn);
                    } else {
                        fact.createLine(null, getAccountBPartner(C_BPartner_ID, as, false, true, conn),
                                this.C_Currency_ID, "", prepaymentamt, Fact_Acct_Group_ID, nextSeqNo(SeqNo),
                                DocumentType, conn);
                    }
                }
            } else {
                fact.createLine(null, getAccountBPartner(C_BPartner_ID, as, false, false, conn),
                        this.C_Currency_ID, "", Amounts[AMTTYPE_Gross], Fact_Acct_Group_ID, nextSeqNo(SeqNo),
                        DocumentType, conn);
            }

        }
        // Charge DR
        fact.createLine(null, getAccount(AcctServer.ACCTTYPE_Charge, as, conn), this.C_Currency_ID,
                getAmount(AcctServer.AMTTYPE_Charge), "", Fact_Acct_Group_ID, nextSeqNo(SeqNo), DocumentType,
                conn);
        BigDecimal grossamt = new BigDecimal(Amounts[AMTTYPE_Gross]);
        BigDecimal prepayment = new BigDecimal(prepaymentamt);
        // TaxCredit DR
        for (int i = 0; m_taxes != null && i < m_taxes.length; i++) {
            // New docLine created to assign C_Tax_ID value to the entry
            DocLine docLine = new DocLine(DocumentType, Record_ID, "");
            docLine.m_C_Tax_ID = m_taxes[i].m_C_Tax_ID;
            OBContext.setAdminMode(true);
            int precission = 0;
            try {
                Currency currency = OBDal.getInstance().get(Currency.class, C_Currency_ID);
                precission = currency.getStandardPrecision().intValue();
            } finally {
                OBContext.restorePreviousMode();
            }
            if (!m_taxes[i].m_isTaxUndeductable) {
                BigDecimal percentageFinalAccount = CashVATUtil._100;
                final BigDecimal taxesAmountTotal = new BigDecimal(
                        StringUtils.isBlank(m_taxes[i].getAmount()) ? "0" : m_taxes[i].getAmount());
                BigDecimal taxToTransAccount = BigDecimal.ZERO;
                if (IsReversal.equals("Y")) {
                    if (isCashVAT && m_taxes[i].m_isCashVAT) {
                        if ((m_payments == null || m_payments.length == 0)
                                && (m_debt_payments == null || m_debt_payments.length == 0)
                                && (!prepaymentamt.equals("0"))) {
                            percentageFinalAccount = ((prepayment.multiply(new BigDecimal(100)))
                                    .divide(grossamt.abs(), precission, RoundingMode.HALF_UP));
                            taxToTransAccount = CashVATUtil.calculatePercentageAmount(
                                    CashVATUtil._100.subtract(percentageFinalAccount), taxesAmountTotal,
                                    C_Currency_ID);
                        } else {
                            percentageFinalAccount = CashVATUtil
                                    .calculatePrepaidPercentageForCashVATTax(m_taxes[i].m_C_Tax_ID, Record_ID);
                            taxToTransAccount = CashVATUtil.calculatePercentageAmount(
                                    CashVATUtil._100.subtract(percentageFinalAccount), taxesAmountTotal,
                                    C_Currency_ID);
                        }
                        fact.createLine(docLine,
                                m_taxes[i].getAccount(DocTax.ACCTTYPE_TaxCredit_Trans, as, conn),
                                this.C_Currency_ID, "", taxToTransAccount.toString(), Fact_Acct_Group_ID,
                                nextSeqNo(SeqNo), DocumentType, conn);
                    }
                    final BigDecimal taxToFinalAccount = taxesAmountTotal.subtract(taxToTransAccount);
                    fact.createLine(docLine, m_taxes[i].getAccount(DocTax.ACCTTYPE_TaxCredit, as, conn),
                            this.C_Currency_ID, "", taxToFinalAccount.toString(), Fact_Acct_Group_ID,
                            nextSeqNo(SeqNo), DocumentType, conn);
                } else {
                    if (isCashVAT && m_taxes[i].m_isCashVAT) {
                        if ((m_payments == null || m_payments.length == 0)
                                && (m_debt_payments == null || m_debt_payments.length == 0)
                                && (!prepaymentamt.equals("0"))) {
                            percentageFinalAccount = ((prepayment.multiply(new BigDecimal(100)))
                                    .divide(grossamt.abs(), precission, RoundingMode.HALF_UP));
                            taxToTransAccount = CashVATUtil.calculatePercentageAmount(
                                    CashVATUtil._100.subtract(percentageFinalAccount), taxesAmountTotal,
                                    C_Currency_ID);
                        } else {
                            percentageFinalAccount = CashVATUtil
                                    .calculatePrepaidPercentageForCashVATTax(m_taxes[i].m_C_Tax_ID, Record_ID);
                            taxToTransAccount = CashVATUtil.calculatePercentageAmount(
                                    CashVATUtil._100.subtract(percentageFinalAccount), taxesAmountTotal,
                                    C_Currency_ID);
                        }
                        fact.createLine(docLine,
                                m_taxes[i].getAccount(DocTax.ACCTTYPE_TaxCredit_Trans, as, conn),
                                this.C_Currency_ID, taxToTransAccount.toString(), "", Fact_Acct_Group_ID,
                                nextSeqNo(SeqNo), DocumentType, conn);
                    }
                    final BigDecimal taxToFinalAccount = taxesAmountTotal.subtract(taxToTransAccount);
                    fact.createLine(docLine, m_taxes[i].getAccount(DocTax.ACCTTYPE_TaxCredit, as, conn),
                            this.C_Currency_ID, taxToFinalAccount.toString(), "", Fact_Acct_Group_ID,
                            nextSeqNo(SeqNo), DocumentType, conn);
                }

            } else {
                DocLineInvoiceData[] data = null;
                try {
                    data = DocLineInvoiceData.selectUndeductable(connectionProvider, Record_ID);
                } catch (ServletException e) {
                    log4jDocInvoice.warn(e);
                }

                BigDecimal cumulativeTaxLineAmount = new BigDecimal(0);
                BigDecimal taxAmount = new BigDecimal(0);
                for (int j = 0; data != null && j < data.length; j++) {
                    DocLine docLine1 = new DocLine(DocumentType, Record_ID, "");
                    docLine1.m_C_Tax_ID = data[j].cTaxId;
                    docLine1.m_C_BPartner_ID = data[j].cBpartnerId;
                    docLine1.m_M_Product_ID = data[j].mProductId;
                    docLine1.m_C_Costcenter_ID = data[j].cCostcenterId;
                    docLine1.m_C_Project_ID = data[j].cProjectId;
                    docLine1.m_User1_ID = data[j].user1id;
                    docLine1.m_User2_ID = data[j].user2id;
                    docLine1.m_C_Activity_ID = data[j].cActivityId;
                    docLine1.m_C_Campaign_ID = data[j].cCampaignId;
                    docLine1.m_A_Asset_ID = data[j].aAssetId;
                    String strtaxAmount = null;

                    try {

                        DocInvoiceData[] dataEx = DocInvoiceData.selectProductAcct(conn,
                                as.getC_AcctSchema_ID(), m_taxes[i].m_C_Tax_ID, Record_ID);
                        if (dataEx.length == 0) {
                            dataEx = DocInvoiceData.selectGLItemAcctForTaxLine(conn, as.getC_AcctSchema_ID(),
                                    m_taxes[i].m_C_Tax_ID, Record_ID);
                        }
                        strtaxAmount = m_taxes[i].getAmount();
                        taxAmount = new BigDecimal(strtaxAmount.equals("") ? "0.00" : strtaxAmount);
                        if (j == data.length - 1) {
                            data[j].taxamt = taxAmount.subtract(cumulativeTaxLineAmount).toPlainString();
                        }
                        try {

                            if (this.DocumentType.equals(AcctServer.DOCTYPE_APInvoice)) {
                                if (IsReversal.equals("Y")) {
                                    fact.createLine(docLine1, Account.getAccount(conn, dataEx[0].pExpenseAcct),
                                            this.C_Currency_ID, "", data[j].taxamt, Fact_Acct_Group_ID,
                                            nextSeqNo(SeqNo), DocumentType, conn);

                                } else {
                                    fact.createLine(docLine1, Account.getAccount(conn, dataEx[0].pExpenseAcct),
                                            this.C_Currency_ID, data[j].taxamt, "", Fact_Acct_Group_ID,
                                            nextSeqNo(SeqNo), DocumentType, conn);
                                }
                            } else if (this.DocumentType.equals(AcctServer.DOCTYPE_APCredit)) {
                                fact.createLine(docLine1, Account.getAccount(conn, dataEx[0].pExpenseAcct),
                                        this.C_Currency_ID, "", data[j].taxamt, Fact_Acct_Group_ID,
                                        nextSeqNo(SeqNo), DocumentType, conn);
                            }
                            cumulativeTaxLineAmount = cumulativeTaxLineAmount
                                    .add(new BigDecimal(data[j].taxamt));
                        } catch (ServletException e) {
                            log4jDocInvoice.error("Exception in createLineForTaxUndeductable method: " + e);
                        }
                    } catch (ServletException e) {
                        log4jDocInvoice.warn(e);
                    }
                }
            }
        }
        // Expense DR
        for (int i = 0; p_lines != null && i < p_lines.length; i++) {
            String amount = p_lines[i].getAmount();
            String amountConverted = "";
            ConversionRateDoc conversionRateCurrentDoc = getConversionRateDoc(TABLEID_Invoice, Record_ID,
                    C_Currency_ID, as.m_C_Currency_ID);
            if (conversionRateCurrentDoc != null) {
                amountConverted = applyRate(new BigDecimal(p_lines[i].getAmount()), conversionRateCurrentDoc,
                        true).setScale(2, BigDecimal.ROUND_HALF_UP).toString();
            } else {
                amountConverted = getConvertedAmt(p_lines[i].getAmount(), C_Currency_ID, as.m_C_Currency_ID,
                        DateAcct, "", AD_Client_ID, AD_Org_ID, conn);
            }
            if (((DocLine_Invoice) p_lines[i]).isDeferred()) {
                amount = createAccDefExpenseFact(fact, (DocLine_Invoice) p_lines[i],
                        ((DocLine_Invoice) p_lines[i]).getAccount(ProductInfo.ACCTTYPE_P_Expense, as, conn),
                        ((DocLine_Invoice) p_lines[i]).getAccount(ProductInfo.ACCTTYPE_P_DefExpense, as, conn),
                        amountConverted, as.m_C_Currency_ID, conn);
                if (IsReversal.equals("Y")) {
                    fact.createLine(p_lines[i],
                            ((DocLine_Invoice) p_lines[i]).getAccount(ProductInfo.ACCTTYPE_P_Expense, as, conn),
                            as.m_C_Currency_ID, "", amount, Fact_Acct_Group_ID, nextSeqNo(SeqNo), DocumentType,
                            conn);
                } else {
                    fact.createLine(p_lines[i],
                            ((DocLine_Invoice) p_lines[i]).getAccount(ProductInfo.ACCTTYPE_P_Expense, as, conn),
                            as.m_C_Currency_ID, amount, "", Fact_Acct_Group_ID, nextSeqNo(SeqNo), DocumentType,
                            conn);
                }
            } else {
                if (IsReversal.equals("Y")) {
                    fact.createLine(p_lines[i],
                            ((DocLine_Invoice) p_lines[i]).getAccount(ProductInfo.ACCTTYPE_P_Expense, as, conn),
                            this.C_Currency_ID, "", amount, Fact_Acct_Group_ID, nextSeqNo(SeqNo), DocumentType,
                            conn);
                } else {
                    fact.createLine(p_lines[i],
                            ((DocLine_Invoice) p_lines[i]).getAccount(ProductInfo.ACCTTYPE_P_Expense, as, conn),
                            this.C_Currency_ID, amount, "", Fact_Acct_Group_ID, nextSeqNo(SeqNo), DocumentType,
                            conn);
                }
            }
            // If expense has been deferred
            if (((DocLine_Invoice) p_lines[i]).isDeferred() && !amount.equals(amountConverted)) {
                amount = new BigDecimal(amountConverted).subtract(new BigDecimal(amount)).toString();
                if (IsReversal.equals("Y")) {
                    fact.createLine(p_lines[i],
                            ((DocLine_Invoice) p_lines[i]).getAccount(ProductInfo.ACCTTYPE_P_DefExpense, as,
                                    conn),
                            as.m_C_Currency_ID, "", amount, Fact_Acct_Group_ID, nextSeqNo(SeqNo), DocumentType,
                            conn);
                } else {
                    fact.createLine(p_lines[i],
                            ((DocLine_Invoice) p_lines[i]).getAccount(ProductInfo.ACCTTYPE_P_DefExpense, as,
                                    conn),
                            as.m_C_Currency_ID, amount, "", Fact_Acct_Group_ID, nextSeqNo(SeqNo), DocumentType,
                            conn);
                }
            }
        }
        // Set Locations
        FactLine[] fLines = fact.getLines();
        for (int i = 0; fLines != null && i < fLines.length; i++) {
            if (fLines[i] != null) {
                fLines[i].setLocationFromBPartner(C_BPartner_Location_ID, true, conn); // from Loc
                fLines[i].setLocationFromOrg(fLines[i].getAD_Org_ID(conn), false, conn); // to Loc
            }
        }
        updateProductInfo(as.getC_AcctSchema_ID(), conn, con); // only API
    }
    // APC
    else if (this.DocumentType.equals(AcctServer.DOCTYPE_APCredit)) {
        log4jDocInvoice.debug("Point 4");
        // Liability DR
        if (m_payments == null || m_payments.length == 0)
            for (int i = 0; m_debt_payments != null && i < m_debt_payments.length; i++) {
                BigDecimal amount = new BigDecimal(m_debt_payments[i].Amount);
                // BigDecimal ZERO = BigDecimal.ZERO;
                fact.createLine(m_debt_payments[i],
                        getAccountBPartner(C_BPartner_ID, as, false, m_debt_payments[i].dpStatus, conn),
                        this.C_Currency_ID,
                        getConvertedAmt(((amount.negate())).toPlainString(),
                                m_debt_payments[i].C_Currency_ID_From, this.C_Currency_ID, DateAcct, "",
                                AD_Client_ID, AD_Org_ID, conn),
                        "", Fact_Acct_Group_ID, nextSeqNo(SeqNo), DocumentType, conn);
            }
        else
            for (int i = 0; m_payments != null && i < m_payments.length; i++) {
                BigDecimal amount = new BigDecimal(m_payments[i].Amount);
                BigDecimal prepaidAmount = new BigDecimal(m_payments[i].PrepaidAmount);
                fact.createLine(m_payments[i], getAccountBPartner(C_BPartner_ID, as, false, false, conn),
                        this.C_Currency_ID, amount.negate().toString(), "", Fact_Acct_Group_ID,
                        nextSeqNo(SeqNo), DocumentType, conn);
                // Pre-payment: Probably not needed as at this point we can not generate pre-payments
                // against APC. Amount is negated
                if (m_payments[i].C_Currency_ID_From.equals(as.m_C_Currency_ID)
                        && prepaidAmount.compareTo(ZERO) != 0) {
                    fact.createLine(m_payments[i], getAccountBPartner(C_BPartner_ID, as, false, true, conn),
                            this.C_Currency_ID, prepaidAmount.negate().toString(), "", Fact_Acct_Group_ID,
                            nextSeqNo(SeqNo), DocumentType, conn);
                } else if (!m_payments[i].C_Currency_ID_From.equals(as.m_C_Currency_ID)) {
                    try {
                        DocInvoiceData[] prepayments = DocInvoiceData.selectPrepayments(connectionProvider,
                                m_payments[i].Line_ID);
                        for (int j = 0; j < prepayments.length; j++) {
                            BigDecimal prePaymentAmt = convertAmount(
                                    new BigDecimal(prepayments[j].prepaidamt).negate(), false, DateAcct,
                                    TABLEID_Payment, prepayments[j].finPaymentId,
                                    m_payments[i].C_Currency_ID_From, as.m_C_Currency_ID, m_payments[i], as,
                                    fact, Fact_Acct_Group_ID, nextSeqNo(SeqNo), conn);
                            fact.createLine(m_payments[i],
                                    getAccountBPartner(C_BPartner_ID, as, false, true, conn),
                                    m_payments[i].C_Currency_ID_From, prePaymentAmt.toString(), "",
                                    Fact_Acct_Group_ID, nextSeqNo(SeqNo), DocumentType, conn);
                        }
                    } catch (ServletException e) {
                        log4jDocInvoice.warn(e);
                    }
                }
            }
        if ((m_payments == null || m_payments.length == 0)
                && (m_debt_payments == null || m_debt_payments.length == 0)) {
            fact.createLine(null, getAccountBPartner(C_BPartner_ID, as, false, false, conn), this.C_Currency_ID,
                    Amounts[AMTTYPE_Gross], "", Fact_Acct_Group_ID, nextSeqNo(SeqNo), DocumentType, conn);
        }
        // Charge CR
        fact.createLine(null, getAccount(AcctServer.ACCTTYPE_Charge, as, conn), this.C_Currency_ID, "",
                getAmount(AcctServer.AMTTYPE_Charge), Fact_Acct_Group_ID, nextSeqNo(SeqNo), DocumentType, conn);
        // TaxCredit CR
        for (int i = 0; m_taxes != null && i < m_taxes.length; i++) {
            // New docLine created to assign C_Tax_ID value to the entry
            DocLine docLine = new DocLine(DocumentType, Record_ID, "");
            docLine.m_C_Tax_ID = m_taxes[i].m_C_Tax_ID;
            if (m_taxes[i].m_isTaxUndeductable) {
                computeTaxUndeductableLine(conn, as, fact, docLine, Fact_Acct_Group_ID, m_taxes[i].m_C_Tax_ID,
                        m_taxes[i].getAmount());

            } else {
                BigDecimal percentageFinalAccount = CashVATUtil._100;
                final BigDecimal taxesAmountTotal = new BigDecimal(
                        StringUtils.isBlank(m_taxes[i].getAmount()) ? "0" : m_taxes[i].getAmount());
                BigDecimal taxToTransAccount = BigDecimal.ZERO;
                if (isCashVAT && m_taxes[i].m_isCashVAT) {
                    percentageFinalAccount = CashVATUtil
                            .calculatePrepaidPercentageForCashVATTax(m_taxes[i].m_C_Tax_ID, Record_ID);
                    taxToTransAccount = CashVATUtil.calculatePercentageAmount(
                            CashVATUtil._100.subtract(percentageFinalAccount), taxesAmountTotal, C_Currency_ID);
                    fact.createLine(docLine, m_taxes[i].getAccount(DocTax.ACCTTYPE_TaxCredit_Trans, as, conn),
                            this.C_Currency_ID, "", taxToTransAccount.toString(), Fact_Acct_Group_ID,
                            nextSeqNo(SeqNo), DocumentType, conn);
                }
                final BigDecimal taxToFinalAccount = taxesAmountTotal.subtract(taxToTransAccount);
                fact.createLine(docLine, m_taxes[i].getAccount(DocTax.ACCTTYPE_TaxCredit, as, conn),
                        this.C_Currency_ID, "", taxToFinalAccount.toString(), Fact_Acct_Group_ID,
                        nextSeqNo(SeqNo), DocumentType, conn);
            }
        }
        // Expense CR
        for (int i = 0; p_lines != null && i < p_lines.length; i++) {
            String amount = p_lines[i].getAmount();
            String amountConverted = "";
            ConversionRateDoc conversionRateCurrentDoc = getConversionRateDoc(TABLEID_Invoice, Record_ID,
                    C_Currency_ID, as.m_C_Currency_ID);
            if (conversionRateCurrentDoc != null) {
                amountConverted = applyRate(new BigDecimal(p_lines[i].getAmount()), conversionRateCurrentDoc,
                        true).setScale(2, BigDecimal.ROUND_HALF_UP).toString();
            } else {
                amountConverted = getConvertedAmt(p_lines[i].getAmount(), C_Currency_ID, as.m_C_Currency_ID,
                        DateAcct, "", AD_Client_ID, AD_Org_ID, conn);
            }
            Account account = ((DocLine_Invoice) p_lines[i]).getAccount(ProductInfo.ACCTTYPE_P_Expense, as,
                    conn);
            if (((DocLine_Invoice) p_lines[i]).isDeferred()) {
                amount = createAccDefExpenseFact(fact, (DocLine_Invoice) p_lines[i], account,
                        ((DocLine_Invoice) p_lines[i]).getAccount(ProductInfo.ACCTTYPE_P_DefExpense, as, conn),
                        amountConverted, as.m_C_Currency_ID, conn);
                fact.createLine(p_lines[i], account, as.m_C_Currency_ID, "", amount, Fact_Acct_Group_ID,
                        nextSeqNo(SeqNo), DocumentType, conn);
            } else {
                fact.createLine(p_lines[i], account, this.C_Currency_ID, "", amount, Fact_Acct_Group_ID,
                        nextSeqNo(SeqNo), DocumentType, conn);
            }
            // If expense has been deferred
            if (((DocLine_Invoice) p_lines[i]).isDeferred() && !amount.equals(amountConverted)) {
                amount = new BigDecimal(amountConverted).subtract(new BigDecimal(amount)).toString();
                fact.createLine(p_lines[i],
                        ((DocLine_Invoice) p_lines[i]).getAccount(ProductInfo.ACCTTYPE_P_DefExpense, as, conn),
                        as.m_C_Currency_ID, "", amount, Fact_Acct_Group_ID, nextSeqNo(SeqNo), DocumentType,
                        conn);
            }

        }
        // Set Locations
        FactLine[] fLines = fact.getLines();
        for (int i = 0; fLines != null && i < fLines.length; i++) {
            if (fLines[i] != null) {
                fLines[i].setLocationFromBPartner(C_BPartner_Location_ID, true, conn); // from Loc
                fLines[i].setLocationFromOrg(fLines[i].getAD_Org_ID(conn), false, conn); // to Loc
            }
        }
    } else {
        log4jDocInvoice.warn("Doc_Invoice - DocumentType unknown: " + this.DocumentType);
        fact = null;
    }
    SeqNo = "0";
    return fact;
}

From source file:org.yes.cart.payment.impl.PaymentProcessorSurrogate.java

/**
 * Calculate delivery amount according to shipment sla cost and items in particular delivery.
 *
 * @param order    order//from   w  w w.  ja v  a2 s  .  co m
 * @param delivery delivery
 * @param payment  payment
 */
private void fillPaymentAmount(final CustomerOrder order, final CustomerOrderDelivery delivery,
        final Payment payment) {
    BigDecimal rez = BigDecimal.ZERO.setScale(Constants.DEFAULT_SCALE);
    PaymentLine shipmentLine = null;
    for (PaymentLine paymentLine : payment.getOrderItems()) {
        if (paymentLine.isShipment()) {
            shipmentLine = paymentLine;
        } else {
            // unit price already includes item level promotions
            rez = rez.add(paymentLine.getQuantity().multiply(paymentLine.getUnitPrice())
                    .setScale(Constants.DEFAULT_SCALE, BigDecimal.ROUND_HALF_UP));
        }
    }
    if (order.isPromoApplied()) {
        // work out the percentage of order level promotion per delivery

        // work out the real sub total using item promotional prices
        // DO NOT use the order.getListPrice() as this is the list price in catalog and we calculate
        // promotions against sale price
        BigDecimal orderTotalList = BigDecimal.ZERO;
        for (final CustomerOrderDet detail : order.getOrderDetail()) {
            orderTotalList = orderTotalList.add(detail.getQty().multiply(detail.getGrossPrice())
                    .setScale(Constants.DEFAULT_SCALE, BigDecimal.ROUND_HALF_UP));
        }

        final BigDecimal orderTotal = order.getGrossPrice();
        // take the list price (sub total of items using list price)
        final BigDecimal discount = orderTotalList.subtract(orderTotal).divide(orderTotalList, 10,
                RoundingMode.HALF_UP);
        // scale delivery items total in accordance with order level discount percentage
        rez = rez.multiply(BigDecimal.ONE.subtract(discount)).setScale(Constants.DEFAULT_SCALE,
                BigDecimal.ROUND_HALF_UP);
    }
    if (shipmentLine != null) {
        // shipping price already includes shipping level promotions
        rez = rez.add(shipmentLine.getUnitPrice()).setScale(Constants.DEFAULT_SCALE, BigDecimal.ROUND_HALF_UP);
    }
    payment.setPaymentAmount(rez);
    payment.setOrderCurrency(order.getCurrency());
    payment.setOrderLocale(order.getLocale());
}

From source file:org.egov.tl.service.TradeLicenseService.java

public void recalculateDemand(final List<FeeMatrixDetail> feeList, TradeLicense license) {
    final LicenseDemand licenseDemand = license.getCurrentDemand();
    // Recalculating current demand detail according to fee matrix
    for (final EgDemandDetails dmd : licenseDemand.getEgDemandDetails())
        for (final FeeMatrixDetail fm : feeList)
            if (licenseDemand.getEgInstallmentMaster().equals(dmd.getEgDemandReason().getEgInstallmentMaster())
                    && dmd.getEgDemandReason().getEgDemandReasonMaster().getCode()
                            .equalsIgnoreCase(fm.getFeeMatrix().getFeeType().getName())) {
                BigDecimal tradeAmt = calculateAmountByRateType(license, fm);
                dmd.setAmount(tradeAmt.setScale(0, RoundingMode.HALF_UP));
            }//from   w  w w  . ja v a  2s  . c  o  m
    calcPenaltyDemandDetails(license, licenseDemand);
    licenseDemand.recalculateBaseDemand();
}