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:op.care.med.inventory.PnlInventory.java

private JPanel createContentPanel4(final MedStock stock) {
    //        final String key = stock.getID() + ".xstock";

    //        if (!contentmap.containsKey(key)) {

    final JPanel pnlTX = new JPanel(new VerticalLayout());
    //            pnlTX.setLayout(new BoxLayout(pnlTX, BoxLayout.PAGE_AXIS));

    pnlTX.setOpaque(true);//  w  w  w. j  a  v a2 s  .  c  o  m
    //        pnlTX.setBackground(Color.white);
    synchronized (lstInventories) {
        pnlTX.setBackground(getColor(SYSConst.light2, lstInventories.indexOf(stock.getInventory()) % 2 != 0));
    }

    /***
     *         _       _     _ _______  __
     *        / \   __| | __| |_   _\ \/ /
     *       / _ \ / _` |/ _` | | |  \  /
     *      / ___ \ (_| | (_| | | |  /  \
     *     /_/   \_\__,_|\__,_| |_| /_/\_\
     *
     */
    JideButton btnAddTX = GUITools.createHyperlinkButton("nursingrecords.inventory.newmedstocktx",
            SYSConst.icon22add, new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    new DlgTX(new MedStockTransaction(stock, BigDecimal.ONE,
                            MedStockTransactionTools.STATE_EDIT_MANUAL), new Closure() {
                                @Override
                                public void execute(Object o) {
                                    if (o != null) {
                                        EntityManager em = OPDE.createEM();
                                        try {
                                            em.getTransaction().begin();

                                            final MedStockTransaction myTX = (MedStockTransaction) em.merge(o);
                                            MedStock myStock = em.merge(stock);
                                            em.lock(myStock, LockModeType.OPTIMISTIC);
                                            em.lock(myStock.getInventory(), LockModeType.OPTIMISTIC);
                                            em.lock(em.merge(myTX.getStock().getInventory().getResident()),
                                                    LockModeType.OPTIMISTIC);
                                            em.getTransaction().commit();

                                            createCP4(myStock.getInventory());

                                            buildPanel();
                                        } catch (OptimisticLockException ole) {
                                            OPDE.warn(ole);
                                            if (em.getTransaction().isActive()) {
                                                em.getTransaction().rollback();
                                            }
                                            if (ole.getMessage().indexOf("Class> entity.info.Resident") > -1) {
                                                OPDE.getMainframe().emptyFrame();
                                                OPDE.getMainframe().afterLogin();
                                            }
                                            OPDE.getDisplayManager()
                                                    .addSubMessage(DisplayManager.getLockMessage());
                                        } catch (Exception e) {
                                            if (em.getTransaction().isActive()) {
                                                em.getTransaction().rollback();
                                            }
                                            OPDE.fatal(e);
                                        } finally {
                                            em.close();
                                        }
                                    }
                                }
                            });
                }
            });
    btnAddTX.setEnabled(!stock.isClosed());
    pnlTX.add(btnAddTX);

    /***
     *      ____  _                           _ _   _______  __
     *     / ___|| |__   _____      __   __ _| | | |_   _\ \/ /___
     *     \___ \| '_ \ / _ \ \ /\ / /  / _` | | |   | |  \  // __|
     *      ___) | | | | (_) \ V  V /  | (_| | | |   | |  /  \\__ \
     *     |____/|_| |_|\___/ \_/\_/    \__,_|_|_|   |_| /_/\_\___/
     *
     */
    OPDE.getMainframe().setBlocked(true);
    OPDE.getDisplayManager().setProgressBarMessage(new DisplayMessage(SYSTools.xx("misc.msg.wait"), -1, 100));

    SwingWorker worker = new SwingWorker() {

        @Override
        protected Object doInBackground() throws Exception {
            int progress = 0;

            List<MedStockTransaction> listTX = MedStockTransactionTools.getAll(stock);
            OPDE.getDisplayManager().setProgressBarMessage(
                    new DisplayMessage(SYSTools.xx("misc.msg.wait"), progress, listTX.size()));

            BigDecimal rowsum = MedStockTools.getSum(stock);
            //                BigDecimal rowsum = MedStockTools.getSum(stock);
            //                Collections.sort(stock.getStockTransaction());
            for (final MedStockTransaction tx : listTX) {
                progress++;
                OPDE.getDisplayManager().setProgressBarMessage(
                        new DisplayMessage(SYSTools.xx("misc.msg.wait"), progress, listTX.size()));
                String title = "<html><table border=\"0\">" + "<tr>" + "<td width=\"130\" align=\"left\">"
                        + DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.SHORT)
                                .format(tx.getPit())
                        + "<br/>[" + tx.getID() + "]" + "</td>" + "<td width=\"200\" align=\"center\">"
                        + SYSTools.catchNull(tx.getText(), "--") + "</td>" +

                        "<td width=\"100\" align=\"right\">"
                        + NumberFormat.getNumberInstance().format(tx.getAmount()) + "</td>" +

                        "<td width=\"100\" align=\"right\">"
                        + (rowsum.compareTo(BigDecimal.ZERO) < 0 ? "<font color=\"red\">" : "")
                        + NumberFormat.getNumberInstance().format(rowsum)
                        + (rowsum.compareTo(BigDecimal.ZERO) < 0 ? "</font>" : "") + "</td>" +

                        (stock.getTradeForm().isWeightControlled() ? "<td width=\"100\" align=\"right\">"
                                + NumberFormat.getNumberInstance().format(tx.getWeight()) + "g" + "</td>" : "")
                        +

                        "<td width=\"100\" align=\"left\">" + SYSTools.anonymizeUser(tx.getUser().getUID())
                        + "</td>" + "</tr>" + "</table>" +

                        "</font></html>";

                rowsum = rowsum.subtract(tx.getAmount());

                final DefaultCPTitle pnlTitle = new DefaultCPTitle(title, null);

                //                pnlTitle.getLeft().addMouseListener();

                if (OPDE.getAppInfo().isAllowedTo(InternalClassACL.DELETE, "nursingrecords.inventory")) {
                    /***
                     *      ____       _ _______  __
                     *     |  _ \  ___| |_   _\ \/ /
                     *     | | | |/ _ \ | | |  \  /
                     *     | |_| |  __/ | | |  /  \
                     *     |____/ \___|_| |_| /_/\_\
                     *
                     */
                    final JButton btnDelTX = new JButton(SYSConst.icon22delete);
                    btnDelTX.setPressedIcon(SYSConst.icon22deletePressed);
                    btnDelTX.setAlignmentX(Component.RIGHT_ALIGNMENT);
                    btnDelTX.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
                    btnDelTX.setContentAreaFilled(false);
                    btnDelTX.setBorder(null);
                    btnDelTX.setToolTipText(SYSTools.xx("nursingrecords.inventory.tx.btndelete.tooltip"));
                    btnDelTX.addActionListener(new ActionListener() {
                        @Override
                        public void actionPerformed(ActionEvent actionEvent) {
                            new DlgYesNo(SYSTools.xx("misc.questions.delete1") + "<br/><i>"
                                    + DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.SHORT)
                                            .format(tx.getPit())
                                    + "&nbsp;" + tx.getUser().getUID() + "</i><br/>"
                                    + SYSTools.xx("misc.questions.delete2"), SYSConst.icon48delete,
                                    new Closure() {
                                        @Override
                                        public void execute(Object answer) {
                                            if (answer.equals(JOptionPane.YES_OPTION)) {
                                                EntityManager em = OPDE.createEM();
                                                try {
                                                    em.getTransaction().begin();

                                                    MedStockTransaction myTX = em.merge(tx);
                                                    MedStock myStock = em.merge(stock);
                                                    em.lock(em.merge(
                                                            myTX.getStock().getInventory().getResident()),
                                                            LockModeType.OPTIMISTIC);
                                                    em.lock(myStock, LockModeType.OPTIMISTIC);
                                                    em.lock(myStock.getInventory(), LockModeType.OPTIMISTIC);
                                                    em.remove(myTX);
                                                    //                                                myStock.getStockTransaction().remove(myTX);
                                                    em.getTransaction().commit();

                                                    //                                                synchronized (lstInventories) {
                                                    //                                                    int indexInventory = lstInventories.indexOf(stock.getInventory());
                                                    //                                                    int indexStock = lstInventories.get(indexInventory).getMedStocks().indexOf(stock);
                                                    //                                                    lstInventories.get(indexInventory).getMedStocks().remove(stock);
                                                    //                                                    lstInventories.get(indexInventory).getMedStocks().add(indexStock, myStock);
                                                    //                                                }

                                                    //                                                synchronized (linemap) {
                                                    //                                                    linemap.remove(myTX);
                                                    //                                                }

                                                    createCP4(myStock.getInventory());

                                                    buildPanel();
                                                } catch (OptimisticLockException ole) {
                                                    OPDE.warn(ole);
                                                    if (em.getTransaction().isActive()) {
                                                        em.getTransaction().rollback();
                                                    }
                                                    if (ole.getMessage()
                                                            .indexOf("Class> entity.info.Resident") > -1) {
                                                        OPDE.getMainframe().emptyFrame();
                                                        OPDE.getMainframe().afterLogin();
                                                    }
                                                    OPDE.getDisplayManager()
                                                            .addSubMessage(DisplayManager.getLockMessage());
                                                } catch (Exception e) {
                                                    if (em.getTransaction().isActive()) {
                                                        em.getTransaction().rollback();
                                                    }
                                                    OPDE.fatal(e);
                                                } finally {
                                                    em.close();
                                                }
                                            }
                                        }
                                    });

                        }
                    });
                    btnDelTX.setEnabled(
                            !stock.isClosed() && (tx.getState() == MedStockTransactionTools.STATE_DEBIT
                                    || tx.getState() == MedStockTransactionTools.STATE_EDIT_MANUAL));
                    pnlTitle.getRight().add(btnDelTX);
                }

                /***
                 *      _   _           _         _______  __
                 *     | | | |_ __   __| | ___   |_   _\ \/ /
                 *     | | | | '_ \ / _` |/ _ \    | |  \  /
                 *     | |_| | | | | (_| | (_) |   | |  /  \
                 *      \___/|_| |_|\__,_|\___/    |_| /_/\_\
                 *
                 */
                final JButton btnUndoTX = new JButton(SYSConst.icon22undo);
                btnUndoTX.setPressedIcon(SYSConst.icon22Pressed);
                btnUndoTX.setAlignmentX(Component.RIGHT_ALIGNMENT);
                btnUndoTX.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
                btnUndoTX.setContentAreaFilled(false);
                btnUndoTX.setBorder(null);
                btnUndoTX.setToolTipText(SYSTools.xx("nursingrecords.inventory.tx.btnUndoTX.tooltip"));
                btnUndoTX.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent actionEvent) {
                        new DlgYesNo(
                                SYSTools.xx("misc.questions.undo1") + "<br/><i>"
                                        + DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.SHORT)
                                                .format(tx.getPit())
                                        + "&nbsp;" + tx.getUser().getUID() + "</i><br/>"
                                        + SYSTools.xx("misc.questions.undo2"),
                                SYSConst.icon48undo, new Closure() {
                                    @Override
                                    public void execute(Object answer) {
                                        if (answer.equals(JOptionPane.YES_OPTION)) {
                                            EntityManager em = OPDE.createEM();
                                            try {
                                                em.getTransaction().begin();
                                                MedStock myStock = em.merge(stock);
                                                final MedStockTransaction myOldTX = em.merge(tx);

                                                myOldTX.setState(MedStockTransactionTools.STATE_CANCELLED);
                                                final MedStockTransaction myNewTX = em
                                                        .merge(new MedStockTransaction(myStock,
                                                                myOldTX.getAmount().negate(),
                                                                MedStockTransactionTools.STATE_CANCEL_REC));
                                                myOldTX.setText(SYSTools.xx("misc.msg.reversedBy") + ": "
                                                        + DateFormat
                                                                .getDateTimeInstance(DateFormat.DEFAULT,
                                                                        DateFormat.SHORT)
                                                                .format(myNewTX.getPit()));
                                                myNewTX.setText(SYSTools.xx("misc.msg.reversalFor") + ": "
                                                        + DateFormat
                                                                .getDateTimeInstance(DateFormat.DEFAULT,
                                                                        DateFormat.SHORT)
                                                                .format(myOldTX.getPit()));

                                                //                                            myStock.getStockTransaction().add(myNewTX);
                                                //                                            myStock.getStockTransaction().remove(tx);
                                                //                                            myStock.getStockTransaction().add(myOldTX);

                                                em.lock(em
                                                        .merge(myNewTX.getStock().getInventory().getResident()),
                                                        LockModeType.OPTIMISTIC);
                                                em.lock(myStock, LockModeType.OPTIMISTIC);
                                                em.lock(myStock.getInventory(), LockModeType.OPTIMISTIC);

                                                em.getTransaction().commit();

                                                //                                            synchronized (lstInventories) {
                                                //                                                int indexInventory = lstInventories.indexOf(stock.getInventory());
                                                //                                                int indexStock = lstInventories.get(indexInventory).getMedStocks().indexOf(stock);
                                                //                                                lstInventories.get(indexInventory).getMedStocks().remove(stock);
                                                //                                                lstInventories.get(indexInventory).getMedStocks().add(indexStock, myStock);
                                                //                                            }

                                                //                                            synchronized (linemap) {
                                                //                                                linemap.remove(tx);
                                                //                                            }
                                                createCP4(myStock.getInventory());
                                                buildPanel();
                                                //                                            SwingUtilities.invokeLater(new Runnable() {
                                                //                                                @Override
                                                //                                                public void run() {
                                                //                                                    synchronized (linemap) {
                                                //                                                        GUITools.flashBackground(linemap.get(myOldTX), Color.RED, 2);
                                                //                                                        GUITools.flashBackground(linemap.get(myNewTX), Color.YELLOW, 2);
                                                //                                                    }
                                                //                                                }
                                                //                                            });
                                            } catch (OptimisticLockException ole) {
                                                OPDE.warn(ole);
                                                if (em.getTransaction().isActive()) {
                                                    em.getTransaction().rollback();
                                                }
                                                if (ole.getMessage()
                                                        .indexOf("Class> entity.info.Resident") > -1) {
                                                    OPDE.getMainframe().emptyFrame();
                                                    OPDE.getMainframe().afterLogin();
                                                }
                                                OPDE.getDisplayManager()
                                                        .addSubMessage(DisplayManager.getLockMessage());
                                            } catch (Exception e) {
                                                if (em.getTransaction().isActive()) {
                                                    em.getTransaction().rollback();
                                                }
                                                OPDE.fatal(e);
                                            } finally {
                                                em.close();
                                            }
                                        }
                                    }
                                });

                    }
                });
                btnUndoTX.setEnabled(!stock.isClosed() && (tx.getState() == MedStockTransactionTools.STATE_DEBIT
                        || tx.getState() == MedStockTransactionTools.STATE_EDIT_MANUAL));
                pnlTitle.getRight().add(btnUndoTX);

                if (stock.getTradeForm().isWeightControlled() && OPDE.getAppInfo()
                        .isAllowedTo(InternalClassACL.MANAGER, "nursingrecords.inventory")) {
                    /***
                     *               _ __        __   _       _     _
                     *      ___  ___| |\ \      / /__(_) __ _| |__ | |_
                     *     / __|/ _ \ __\ \ /\ / / _ \ |/ _` | '_ \| __|
                     *     \__ \  __/ |_ \ V  V /  __/ | (_| | | | | |_
                     *     |___/\___|\__| \_/\_/ \___|_|\__, |_| |_|\__|
                     *                                  |___/
                     */
                    final JButton btnSetWeight = new JButton(SYSConst.icon22scales);
                    btnSetWeight.setPressedIcon(SYSConst.icon22Pressed);
                    btnSetWeight.setAlignmentX(Component.RIGHT_ALIGNMENT);
                    btnSetWeight.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
                    btnSetWeight.setContentAreaFilled(false);
                    btnSetWeight.setBorder(null);
                    btnSetWeight.setToolTipText(SYSTools.xx("nursingrecords.inventory.tx.btnUndoTX.tooltip"));
                    btnSetWeight.addActionListener(new ActionListener() {
                        @Override
                        public void actionPerformed(ActionEvent actionEvent) {

                            BigDecimal weight;
                            new DlgYesNo(SYSConst.icon48scales, new Closure() {
                                @Override
                                public void execute(Object o) {
                                    if (!SYSTools.catchNull(o).isEmpty()) {
                                        BigDecimal weight = (BigDecimal) o;

                                        EntityManager em = OPDE.createEM();
                                        try {
                                            em.getTransaction().begin();
                                            MedStock myStock = em.merge(stock);
                                            final MedStockTransaction myTX = em.merge(tx);
                                            em.lock(myTX, LockModeType.OPTIMISTIC);
                                            myTX.setWeight(weight);
                                            em.lock(myStock, LockModeType.OPTIMISTIC);
                                            em.lock(myStock.getInventory(), LockModeType.OPTIMISTIC);

                                            em.getTransaction().commit();

                                            createCP4(myStock.getInventory());
                                            buildPanel();
                                        } catch (OptimisticLockException ole) {
                                            OPDE.warn(ole);
                                            if (em.getTransaction().isActive()) {
                                                em.getTransaction().rollback();
                                            }
                                            if (ole.getMessage().indexOf("Class> entity.info.Resident") > -1) {
                                                OPDE.getMainframe().emptyFrame();
                                                OPDE.getMainframe().afterLogin();
                                            }
                                            OPDE.getDisplayManager()
                                                    .addSubMessage(DisplayManager.getLockMessage());
                                        } catch (Exception e) {
                                            if (em.getTransaction().isActive()) {
                                                em.getTransaction().rollback();
                                            }
                                            OPDE.fatal(e);
                                        } finally {
                                            em.close();
                                        }
                                    }
                                }
                            }, "nursingrecords.bhp.weight",
                                    NumberFormat.getNumberInstance().format(tx.getWeight()),
                                    new Validator<BigDecimal>() {
                                        @Override
                                        public boolean isValid(String value) {
                                            BigDecimal bd = parse(value);
                                            return bd != null && bd.compareTo(BigDecimal.ZERO) > 0;

                                        }

                                        @Override
                                        public BigDecimal parse(String text) {
                                            return SYSTools.parseDecimal(text);
                                        }
                                    });

                        }
                    });
                    btnSetWeight.setEnabled(
                            !stock.isClosed() && (tx.getState() == MedStockTransactionTools.STATE_DEBIT
                                    || tx.getState() == MedStockTransactionTools.STATE_CREDIT
                                    || tx.getState() == MedStockTransactionTools.STATE_EDIT_MANUAL));
                    pnlTitle.getRight().add(btnSetWeight);
                }

                pnlTX.add(pnlTitle.getMain());
            }

            return null;
        }

        @Override
        protected void done() {
            OPDE.getDisplayManager().setProgressBarMessage(null);
            OPDE.getMainframe().setBlocked(false);
        }
    };
    worker.execute();

    return pnlTX;
}

From source file:org.apache.ofbiz.accounting.invoice.InvoiceServices.java

public static Map<String, Object> createInvoiceForOrder(DispatchContext dctx, Map<String, Object> context) {
    Delegator delegator = dctx.getDelegator();
    LocalDispatcher dispatcher = dctx.getDispatcher();
    GenericValue userLogin = (GenericValue) context.get("userLogin");
    Locale locale = (Locale) context.get("locale");

    if (DECIMALS == -1 || ROUNDING == -1) {
        return ServiceUtil.returnError(
                UtilProperties.getMessage(resource, "AccountingAritmeticPropertiesNotConfigured", locale));
    }//from  w w  w . j  a  v  a2s.c  om

    String orderId = (String) context.get("orderId");
    List<GenericValue> billItems = UtilGenerics.checkList(context.get("billItems"));
    String invoiceId = (String) context.get("invoiceId");

    if (UtilValidate.isEmpty(billItems)) {
        Debug.logVerbose("No order items to invoice; not creating invoice; returning success", module);
        return ServiceUtil
                .returnSuccess(UtilProperties.getMessage(resource, "AccountingNoOrderItemsToInvoice", locale));
    }

    try {
        GenericValue orderHeader = EntityQuery.use(delegator).from("OrderHeader").where("orderId", orderId)
                .queryOne();
        if (orderHeader == null) {
            return ServiceUtil
                    .returnError(UtilProperties.getMessage(resource, "AccountingNoOrderHeader", locale));
        }

        // figure out the invoice type
        String invoiceType = null;

        String orderType = orderHeader.getString("orderTypeId");
        if (orderType.equals("SALES_ORDER")) {
            invoiceType = "SALES_INVOICE";
        } else if (orderType.equals("PURCHASE_ORDER")) {
            invoiceType = "PURCHASE_INVOICE";
        }

        // Set the precision depending on the type of invoice
        int invoiceTypeDecimals = UtilNumber.getBigDecimalScale("invoice." + invoiceType + ".decimals");
        if (invoiceTypeDecimals == -1)
            invoiceTypeDecimals = DECIMALS;

        // Make an order read helper from the order
        OrderReadHelper orh = new OrderReadHelper(orderHeader);

        // get the product store
        GenericValue productStore = orh.getProductStore();

        // get the shipping adjustment mode (Y = Pro-Rate; N = First-Invoice)
        String prorateShipping = productStore != null ? productStore.getString("prorateShipping") : "Y";
        if (prorateShipping == null) {
            prorateShipping = "Y";
        }

        // get the billing parties
        String billToCustomerPartyId = orh.getBillToParty().getString("partyId");
        String billFromVendorPartyId = orh.getBillFromParty().getString("partyId");

        // get some price totals
        BigDecimal shippableAmount = orh.getShippableTotal(null);
        BigDecimal shippableQuantity = orh.getShippableQuantity(null);
        BigDecimal orderSubTotal = orh.getOrderItemsSubTotal();
        BigDecimal orderQuantity = orh.getTotalOrderItemsQuantity();

        // these variables are for pro-rating order amounts across invoices, so they should not be rounded off for maximum accuracy
        BigDecimal invoiceShipProRateAmount = ZERO;
        BigDecimal invoiceShippableQuantity = ZERO;
        BigDecimal invoiceSubTotal = ZERO;
        BigDecimal invoiceQuantity = ZERO;

        GenericValue billingAccount = orderHeader.getRelatedOne("BillingAccount", false);
        String billingAccountId = billingAccount != null ? billingAccount.getString("billingAccountId") : null;

        Timestamp invoiceDate = (Timestamp) context.get("eventDate");
        if (UtilValidate.isEmpty(invoiceDate)) {
            // TODO: ideally this should be the same time as when a shipment is sent and be passed in as a parameter
            invoiceDate = UtilDateTime.nowTimestamp();
        }
        // TODO: perhaps consider billing account net days term as well?
        Long orderTermNetDays = orh.getOrderTermNetDays();
        Timestamp dueDate = null;
        if (orderTermNetDays != null) {
            dueDate = UtilDateTime.getDayEnd(invoiceDate, orderTermNetDays);
        }

        // create the invoice record
        if (UtilValidate.isEmpty(invoiceId)) {
            Map<String, Object> createInvoiceContext = new HashMap<String, Object>();
            createInvoiceContext.put("partyId", billToCustomerPartyId);
            createInvoiceContext.put("partyIdFrom", billFromVendorPartyId);
            createInvoiceContext.put("billingAccountId", billingAccountId);
            createInvoiceContext.put("invoiceDate", invoiceDate);
            createInvoiceContext.put("dueDate", dueDate);
            createInvoiceContext.put("invoiceTypeId", invoiceType);
            // start with INVOICE_IN_PROCESS, in the INVOICE_READY we can't change the invoice (or shouldn't be able to...)
            createInvoiceContext.put("statusId", "INVOICE_IN_PROCESS");
            createInvoiceContext.put("currencyUomId", orderHeader.getString("currencyUom"));
            createInvoiceContext.put("userLogin", userLogin);

            // store the invoice first
            Map<String, Object> createInvoiceResult = dispatcher.runSync("createInvoice", createInvoiceContext);
            if (ServiceUtil.isError(createInvoiceResult)) {
                return ServiceUtil.returnError(
                        UtilProperties.getMessage(resource, "AccountingErrorCreatingInvoiceFromOrder", locale),
                        null, null, createInvoiceResult);
            }

            // call service, not direct entity op: delegator.create(invoice);
            invoiceId = (String) createInvoiceResult.get("invoiceId");
        }

        // order roles to invoice roles
        List<GenericValue> orderRoles = orderHeader.getRelated("OrderRole", null, null, false);
        Map<String, Object> createInvoiceRoleContext = new HashMap<String, Object>();
        createInvoiceRoleContext.put("invoiceId", invoiceId);
        createInvoiceRoleContext.put("userLogin", userLogin);
        for (GenericValue orderRole : orderRoles) {
            createInvoiceRoleContext.put("partyId", orderRole.getString("partyId"));
            createInvoiceRoleContext.put("roleTypeId", orderRole.getString("roleTypeId"));
            Map<String, Object> createInvoiceRoleResult = dispatcher.runSync("createInvoiceRole",
                    createInvoiceRoleContext);
            if (ServiceUtil.isError(createInvoiceRoleResult)) {
                return ServiceUtil.returnError(
                        UtilProperties.getMessage(resource, "AccountingErrorCreatingInvoiceFromOrder", locale),
                        null, null, createInvoiceRoleResult);
            }
        }

        // order terms to invoice terms.
        // TODO: it might be nice to filter OrderTerms to only copy over financial terms.
        List<GenericValue> orderTerms = orh.getOrderTerms();
        createInvoiceTerms(delegator, dispatcher, invoiceId, orderTerms, userLogin, locale);

        // billing accounts
        // List billingAccountTerms = null;
        // for billing accounts we will use related information
        if (billingAccount != null) {
            /*
             * jacopoc: billing account terms were already copied as order terms
             *          when the order was created.
            // get the billing account terms
            billingAccountTerms = billingAccount.getRelated("BillingAccountTerm", null, null, false);
                    
            // set the invoice terms as defined for the billing account
            createInvoiceTerms(delegator, dispatcher, invoiceId, billingAccountTerms, userLogin, locale);
            */
            // set the invoice bill_to_customer from the billing account
            List<GenericValue> billToRoles = billingAccount.getRelated("BillingAccountRole",
                    UtilMisc.toMap("roleTypeId", "BILL_TO_CUSTOMER"), null, false);
            for (GenericValue billToRole : billToRoles) {
                if (!(billToRole.getString("partyId").equals(billToCustomerPartyId))) {
                    createInvoiceRoleContext = UtilMisc.toMap("invoiceId", invoiceId, "partyId",
                            billToRole.get("partyId"), "roleTypeId", "BILL_TO_CUSTOMER", "userLogin",
                            userLogin);
                    Map<String, Object> createInvoiceRoleResult = dispatcher.runSync("createInvoiceRole",
                            createInvoiceRoleContext);
                    if (ServiceUtil.isError(createInvoiceRoleResult)) {
                        return ServiceUtil.returnError(
                                UtilProperties.getMessage(resource,
                                        "AccountingErrorCreatingInvoiceRoleFromOrder", locale),
                                null, null, createInvoiceRoleResult);
                    }
                }
            }

            // set the bill-to contact mech as the contact mech of the billing account
            if (UtilValidate.isNotEmpty(billingAccount.getString("contactMechId"))) {
                Map<String, Object> createBillToContactMechContext = UtilMisc.toMap("invoiceId", invoiceId,
                        "contactMechId", billingAccount.getString("contactMechId"), "contactMechPurposeTypeId",
                        "BILLING_LOCATION", "userLogin", userLogin);
                Map<String, Object> createBillToContactMechResult = dispatcher
                        .runSync("createInvoiceContactMech", createBillToContactMechContext);
                if (ServiceUtil.isError(createBillToContactMechResult)) {
                    return ServiceUtil.returnError(
                            UtilProperties.getMessage(resource,
                                    "AccountingErrorCreatingInvoiceContactMechFromOrder", locale),
                            null, null, createBillToContactMechResult);
                }
            }
        } else {
            List<GenericValue> billingLocations = orh.getBillingLocations();
            if (UtilValidate.isNotEmpty(billingLocations)) {
                for (GenericValue ocm : billingLocations) {
                    Map<String, Object> createBillToContactMechContext = UtilMisc.toMap("invoiceId", invoiceId,
                            "contactMechId", ocm.getString("contactMechId"), "contactMechPurposeTypeId",
                            "BILLING_LOCATION", "userLogin", userLogin);
                    Map<String, Object> createBillToContactMechResult = dispatcher
                            .runSync("createInvoiceContactMech", createBillToContactMechContext);
                    if (ServiceUtil.isError(createBillToContactMechResult)) {
                        return ServiceUtil.returnError(
                                UtilProperties.getMessage(resource,
                                        "AccountingErrorCreatingInvoiceContactMechFromOrder", locale),
                                null, null, createBillToContactMechResult);
                    }
                }
            } else {
                Debug.logWarning("No billing locations found for order [" + orderId
                        + "] and none were created for Invoice [" + invoiceId + "]", module);
            }
        }

        // get a list of the payment method types
        //DEJ20050705 doesn't appear to be used: List paymentPreferences = orderHeader.getRelated("OrderPaymentPreference", null, null, false);

        // create the bill-from (or pay-to) contact mech as the primary PAYMENT_LOCATION of the party from the store
        GenericValue payToAddress = null;
        if (invoiceType.equals("PURCHASE_INVOICE")) {
            // for purchase orders, the pay to address is the BILLING_LOCATION of the vendor
            GenericValue billFromVendor = orh.getPartyFromRole("BILL_FROM_VENDOR");
            if (billFromVendor != null) {
                List<GenericValue> billingContactMechs = billFromVendor.getRelatedOne("Party", false)
                        .getRelated("PartyContactMechPurpose",
                                UtilMisc.toMap("contactMechPurposeTypeId", "BILLING_LOCATION"), null, false);
                if (UtilValidate.isNotEmpty(billingContactMechs)) {
                    payToAddress = EntityUtil.getFirst(billingContactMechs);
                }
            }
        } else {
            // for sales orders, it is the payment address on file for the store
            payToAddress = PaymentWorker.getPaymentAddress(delegator, productStore.getString("payToPartyId"));
        }
        if (payToAddress != null) {
            Map<String, Object> createPayToContactMechContext = UtilMisc.toMap("invoiceId", invoiceId,
                    "contactMechId", payToAddress.getString("contactMechId"), "contactMechPurposeTypeId",
                    "PAYMENT_LOCATION", "userLogin", userLogin);
            Map<String, Object> createPayToContactMechResult = dispatcher.runSync("createInvoiceContactMech",
                    createPayToContactMechContext);
            if (ServiceUtil.isError(createPayToContactMechResult)) {
                return ServiceUtil.returnError(
                        UtilProperties.getMessage(resource,
                                "AccountingErrorCreatingInvoiceContactMechFromOrder", locale),
                        null, null, createPayToContactMechResult);
            }
        }

        // sequence for items - all OrderItems or InventoryReservations + all Adjustments
        int invoiceItemSeqNum = 1;
        String invoiceItemSeqId = UtilFormatOut.formatPaddedNumber(invoiceItemSeqNum,
                INVOICE_ITEM_SEQUENCE_ID_DIGITS);

        // create the item records
        for (GenericValue currentValue : billItems) {
            GenericValue itemIssuance = null;
            GenericValue orderItem = null;
            GenericValue shipmentReceipt = null;
            if ("ItemIssuance".equals(currentValue.getEntityName())) {
                itemIssuance = currentValue;
            } else if ("OrderItem".equals(currentValue.getEntityName())) {
                orderItem = currentValue;
            } else if ("ShipmentReceipt".equals(currentValue.getEntityName())) {
                shipmentReceipt = currentValue;
            } else {
                Debug.logError("Unexpected entity " + currentValue + " of type " + currentValue.getEntityName(),
                        module);
            }

            if (orderItem == null && itemIssuance != null) {
                orderItem = itemIssuance.getRelatedOne("OrderItem", false);
            } else if ((orderItem == null) && (shipmentReceipt != null)) {
                orderItem = shipmentReceipt.getRelatedOne("OrderItem", false);
            } else if ((orderItem == null) && (itemIssuance == null) && (shipmentReceipt == null)) {
                Debug.logError(
                        "Cannot create invoice when orderItem, itemIssuance, and shipmentReceipt are all null",
                        module);
                return ServiceUtil.returnError(UtilProperties.getMessage(resource,
                        "AccountingIllegalValuesPassedToCreateInvoiceService", locale));
            }
            GenericValue product = null;
            if (orderItem.get("productId") != null) {
                product = orderItem.getRelatedOne("Product", false);
            }

            // get some quantities
            BigDecimal billingQuantity = null;
            if (itemIssuance != null) {
                billingQuantity = itemIssuance.getBigDecimal("quantity");
                BigDecimal cancelQty = itemIssuance.getBigDecimal("cancelQuantity");
                if (cancelQty == null) {
                    cancelQty = ZERO;
                }
                billingQuantity = billingQuantity.subtract(cancelQty).setScale(DECIMALS, ROUNDING);
            } else if (shipmentReceipt != null) {
                billingQuantity = shipmentReceipt.getBigDecimal("quantityAccepted");
            } else {
                BigDecimal orderedQuantity = OrderReadHelper.getOrderItemQuantity(orderItem);
                BigDecimal invoicedQuantity = OrderReadHelper.getOrderItemInvoicedQuantity(orderItem);
                billingQuantity = orderedQuantity.subtract(invoicedQuantity);
                if (billingQuantity.compareTo(ZERO) < 0) {
                    billingQuantity = ZERO;
                }
            }
            if (billingQuantity == null)
                billingQuantity = ZERO;

            // check if shipping applies to this item.  Shipping is calculated for sales invoices, not purchase invoices.
            boolean shippingApplies = false;
            if ((product != null) && (ProductWorker.shippingApplies(product))
                    && (invoiceType.equals("SALES_INVOICE"))) {
                shippingApplies = true;
            }

            BigDecimal billingAmount = BigDecimal.ZERO;
            GenericValue OrderAdjustment = EntityUtil.getFirst(orderItem.getRelated("OrderAdjustment",
                    UtilMisc.toMap("orderAdjustmentTypeId", "VAT_TAX"), null, false));
            /* Apply formula to get actual product price to set amount in invoice item
            Formula is: productPrice = (productPriceWithTax.multiply(100)) / (orderAdj sourcePercentage + 100))
            product price = (43*100) / (20+100) = 35.83 (Here product price is 43 with VAT)
             */
            if (UtilValidate.isNotEmpty(OrderAdjustment)
                    && (OrderAdjustment.getBigDecimal("amount").signum() == 0)
                    && UtilValidate.isNotEmpty(OrderAdjustment.getBigDecimal("amountAlreadyIncluded"))
                    && OrderAdjustment.getBigDecimal("amountAlreadyIncluded").signum() != 0) {
                BigDecimal sourcePercentageTotal = OrderAdjustment.getBigDecimal("sourcePercentage")
                        .add(new BigDecimal(100));
                billingAmount = orderItem.getBigDecimal("unitPrice")
                        .divide(sourcePercentageTotal, 100, ROUNDING).multiply(new BigDecimal(100))
                        .setScale(invoiceTypeDecimals, ROUNDING);
            } else {
                billingAmount = orderItem.getBigDecimal("unitPrice").setScale(invoiceTypeDecimals, ROUNDING);
            }

            Map<String, Object> createInvoiceItemContext = new HashMap<String, Object>();
            createInvoiceItemContext.put("invoiceId", invoiceId);
            createInvoiceItemContext.put("invoiceItemSeqId", invoiceItemSeqId);
            createInvoiceItemContext.put("invoiceItemTypeId",
                    getInvoiceItemType(delegator, (orderItem.getString("orderItemTypeId")),
                            (product == null ? null : product.getString("productTypeId")), invoiceType,
                            "INV_FPROD_ITEM"));
            createInvoiceItemContext.put("description", orderItem.get("itemDescription"));
            createInvoiceItemContext.put("quantity", billingQuantity);
            createInvoiceItemContext.put("amount", billingAmount);
            createInvoiceItemContext.put("productId", orderItem.get("productId"));
            createInvoiceItemContext.put("productFeatureId", orderItem.get("productFeatureId"));
            createInvoiceItemContext.put("overrideGlAccountId", orderItem.get("overrideGlAccountId"));
            createInvoiceItemContext.put("userLogin", userLogin);

            String itemIssuanceId = null;
            if (itemIssuance != null && itemIssuance.get("inventoryItemId") != null) {
                itemIssuanceId = itemIssuance.getString("itemIssuanceId");
                createInvoiceItemContext.put("inventoryItemId", itemIssuance.get("inventoryItemId"));
            }
            // similarly, tax only for purchase invoices
            if ((product != null) && (invoiceType.equals("SALES_INVOICE"))) {
                createInvoiceItemContext.put("taxableFlag", product.get("taxable"));
            }

            Map<String, Object> createInvoiceItemResult = dispatcher.runSync("createInvoiceItem",
                    createInvoiceItemContext);
            if (ServiceUtil.isError(createInvoiceItemResult)) {
                return ServiceUtil
                        .returnError(
                                UtilProperties.getMessage(resource,
                                        "AccountingErrorCreatingInvoiceItemFromOrder", locale),
                                null, null, createInvoiceItemResult);
            }

            // this item total
            BigDecimal thisAmount = billingAmount.multiply(billingQuantity).setScale(invoiceTypeDecimals,
                    ROUNDING);

            // add to the ship amount only if it applies to this item
            if (shippingApplies) {
                invoiceShipProRateAmount = invoiceShipProRateAmount.add(thisAmount)
                        .setScale(invoiceTypeDecimals, ROUNDING);
                invoiceShippableQuantity = invoiceQuantity.add(billingQuantity).setScale(invoiceTypeDecimals,
                        ROUNDING);
            }

            // increment the invoice subtotal
            invoiceSubTotal = invoiceSubTotal.add(thisAmount).setScale(100, ROUNDING);

            // increment the invoice quantity
            invoiceQuantity = invoiceQuantity.add(billingQuantity).setScale(invoiceTypeDecimals, ROUNDING);

            // create the OrderItemBilling record
            Map<String, Object> createOrderItemBillingContext = new HashMap<String, Object>();
            createOrderItemBillingContext.put("invoiceId", invoiceId);
            createOrderItemBillingContext.put("invoiceItemSeqId", invoiceItemSeqId);
            createOrderItemBillingContext.put("orderId", orderItem.get("orderId"));
            createOrderItemBillingContext.put("orderItemSeqId", orderItem.get("orderItemSeqId"));
            createOrderItemBillingContext.put("itemIssuanceId", itemIssuanceId);
            createOrderItemBillingContext.put("quantity", billingQuantity);
            createOrderItemBillingContext.put("amount", billingAmount);
            createOrderItemBillingContext.put("userLogin", userLogin);
            if ((shipmentReceipt != null) && (shipmentReceipt.getString("receiptId") != null)) {
                createOrderItemBillingContext.put("shipmentReceiptId", shipmentReceipt.getString("receiptId"));
            }

            Map<String, Object> createOrderItemBillingResult = dispatcher.runSync("createOrderItemBilling",
                    createOrderItemBillingContext);
            if (ServiceUtil.isError(createOrderItemBillingResult)) {
                return ServiceUtil
                        .returnError(
                                UtilProperties.getMessage(resource,
                                        "AccountingErrorCreatingOrderItemBillingFromOrder", locale),
                                null, null, createOrderItemBillingResult);
            }

            if ("ItemIssuance".equals(currentValue.getEntityName())) {
                /* Find ShipmentItemBilling based on shipmentId, shipmentItemSeqId, invoiceId, invoiceItemSeqId as
                   because if any order item has multiple quantity and reserved by multiple inventories then there will be multiple invoice items.
                   In that case ShipmentItemBilling was creating only for one invoice item. Fixed under OFBIZ-6806.
                */
                List<GenericValue> shipmentItemBillings = EntityQuery.use(delegator).from("ShipmentItemBilling")
                        .where("shipmentId", currentValue.get("shipmentId"), "shipmentItemSeqId",
                                currentValue.get("shipmentItemSeqId"), "invoiceId", invoiceId,
                                "invoiceItemSeqId", invoiceItemSeqId)
                        .queryList();
                if (UtilValidate.isEmpty(shipmentItemBillings)) {

                    // create the ShipmentItemBilling record
                    GenericValue shipmentItemBilling = delegator.makeValue("ShipmentItemBilling",
                            UtilMisc.toMap("invoiceId", invoiceId, "invoiceItemSeqId", invoiceItemSeqId));
                    shipmentItemBilling.put("shipmentId", currentValue.get("shipmentId"));
                    shipmentItemBilling.put("shipmentItemSeqId", currentValue.get("shipmentItemSeqId"));
                    shipmentItemBilling.create();
                }
            }

            String parentInvoiceItemSeqId = invoiceItemSeqId;
            // increment the counter
            invoiceItemSeqNum++;
            invoiceItemSeqId = UtilFormatOut.formatPaddedNumber(invoiceItemSeqNum,
                    INVOICE_ITEM_SEQUENCE_ID_DIGITS);

            // Get the original order item from the DB, in case the quantity has been overridden
            GenericValue originalOrderItem = EntityQuery.use(delegator).from("OrderItem")
                    .where("orderId", orderId, "orderItemSeqId", orderItem.get("orderItemSeqId")).queryOne();

            // create the item adjustment as line items
            List<GenericValue> itemAdjustments = OrderReadHelper.getOrderItemAdjustmentList(orderItem,
                    orh.getAdjustments());
            for (GenericValue adj : itemAdjustments) {

                // Check against OrderAdjustmentBilling to see how much of this adjustment has already been invoiced
                BigDecimal adjAlreadyInvoicedAmount = null;
                try {
                    Map<String, Object> checkResult = dispatcher.runSync("calculateInvoicedAdjustmentTotal",
                            UtilMisc.toMap("orderAdjustment", adj));
                    adjAlreadyInvoicedAmount = (BigDecimal) checkResult.get("invoicedTotal");
                } catch (GenericServiceException e) {
                    Debug.logError(e, "Accounting trouble calling calculateInvoicedAdjustmentTotal service",
                            module);
                    return ServiceUtil.returnError(UtilProperties.getMessage(resource,
                            "AccountingTroubleCallingCalculateInvoicedAdjustmentTotalService", locale));
                }

                //                    if (adj.get("amount") == null) { TODO check usage with webPos. Was: fix a bug coming from POS in case of use of a discount (on item(s) or sale, item(s) here) and a cash amount higher than total (hence issuing change)
                //                        continue;
                //                    }
                // Set adjustment amount as amountAlreadyIncluded to continue invoice item creation process
                Boolean isTaxIncludedInPrice = adj.getString("orderAdjustmentTypeId").equals("VAT_TAX")
                        && UtilValidate.isNotEmpty(adj.getBigDecimal("amountAlreadyIncluded"))
                        && adj.getBigDecimal("amountAlreadyIncluded").signum() != 0;
                if ((adj.getBigDecimal("amount").signum() == 0) && isTaxIncludedInPrice) {
                    adj.set("amount", adj.getBigDecimal("amountAlreadyIncluded"));
                }
                // If the absolute invoiced amount >= the abs of the adjustment amount, the full amount has already been invoiced, so skip this adjustment
                if (adjAlreadyInvoicedAmount.abs().compareTo(
                        adj.getBigDecimal("amount").setScale(invoiceTypeDecimals, ROUNDING).abs()) > 0) {
                    continue;
                }

                BigDecimal originalOrderItemQuantity = OrderReadHelper.getOrderItemQuantity(originalOrderItem);
                BigDecimal amount = ZERO;
                if (originalOrderItemQuantity.signum() != 0) {
                    if (adj.get("amount") != null) {
                        if ("PROMOTION_ADJUSTMENT".equals(adj.getString("orderAdjustmentTypeId"))
                                && adj.get("productPromoId") != null) {
                            /* Find negative amountAlreadyIncluded in OrderAdjustment to subtract it from discounted amount.
                                                                  As we stored negative sales tax amount in order adjustment for discounted item.
                             */
                            List<EntityExpr> exprs = UtilMisc.toList(
                                    EntityCondition.makeCondition("orderId", EntityOperator.EQUALS,
                                            orderItem.getString("orderId")),
                                    EntityCondition.makeCondition("orderItemSeqId", EntityOperator.EQUALS,
                                            orderItem.getString("orderItemSeqId")),
                                    EntityCondition.makeCondition("orderAdjustmentTypeId",
                                            EntityOperator.EQUALS, "VAT_TAX"),
                                    EntityCondition.makeCondition("amountAlreadyIncluded",
                                            EntityOperator.LESS_THAN, BigDecimal.ZERO));
                            EntityCondition andCondition = EntityCondition.makeCondition(exprs,
                                    EntityOperator.AND);
                            GenericValue orderAdjustment = EntityUtil.getFirst(delegator
                                    .findList("OrderAdjustment", andCondition, null, null, null, false));
                            if (UtilValidate.isNotEmpty(orderAdjustment)) {
                                amount = adj.getBigDecimal("amount")
                                        .subtract(orderAdjustment.getBigDecimal("amountAlreadyIncluded"))
                                        .setScale(100, ROUNDING);
                            } else {
                                amount = adj.getBigDecimal("amount");
                            }
                        } else {
                            // pro-rate the amount
                            // set decimals = 100 means we don't round this intermediate value, which is very important
                            if (isTaxIncludedInPrice) {
                                BigDecimal priceWithTax = originalOrderItem.getBigDecimal("unitPrice");
                                // Get tax included in item price
                                amount = priceWithTax.subtract(billingAmount);
                                amount = amount.multiply(billingQuantity);
                                // get adjustment amount
                                /* Get tax amount of other invoice and calculate remaining amount need to store in invoice item(Handle case of of partial shipment and promotional item)
                                                                      to adjust tax amount in invoice item. 
                                 */
                                BigDecimal otherInvoiceTaxAmount = BigDecimal.ZERO;
                                GenericValue orderAdjBilling = EntityUtil.getFirst(delegator.findByAnd(
                                        "OrderAdjustmentBilling",
                                        UtilMisc.toMap("orderAdjustmentId", adj.getString("orderAdjustmentId")),
                                        null, false));
                                if (UtilValidate.isNotEmpty(orderAdjBilling)) {
                                    List<GenericValue> invoiceItems = delegator.findByAnd("InvoiceItem",
                                            UtilMisc.toMap("invoiceId", orderAdjBilling.getString("invoiceId"),
                                                    "invoiceItemTypeId", "ITM_SALES_TAX", "productId",
                                                    originalOrderItem.getString("productId")),
                                            null, isTaxIncludedInPrice);
                                    for (GenericValue invoiceItem : invoiceItems) {
                                        otherInvoiceTaxAmount = otherInvoiceTaxAmount
                                                .add(invoiceItem.getBigDecimal("amount"));
                                    }
                                    if (otherInvoiceTaxAmount.compareTo(BigDecimal.ZERO) > 0) {
                                        BigDecimal remainingAmount = adj.getBigDecimal("amountAlreadyIncluded")
                                                .subtract(otherInvoiceTaxAmount);
                                        amount = amount.min(remainingAmount);
                                    }
                                }
                                amount = amount.min(adj.getBigDecimal("amountAlreadyIncluded")).setScale(100,
                                        ROUNDING);
                            } else {
                                amount = adj.getBigDecimal("amount").divide(originalOrderItemQuantity, 100,
                                        ROUNDING);
                                amount = amount.multiply(billingQuantity);
                            }
                        }
                        // Tax needs to be rounded differently from other order adjustments
                        if (adj.getString("orderAdjustmentTypeId").equals("SALES_TAX")) {
                            amount = amount.setScale(TAX_DECIMALS, TAX_ROUNDING);
                        } else {
                            amount = amount.setScale(invoiceTypeDecimals, ROUNDING);
                        }
                    } else if (adj.get("sourcePercentage") != null) {
                        // pro-rate the amount
                        // set decimals = 100 means we don't round this intermediate value, which is very important
                        BigDecimal percent = adj.getBigDecimal("sourcePercentage");
                        percent = percent.divide(new BigDecimal(100), 100, ROUNDING);
                        amount = billingAmount.multiply(percent);
                        amount = amount.divide(originalOrderItemQuantity, 100, ROUNDING);
                        amount = amount.multiply(billingQuantity);
                        amount = amount.setScale(invoiceTypeDecimals, ROUNDING);
                    }
                }
                if (amount.signum() != 0) {
                    Map<String, Object> createInvoiceItemAdjContext = new HashMap<String, Object>();
                    createInvoiceItemAdjContext.put("invoiceId", invoiceId);
                    createInvoiceItemAdjContext.put("invoiceItemSeqId", invoiceItemSeqId);
                    createInvoiceItemAdjContext.put("invoiceItemTypeId", getInvoiceItemType(delegator,
                            adj.getString("orderAdjustmentTypeId"), null, invoiceType, "INVOICE_ITM_ADJ"));
                    createInvoiceItemAdjContext.put("quantity", BigDecimal.ONE);
                    createInvoiceItemAdjContext.put("amount", amount);
                    createInvoiceItemAdjContext.put("productId", orderItem.get("productId"));
                    createInvoiceItemAdjContext.put("productFeatureId", orderItem.get("productFeatureId"));
                    createInvoiceItemAdjContext.put("overrideGlAccountId", adj.get("overrideGlAccountId"));
                    createInvoiceItemAdjContext.put("parentInvoiceId", invoiceId);
                    createInvoiceItemAdjContext.put("parentInvoiceItemSeqId", parentInvoiceItemSeqId);
                    createInvoiceItemAdjContext.put("userLogin", userLogin);
                    createInvoiceItemAdjContext.put("taxAuthPartyId", adj.get("taxAuthPartyId"));
                    createInvoiceItemAdjContext.put("taxAuthGeoId", adj.get("taxAuthGeoId"));
                    createInvoiceItemAdjContext.put("taxAuthorityRateSeqId", adj.get("taxAuthorityRateSeqId"));

                    // some adjustments fill out the comments field instead
                    String description = (UtilValidate.isEmpty(adj.getString("description"))
                            ? adj.getString("comments")
                            : adj.getString("description"));
                    createInvoiceItemAdjContext.put("description", description);

                    // invoice items for sales tax are not taxable themselves
                    // TODO: This is not an ideal solution. Instead, we need to use OrderAdjustment.includeInTax when it is implemented
                    if (!(adj.getString("orderAdjustmentTypeId").equals("SALES_TAX"))) {
                        createInvoiceItemAdjContext.put("taxableFlag", product.get("taxable"));
                    }

                    // If the OrderAdjustment is associated to a ProductPromo,
                    // and the field ProductPromo.overrideOrgPartyId is set,
                    // copy the value to InvoiceItem.overrideOrgPartyId: this
                    // represent an organization override for the payToPartyId
                    if (UtilValidate.isNotEmpty(adj.getString("productPromoId"))) {
                        try {
                            GenericValue productPromo = adj.getRelatedOne("ProductPromo", false);
                            if (UtilValidate.isNotEmpty(productPromo.getString("overrideOrgPartyId"))) {
                                createInvoiceItemAdjContext.put("overrideOrgPartyId",
                                        productPromo.getString("overrideOrgPartyId"));
                            }
                        } catch (GenericEntityException e) {
                            Debug.logError(e, "Error looking up ProductPromo with id ["
                                    + adj.getString("productPromoId") + "]", module);
                        }
                    }

                    Map<String, Object> createInvoiceItemAdjResult = dispatcher.runSync("createInvoiceItem",
                            createInvoiceItemAdjContext);
                    if (ServiceUtil.isError(createInvoiceItemAdjResult)) {
                        return ServiceUtil.returnError(
                                UtilProperties.getMessage(resource,
                                        "AccountingErrorCreatingInvoiceItemFromOrder", locale),
                                null, null, createInvoiceItemAdjResult);
                    }

                    // Create the OrderAdjustmentBilling record
                    Map<String, Object> createOrderAdjustmentBillingContext = new HashMap<String, Object>();
                    createOrderAdjustmentBillingContext.put("orderAdjustmentId",
                            adj.getString("orderAdjustmentId"));
                    createOrderAdjustmentBillingContext.put("invoiceId", invoiceId);
                    createOrderAdjustmentBillingContext.put("invoiceItemSeqId", invoiceItemSeqId);
                    createOrderAdjustmentBillingContext.put("amount", amount);
                    createOrderAdjustmentBillingContext.put("userLogin", userLogin);

                    Map<String, Object> createOrderAdjustmentBillingResult = dispatcher
                            .runSync("createOrderAdjustmentBilling", createOrderAdjustmentBillingContext);
                    if (ServiceUtil.isError(createOrderAdjustmentBillingResult)) {
                        return ServiceUtil.returnError(
                                UtilProperties.getMessage(resource,
                                        "AccountingErrorCreatingOrderAdjustmentBillingFromOrder", locale),
                                null, null, createOrderAdjustmentBillingContext);
                    }

                    // this adjustment amount
                    BigDecimal thisAdjAmount = amount;

                    // adjustments only apply to totals when they are not tax or shipping adjustments
                    if (!"SALES_TAX".equals(adj.getString("orderAdjustmentTypeId"))
                            && !"SHIPPING_ADJUSTMENT".equals(adj.getString("orderAdjustmentTypeId"))) {
                        // increment the invoice subtotal
                        invoiceSubTotal = invoiceSubTotal.add(thisAdjAmount).setScale(100, ROUNDING);

                        // add to the ship amount only if it applies to this item
                        if (shippingApplies) {
                            invoiceShipProRateAmount = invoiceShipProRateAmount.add(thisAdjAmount)
                                    .setScale(invoiceTypeDecimals, ROUNDING);
                        }
                    }

                    // increment the counter
                    invoiceItemSeqNum++;
                    invoiceItemSeqId = UtilFormatOut.formatPaddedNumber(invoiceItemSeqNum,
                            INVOICE_ITEM_SEQUENCE_ID_DIGITS);
                }
            }
        }

        // create header adjustments as line items -- always to tax/shipping last
        Map<GenericValue, BigDecimal> shipAdjustments = new HashMap<GenericValue, BigDecimal>();
        Map<GenericValue, BigDecimal> taxAdjustments = new HashMap<GenericValue, BigDecimal>();

        List<GenericValue> headerAdjustments = orh.getOrderHeaderAdjustments();
        for (GenericValue adj : headerAdjustments) {

            // Check against OrderAdjustmentBilling to see how much of this adjustment has already been invoiced
            BigDecimal adjAlreadyInvoicedAmount = null;
            try {
                Map<String, Object> checkResult = dispatcher.runSync("calculateInvoicedAdjustmentTotal",
                        UtilMisc.toMap("orderAdjustment", adj));
                adjAlreadyInvoicedAmount = ((BigDecimal) checkResult.get("invoicedTotal"))
                        .setScale(invoiceTypeDecimals, ROUNDING);
            } catch (GenericServiceException e) {
                Debug.logError(e, "Accounting trouble calling calculateInvoicedAdjustmentTotal service",
                        module);
                return ServiceUtil.returnError(UtilProperties.getMessage(resource,
                        "AccountingTroubleCallingCalculateInvoicedAdjustmentTotalService", locale));
            }

            //                if (null == adj.get("amount")) { TODO check usage with webPos. Was: fix a bug coming from POS in case of use of a discount (on item(s) or sale, sale here) and a cash amount higher than total (hence issuing change)
            //                    continue;
            //                }
            // If the absolute invoiced amount >= the abs of the adjustment amount, the full amount has already been invoiced, so skip this adjustment
            if (adjAlreadyInvoicedAmount.abs().compareTo(
                    adj.getBigDecimal("amount").setScale(invoiceTypeDecimals, ROUNDING).abs()) >= 0) {
                continue;
            }

            if ("SHIPPING_CHARGES".equals(adj.getString("orderAdjustmentTypeId"))) {
                shipAdjustments.put(adj, adjAlreadyInvoicedAmount);
            } else if ("SALES_TAX".equals(adj.getString("orderAdjustmentTypeId"))) {
                taxAdjustments.put(adj, adjAlreadyInvoicedAmount);
            } else {
                // these will effect the shipping pro-rate (unless commented)
                // other adjustment type
                BigDecimal divisor = orderSubTotal;
                BigDecimal multiplier = invoiceSubTotal;
                if (BigDecimal.ZERO.compareTo(multiplier) == 0 && BigDecimal.ZERO.compareTo(divisor) == 0) {
                    // if multiplier and divisor are equal to zero then use the quantities instead of the amounts
                    // this is useful when the order has free items and misc charges
                    divisor = orderQuantity;
                    multiplier = invoiceQuantity;
                }

                calcHeaderAdj(delegator, adj, invoiceType, invoiceId, invoiceItemSeqId, divisor, multiplier,
                        adj.getBigDecimal("amount").setScale(invoiceTypeDecimals, ROUNDING),
                        invoiceTypeDecimals, ROUNDING, userLogin, dispatcher, locale);
                // invoiceShipProRateAmount += adjAmount;
                // do adjustments compound or are they based off subtotal? Here we will (unless commented)
                // invoiceSubTotal += adjAmount;

                // increment the counter
                invoiceItemSeqNum++;
                invoiceItemSeqId = UtilFormatOut.formatPaddedNumber(invoiceItemSeqNum,
                        INVOICE_ITEM_SEQUENCE_ID_DIGITS);
            }
        }

        // next do the shipping adjustments.  Note that we do not want to add these to the invoiceSubTotal or orderSubTotal for pro-rating tax later, as that would cause
        // numerator/denominator problems when the shipping is not pro-rated but rather charged all on the first invoice
        for (GenericValue adj : shipAdjustments.keySet()) {
            BigDecimal adjAlreadyInvoicedAmount = shipAdjustments.get(adj);

            if ("N".equalsIgnoreCase(prorateShipping)) {

                // Set the divisor and multiplier to 1 to avoid prorating
                BigDecimal divisor = BigDecimal.ONE;
                BigDecimal multiplier = BigDecimal.ONE;

                // The base amount in this case is the adjustment amount minus the total already invoiced for that adjustment, since
                //  it won't be prorated
                BigDecimal baseAmount = adj.getBigDecimal("amount").setScale(invoiceTypeDecimals, ROUNDING)
                        .subtract(adjAlreadyInvoicedAmount);
                calcHeaderAdj(delegator, adj, invoiceType, invoiceId, invoiceItemSeqId, divisor, multiplier,
                        baseAmount, invoiceTypeDecimals, ROUNDING, userLogin, dispatcher, locale);
            } else {

                // Pro-rate the shipping amount based on shippable information
                BigDecimal divisor = shippableAmount;
                BigDecimal multiplier = invoiceShipProRateAmount;
                if (BigDecimal.ZERO.compareTo(multiplier) == 0 && BigDecimal.ZERO.compareTo(divisor) == 0) {
                    // if multiplier and divisor are equal to zero then use the quantities instead of the amounts
                    // this is useful when the order has free items and shipping charges
                    divisor = shippableQuantity;
                    multiplier = invoiceShippableQuantity;
                }

                // The base amount in this case is the adjustment amount, since we want to prorate based on the full amount
                BigDecimal baseAmount = adj.getBigDecimal("amount").setScale(invoiceTypeDecimals, ROUNDING);
                calcHeaderAdj(delegator, adj, invoiceType, invoiceId, invoiceItemSeqId, divisor, multiplier,
                        baseAmount, invoiceTypeDecimals, ROUNDING, userLogin, dispatcher, locale);
            }

            // Increment the counter
            invoiceItemSeqNum++;
            invoiceItemSeqId = UtilFormatOut.formatPaddedNumber(invoiceItemSeqNum,
                    INVOICE_ITEM_SEQUENCE_ID_DIGITS);
        }

        // last do the tax adjustments
        String prorateTaxes = productStore != null ? productStore.getString("prorateTaxes") : "Y";
        if (prorateTaxes == null) {
            prorateTaxes = "Y";
        }
        for (Map.Entry<GenericValue, BigDecimal> entry : taxAdjustments.entrySet()) {
            GenericValue adj = entry.getKey();
            BigDecimal adjAlreadyInvoicedAmount = entry.getValue();
            BigDecimal adjAmount = null;

            if ("N".equalsIgnoreCase(prorateTaxes)) {

                // Set the divisor and multiplier to 1 to avoid prorating
                BigDecimal divisor = BigDecimal.ONE;
                BigDecimal multiplier = BigDecimal.ONE;

                // The base amount in this case is the adjustment amount minus the total already invoiced for that adjustment, since
                //  it won't be prorated
                BigDecimal baseAmount = adj.getBigDecimal("amount").setScale(TAX_DECIMALS, TAX_ROUNDING)
                        .subtract(adjAlreadyInvoicedAmount);
                adjAmount = calcHeaderAdj(delegator, adj, invoiceType, invoiceId, invoiceItemSeqId, divisor,
                        multiplier, baseAmount, TAX_DECIMALS, TAX_ROUNDING, userLogin, dispatcher, locale);
            } else {

                // Pro-rate the tax amount based on shippable information
                BigDecimal divisor = orderSubTotal;
                BigDecimal multiplier = invoiceSubTotal;

                // The base amount in this case is the adjustment amount, since we want to prorate based on the full amount
                BigDecimal baseAmount = adj.getBigDecimal("amount");
                adjAmount = calcHeaderAdj(delegator, adj, invoiceType, invoiceId, invoiceItemSeqId, divisor,
                        multiplier, baseAmount, TAX_DECIMALS, TAX_ROUNDING, userLogin, dispatcher, locale);
            }
            invoiceSubTotal = invoiceSubTotal.add(adjAmount).setScale(invoiceTypeDecimals, ROUNDING);

            // Increment the counter
            invoiceItemSeqNum++;
            invoiceItemSeqId = UtilFormatOut.formatPaddedNumber(invoiceItemSeqNum,
                    INVOICE_ITEM_SEQUENCE_ID_DIGITS);
        }

        // check for previous order payments
        List<GenericValue> orderPaymentPrefs = EntityQuery.use(delegator).from("OrderPaymentPreference").where(
                EntityCondition.makeCondition("orderId", EntityOperator.EQUALS, orderId),
                EntityCondition.makeCondition("statusId", EntityOperator.NOT_EQUAL, "PAYMENT_CANCELLED"))
                .queryList();
        List<GenericValue> currentPayments = new LinkedList<GenericValue>();
        for (GenericValue paymentPref : orderPaymentPrefs) {
            List<GenericValue> payments = paymentPref.getRelated("Payment", null, null, false);
            currentPayments.addAll(payments);
        }
        // apply these payments to the invoice if they have any remaining amount to apply
        for (GenericValue payment : currentPayments) {
            if ("PMNT_VOID".equals(payment.getString("statusId"))
                    || "PMNT_CANCELLED".equals(payment.getString("statusId"))) {
                continue;
            }
            BigDecimal notApplied = PaymentWorker.getPaymentNotApplied(payment);
            if (notApplied.signum() > 0) {
                Map<String, Object> appl = new HashMap<String, Object>();
                appl.put("paymentId", payment.get("paymentId"));
                appl.put("invoiceId", invoiceId);
                appl.put("billingAccountId", billingAccountId);
                appl.put("amountApplied", notApplied);
                appl.put("userLogin", userLogin);
                Map<String, Object> createPayApplResult = dispatcher.runSync("createPaymentApplication", appl);
                if (ServiceUtil.isError(createPayApplResult)) {
                    return ServiceUtil
                            .returnError(
                                    UtilProperties.getMessage(resource,
                                            "AccountingErrorCreatingInvoiceFromOrder", locale),
                                    null, null, createPayApplResult);
                }
            }
        }

        // Should all be in place now. Depending on the ProductStore.autoApproveInvoice setting, set status to INVOICE_READY (unless it's a purchase invoice, which we set to INVOICE_IN_PROCESS)
        String autoApproveInvoice = productStore != null ? productStore.getString("autoApproveInvoice") : "Y";
        if (!"N".equals(autoApproveInvoice)) {
            String nextStatusId = "PURCHASE_INVOICE".equals(invoiceType) ? "INVOICE_IN_PROCESS"
                    : "INVOICE_READY";
            Map<String, Object> setInvoiceStatusResult = dispatcher.runSync("setInvoiceStatus",
                    UtilMisc.<String, Object>toMap("invoiceId", invoiceId, "statusId", nextStatusId,
                            "userLogin", userLogin));
            if (ServiceUtil.isError(setInvoiceStatusResult)) {
                return ServiceUtil.returnError(
                        UtilProperties.getMessage(resource, "AccountingErrorCreatingInvoiceFromOrder", locale),
                        null, null, setInvoiceStatusResult);
            }
        }

        Map<String, Object> resp = ServiceUtil.returnSuccess();
        resp.put("invoiceId", invoiceId);
        resp.put("invoiceTypeId", invoiceType);
        return resp;
    } catch (GenericEntityException e) {
        Debug.logError(e, "Entity/data problem creating invoice from order items: " + e.toString(), module);
        return ServiceUtil.returnError(
                UtilProperties.getMessage(resource, "AccountingEntityDataProblemCreatingInvoiceFromOrderItems",
                        UtilMisc.toMap("reason", e.toString()), locale));
    } catch (GenericServiceException e) {
        Debug.logError(e, "Service/other problem creating invoice from order items: " + e.toString(), module);
        return ServiceUtil.returnError(UtilProperties.getMessage(resource,
                "AccountingServiceOtherProblemCreatingInvoiceFromOrderItems",
                UtilMisc.toMap("reason", e.toString()), locale));
    }
}

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

private PdfPTable createBudgetaryAppropriationTable(final AbstractEstimate estimate,
        final String appropriationNumber) throws DocumentException {
    int isReject = -1;
    final List<FinancialDetail> financialdetails = estimate.getFinancialDetails();
    BigDecimal totalGrant;/*  ww w.  ja va  2 s.  c om*/
    BigDecimal budgetAvailable;
    BigDecimal balOnHand;
    BigDecimal amtAppropriated;
    BigDecimal totGrantafterMultiFactor = BigDecimal.ZERO;

    estimateAppropriationService = abstractEstimateService.getEstimateAppropriationService();
    abstractEstimateAppropriationList = estimateAppropriationService.findAllBy(
            "from AbstractEstimateAppropriation aea where aea.abstractEstimate.id=? and aea.budgetUsage.id is not null order by aea.budgetUsage.id,aea.budgetUsage.financialYearId asc",
            estimate.getId());

    final PdfPTable budgetaryAppropriationTable = new PdfPTable(1);
    budgetaryAppropriationTable.setWidthPercentage(100);
    budgetaryAppropriationTable.setWidths(new float[] { 8f });
    if (appropriationNumber != null && appropriationNumber.toUpperCase().contains("BC"))
        isReject = 1;

    if (appropriationNumber != null && estimate.getTotalAmount() != null && isReject == -1)
        for (final FinancialDetail financialDetail : financialdetails)
            if (financialDetail.getBudgetGroup() != null) {
                addRow(budgetaryAppropriationTable, true, centerPara("Budget Head"),
                        centerPara(financialDetail.getBudgetGroup().getName()));
                addRow(budgetaryAppropriationTable, true, makePara("Function Center"),
                        centerPara(financialDetail.getFunction().getName()));
                addRow(budgetaryAppropriationTable, true, makePara("Amount of the Estimate "),
                        rightPara(toCurrency(estimate.getTotalAmount())));
            }
    final PdfPTable appropriationDetailTable = new PdfPTable(8);
    int count = 0;
    for (final AbstractEstimateAppropriation abstractEstimateAppropriation : abstractEstimateAppropriationList)
        if (abstractEstimateAppropriation.getBudgetUsage().getConsumedAmount() != 0) {
            final Department dept = getDeptFromBudgtAppropriationNo(
                    abstractEstimateAppropriation.getBudgetUsage().getAppropriationnumber());
            totalGrant = abstractEstimateService.getTotalGrantForYearAsOnDate(financialdetails.get(0),
                    abstractEstimateAppropriation.getBudgetUsage().getFinancialYearId().longValue(),
                    Integer.parseInt(dept.getId().toString()),
                    abstractEstimateAppropriation.getBudgetUsage().getUpdatedTime());
            final BigDecimal planningBudgetPerc = abstractEstimateService.getPlanningBudgetPercentage(
                    financialdetails.get(0),
                    abstractEstimateAppropriation.getBudgetUsage().getFinancialYearId().longValue(),
                    Integer.parseInt(dept.getId().toString()));
            if (planningBudgetPerc != null && planningBudgetPerc.compareTo(BigDecimal.ZERO) != 0) {
                totGrantafterMultiFactor = totalGrant.multiply(planningBudgetPerc.divide(new BigDecimal(100)));
                appValue = planningBudgetPerc.divide(new BigDecimal(100)).toString();
            }
            budgetAvailable = abstractEstimateAppropriation.getBalanceAvailable();
            balOnHand = budgetAvailable
                    .add(new BigDecimal(abstractEstimateAppropriation.getBudgetUsage().getConsumedAmount()));
            amtAppropriated = totGrantafterMultiFactor.subtract(balOnHand);
            // Print only for the first time
            if (count == 0) {
                addRow(budgetaryAppropriationTable, false, makePara(""),
                        centerPara("Financial Year Wise Appropriation Details "));
                addRow(appropriationDetailTable, true, makePara(8f, "Department"),
                        makePara(8f, "Appropriation Number"), makePara(8f, "Total Grant"),
                        makePara(8f, appValue + " Times Total Grant"),
                        makePara(8f, "Amount Appropriated so far"), makePara(8f, "Amount Appropriated"),
                        makePara(8f, "Balance on Hand"), makePara(8f, "Balance After Appropriation"));
            }
            addRow(appropriationDetailTable, true, rightPara(8f, dept.getName()),
                    makePara(8f, abstractEstimateAppropriation.getBudgetUsage().getAppropriationnumber()),
                    rightPara(8f, toCurrency(totalGrant.doubleValue())),
                    rightPara(8f, toCurrency(totGrantafterMultiFactor.doubleValue())),
                    rightPara(8f, toCurrency(amtAppropriated.doubleValue())),
                    rightPara(8f,
                            toCurrency(abstractEstimateAppropriation.getBudgetUsage().getConsumedAmount())),
                    rightPara(8f, toCurrency(balOnHand.doubleValue())),
                    rightPara(8f, toCurrency(budgetAvailable.doubleValue())));
            count++;
        }

    final PdfPCell appDetailpdfCell = new PdfPCell(appropriationDetailTable);
    appropriationDetailTable.setWidthPercentage(100);
    budgetaryAppropriationTable.addCell(appDetailpdfCell);
    return budgetaryAppropriationTable;
}

From source file:net.sourceforge.fenixedu.domain.credits.util.AnnualTeachingCreditsBean.java

public void calculateCredits() {
    masterDegreeThesesCredits = teacher.getMasterDegreeThesesCredits(executionYear);
    phdDegreeThesesCredits = teacher.getPhdDegreeThesesCredits(executionYear);
    projectsTutorialsCredits = teacher.getProjectsTutorialsCredits(executionYear);

    BigDecimal yearCreditsForFinalCredits = BigDecimal.ZERO;
    BigDecimal annualTeachingLoadFinalCredits = BigDecimal.ZERO;

    boolean hasOrientantionCredits = false;
    boolean hasFinalAndAccumulatedCredits = false;

    for (ExecutionSemester executionSemester : executionYear.getExecutionPeriodsSet()) {
        if (getTeacher().isActiveForSemester(executionSemester)
                || getTeacher().hasTeacherAuthorization(executionSemester)) {
            BigDecimal thisSemesterManagementFunctionCredits = new BigDecimal(
                    getTeacher().getManagementFunctionsCredits(executionSemester));
            managementFunctionCredits = managementFunctionCredits.add(thisSemesterManagementFunctionCredits);
            serviceExemptionCredits = serviceExemptionCredits
                    .add(new BigDecimal(getTeacher().getServiceExemptionCredits(executionSemester)));
            BigDecimal thisSemesterTeachingLoad = new BigDecimal(
                    getTeacher().getMandatoryLessonHours(executionSemester));
            annualTeachingLoad = annualTeachingLoad.add(thisSemesterTeachingLoad).setScale(2,
                    BigDecimal.ROUND_HALF_UP);
            TeacherService teacherService = getTeacher().getTeacherServiceByExecutionPeriod(executionSemester);
            BigDecimal thisSemesterCreditsReduction = BigDecimal.ZERO;
            if (teacherService != null) {
                teachingCredits = teachingCredits
                        .add(new BigDecimal(teacherService.getTeachingDegreeCredits()));
                thisSemesterCreditsReduction = teacherService.getReductionServiceCredits();
                othersCredits = othersCredits.add(new BigDecimal(teacherService.getOtherServiceCredits()));
            }/*from   ww w . j av a  2 s  .c  o  m*/
            creditsReduction = creditsReduction.add(thisSemesterCreditsReduction);
            BigDecimal reductionAndManagement = thisSemesterManagementFunctionCredits
                    .add(thisSemesterCreditsReduction);
            BigDecimal thisSemesterYearCredits = thisSemesterTeachingLoad;
            if (thisSemesterTeachingLoad.compareTo(reductionAndManagement) > 0) {
                thisSemesterYearCredits = reductionAndManagement;
            } else {
                setHasAnyLimitation(true);
            }
            yearCredits = yearCredits.add(thisSemesterYearCredits);
            if (getTeacher().isActiveForSemester(executionSemester)
                    && !getTeacher().isMonitor(executionSemester)) {
                yearCreditsForFinalCredits = yearCreditsForFinalCredits.add(thisSemesterYearCredits);
                annualTeachingLoadFinalCredits = annualTeachingLoadFinalCredits.add(thisSemesterTeachingLoad);
                if (executionSemester.getSemester() == 2) {
                    hasFinalAndAccumulatedCredits = true;
                } else {
                    hasOrientantionCredits = true;
                }
            }
        }
    }
    yearCredits = yearCredits.add(teachingCredits).add(serviceExemptionCredits).add(othersCredits);
    yearCreditsForFinalCredits = yearCreditsForFinalCredits.add(teachingCredits).add(serviceExemptionCredits)
            .add(othersCredits);
    if (hasOrientantionCredits) {
        yearCredits = yearCredits.add(getMasterDegreeThesesCredits()).add(getPhdDegreeThesesCredits())
                .add(getProjectsTutorialsCredits()).setScale(2, BigDecimal.ROUND_HALF_UP);
        yearCreditsForFinalCredits = yearCreditsForFinalCredits.add(getMasterDegreeThesesCredits())
                .add(getPhdDegreeThesesCredits()).add(getProjectsTutorialsCredits());
    }
    if (hasFinalAndAccumulatedCredits) {
        finalCredits = yearCreditsForFinalCredits.subtract(annualTeachingLoadFinalCredits);
        BigDecimal lastYearAccumulated = getPreviousAccumulatedCredits();
        accumulatedCredits = (finalCredits.add(lastYearAccumulated)).setScale(2, BigDecimal.ROUND_HALF_UP);
        finalCredits = finalCredits.setScale(2, BigDecimal.ROUND_HALF_UP);
    }
}

From source file:org.sakaiproject.tool.assessment.services.GradingService.java

public boolean getCalcQResult(ItemGradingData data, ItemDataIfc itemdata,
        Map<Integer, String> calculatedAnswersMap, int calcQuestionAnswerSequence) {
    boolean result = false;

    if (data.getAnswerText() == null)
        return result;

    if (!calculatedAnswersMap.containsKey(calcQuestionAnswerSequence)) {
        return result;
    }// w w w  .java  2  s.  c  o m
    // this variable should look something like this "42.1|2,2"
    String allAnswerText = calculatedAnswersMap.get(calcQuestionAnswerSequence).toString();

    // NOTE: this correctAnswer will already have been trimmed to the appropriate number of decimals
    BigDecimal correctAnswer = new BigDecimal(getAnswerExpression(allAnswerText));

    // Determine if the acceptable variance is a constant or a % of the answer
    String varianceString = allAnswerText.substring(allAnswerText.indexOf("|") + 1, allAnswerText.indexOf(","));
    BigDecimal acceptableVariance = BigDecimal.ZERO;
    if (varianceString.contains("%")) {
        double percentage = Double.valueOf(varianceString.substring(0, varianceString.indexOf("%")));
        acceptableVariance = correctAnswer.multiply(new BigDecimal(percentage / 100));
    } else {
        acceptableVariance = new BigDecimal(varianceString);
    }

    String userAnswerString = data.getAnswerText().replaceAll(",", "").trim();
    BigDecimal userAnswer;
    try {
        userAnswer = new BigDecimal(userAnswerString);
    } catch (NumberFormatException nfe) {
        return result;
    }

    // this compares the correctAnswer against the userAnsewr
    BigDecimal answerDiff = (correctAnswer.subtract(userAnswer));
    boolean closeEnough = (answerDiff.abs().compareTo(acceptableVariance.abs()) <= 0);
    if (closeEnough) {
        result = true;
    }
    return result;

}

From source file:org.egov.ptis.service.es.PropertyTaxElasticSearchIndexService.java

/**
 * Prepare list of TaxPayerDetails for each bill collector by summing up the values in each ward for the respective bil
 * collector/*from w w  w. ja v a  2  s.  c o m*/
 *
 * @param collectionDetailsRequest
 * @param billCollectorWiseMap
 * @param billCollectorWiseTaxPayerDetails
 */
private void prepareTaxersInfoForBillCollectors(final CollectionDetailsRequest collectionDetailsRequest,
        final Map<String, List<TaxPayerDetails>> billCollectorWiseMap,
        final List<TaxPayerDetails> billCollectorWiseTaxPayerDetails) {
    BigDecimal cytdColl;
    BigDecimal lytdColl;
    BigDecimal cytdDmd;
    BigDecimal totalDmd;
    TaxPayerDetails taxPayerDetails;
    String[] userNameNumberArr;
    for (final Entry<String, List<TaxPayerDetails>> entry : billCollectorWiseMap.entrySet()) {
        taxPayerDetails = new TaxPayerDetails();
        cytdColl = BigDecimal.ZERO;
        lytdColl = BigDecimal.ZERO;
        cytdDmd = BigDecimal.ZERO;
        totalDmd = BigDecimal.ZERO;
        userNameNumberArr = entry.getKey().split("~");
        for (final TaxPayerDetails taxPayer : entry.getValue()) {
            totalDmd = totalDmd.add(taxPayer.getTotalDmd() == null ? BigDecimal.ZERO : taxPayer.getTotalDmd());
            cytdColl = cytdColl.add(taxPayer.getCytdColl() == null ? BigDecimal.ZERO : taxPayer.getCytdColl());
            cytdDmd = cytdDmd.add(taxPayer.getCytdDmd() == null ? BigDecimal.ZERO : taxPayer.getCytdDmd());
            lytdColl = lytdColl.add(taxPayer.getLytdColl() == null ? BigDecimal.ZERO : taxPayer.getLytdColl());
        }

        if (DASHBOARD_GROUPING_BILLCOLLECTORWISE.equalsIgnoreCase(collectionDetailsRequest.getType())) {
            taxPayerDetails
                    .setBillCollector(userNameNumberArr.length > 0 ? userNameNumberArr[0] : StringUtils.EMPTY);
            taxPayerDetails
                    .setBillCollMobNo(userNameNumberArr.length > 1 ? userNameNumberArr[1] : StringUtils.EMPTY);
            taxPayerDetails.setBillCollectorCode(
                    userNameNumberArr.length > 2 ? userNameNumberArr[2] : StringUtils.EMPTY);
        } else if (DASHBOARD_GROUPING_REVENUEINSPECTORWISE
                .equalsIgnoreCase(collectionDetailsRequest.getType())) {
            taxPayerDetails.setRevenueInspector(
                    userNameNumberArr.length > 0 ? userNameNumberArr[0] : StringUtils.EMPTY);
            taxPayerDetails.setRevInspectorMobNo(
                    userNameNumberArr.length > 1 ? userNameNumberArr[1] : StringUtils.EMPTY);
            taxPayerDetails.setRevenueInspectorCode(
                    userNameNumberArr.length > 2 ? userNameNumberArr[2] : StringUtils.EMPTY);
        } else if (DASHBOARD_GROUPING_REVENUEOFFICERWISE.equalsIgnoreCase(collectionDetailsRequest.getType())) {
            taxPayerDetails
                    .setRevenueOfficer(userNameNumberArr.length > 0 ? userNameNumberArr[0] : StringUtils.EMPTY);
            taxPayerDetails.setRevOfficerMobNo(
                    userNameNumberArr.length > 1 ? userNameNumberArr[1] : StringUtils.EMPTY);
            taxPayerDetails.setRevenueOfficerCode(
                    userNameNumberArr.length > 2 ? userNameNumberArr[2] : StringUtils.EMPTY);
        }

        taxPayerDetails.setRegionName(collectionDetailsRequest.getRegionName());
        taxPayerDetails.setDistrictName(collectionDetailsRequest.getDistrictName());
        taxPayerDetails.setUlbGrade(collectionDetailsRequest.getUlbGrade());
        taxPayerDetails.setCytdColl(cytdColl);
        taxPayerDetails.setCytdDmd(cytdDmd);
        taxPayerDetails.setCytdBalDmd(cytdDmd.subtract(cytdColl));
        taxPayerDetails.setTotalDmd(totalDmd);
        taxPayerDetails.setLytdColl(lytdColl);
        if (cytdDmd.compareTo(BigDecimal.ZERO) > 0)
            taxPayerDetails.setAchievement(
                    cytdColl.multiply(BIGDECIMAL_100).divide(cytdDmd, 1, BigDecimal.ROUND_HALF_UP));
        if (lytdColl.compareTo(BigDecimal.ZERO) == 0)
            taxPayerDetails.setLyVar(BIGDECIMAL_100);
        else
            taxPayerDetails.setLyVar(cytdColl.subtract(lytdColl).multiply(BIGDECIMAL_100).divide(lytdColl, 1,
                    BigDecimal.ROUND_HALF_UP));

        billCollectorWiseTaxPayerDetails.add(taxPayerDetails);
    }
}

From source file:org.sakaiproject.tool.assessment.services.GradingService.java

/**
 * CALCULATED_QUESTION/*w ww  .jav a 2 s  .  c  o m*/
 * Returns a double score value for the ItemGrading element being scored for a Calculated Question
 * 
 * @param calcQuestionAnswerSequence the order of answers in the list
 * @return score for the item.
 */
public double getCalcQScore(ItemGradingData data, ItemDataIfc itemdata,
        Map<Integer, String> calculatedAnswersMap, int calcQuestionAnswerSequence) {
    double totalScore = (double) 0;

    if (data.getAnswerText() == null)
        return totalScore; // zero for blank

    if (!calculatedAnswersMap.containsKey(calcQuestionAnswerSequence)) {
        return totalScore;
    }
    // this variable should look something like this "42.1|2,2"
    String allAnswerText = calculatedAnswersMap.get(calcQuestionAnswerSequence).toString();

    // NOTE: this correctAnswer will already have been trimmed to the appropriate number of decimals
    BigDecimal correctAnswer = new BigDecimal(getAnswerExpression(allAnswerText));

    // Determine if the acceptable variance is a constant or a % of the answer
    String varianceString = allAnswerText.substring(allAnswerText.indexOf("|") + 1, allAnswerText.indexOf(","));
    BigDecimal acceptableVariance = BigDecimal.ZERO;
    if (varianceString.contains("%")) {
        double percentage = Double.valueOf(varianceString.substring(0, varianceString.indexOf("%")));
        acceptableVariance = correctAnswer.multiply(new BigDecimal(percentage / 100));
    } else {
        acceptableVariance = new BigDecimal(varianceString);
    }

    String userAnswerString = data.getAnswerText().replaceAll(",", "").trim();
    BigDecimal userAnswer;
    try {
        userAnswer = new BigDecimal(userAnswerString);
    } catch (NumberFormatException nfe) {
        return totalScore; // zero because it's not even a number!
    }
    //double userAnswer = Double.valueOf(userAnswerString);

    // this compares the correctAnswer against the userAnsewr
    BigDecimal answerDiff = (correctAnswer.subtract(userAnswer));
    boolean closeEnough = (answerDiff.abs().compareTo(acceptableVariance.abs()) <= 0);
    if (closeEnough) {
        totalScore += itemdata.getScore();
    }
    return totalScore;

}

From source file:org.kuali.kpme.tklm.time.rules.overtime.weekly.service.WeeklyOvertimeRuleServiceImpl.java

protected BigDecimal applyPositiveOvertimeOnTimeBlockOld(TimeBlockBo timeBlock, String overtimeEarnCode,
        Set<String> convertFromEarnCodes, BigDecimal overtimeHours) {
    BigDecimal applied = BigDecimal.ZERO;
    List<TimeHourDetailBo> timeHourDetails = timeBlock.getTimeHourDetails();
    List<TimeHourDetailBo> newTimeHourDetails = new ArrayList<TimeHourDetailBo>();

    LOG.info("INITIAL block; " + timeBlock.getTkTimeBlockId() + "overtimeHours = " + overtimeHours
            + " overall timeblock hours = " + timeBlock.getHours() + " earnCode = " + timeBlock.getEarnCode()
            + " OT = " + overtimeEarnCode + " convertFrom = " + convertFromEarnCodes + " startDate = "
            + timeBlock.getBeginDateTime());
    for (TimeHourDetailBo timeHourDetail : timeHourDetails) {
        LOG.info("EC = " + timeHourDetail.getEarnCode() + " hours = " + timeHourDetail.getHours() + " OT = "
                + overtimeEarnCode + " convertFrom = " + convertFromEarnCodes);
    }/*from  w  ww  .  j  av a 2s .com*/

    //LOG.info("before timeBlock hours = " + timeBlock.getHours() + "OT Hours = " + overtimeHours + " timeHourDetail Size = " + timeHourDetails.size());

    for (TimeHourDetailBo timeHourDetail : timeHourDetails) {
        if (convertFromEarnCodes.contains(timeHourDetail.getEarnCode())) {
            if (timeHourDetail.getHours().compareTo(overtimeHours) >= 0) {
                applied = overtimeHours;
            } else {
                applied = timeHourDetail.getHours();
            }

            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_UP);

            TimeHourDetailBo overtimeTimeHourDetail = getTimeHourDetailByEarnCode(timeHourDetails,
                    Collections.singletonList(overtimeEarnCode));
            if (overtimeTimeHourDetail != null) {
                overtimeTimeHourDetail
                        .setHours(overtimeTimeHourDetail.getHours().add(hours, HrConstants.MATH_CONTEXT));
                //overtimeTimeHourDetail.setHours(hours);
            } else {
                TimeHourDetailBo newTimeHourDetail = new TimeHourDetailBo();
                newTimeHourDetail.setTkTimeBlockId(timeBlock.getTkTimeBlockId());
                newTimeHourDetail.setEarnCode(overtimeEarnCode);
                newTimeHourDetail.setHours(hours);

                newTimeHourDetails.add(newTimeHourDetail);
            }

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

    for (TimeHourDetailBo newTimeHourDetail : newTimeHourDetails) {
        timeBlock.addTimeHourDetail(newTimeHourDetail);
    }

    LOG.info("END block; " + timeBlock.getTkTimeBlockId() + " overall timeblock hours = " + timeBlock.getHours()
            + " earnCode = " + timeBlock.getEarnCode());
    for (TimeHourDetailBo timeHourDetail : timeHourDetails) {
        LOG.info("EC = " + timeHourDetail.getEarnCode() + " hours = " + timeHourDetail.getHours() + " OT = "
                + overtimeEarnCode + " convertFrom = " + convertFromEarnCodes);
    }

    return overtimeHours.subtract(applied);
}

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

/**
 * @see org.kuali.kfs.module.purap.service.PurapAccountingService#generateAccountDistributionForProration(java.util.List,
 *      org.kuali.rice.core.api.util.type.KualiDecimal, java.lang.Integer)
 *///from  www . j av a2  s.c o m
@Override
public List<PurApAccountingLine> generateAccountDistributionForProration(List<SourceAccountingLine> accounts,
        KualiDecimal totalAmount, Integer percentScale, Class clazz) {
    String methodName = "generateAccountDistributionForProration()";
    if (LOG.isDebugEnabled()) {
        LOG.debug(methodName + " started");
    }
    List<PurApAccountingLine> newAccounts = new ArrayList();

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

/**
 * Create Facts (the accounting logic) for ARI, ARC, ARF, API, APC.
 * //from   w  ww.j av  a 2s  .  c  o  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;
}