Example usage for java.math BigDecimal negate

List of usage examples for java.math BigDecimal negate

Introduction

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

Prototype

public BigDecimal negate() 

Source Link

Document

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

Usage

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

public static Map<String, Object> createCommissionInvoices(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");
    List<String> salesInvoiceIds = UtilGenerics.checkList(context.get("invoiceIds"));
    List<Map<String, String>> invoicesCreated = new LinkedList<Map<String, String>>();
    Map<String, List<Map<String, Object>>> commissionParties = new HashMap<String, List<Map<String, Object>>>();
    for (String salesInvoiceId : salesInvoiceIds) {
        List<String> salesRepPartyIds = UtilGenerics.checkList(context.get("partyIds"));
        BigDecimal amountTotal = InvoiceWorker.getInvoiceTotal(delegator, salesInvoiceId);
        if (amountTotal.signum() == 0) {
            Debug.logWarning("Invoice [" + salesInvoiceId + "] has an amount total of [" + amountTotal
                    + "], so no commission invoice will be created", module);
            return ServiceUtil.returnError(UtilProperties.getMessage(resource,
                    "AccountingInvoiceCommissionZeroInvoiceAmount", locale));
        }/*w ww .  j  a va  2 s . co  m*/
        BigDecimal appliedFraction = amountTotal.divide(amountTotal, 12, ROUNDING);
        GenericValue invoice = null;
        boolean isReturn = false;
        List<String> billFromVendorInvoiceRoles = new ArrayList<String>();
        List<GenericValue> invoiceItems = new ArrayList<GenericValue>();
        try {
            List<EntityExpr> invoiceRoleConds = UtilMisc.toList(
                    EntityCondition.makeCondition("invoiceId", EntityOperator.EQUALS, salesInvoiceId),
                    EntityCondition.makeCondition("roleTypeId", EntityOperator.EQUALS, "BILL_FROM_VENDOR"));
            EntityQuery roleQuery = EntityQuery.use(delegator).select("partyId").from("InvoiceRole")
                    .where(invoiceRoleConds);
            billFromVendorInvoiceRoles = EntityUtil.getFieldListFromEntityList(roleQuery.queryList(), "partyId",
                    true);

            invoiceRoleConds = UtilMisc.toList(
                    EntityCondition.makeCondition("invoiceId", EntityOperator.EQUALS, salesInvoiceId),
                    EntityCondition.makeCondition("roleTypeId", EntityOperator.EQUALS, "SALES_REP"));
            // if the receiving parties is empty then we will create commission invoices for all sales agent associated to sales invoice.
            if (UtilValidate.isEmpty(salesRepPartyIds)) {
                salesRepPartyIds = EntityUtil.getFieldListFromEntityList(
                        roleQuery.where(invoiceRoleConds).queryList(), "partyId", true);
                if (UtilValidate.isEmpty(salesRepPartyIds)) {
                    return ServiceUtil.returnError(UtilProperties.getMessage(resource,
                            "No party found with role sales representative for sales invoice " + salesInvoiceId,
                            locale));
                }
            } else {
                List<String> salesInvoiceRolePartyIds = EntityUtil.getFieldListFromEntityList(
                        roleQuery.where(invoiceRoleConds).queryList(), "partyId", true);
                if (UtilValidate.isNotEmpty(salesInvoiceRolePartyIds)) {
                    salesRepPartyIds = UtilGenerics.checkList(
                            CollectionUtils.intersection(salesRepPartyIds, salesInvoiceRolePartyIds));
                }
            }
            invoice = EntityQuery.use(delegator).from("Invoice").where("invoiceId", salesInvoiceId).queryOne();
            String invoiceTypeId = invoice.getString("invoiceTypeId");
            if ("CUST_RTN_INVOICE".equals(invoiceTypeId)) {
                isReturn = true;
            } else if (!"SALES_INVOICE".equals(invoiceTypeId)) {
                Debug.logWarning("This type of invoice has no commission; returning success", module);
                return ServiceUtil.returnError(
                        UtilProperties.getMessage(resource, "AccountingInvoiceCommissionInvalid", locale));
            }
            invoiceItems = EntityQuery.use(delegator).from("InvoiceItem").where("invoiceId", salesInvoiceId)
                    .queryList();
        } catch (GenericEntityException e) {
            return ServiceUtil.returnError(e.getMessage());
        }
        // Map of commission Lists (of Maps) for each party.
        // Determine commissions for various parties.
        for (GenericValue invoiceItem : invoiceItems) {
            BigDecimal amount = ZERO;
            BigDecimal quantity = ZERO;
            quantity = invoiceItem.getBigDecimal("quantity");
            amount = invoiceItem.getBigDecimal("amount");
            amount = isReturn ? amount.negate() : amount;
            String productId = invoiceItem.getString("productId");
            String invoiceItemSeqId = invoiceItem.getString("invoiceItemSeqId");
            String invoiceId = invoiceItem.getString("invoiceId");
            // Determine commission parties for this invoiceItem
            if (UtilValidate.isNotEmpty(productId)) {
                Map<String, Object> resultMap = null;
                try {
                    resultMap = dispatcher.runSync("getCommissionForProduct",
                            UtilMisc.<String, Object>toMap("productId", productId, "invoiceId", invoiceId,
                                    "invoiceItemSeqId", invoiceItemSeqId, "invoiceItemTypeId",
                                    invoiceItem.getString("invoiceItemTypeId"), "amount", amount, "quantity",
                                    quantity, "userLogin", userLogin));
                } catch (GenericServiceException e) {
                    return ServiceUtil.returnError(e.getMessage());
                }
                // build a Map of partyIds (both to and from) in a commission and the amounts
                // Note that getCommissionForProduct returns a List of Maps with a lot values.  See services.xml definition for reference.
                List<Map<String, Object>> itemCommissions = UtilGenerics
                        .checkList(resultMap.get("commissions"));
                if (UtilValidate.isNotEmpty(itemCommissions)) {
                    for (Map<String, Object> commissionMap : itemCommissions) {
                        commissionMap.put("invoice", invoice);
                        commissionMap.put("appliedFraction", appliedFraction);
                        if (!billFromVendorInvoiceRoles.contains(commissionMap.get("partyIdFrom"))
                                || !salesRepPartyIds.contains(commissionMap.get("partyIdTo"))) {
                            continue;
                        }
                        String partyIdFromTo = (String) commissionMap.get("partyIdFrom")
                                + (String) commissionMap.get("partyIdTo");
                        if (!commissionParties.containsKey(partyIdFromTo)) {
                            commissionParties.put(partyIdFromTo, UtilMisc.toList(commissionMap));
                        } else {
                            (commissionParties.get(partyIdFromTo)).add(commissionMap);
                        }
                    }
                }
            }
        }
    }
    Timestamp now = UtilDateTime.nowTimestamp();
    // Create invoice for each commission receiving party
    for (Map.Entry<String, List<Map<String, Object>>> commissionParty : commissionParties.entrySet()) {
        List<GenericValue> toStore = new LinkedList<GenericValue>();
        List<Map<String, Object>> commList = commissionParty.getValue();
        // get the billing parties
        if (UtilValidate.isEmpty(commList)) {
            continue;
        }
        // From and To are reversed between commission and invoice
        String partyIdBillTo = (String) (commList.get(0)).get("partyIdFrom");
        String partyIdBillFrom = (String) (commList.get(0)).get("partyIdTo");
        GenericValue invoice = (GenericValue) (commList.get(0)).get("invoice");
        BigDecimal appliedFraction = (BigDecimal) (commList.get(0)).get("appliedFraction");
        Long days = (Long) (commList.get(0)).get("days");
        // create the invoice record
        // To and From are in commission's sense, opposite for invoice
        Map<String, Object> createInvoiceMap = new HashMap<String, Object>();
        createInvoiceMap.put("partyId", partyIdBillTo);
        createInvoiceMap.put("partyIdFrom", partyIdBillFrom);
        createInvoiceMap.put("invoiceDate", now);
        // if there were days associated with the commission agreement, then set a dueDate for the invoice.
        if (days != null) {
            createInvoiceMap.put("dueDate", UtilDateTime.getDayEnd(now, days));
        }
        createInvoiceMap.put("invoiceTypeId", "COMMISSION_INVOICE");
        // start with INVOICE_IN_PROCESS, in the INVOICE_READY we can't change the invoice (or shouldn't be able to...)
        createInvoiceMap.put("statusId", "INVOICE_IN_PROCESS");
        createInvoiceMap.put("currencyUomId", invoice.getString("currencyUomId"));
        createInvoiceMap.put("userLogin", userLogin);
        // store the invoice first
        Map<String, Object> createInvoiceResult = null;
        try {
            createInvoiceResult = dispatcher.runSync("createInvoice", createInvoiceMap);
        } catch (GenericServiceException e) {
            return ServiceUtil.returnError(
                    UtilProperties.getMessage(resource, "AccountingInvoiceCommissionError", locale), null, null,
                    createInvoiceResult);
        }
        String invoiceId = (String) createInvoiceResult.get("invoiceId");
        // create the bill-from (or pay-to) contact mech as the primary PAYMENT_LOCATION of the party from the store
        GenericValue partyContactMechPurpose = null;
        try {
            partyContactMechPurpose = EntityQuery.use(delegator).from("PartyContactMechPurpose")
                    .where("partyId", partyIdBillTo, "contactMechPurposeTypeId", "BILLING_LOCATION")
                    .queryFirst();
        } catch (GenericEntityException e) {
            return ServiceUtil.returnError(e.getMessage());
        }
        if (partyContactMechPurpose != null) {
            GenericValue invoiceContactMech = delegator.makeValue("InvoiceContactMech",
                    UtilMisc.toMap("invoiceId", invoiceId, "contactMechId",
                            partyContactMechPurpose.getString("contactMechId"), "contactMechPurposeTypeId",
                            "BILLING_LOCATION"));
            toStore.add(invoiceContactMech);
        }
        try {
            partyContactMechPurpose = EntityQuery.use(delegator).from("PartyContactMechPurpose")
                    .where("partyId", partyIdBillTo, "contactMechPurposeTypeId", "PAYMENT_LOCATION")
                    .queryFirst();
        } catch (GenericEntityException e) {
            return ServiceUtil.returnError(e.getMessage());
        }
        if (partyContactMechPurpose != null) {
            GenericValue invoiceContactMech = delegator.makeValue("InvoiceContactMech",
                    UtilMisc.toMap("invoiceId", invoiceId, "contactMechId",
                            partyContactMechPurpose.getString("contactMechId"), "contactMechPurposeTypeId",
                            "PAYMENT_LOCATION"));
            toStore.add(invoiceContactMech);
        }
        // create the item records
        for (Map<String, Object> commissionMap : commList) {
            BigDecimal elemAmount = ((BigDecimal) commissionMap.get("commission")).multiply(appliedFraction);
            BigDecimal quantity = (BigDecimal) commissionMap.get("quantity");
            String invoiceIdFrom = (String) commissionMap.get("invoiceId");
            String invoiceItemSeqIdFrom = (String) commissionMap.get("invoiceItemSeqId");
            elemAmount = elemAmount.setScale(DECIMALS, ROUNDING);
            Map<String, Object> resMap = null;
            try {
                resMap = dispatcher.runSync("createInvoiceItem",
                        UtilMisc.toMap("invoiceId", invoiceId, "productId", commissionMap.get("productId"),
                                "invoiceItemTypeId", "COMM_INV_ITEM", "quantity", quantity, "amount",
                                elemAmount, "userLogin", userLogin));
                dispatcher.runSync("createInvoiceItemAssoc",
                        UtilMisc.toMap("invoiceIdFrom", invoiceIdFrom, "invoiceItemSeqIdFrom",
                                invoiceItemSeqIdFrom, "invoiceIdTo", invoiceId, "invoiceItemSeqIdTo",
                                resMap.get("invoiceItemSeqId"), "invoiceItemAssocTypeId", "COMMISSION_INVOICE",
                                "partyIdFrom", partyIdBillFrom, "partyIdTo", partyIdBillTo, "quantity",
                                quantity, "amount", elemAmount, "userLogin", userLogin));
            } catch (GenericServiceException e) {
                return ServiceUtil.returnError(e.getMessage());
            }
            if (ServiceUtil.isError(resMap)) {
                return ServiceUtil.returnError(
                        UtilProperties.getMessage(resource, "AccountingInvoiceCommissionErrorItem", locale),
                        null, null, resMap);
            }
        }
        // store value objects
        try {
            delegator.storeAll(toStore);
        } catch (GenericEntityException e) {
            Debug.logError(e, "Entity/data problem creating commission invoice: " + e.toString(), module);
            return ServiceUtil.returnError(
                    UtilProperties.getMessage(resource, "AccountingInvoiceCommissionEntityDataProblem",
                            UtilMisc.toMap("reason", e.toString()), locale));
        }
        invoicesCreated.add(UtilMisc.<String, String>toMap("commissionInvoiceId", invoiceId,
                "salesRepresentative ", partyIdBillFrom));
    }
    String invCreated = Integer.toString(invoicesCreated.size());
    Map<String, Object> result = ServiceUtil.returnSuccess(UtilProperties.getMessage(resource,
            "AccountingCommissionInvoicesCreated", UtilMisc.toMap("invoicesCreated", invCreated), locale));
    Debug.logInfo("Created Commission invoices for each commission receiving parties " + invCreated, module);
    result.put("invoicesCreated", invoicesCreated);
    return result;
}

From source file:op.allowance.PnlAllowance.java

private PnlTX getPnlTX(Resident resident, final Allowance allowance) {
    final BigDecimal editAmount = allowance != null ? allowance.getAmount() : null;
    final Allowance allow = (allowance == null ? new Allowance(resident) : allowance);

    return new PnlTX(allow, new Closure() {
        @Override//from   w  w  w . j a  v  a 2s.  co m
        public void execute(Object o) {
            if (o != null) {

                EntityManager em = OPDE.createEM();
                try {
                    em.getTransaction().begin();
                    final Allowance myAllowance = em.merge((Allowance) o);
                    em.lock(em.merge(myAllowance.getResident()), LockModeType.OPTIMISTIC);
                    em.getTransaction().commit();

                    DateTime txDate = new DateTime(myAllowance.getPit());

                    final String keyResident = myAllowance.getResident().getRID();
                    final String keyYear = myAllowance.getResident().getRID() + "-" + txDate.getYear();
                    final String keyMonth = myAllowance.getResident().getRID() + "-" + txDate.getYear() + "-"
                            + txDate.getMonthOfYear();

                    if (!lstResidents.contains(myAllowance.getResident())) {
                        lstResidents.add(myAllowance.getResident());
                        Collections.sort(lstResidents);
                    }

                    if (!cashmap.containsKey(keyMonth)) {
                        cashmap.put(keyMonth,
                                AllowanceTools.getMonth(myAllowance.getResident(), myAllowance.getPit()));
                    } else {

                        if (cashmap.get(keyMonth).contains(myAllowance)) {
                            cashmap.get(keyMonth).remove(myAllowance);
                        }
                        cashmap.get(keyMonth).add(myAllowance);

                        Collections.sort(cashmap.get(keyMonth));
                    }

                    // little trick to fix the carries
                    if (editAmount != null) {
                        updateCarrySums(myAllowance.getResident(), new LocalDate(myAllowance.getPit()),
                                editAmount.negate());
                    }
                    // add the new / edited amount
                    updateCarrySums(myAllowance);

                    createCP4(myAllowance.getResident());

                    try {
                        if (cpMap.get(keyResident).isCollapsed())
                            cpMap.get(keyResident).setCollapsed(false);
                        if (cpMap.get(keyYear).isCollapsed())
                            cpMap.get(keyYear).setCollapsed(false);
                        if (cpMap.get(keyMonth).isCollapsed())
                            cpMap.get(keyMonth).setCollapsed(false);
                    } catch (PropertyVetoException e) {
                        e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
                    }

                    buildPanel();

                    GUITools.scroll2show(jspCash, cpMap.get(keyMonth), cpsCash, new Closure() {
                        @Override
                        public void execute(Object o) {
                            GUITools.flashBackground(linemap.get(myAllowance), 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();
                }

            }
        }
    });
}

From source file:org.efaps.esjp.accounting.transaction.Create_Base.java

/**
 * Used form a from to create the transaction for opening a balance.
 *
 * @param _parameter Paramter as passed from the eFaps API
 * @return new Return/* www.  j  a v  a2s. co  m*/
 * @throws EFapsException on error
 */
public Return createTransactionOpeningBalance(final Parameter _parameter) throws EFapsException {
    final String debitAccOId = _parameter.getParameterValue("accountLink_Debit");
    final String[] amounts = _parameter.getParameterValues("amount");
    final String[] accounts = _parameter.getParameterValues("accountLink_Credit");
    final Instance periodInst = _parameter.getInstance();

    final Insert insert = new Insert(CIAccounting.TransactionOpeningBalance);
    insert.add(CIAccounting.TransactionOpeningBalance.Name, 0);
    insert.add(CIAccounting.TransactionOpeningBalance.Description,
            DBProperties.getProperty("org.efaps.esjp.accounting.Transaction.openingBalance.description"));
    insert.add(CIAccounting.TransactionOpeningBalance.Date, _parameter.getParameterValue("date"));
    insert.add(CIAccounting.TransactionOpeningBalance.PeriodLink, periodInst.getId());
    insert.add(CIAccounting.TransactionOpeningBalance.Status,
            ((Long) Status.find(CIAccounting.TransactionStatus.uuid, "Open").getId()).toString());
    insert.execute();

    BigDecimal debitAmount = BigDecimal.ZERO;
    final CurrencyInst curr = new Period().getCurrency(periodInst);
    final DecimalFormat formater = NumberFormatter.get().getFormatter(null, 2);
    for (int i = 0; i < amounts.length; i++) {
        final Instance accInst = Instance.get(accounts[i]);
        final PrintQuery print = new PrintQuery(accInst);
        print.addAttribute(CIAccounting.AccountAbstract.SumReport);
        print.execute();

        final BigDecimal sumreport = print.<BigDecimal>getAttribute(CIAccounting.AccountAbstract.SumReport);
        try {
            BigDecimal amount = (BigDecimal) formater.parse(amounts[i]);
            amount = amount.subtract(sumreport == null ? BigDecimal.ZERO : sumreport);
            final CIType type = amount.compareTo(BigDecimal.ZERO) > 0 ? CIAccounting.TransactionPositionCredit
                    : CIAccounting.TransactionPositionDebit;
            final Insert posInsert = new Insert(type);
            posInsert.add(CIAccounting.TransactionPositionAbstract.AccountLink, accInst.getId());
            posInsert.add(CIAccounting.TransactionPositionAbstract.Amount, amount);
            posInsert.add(CIAccounting.TransactionPositionAbstract.CurrencyLink, curr.getInstance().getId());
            posInsert.add(CIAccounting.TransactionPositionAbstract.Rate, new Object[] { 1, 1 });
            posInsert.add(CIAccounting.TransactionPositionAbstract.RateAmount, amount);
            posInsert.add(CIAccounting.TransactionPositionAbstract.RateCurrencyLink,
                    curr.getInstance().getId());
            posInsert.add(CIAccounting.TransactionPositionAbstract.TransactionLink,
                    insert.getInstance().getId());
            posInsert.execute();
            debitAmount = debitAmount.add(amount);
        } catch (final ParseException e) {
            throw new EFapsException(Create_Base.class, "createTransactionOpeningBalance", e);
        }
    }
    final Instance accInst = Instance.get(debitAccOId);
    final CIType type = debitAmount.compareTo(BigDecimal.ZERO) < 0 ? CIAccounting.TransactionPositionCredit
            : CIAccounting.TransactionPositionDebit;
    final Insert posInsert = new Insert(type);
    posInsert.add(CIAccounting.TransactionPositionAbstract.AccountLink, accInst.getId());
    posInsert.add(CIAccounting.TransactionPositionAbstract.Amount, debitAmount.negate());
    posInsert.add(CIAccounting.TransactionPositionAbstract.CurrencyLink, curr.getInstance().getId());
    posInsert.add(CIAccounting.TransactionPositionAbstract.Rate, new Object[] { 1, 1 });
    posInsert.add(CIAccounting.TransactionPositionAbstract.RateAmount, debitAmount.negate());
    posInsert.add(CIAccounting.TransactionPositionAbstract.RateCurrencyLink, curr.getInstance().getId());
    posInsert.add(CIAccounting.TransactionPositionAbstract.TransactionLink, insert.getInstance().getId());
    posInsert.execute();

    return new Return();
}

From source file:org.ballerinalang.bre.bvm.BVM.java

private static void execBinaryOpCodes(Strand ctx, StackFrame sf, int opcode, int[] operands) {
    int i;//w  ww .  j a  va2s  . com
    int j;
    int k;
    BDecimal lhsValue;
    BDecimal rhsValue;

    switch (opcode) {
    case InstructionCodes.IADD:
        i = operands[0];
        j = operands[1];
        k = operands[2];
        sf.longRegs[k] = sf.longRegs[i] + sf.longRegs[j];
        break;
    case InstructionCodes.FADD:
        i = operands[0];
        j = operands[1];
        k = operands[2];
        sf.doubleRegs[k] = sf.doubleRegs[i] + sf.doubleRegs[j];
        break;
    case InstructionCodes.SADD:
        i = operands[0];
        j = operands[1];
        k = operands[2];
        sf.stringRegs[k] = sf.stringRegs[i] + sf.stringRegs[j];
        break;
    case InstructionCodes.DADD:
        i = operands[0];
        j = operands[1];
        k = operands[2];
        lhsValue = (BDecimal) sf.refRegs[i];
        rhsValue = (BDecimal) sf.refRegs[j];
        sf.refRegs[k] = lhsValue.add(rhsValue);
        break;
    case InstructionCodes.XMLADD:
        i = operands[0];
        j = operands[1];
        k = operands[2];
        BXML lhsXMLVal = (BXML) sf.refRegs[i];
        BXML rhsXMLVal = (BXML) sf.refRegs[j];

        // Here it is assumed that a refType addition can only be a xml-concat.
        sf.refRegs[k] = XMLUtils.concatenate(lhsXMLVal, rhsXMLVal);
        break;
    case InstructionCodes.ISUB:
        i = operands[0];
        j = operands[1];
        k = operands[2];
        sf.longRegs[k] = sf.longRegs[i] - sf.longRegs[j];
        break;
    case InstructionCodes.FSUB:
        i = operands[0];
        j = operands[1];
        k = operands[2];
        sf.doubleRegs[k] = sf.doubleRegs[i] - sf.doubleRegs[j];
        break;
    case InstructionCodes.DSUB:
        i = operands[0];
        j = operands[1];
        k = operands[2];
        lhsValue = (BDecimal) sf.refRegs[i];
        rhsValue = (BDecimal) sf.refRegs[j];
        sf.refRegs[k] = lhsValue.subtract(rhsValue);
        break;
    case InstructionCodes.IMUL:
        i = operands[0];
        j = operands[1];
        k = operands[2];
        sf.longRegs[k] = sf.longRegs[i] * sf.longRegs[j];
        break;
    case InstructionCodes.FMUL:
        i = operands[0];
        j = operands[1];
        k = operands[2];
        sf.doubleRegs[k] = sf.doubleRegs[i] * sf.doubleRegs[j];
        break;
    case InstructionCodes.DMUL:
        i = operands[0];
        j = operands[1];
        k = operands[2];
        lhsValue = (BDecimal) sf.refRegs[i];
        rhsValue = (BDecimal) sf.refRegs[j];
        sf.refRegs[k] = lhsValue.multiply(rhsValue);
        break;
    case InstructionCodes.IDIV:
        i = operands[0];
        j = operands[1];
        k = operands[2];
        if (sf.longRegs[j] == 0) {
            ctx.setError(
                    BLangVMErrors.createError(ctx, BallerinaErrorReasons.DIVISION_BY_ZERO_ERROR, " / by zero"));
            handleError(ctx);
            break;
        }

        sf.longRegs[k] = sf.longRegs[i] / sf.longRegs[j];
        break;
    case InstructionCodes.FDIV:
        i = operands[0];
        j = operands[1];
        k = operands[2];
        sf.doubleRegs[k] = sf.doubleRegs[i] / sf.doubleRegs[j];
        break;
    case InstructionCodes.DDIV:
        i = operands[0];
        j = operands[1];
        k = operands[2];
        lhsValue = (BDecimal) sf.refRegs[i];
        rhsValue = (BDecimal) sf.refRegs[j];
        sf.refRegs[k] = lhsValue.divide(rhsValue);
        break;
    case InstructionCodes.IMOD:
        i = operands[0];
        j = operands[1];
        k = operands[2];
        if (sf.longRegs[j] == 0) {
            ctx.setError(
                    BLangVMErrors.createError(ctx, BallerinaErrorReasons.DIVISION_BY_ZERO_ERROR, " / by zero"));
            handleError(ctx);
            break;
        }

        sf.longRegs[k] = sf.longRegs[i] % sf.longRegs[j];
        break;
    case InstructionCodes.FMOD:
        i = operands[0];
        j = operands[1];
        k = operands[2];
        sf.doubleRegs[k] = sf.doubleRegs[i] % sf.doubleRegs[j];
        break;
    case InstructionCodes.DMOD:
        i = operands[0];
        j = operands[1];
        k = operands[2];
        lhsValue = (BDecimal) sf.refRegs[i];
        rhsValue = (BDecimal) sf.refRegs[j];
        sf.refRegs[k] = lhsValue.remainder(rhsValue);
        break;
    case InstructionCodes.INEG:
        i = operands[0];
        j = operands[1];
        sf.longRegs[j] = -sf.longRegs[i];
        break;
    case InstructionCodes.FNEG:
        i = operands[0];
        j = operands[1];
        sf.doubleRegs[j] = -sf.doubleRegs[i];
        break;
    case InstructionCodes.DNEG:
        i = operands[0];
        j = operands[1];
        BigDecimal value = ((BDecimal) sf.refRegs[i]).decimalValue();
        sf.refRegs[j] = new BDecimal(value.negate());
        break;
    case InstructionCodes.BNOT:
        i = operands[0];
        j = operands[1];
        sf.intRegs[j] = sf.intRegs[i] == 0 ? 1 : 0;
        break;
    case InstructionCodes.IEQ:
        i = operands[0];
        j = operands[1];
        k = operands[2];
        sf.intRegs[k] = sf.longRegs[i] == sf.longRegs[j] ? 1 : 0;
        break;
    case InstructionCodes.FEQ:
        i = operands[0];
        j = operands[1];
        k = operands[2];
        sf.intRegs[k] = sf.doubleRegs[i] == sf.doubleRegs[j] ? 1 : 0;
        break;
    case InstructionCodes.SEQ:
        i = operands[0];
        j = operands[1];
        k = operands[2];
        sf.intRegs[k] = StringUtils.isEqual(sf.stringRegs[i], sf.stringRegs[j]) ? 1 : 0;
        break;
    case InstructionCodes.BEQ:
        i = operands[0];
        j = operands[1];
        k = operands[2];
        sf.intRegs[k] = sf.intRegs[i] == sf.intRegs[j] ? 1 : 0;
        break;
    case InstructionCodes.DEQ:
        i = operands[0];
        j = operands[1];
        k = operands[2];
        lhsValue = (BDecimal) sf.refRegs[i];
        rhsValue = (BDecimal) sf.refRegs[j];
        sf.intRegs[k] = isDecimalRealNumber(lhsValue) && isDecimalRealNumber(rhsValue)
                && lhsValue.decimalValue().compareTo(rhsValue.decimalValue()) == 0 ? 1 : 0;
        break;
    case InstructionCodes.REQ:
        i = operands[0];
        j = operands[1];
        k = operands[2];
        if (sf.refRegs[i] == null) {
            sf.intRegs[k] = sf.refRegs[j] == null ? 1 : 0;
        } else {
            sf.intRegs[k] = isEqual(sf.refRegs[i], sf.refRegs[j], new ArrayList<>()) ? 1 : 0;
        }
        break;
    case InstructionCodes.REF_EQ:
        i = operands[0];
        j = operands[1];
        k = operands[2];
        sf.intRegs[k] = isReferenceEqual(sf.refRegs[i], sf.refRegs[j]) ? 1 : 0;
        break;
    case InstructionCodes.TEQ:
        i = operands[0];
        j = operands[1];
        k = operands[2];
        if (sf.refRegs[i] == null || sf.refRegs[j] == null) {
            handleNullRefError(ctx);
            break; //TODO is this correct?
        }
        sf.intRegs[k] = sf.refRegs[i].equals(sf.refRegs[j]) ? 1 : 0;
        break;

    case InstructionCodes.INE:
        i = operands[0];
        j = operands[1];
        k = operands[2];
        sf.intRegs[k] = sf.longRegs[i] != sf.longRegs[j] ? 1 : 0;
        break;
    case InstructionCodes.FNE:
        i = operands[0];
        j = operands[1];
        k = operands[2];
        sf.intRegs[k] = sf.doubleRegs[i] != sf.doubleRegs[j] ? 1 : 0;
        break;
    case InstructionCodes.SNE:
        i = operands[0];
        j = operands[1];
        k = operands[2];
        sf.intRegs[k] = !StringUtils.isEqual(sf.stringRegs[i], sf.stringRegs[j]) ? 1 : 0;
        break;
    case InstructionCodes.BNE:
        i = operands[0];
        j = operands[1];
        k = operands[2];
        sf.intRegs[k] = sf.intRegs[i] != sf.intRegs[j] ? 1 : 0;
        break;
    case InstructionCodes.DNE:
        i = operands[0];
        j = operands[1];
        k = operands[2];
        lhsValue = (BDecimal) sf.refRegs[i];
        rhsValue = (BDecimal) sf.refRegs[j];
        sf.intRegs[k] = !isDecimalRealNumber(lhsValue) || !isDecimalRealNumber(rhsValue)
                || lhsValue.decimalValue().compareTo(rhsValue.decimalValue()) != 0 ? 1 : 0;
        break;
    case InstructionCodes.RNE:
        i = operands[0];
        j = operands[1];
        k = operands[2];
        if (sf.refRegs[i] == null) {
            sf.intRegs[k] = (sf.refRegs[j] != null) ? 1 : 0;
        } else {
            sf.intRegs[k] = (!isEqual(sf.refRegs[i], sf.refRegs[j], new ArrayList<>())) ? 1 : 0;
        }
        break;
    case InstructionCodes.REF_NEQ:
        i = operands[0];
        j = operands[1];
        k = operands[2];
        sf.intRegs[k] = isReferenceInequal(sf.refRegs[i], sf.refRegs[j]) ? 1 : 0;
        break;
    case InstructionCodes.TNE:
        i = operands[0];
        j = operands[1];
        k = operands[2];
        if (sf.refRegs[i] == null || sf.refRegs[j] == null) {
            handleNullRefError(ctx);
            break; //TODO is this correct?
        }
        sf.intRegs[k] = (!sf.refRegs[i].equals(sf.refRegs[j])) ? 1 : 0;
        break;
    case InstructionCodes.IAND:
        i = operands[0];
        j = operands[1];
        k = operands[2];
        sf.longRegs[k] = sf.longRegs[i] & sf.longRegs[j];
        break;
    case InstructionCodes.IOR:
        i = operands[0];
        j = operands[1];
        k = operands[2];
        sf.longRegs[k] = sf.longRegs[i] | sf.longRegs[j];
        break;
    case InstructionCodes.IXOR:
        i = operands[0];
        j = operands[1];
        k = operands[2];
        sf.longRegs[k] = sf.longRegs[i] ^ sf.longRegs[j];
        break;
    case InstructionCodes.BILSHIFT:
        i = operands[0];
        j = operands[1];
        k = operands[2];
        sf.longRegs[k] = Byte.toUnsignedLong((byte) (sf.longRegs[i] << sf.longRegs[j]));
        break;
    case InstructionCodes.BIRSHIFT:
        i = operands[0];
        j = operands[1];
        k = operands[2];
        sf.longRegs[k] = Byte.toUnsignedLong((byte) ((byte) sf.longRegs[i] >> sf.longRegs[j]));
        break;
    case InstructionCodes.IRSHIFT:
        i = operands[0];
        j = operands[1];
        k = operands[2];
        sf.longRegs[k] = sf.longRegs[i] >> sf.longRegs[j];
        break;
    case InstructionCodes.ILSHIFT:
        i = operands[0];
        j = operands[1];
        k = operands[2];
        sf.longRegs[k] = sf.longRegs[i] << sf.longRegs[j];
        break;
    case InstructionCodes.IURSHIFT:
        i = operands[0];
        j = operands[1];
        k = operands[2];
        sf.longRegs[k] = sf.longRegs[i] >>> sf.longRegs[j];
        break;
    case InstructionCodes.TYPE_TEST:
        i = operands[0];
        j = operands[1];
        k = operands[2];
        TypeRefCPEntry typeRefCPEntry = (TypeRefCPEntry) sf.constPool[j];
        sf.intRegs[k] = checkIsType(sf.refRegs[i], typeRefCPEntry.getType()) ? 1 : 0;
        break;
    case InstructionCodes.IS_LIKE:
        i = operands[0];
        j = operands[1];
        k = operands[2];
        typeRefCPEntry = (TypeRefCPEntry) sf.constPool[j];
        sf.intRegs[k] = checkIsLikeType(sf.refRegs[i], typeRefCPEntry.getType()) ? 1 : 0;
        break;
    default:
        throw new UnsupportedOperationException();
    }
}

From source file:org.openbravo.advpaymentmngt.process.FIN_PaymentProcess.java

private void processPayment(FIN_Payment payment, String strAction, Boolean isPosOrder, String paymentDate,
        String comingFrom, String selectedCreditLineIds) throws OBException {
    dao = new AdvPaymentMngtDao();
    String msg = "";
    try {/* ww w  .j av  a  2 s.com*/
        final boolean isReceipt = payment.isReceipt();
        if (strAction.equals("P") || strAction.equals("D")) {
            if (payment.getBusinessPartner() != null) {
                if (FIN_Utility.isBlockedBusinessPartner(payment.getBusinessPartner().getId(), isReceipt, 4)) {
                    // If the Business Partner is blocked for Payments, the Payment will not be completed.
                    msg = OBMessageUtils.messageBD("ThebusinessPartner") + " "
                            + payment.getBusinessPartner().getIdentifier() + " "
                            + OBMessageUtils.messageBD("BusinessPartnerBlocked");
                    throw new OBException(msg);
                }
            } else {
                OBContext.setAdminMode(true);
                try {
                    for (FIN_PaymentDetail pd : payment.getFINPaymentDetailList()) {
                        for (FIN_PaymentScheduleDetail psd : pd.getFINPaymentScheduleDetailList()) {
                            BusinessPartner bPartner = null;
                            if (psd.getInvoicePaymentSchedule() != null) {
                                bPartner = psd.getInvoicePaymentSchedule().getInvoice().getBusinessPartner();
                            } else if (psd.getOrderPaymentSchedule() != null) {
                                bPartner = psd.getOrderPaymentSchedule().getOrder().getBusinessPartner();
                            }
                            if (bPartner != null && FIN_Utility.isBlockedBusinessPartner(bPartner.getId(),
                                    payment.isReceipt(), 4)) {
                                // If the Business Partner is blocked for Payments, the Payment will not be
                                // completed.
                                msg = OBMessageUtils.messageBD("ThebusinessPartner") + " "
                                        + bPartner.getIdentifier() + " "
                                        + OBMessageUtils.messageBD("BusinessPartnerBlocked");
                                throw new OBException(msg);
                            }
                        }
                    }
                } finally {
                    OBContext.restorePreviousMode();
                }
            }
        }

        if (strAction.equals("P") || strAction.equals("D")) {
            // Guess if this is a refund payment
            boolean isRefund = false;
            OBContext.setAdminMode(false);
            try {
                List<FIN_PaymentDetail> paymentDetailList = payment.getFINPaymentDetailList();
                if (paymentDetailList.size() > 0) {
                    for (FIN_PaymentDetail det : paymentDetailList) {
                        if (det.isRefund()) {
                            isRefund = true;
                            break;
                        }
                    }
                }
            } finally {
                OBContext.restorePreviousMode();
            }
            if (!isRefund) {
                // Undo Used credit as it will be calculated again
                payment.setUsedCredit(BigDecimal.ZERO);
                OBDal.getInstance().save(payment);
            }

            boolean documentEnabled = getDocumentConfirmation(null, payment.getId());
            boolean periodNotAvailable = documentEnabled
                    && !FIN_Utility.isPeriodOpen(payment.getClient().getId(),
                            payment.getDocumentType().getDocumentCategory(), payment.getOrganization().getId(),
                            OBDateUtils.formatDate(payment.getPaymentDate()))
                    && FIN_Utility.periodControlOpened(FIN_Payment.TABLE_NAME, payment.getId(),
                            FIN_Payment.TABLE_NAME + "_ID", "LE");
            if (periodNotAvailable) {
                msg = OBMessageUtils.messageBD("PeriodNotAvailable");
                throw new OBException(msg);
            }
            Set<String> documentOrganizations = OBContext.getOBContext()
                    .getOrganizationStructureProvider(payment.getClient().getId())
                    .getNaturalTree(payment.getOrganization().getId());
            if (!documentOrganizations.contains(payment.getAccount().getOrganization().getId())) {
                msg = OBMessageUtils.messageBD("APRM_FinancialAccountNotInNaturalTree");
                throw new OBException(msg);
            }
            Set<String> invoiceDocNos = new TreeSet<String>();
            Set<String> orderDocNos = new TreeSet<String>();
            Set<String> glitems = new TreeSet<String>();
            BigDecimal paymentAmount = BigDecimal.ZERO;
            BigDecimal paymentWriteOfAmount = BigDecimal.ZERO;

            // FIXME: added to access the FIN_PaymentSchedule and FIN_PaymentScheduleDetail tables to be
            // removed when new security implementation is done
            OBContext.setAdminMode();
            boolean flushDone = false;
            try {
                String strRefundCredit = "";
                // update payment schedule amount
                List<FIN_PaymentDetail> paymentDetails = payment.getFINPaymentDetailList();

                // Show error message when payment has no lines
                if (paymentDetails.size() == 0) {
                    msg = OBMessageUtils.messageBD("APRM_PaymentNoLines");
                    log4j.debug(msg);
                    throw new OBException(msg, false);
                }
                for (FIN_PaymentDetail paymentDetail : paymentDetails) {
                    for (FIN_PaymentScheduleDetail paymentScheduleDetail : paymentDetail
                            .getFINPaymentScheduleDetailList()) {
                        paymentAmount = paymentAmount.add(paymentScheduleDetail.getAmount());
                        BigDecimal writeoff = paymentScheduleDetail.getWriteoffAmount();
                        if (writeoff == null)
                            writeoff = BigDecimal.ZERO;
                        paymentWriteOfAmount = paymentWriteOfAmount.add(writeoff);
                        if (paymentScheduleDetail.getInvoicePaymentSchedule() != null) {
                            final Invoice invoice = paymentScheduleDetail.getInvoicePaymentSchedule()
                                    .getInvoice();
                            invoiceDocNos
                                    .add(FIN_Utility.getDesiredDocumentNo(payment.getOrganization(), invoice));
                        }
                        if (paymentScheduleDetail.getOrderPaymentSchedule() != null) {
                            orderDocNos.add(
                                    paymentScheduleDetail.getOrderPaymentSchedule().getOrder().getDocumentNo());
                        }
                        if (paymentScheduleDetail.getInvoicePaymentSchedule() == null
                                && paymentScheduleDetail.getOrderPaymentSchedule() == null
                                && paymentScheduleDetail.getPaymentDetails().getGLItem() == null) {
                            if (paymentDetail.isRefund())
                                strRefundCredit = OBMessageUtils.messageBD("APRM_RefundAmount");
                            else {
                                strRefundCredit = OBMessageUtils.messageBD("APRM_CreditAmount");
                                payment.setGeneratedCredit(paymentDetail.getAmount());
                            }
                            strRefundCredit += ": " + paymentDetail.getAmount().toString();
                        }
                    }
                    if (paymentDetail.getGLItem() != null)
                        glitems.add(paymentDetail.getGLItem().getName());
                }
                // Set description
                if (!isPosOrder) {
                    StringBuffer description = new StringBuffer();

                    if (payment.getDescription() != null && !payment.getDescription().equals(""))
                        description.append(payment.getDescription()).append("\n");
                    if (!invoiceDocNos.isEmpty()) {
                        description.append(OBMessageUtils.messageBD("InvoiceDocumentno"));
                        description.append(": ").append(
                                invoiceDocNos.toString().substring(1, invoiceDocNos.toString().length() - 1));
                        description.append("\n");
                    }
                    if (!orderDocNos.isEmpty()) {
                        description.append(OBMessageUtils.messageBD("OrderDocumentno"));
                        description.append(": ").append(
                                orderDocNos.toString().substring(1, orderDocNos.toString().length() - 1));
                        description.append("\n");
                    }
                    if (!glitems.isEmpty()) {
                        description.append(OBMessageUtils.messageBD("APRM_GLItem"));
                        description.append(": ")
                                .append(glitems.toString().substring(1, glitems.toString().length() - 1));
                        description.append("\n");
                    }
                    if (!"".equals(strRefundCredit))
                        description.append(strRefundCredit).append("\n");

                    String truncateDescription = (description.length() > 255)
                            ? description.substring(0, 251).concat("...").toString()
                            : description.toString();
                    payment.setDescription(truncateDescription);
                }

                if (paymentAmount.compareTo(payment.getAmount()) != 0) {
                    payment.setUsedCredit(paymentAmount.subtract(payment.getAmount()));
                }
                if (payment.getUsedCredit().compareTo(BigDecimal.ZERO) != 0) {
                    updateUsedCredit(payment, selectedCreditLineIds);
                }

                payment.setWriteoffAmount(paymentWriteOfAmount);
                payment.setProcessed(true);
                payment.setAPRMProcessPayment("RE");
                if (payment.getGeneratedCredit() == null) {
                    payment.setGeneratedCredit(BigDecimal.ZERO);
                }
                if (BigDecimal.ZERO.compareTo(payment.getUsedCredit()) != 0
                        || BigDecimal.ZERO.compareTo(payment.getGeneratedCredit()) != 0) {
                    BusinessPartner businessPartner = payment.getBusinessPartner();
                    if (businessPartner == null) {
                        msg = OBMessageUtils.messageBD("APRM_CreditWithoutBPartner");
                        throw new OBException(msg);
                    }
                    String currency = null;
                    if (businessPartner.getCurrency() == null) {
                        currency = payment.getCurrency().getId();
                        businessPartner.setCurrency(payment.getCurrency());
                    } else {
                        currency = businessPartner.getCurrency().getId();
                    }
                    if (!payment.getCurrency().getId().equals(currency)) {
                        msg = String.format(OBMessageUtils.messageBD("APRM_CreditCurrency"),
                                businessPartner.getCurrency().getISOCode());
                        throw new OBException(msg);
                    }
                }
                // Execution Process
                if (!isPosOrder && dao.isAutomatedExecutionPayment(payment.getAccount(),
                        payment.getPaymentMethod(), payment.isReceipt())) {
                    try {
                        payment.setStatus("RPAE");

                        if (dao.hasNotDeferredExecutionProcess(payment.getAccount(), payment.getPaymentMethod(),
                                payment.isReceipt())) {
                            PaymentExecutionProcess executionProcess = dao.getExecutionProcess(payment);
                            if (dao.isAutomaticExecutionProcess(executionProcess)) {
                                final List<FIN_Payment> payments = new ArrayList<FIN_Payment>(1);
                                payments.add(payment);
                                FIN_ExecutePayment executePayment = new FIN_ExecutePayment();
                                executePayment.init("APP", executionProcess, payments, null,
                                        payment.getOrganization());
                                executePayment.addInternalParameter("comingFrom", comingFrom);
                                OBError result = executePayment.execute();
                                if ("Error".equals(result.getType())) {
                                    msg = OBMessageUtils.messageBD(result.getMessage());
                                } else if (!"".equals(result.getMessage())) {
                                    String execProcessMsg = OBMessageUtils.messageBD(result.getMessage());
                                    if (!"".equals(msg)) {
                                        msg += "<br>";
                                    }
                                    msg += execProcessMsg;
                                }
                            }
                        }
                    } catch (final NoExecutionProcessFoundException e) {
                        msg = OBMessageUtils.messageBD("NoExecutionProcessFound");
                        throw new OBException(msg);
                    } catch (final Exception e) {
                        msg = OBMessageUtils.messageBD("IssueOnExecutionProcess");
                        throw new OBException(msg);
                    }
                } else {
                    BusinessPartner businessPartner = payment.getBusinessPartner();
                    // When credit is used (consumed) we compensate so_creditused as this amount is already
                    // included in the payment details. Credit consumed should not affect to so_creditused
                    if (payment.getGeneratedCredit().compareTo(BigDecimal.ZERO) == 0
                            && payment.getUsedCredit().compareTo(BigDecimal.ZERO) != 0) {
                        if (isReceipt) {
                            increaseCustomerCredit(businessPartner, payment.getUsedCredit());
                        } else {
                            decreaseCustomerCredit(businessPartner, payment.getUsedCredit());
                        }
                    }

                    for (FIN_PaymentDetail paymentDetail : payment.getFINPaymentDetailList()) {

                        List<FIN_PaymentScheduleDetail> orderPaymentScheduleDetails = new ArrayList<FIN_PaymentScheduleDetail>(
                                paymentDetail.getFINPaymentScheduleDetailList());

                        // Get payment schedule detail list ordered by amount asc.
                        // First negative if they exist and then positives
                        if (orderPaymentScheduleDetails.size() > 1) {
                            Collections.sort(orderPaymentScheduleDetails,
                                    new Comparator<FIN_PaymentScheduleDetail>() {
                                        @Override
                                        public int compare(FIN_PaymentScheduleDetail o1,
                                                FIN_PaymentScheduleDetail o2) {
                                            // TODO Auto-generated method stub
                                            return o1.getAmount().compareTo(o2.getAmount());
                                        }
                                    });
                        }

                        for (FIN_PaymentScheduleDetail paymentScheduleDetail : orderPaymentScheduleDetails) {
                            BigDecimal amount = paymentScheduleDetail.getAmount()
                                    .add(paymentScheduleDetail.getWriteoffAmount());
                            // Do not restore paid amounts if the payment is awaiting execution.
                            boolean invoicePaidAmounts = (FIN_Utility
                                    .seqnumberpaymentstatus(isReceipt ? "RPR" : "PPM")) >= (FIN_Utility
                                            .seqnumberpaymentstatus(FIN_Utility.invoicePaymentStatus(payment)));
                            paymentScheduleDetail.setInvoicePaid(false);
                            // Payment = 0 when the payment is generated by a invoice that consume credit
                            if (invoicePaidAmounts
                                    || (payment.getAmount().compareTo(new BigDecimal("0.00")) == 0)) {
                                if (paymentScheduleDetail.getInvoicePaymentSchedule() != null) {
                                    // BP SO_CreditUsed
                                    businessPartner = paymentScheduleDetail.getInvoicePaymentSchedule()
                                            .getInvoice().getBusinessPartner();

                                    // Payments update credit opposite to invoices
                                    BigDecimal paidAmount = BigDecimal.ZERO;
                                    Invoice invoiceForConversion = paymentScheduleDetail
                                            .getInvoicePaymentSchedule() != null
                                                    ? paymentScheduleDetail.getInvoicePaymentSchedule()
                                                            .getInvoice()
                                                    : null;
                                    paidAmount = BigDecimal.ZERO;
                                    String fromCurrency = payment.getCurrency().getId();
                                    if (businessPartner.getCurrency() == null) {
                                        String errorMSG = OBMessageUtils.messageBD("InitBPCurrencyLnk", false);
                                        msg = String.format(errorMSG, businessPartner.getId(),
                                                businessPartner.getName());
                                        throw new OBException(msg);
                                    }
                                    String toCurrency = businessPartner.getCurrency().getId();
                                    if (!fromCurrency.equals(toCurrency)) {
                                        BigDecimal exchangeRate = BigDecimal.ZERO;
                                        // check at invoice document level
                                        List<ConversionRateDoc> conversionRateDocumentForInvoice = getConversionRateDocumentForInvoice(
                                                invoiceForConversion);
                                        if (conversionRateDocumentForInvoice.size() > 0) {
                                            exchangeRate = conversionRateDocumentForInvoice.get(0).getRate();
                                        } else {
                                            // global
                                            exchangeRate = getConversionRate(payment.getOrganization().getId(),
                                                    fromCurrency, toCurrency,
                                                    invoiceForConversion != null
                                                            ? invoiceForConversion.getInvoiceDate()
                                                            : payment.getPaymentDate());
                                        }
                                        if (exchangeRate == BigDecimal.ZERO) {
                                            msg = OBMessageUtils.messageBD("NoCurrencyConversion");
                                            throw new OBException(msg);
                                        }
                                        paidAmount = amount.multiply(exchangeRate);
                                    } else {
                                        paidAmount = amount;
                                    }
                                    if (isReceipt) {
                                        decreaseCustomerCredit(businessPartner, paidAmount);
                                    } else {
                                        increaseCustomerCredit(businessPartner, paidAmount);
                                    }
                                    FIN_AddPayment.updatePaymentScheduleAmounts(paymentDetail,
                                            paymentScheduleDetail.getInvoicePaymentSchedule(),
                                            paymentScheduleDetail.getAmount(),
                                            paymentScheduleDetail.getWriteoffAmount());
                                    paymentScheduleDetail.setInvoicePaid(true);
                                }

                                if (paymentScheduleDetail.getOrderPaymentSchedule() != null) {
                                    FIN_AddPayment.updatePaymentScheduleAmounts(paymentDetail,
                                            paymentScheduleDetail.getOrderPaymentSchedule(),
                                            paymentScheduleDetail.getAmount(),
                                            paymentScheduleDetail.getWriteoffAmount());
                                    paymentScheduleDetail.setInvoicePaid(true);
                                }
                                // when generating credit for a BP SO_CreditUsed is also updated
                                if (paymentScheduleDetail.getInvoicePaymentSchedule() == null
                                        && paymentScheduleDetail.getOrderPaymentSchedule() == null
                                        && paymentScheduleDetail.getPaymentDetails().getGLItem() == null
                                        && !paymentDetail.isRefund()) {
                                    // BP SO_CreditUsed
                                    if (isReceipt) {
                                        decreaseCustomerCredit(businessPartner, amount);
                                    } else {
                                        increaseCustomerCredit(businessPartner, amount);
                                    }
                                }
                            }
                        }
                    }
                    payment.setStatus(isReceipt ? "RPR" : "PPM");

                    if ((strAction.equals("D") || FIN_Utility.isAutomaticDepositWithdrawn(payment))
                            && payment.getAmount().compareTo(BigDecimal.ZERO) != 0
                            && !"TRANSACTION".equals(comingFrom)) {
                        triggerAutomaticFinancialAccountTransaction(payment);
                        flushDone = true;
                    }
                }
                if (!payment.getAccount().getCurrency().equals(payment.getCurrency())
                        && getConversionRateDocument(payment).size() == 0) {
                    insertConversionRateDocument(payment);
                    flushDone = true;
                }
            } finally {
                if (!flushDone) {
                    OBDal.getInstance().flush();
                }
                OBContext.restorePreviousMode();
            }

            // ***********************
            // Reverse Payment
            // ***********************
        } else if (strAction.equals("RV")) {
            FIN_Payment reversedPayment = (FIN_Payment) DalUtil.copy(payment, false);
            OBContext.setAdminMode();
            try {
                if (BigDecimal.ZERO.compareTo(payment.getGeneratedCredit()) != 0
                        && BigDecimal.ZERO.compareTo(payment.getUsedCredit()) != 0) {
                    throw new OBException("@APRM_CreditConsumed@");
                } else if (BigDecimal.ZERO.compareTo(payment.getGeneratedCredit()) != 0
                        && BigDecimal.ZERO.compareTo(payment.getUsedCredit()) == 0) {
                    reversedPayment.setUsedCredit(payment.getGeneratedCredit());
                    reversedPayment.setGeneratedCredit(BigDecimal.ZERO);
                } else {
                    reversedPayment.setUsedCredit(BigDecimal.ZERO);
                    reversedPayment.setGeneratedCredit(BigDecimal.ZERO);
                }
                reversedPayment.setDocumentNo(
                        "*R*" + FIN_Utility.getDocumentNo(payment.getDocumentType(), "FIN_Payment"));
                reversedPayment.setPaymentDate(FIN_Utility.getDate(paymentDate));
                reversedPayment.setDescription("");
                reversedPayment.setProcessed(false);
                reversedPayment.setPosted("N");
                reversedPayment.setProcessNow(false);
                reversedPayment.setAPRMProcessPayment("P");
                reversedPayment.setStatus("RPAP");
                // Amounts
                reversedPayment.setAmount(payment.getAmount().negate());
                reversedPayment.setWriteoffAmount(payment.getWriteoffAmount().negate());
                reversedPayment.setFinancialTransactionAmount(payment.getFinancialTransactionAmount().negate());
                OBDal.getInstance().save(reversedPayment);

                List<FIN_PaymentDetail> reversedDetails = new ArrayList<FIN_PaymentDetail>();

                OBDal.getInstance().save(reversedPayment);
                List<FIN_Payment_Credit> credits = payment.getFINPaymentCreditList();

                for (FIN_PaymentDetail pd : payment.getFINPaymentDetailList()) {
                    FIN_PaymentDetail reversedPaymentDetail = (FIN_PaymentDetail) DalUtil.copy(pd, false);
                    reversedPaymentDetail.setFinPayment(reversedPayment);
                    reversedPaymentDetail.setAmount(pd.getAmount().negate());
                    reversedPaymentDetail.setWriteoffAmount(pd.getWriteoffAmount().negate());
                    if (pd.isRefund()) {
                        reversedPaymentDetail.setPrepayment(true);
                        reversedPaymentDetail.setRefund(false);
                        reversedPayment
                                .setGeneratedCredit(reversedPayment.getGeneratedCredit().add(pd.getAmount()));
                        credits = new ArrayList<FIN_Payment_Credit>();
                        OBDal.getInstance().save(reversedPayment);
                    } else if (pd.isPrepayment()
                            && pd.getFINPaymentScheduleDetailList().get(0).getOrderPaymentSchedule() == null) {
                        reversedPaymentDetail.setPrepayment(true);
                        reversedPaymentDetail.setRefund(true);
                    }
                    List<FIN_PaymentScheduleDetail> reversedSchedDetails = new ArrayList<FIN_PaymentScheduleDetail>();
                    OBDal.getInstance().save(reversedPaymentDetail);
                    // Create or update PSD of orders and invoices to set the new outstanding amount
                    for (FIN_PaymentScheduleDetail psd : pd.getFINPaymentScheduleDetailList()) {
                        if (psd.getInvoicePaymentSchedule() != null || psd.getOrderPaymentSchedule() != null) {
                            OBCriteria<FIN_PaymentScheduleDetail> unpaidSchedDet = OBDal.getInstance()
                                    .createCriteria(FIN_PaymentScheduleDetail.class);
                            if (psd.getInvoicePaymentSchedule() != null)
                                unpaidSchedDet.add(Restrictions.eq(
                                        FIN_PaymentScheduleDetail.PROPERTY_INVOICEPAYMENTSCHEDULE,
                                        psd.getInvoicePaymentSchedule()));
                            if (psd.getOrderPaymentSchedule() != null)
                                unpaidSchedDet.add(
                                        Restrictions.eq(FIN_PaymentScheduleDetail.PROPERTY_ORDERPAYMENTSCHEDULE,
                                                psd.getOrderPaymentSchedule()));
                            unpaidSchedDet.add(
                                    Restrictions.isNull(FIN_PaymentScheduleDetail.PROPERTY_PAYMENTDETAILS));
                            List<FIN_PaymentScheduleDetail> openPSDs = unpaidSchedDet.list();
                            // If invoice/order not fully paid, update outstanding amount
                            if (openPSDs.size() > 0) {
                                FIN_PaymentScheduleDetail openPSD = openPSDs.get(0);
                                BigDecimal openAmount = openPSD.getAmount()
                                        .add(psd.getAmount().add(psd.getWriteoffAmount()));
                                if (openAmount.compareTo(BigDecimal.ZERO) == 0) {
                                    OBDal.getInstance().remove(openPSD);
                                } else {
                                    openPSD.setAmount(openAmount);
                                }
                            } else {
                                // If invoice is fully paid create a new schedule detail.
                                FIN_PaymentScheduleDetail openPSD = (FIN_PaymentScheduleDetail) DalUtil
                                        .copy(psd, false);
                                openPSD.setPaymentDetails(null);
                                // Amounts
                                openPSD.setWriteoffAmount(BigDecimal.ZERO);
                                openPSD.setAmount(psd.getAmount().add(psd.getWriteoffAmount()));

                                openPSD.setCanceled(false);
                                OBDal.getInstance().save(openPSD);
                            }
                        }

                        FIN_PaymentScheduleDetail reversedPaymentSchedDetail = (FIN_PaymentScheduleDetail) DalUtil
                                .copy(psd, false);
                        reversedPaymentSchedDetail.setPaymentDetails(reversedPaymentDetail);
                        // Amounts
                        reversedPaymentSchedDetail.setWriteoffAmount(psd.getWriteoffAmount().negate());
                        reversedPaymentSchedDetail.setAmount(psd.getAmount().negate());
                        OBDal.getInstance().save(reversedPaymentSchedDetail);
                        reversedSchedDetails.add(reversedPaymentSchedDetail);

                        if ((FIN_Utility.invoicePaymentStatus(reversedPayment)
                                .equals(reversedPayment.getStatus()))) {
                            reversedPaymentSchedDetail.setInvoicePaid(true);

                        } else {
                            reversedPaymentSchedDetail.setInvoicePaid(false);
                        }
                        OBDal.getInstance().save(reversedPaymentSchedDetail);

                    }

                    reversedPaymentDetail.setFINPaymentScheduleDetailList(reversedSchedDetails);
                    OBDal.getInstance().save(reversedPaymentDetail);
                    reversedDetails.add(reversedPaymentDetail);
                }
                reversedPayment.setFINPaymentDetailList(reversedDetails);
                OBDal.getInstance().save(reversedPayment);

                List<FIN_Payment_Credit> reversedCredits = new ArrayList<FIN_Payment_Credit>();
                for (FIN_Payment_Credit pc : credits) {
                    FIN_Payment_Credit reversedPaymentCredit = (FIN_Payment_Credit) DalUtil.copy(pc, false);
                    reversedPaymentCredit.setAmount(pc.getAmount().negate());
                    reversedPaymentCredit.setCreditPaymentUsed(pc.getCreditPaymentUsed());
                    pc.getCreditPaymentUsed().setUsedCredit(
                            pc.getCreditPaymentUsed().getUsedCredit().add(pc.getAmount().negate()));
                    reversedPaymentCredit.setPayment(reversedPayment);
                    OBDal.getInstance().save(pc.getCreditPaymentUsed());
                    OBDal.getInstance().save(reversedPaymentCredit);
                    reversedCredits.add(reversedPaymentCredit);
                }

                reversedPayment.setFINPaymentCreditList(reversedCredits);
                OBDal.getInstance().save(reversedPayment);

                List<ConversionRateDoc> conversions = new ArrayList<ConversionRateDoc>();
                for (ConversionRateDoc cr : payment.getCurrencyConversionRateDocList()) {
                    ConversionRateDoc reversedCR = (ConversionRateDoc) DalUtil.copy(cr, false);
                    reversedCR.setForeignAmount(cr.getForeignAmount().negate());
                    reversedCR.setPayment(reversedPayment);
                    OBDal.getInstance().save(reversedCR);
                    conversions.add(reversedCR);
                }
                reversedPayment.setCurrencyConversionRateDocList(conversions);
                OBDal.getInstance().save(reversedPayment);

                OBDal.getInstance().flush();
            } finally {
                OBContext.restorePreviousMode();
            }

            payment.setReversedPayment(reversedPayment);
            OBDal.getInstance().save(payment);
            OBDal.getInstance().flush();

            String newStrAction = "P";
            FIN_PaymentProcess fpp = WeldUtils.getInstanceFromStaticBeanManager(FIN_PaymentProcess.class);
            fpp.processPayment(reversedPayment, newStrAction, isPosOrder, paymentDate, comingFrom,
                    selectedCreditLineIds);

            return;

            // ***********************
            // Reactivate Payment
            // ***********************
        } else if (strAction.equals("R") || strAction.equals("RE")) {
            // Already Posted Document
            if ("Y".equals(payment.getPosted())) {
                msg = OBMessageUtils.messageBD("PostedDocument: " + payment.getDocumentNo());
                throw new OBException(msg);
            }
            // Reversed Payment
            if (payment.getReversedPayment() != null) {
                msg = OBMessageUtils.messageBD("APRM_PaymentReversed");
                throw new OBException(msg);
            }
            // Reverse Payment
            if (strAction.equals("RE") && FIN_Utility.isReversePayment(payment)) {
                msg = OBMessageUtils.messageBD("APRM_ReversePayment");
                throw new OBException(msg);
            }

            // Do not reactive the payment if it is tax payment
            if (payment.getFinancialMgmtTaxPaymentList().size() != 0) {
                msg = OBMessageUtils.messageBD("APRM_TaxPaymentReactivation");
                throw new OBException(msg);
            }

            // Transaction exists
            if (hasTransaction(payment)) {
                msg = OBMessageUtils.messageBD("APRM_TransactionExists");
                throw new OBException(msg);
            }
            // Payment with generated credit already used on other payments.
            if (payment.getGeneratedCredit().compareTo(BigDecimal.ZERO) == 1
                    && payment.getUsedCredit().compareTo(BigDecimal.ZERO) == 1) {
                msg = OBMessageUtils.messageBD("APRM_PaymentGeneratedCreditIsUsed");
                throw new OBException(msg);
            }

            if (FIN_Utility.invoicePaymentStatus(payment) == null) {
                msg = String.format(OBMessageUtils.messageBD("APRM_NoPaymentMethod"),
                        payment.getPaymentMethod().getIdentifier(), payment.getDocumentNo(),
                        payment.getAccount().getName());
                throw new OBException(msg);
            }
            // Do not restore paid amounts if the payment is awaiting execution.
            boolean restorePaidAmounts = (FIN_Utility
                    .seqnumberpaymentstatus(payment.getStatus())) == (FIN_Utility
                            .seqnumberpaymentstatus(FIN_Utility.invoicePaymentStatus(payment)));
            // Initialize amounts
            payment.setProcessed(false);
            OBDal.getInstance().save(payment);
            OBDal.getInstance().flush();
            payment.setWriteoffAmount(BigDecimal.ZERO);

            payment.setDescription("");

            // if all line are deleted then update amount to zero
            if (strAction.equals("R")) {
                payment.setAmount(BigDecimal.ZERO);
            }

            payment.setStatus("RPAP");
            payment.setAPRMProcessPayment("P");
            OBDal.getInstance().save(payment);
            OBDal.getInstance().flush();

            final List<FIN_PaymentDetail> removedPD = new ArrayList<FIN_PaymentDetail>();
            List<FIN_PaymentScheduleDetail> removedPDS = new ArrayList<FIN_PaymentScheduleDetail>();
            final List<String> removedPDIds = new ArrayList<String>();
            // FIXME: added to access the FIN_PaymentSchedule and FIN_PaymentScheduleDetail tables to be
            // removed when new security implementation is done
            OBContext.setAdminMode();
            try {
                BusinessPartner businessPartner = payment.getBusinessPartner();
                BigDecimal paidAmount = BigDecimal.ZERO;
                if (!(businessPartner == null)) {
                    // When credit is used (consumed) we compensate so_creditused as this amount is already
                    // included in the payment details. Credit consumed should not affect to so_creditused
                    if (payment.getGeneratedCredit().compareTo(BigDecimal.ZERO) == 0
                            && payment.getUsedCredit().compareTo(BigDecimal.ZERO) != 0) {
                        if (isReceipt) {
                            decreaseCustomerCredit(businessPartner, payment.getUsedCredit());
                        } else {
                            increaseCustomerCredit(businessPartner, payment.getUsedCredit());
                        }
                    }
                }
                List<FIN_PaymentDetail> paymentDetails = payment.getFINPaymentDetailList();
                List<ConversionRateDoc> conversionRates = payment.getCurrencyConversionRateDocList();
                Set<String> invoiceDocNos = new HashSet<String>();
                // Undo Reversed payment relationship
                List<FIN_Payment> revPayments = new ArrayList<FIN_Payment>();
                for (FIN_Payment reversedPayment : payment.getFINPaymentReversedPaymentList()) {
                    reversedPayment.setReversedPayment(null);
                    OBDal.getInstance().save(reversedPayment);
                }
                payment.setFINPaymentReversedPaymentList(revPayments);
                OBDal.getInstance().save(payment);
                for (FIN_PaymentDetail paymentDetail : paymentDetails) {
                    removedPDS = new ArrayList<FIN_PaymentScheduleDetail>();
                    for (FIN_PaymentScheduleDetail paymentScheduleDetail : paymentDetail
                            .getFINPaymentScheduleDetailList()) {
                        Boolean invoicePaidold = paymentScheduleDetail.isInvoicePaid();
                        if (invoicePaidold | paymentScheduleDetail.getInvoicePaymentSchedule() == null) {
                            BigDecimal psdWriteoffAmount = paymentScheduleDetail.getWriteoffAmount();
                            BigDecimal psdAmount = paymentScheduleDetail.getAmount();
                            BigDecimal amount = psdAmount.add(psdWriteoffAmount);
                            if (paymentScheduleDetail.getInvoicePaymentSchedule() != null) {
                                // Remove invoice description related to the credit payments
                                final Invoice invoice = paymentScheduleDetail.getInvoicePaymentSchedule()
                                        .getInvoice();
                                invoiceDocNos.add(invoice.getDocumentNo());
                                final String invDesc = invoice.getDescription();
                                if (invDesc != null) {
                                    final String creditMsg = OBMessageUtils
                                            .messageBD("APRM_InvoiceDescUsedCredit");
                                    if (creditMsg != null) {
                                        StringBuffer newDesc = new StringBuffer();
                                        for (final String line : invDesc.split("\n")) {
                                            if (!line.startsWith(
                                                    creditMsg.substring(0, creditMsg.lastIndexOf("%s")))) {
                                                newDesc.append(line);
                                                if (!"".equals(line))
                                                    newDesc.append("\n");
                                            }
                                        }
                                        if (newDesc.length() > 255) {
                                            newDesc = newDesc.delete(251, newDesc.length());
                                            newDesc = newDesc.append("...\n");
                                        }
                                        invoice.setDescription(newDesc.toString());

                                    }
                                }
                                if (restorePaidAmounts) {
                                    FIN_AddPayment.updatePaymentScheduleAmounts(paymentDetail,
                                            paymentScheduleDetail.getInvoicePaymentSchedule(),
                                            psdAmount.negate(), psdWriteoffAmount.negate());
                                    paymentScheduleDetail.setInvoicePaid(false);
                                    OBDal.getInstance().save(paymentScheduleDetail);
                                    // BP SO_CreditUsed
                                    businessPartner = paymentScheduleDetail.getInvoicePaymentSchedule()
                                            .getInvoice().getBusinessPartner();
                                    Invoice invoiceForConversion = paymentScheduleDetail
                                            .getInvoicePaymentSchedule() != null
                                                    ? paymentScheduleDetail.getInvoicePaymentSchedule()
                                                            .getInvoice()
                                                    : null;
                                    paidAmount = BigDecimal.ZERO;
                                    if (!(businessPartner == null)) {
                                        final Currency fromCurrency = payment.getCurrency();
                                        if (businessPartner.getCurrency() == null) {
                                            String errorMSG = OBMessageUtils.messageBD("InitBPCurrencyLnk",
                                                    false);
                                            msg = String.format(errorMSG, businessPartner.getId(),
                                                    businessPartner.getName());
                                            throw new OBException(msg);
                                        }
                                        final Currency toCurrency = businessPartner.getCurrency();
                                        if (fromCurrency != null && toCurrency != null
                                                && !fromCurrency.getId().equals(toCurrency.getId())) {
                                            BigDecimal exchangeRate = BigDecimal.ZERO;
                                            // check at invoice document level
                                            List<ConversionRateDoc> conversionRateDocumentForInvoice = getConversionRateDocumentForInvoice(
                                                    invoiceForConversion);
                                            if (conversionRateDocumentForInvoice.size() > 0) {
                                                exchangeRate = conversionRateDocumentForInvoice.get(0)
                                                        .getRate();
                                            } else {
                                                // global
                                                exchangeRate = getConversionRate(
                                                        payment.getOrganization().getId(), fromCurrency.getId(),
                                                        toCurrency.getId(),
                                                        invoiceForConversion != null
                                                                ? invoiceForConversion.getInvoiceDate()
                                                                : payment.getPaymentDate());
                                            }
                                            if (exchangeRate == BigDecimal.ZERO) {
                                                msg = OBMessageUtils.messageBD("NoCurrencyConversion");
                                                throw new OBException(msg);
                                            }
                                            paidAmount = amount.multiply(exchangeRate);
                                        } else {
                                            paidAmount = amount;
                                        }
                                        if (isReceipt) {
                                            increaseCustomerCredit(businessPartner, paidAmount);
                                        } else {
                                            decreaseCustomerCredit(businessPartner, paidAmount);
                                        }
                                    }
                                }
                            }
                            if (paymentScheduleDetail.getOrderPaymentSchedule() != null && restorePaidAmounts) {
                                FIN_AddPayment.updatePaymentScheduleAmounts(paymentDetail,
                                        paymentScheduleDetail.getOrderPaymentSchedule(), psdAmount.negate(),
                                        psdWriteoffAmount.negate());
                            }
                            if (restorePaidAmounts) {
                                // when generating credit for a BP SO_CreditUsed is also updated
                                if (paymentScheduleDetail.getInvoicePaymentSchedule() == null
                                        && paymentScheduleDetail.getOrderPaymentSchedule() == null
                                        && paymentScheduleDetail.getPaymentDetails().getGLItem() == null
                                        && restorePaidAmounts && !paymentDetail.isRefund()) {
                                    // BP SO_CreditUsed
                                    if (isReceipt) {
                                        increaseCustomerCredit(businessPartner, amount);
                                    } else {
                                        decreaseCustomerCredit(businessPartner, amount);
                                    }
                                }
                            }
                        }

                        if (strAction.equals("R") || (strAction.equals("RE")
                                && paymentScheduleDetail.getInvoicePaymentSchedule() == null
                                && paymentScheduleDetail.getOrderPaymentSchedule() == null
                                && paymentScheduleDetail.getPaymentDetails().getGLItem() == null)) {
                            FIN_AddPayment.mergePaymentScheduleDetails(paymentScheduleDetail);
                            removedPDS.add(paymentScheduleDetail);
                        }

                    }
                    paymentDetail.getFINPaymentScheduleDetailList().removeAll(removedPDS);
                    if (strAction.equals("R")) {
                        OBDal.getInstance().getSession().refresh(paymentDetail);
                    }
                    // If there is any schedule detail with amount zero, those are deleted
                    // Besides it removes the payment proposal lines linked to the PSD when
                    // a) we are removing the PSD and
                    // b) if we are reactivating a payment (deleting lines only) and we don't come from
                    // payment proposal reactivation process
                    for (FIN_PaymentScheduleDetail psd : removedPDS) {
                        int proposalLinesRemoved = 0;
                        if (BigDecimal.ZERO.compareTo(psd.getAmount()) == 0
                                && BigDecimal.ZERO.compareTo(psd.getWriteoffAmount()) == 0) {
                            paymentDetail.getFINPaymentScheduleDetailList().remove(psd);
                            OBDal.getInstance().getSession().refresh(paymentDetail);
                            if (psd.getInvoicePaymentSchedule() != null) {
                                psd.getInvoicePaymentSchedule()
                                        .getFINPaymentScheduleDetailInvoicePaymentScheduleList().remove(psd);
                            }
                            if (psd.getOrderPaymentSchedule() != null) {
                                psd.getOrderPaymentSchedule()
                                        .getFINPaymentScheduleDetailOrderPaymentScheduleList().remove(psd);
                            }

                            // Before deleting the PSD, we must delete any payment proposal line linked to it
                            proposalLinesRemoved = removePaymentProposalLines(psd);

                            OBDal.getInstance().remove(psd);
                        }

                        // Delete any payment proposal line linked to the PSD if we are reactivating a payment
                        // (deleting lines only), we haven't removed it in a previous step and we don't come
                        // from payment proposal reactivation process
                        if (strAction.equals("R") && proposalLinesRemoved == 0
                                && !StringUtils.equals(comingFrom,
                                        FIN_PaymentProposalProcess.COMINGFROM_PAYMENTPROPOSALPROCESS)) {
                            removePaymentProposalLines(psd);
                        }
                    }
                    if (paymentDetail.getFINPaymentScheduleDetailList().size() == 0) {
                        removedPD.add(paymentDetail);
                        removedPDIds.add(paymentDetail.getId());
                    }
                    OBDal.getInstance().save(paymentDetail);
                }
                for (String pdToRm : removedPDIds) {
                    OBDal.getInstance().remove(OBDal.getInstance().get(FIN_PaymentDetail.class, pdToRm));
                }
                payment.getFINPaymentDetailList().removeAll(removedPD);
                if (strAction.equals("R")) {
                    payment.getCurrencyConversionRateDocList().removeAll(conversionRates);
                    payment.setFinancialTransactionConvertRate(BigDecimal.ZERO);
                }
                OBDal.getInstance().save(payment);

                if (payment.getGeneratedCredit().compareTo(BigDecimal.ZERO) == 0
                        && payment.getUsedCredit().compareTo(BigDecimal.ZERO) != 0) {
                    undoUsedCredit(payment, invoiceDocNos);
                }

                List<FIN_Payment> creditPayments = new ArrayList<FIN_Payment>();
                for (final FIN_Payment_Credit pc : payment.getFINPaymentCreditList()) {
                    creditPayments.add(pc.getCreditPaymentUsed());
                }
                for (final FIN_Payment creditPayment : creditPayments) {
                    // Update Description
                    final String payDesc = creditPayment.getDescription();
                    if (payDesc != null) {
                        final String invoiceDocNoMsg = OBMessageUtils.messageBD("APRM_CreditUsedinInvoice");
                        if (invoiceDocNoMsg != null) {
                            final StringBuffer newDesc = new StringBuffer();
                            for (final String line : payDesc.split("\n")) {
                                boolean include = true;
                                if (line.startsWith(
                                        invoiceDocNoMsg.substring(0, invoiceDocNoMsg.lastIndexOf("%s")))) {
                                    for (final String docNo : invoiceDocNos) {
                                        if (line.indexOf(docNo) > 0) {
                                            include = false;
                                            break;
                                        }
                                    }
                                }
                                if (include) {
                                    newDesc.append(line);
                                    if (!"".equals(line))
                                        newDesc.append("\n");
                                }
                            }
                            // Truncate Description to keep length as 255
                            creditPayment.setDescription(
                                    newDesc.toString().length() > 255 ? newDesc.toString().substring(0, 255)
                                            : newDesc.toString());
                        }
                    }
                }

                payment.getFINPaymentCreditList().clear();
                if (payment.isReceipt() || strAction.equals("R")) {
                    payment.setGeneratedCredit(BigDecimal.ZERO);
                }
                if (strAction.equals("R")) {
                    payment.setUsedCredit(BigDecimal.ZERO);
                }
            } finally {
                OBDal.getInstance().flush();
                OBContext.restorePreviousMode();
            }

        } else if (strAction.equals("V")) {
            // Void
            OBContext.setAdminMode();
            try {
                if (payment.isProcessed()) {
                    // Already Posted Document
                    if ("Y".equals(payment.getPosted())) {
                        msg = OBMessageUtils.messageBD("PostedDocument: " + payment.getDocumentNo());
                        throw new OBException(msg);
                    }
                    // Transaction exists
                    if (hasTransaction(payment)) {
                        msg = OBMessageUtils.messageBD("APRM_TransactionExists");
                        throw new OBException(msg);
                    }
                    // Payment with generated credit already used on other payments.
                    if (payment.getGeneratedCredit().compareTo(BigDecimal.ZERO) == 1
                            && payment.getUsedCredit().compareTo(BigDecimal.ZERO) == 1) {
                        msg = OBMessageUtils.messageBD("APRM_PaymentGeneratedCreditIsUsed");
                        throw new OBException(msg);
                    }
                    // Payment not in Awaiting Execution
                    boolean restorePaidAmounts = (FIN_Utility
                            .seqnumberpaymentstatus(payment.getStatus())) < (FIN_Utility
                                    .seqnumberpaymentstatus(FIN_Utility.invoicePaymentStatus(payment)));
                    if (!restorePaidAmounts) {
                        msg = OBMessageUtils.messageBD("APRM_PaymentNotRPAE_NotVoid");
                        throw new OBException(msg);
                    }

                    /*
                     * Void the payment
                     */
                    payment.setStatus("RPVOID");

                    /*
                     * Cancel all payment schedule details related to the payment
                     */
                    final List<FIN_PaymentScheduleDetail> removedPDS = new ArrayList<FIN_PaymentScheduleDetail>();
                    Set<String> invoiceDocNos = new HashSet<String>();
                    for (final FIN_PaymentDetail paymentDetail : payment.getFINPaymentDetailList()) {
                        for (final FIN_PaymentScheduleDetail paymentScheduleDetail : paymentDetail
                                .getFINPaymentScheduleDetailList()) {
                            Boolean invoicePaidold = paymentScheduleDetail.isInvoicePaid();
                            if (invoicePaidold | paymentScheduleDetail.getInvoicePaymentSchedule() == null) {
                                paymentScheduleDetail.setInvoicePaid(false);
                            }
                            BigDecimal outStandingAmt = BigDecimal.ZERO;

                            if (paymentScheduleDetail.getInvoicePaymentSchedule() != null) {
                                // Related to invoices
                                for (final FIN_PaymentScheduleDetail invScheDetail : paymentScheduleDetail
                                        .getInvoicePaymentSchedule()
                                        .getFINPaymentScheduleDetailInvoicePaymentScheduleList()) {
                                    if (invScheDetail.isCanceled()) {
                                        continue;
                                    }
                                    if (invScheDetail.getPaymentDetails() == null) {
                                        outStandingAmt = outStandingAmt.add(invScheDetail.getAmount())
                                                .add(invScheDetail.getWriteoffAmount());
                                        removedPDS.add(invScheDetail);
                                    } else if (invScheDetail.equals(paymentScheduleDetail)) {
                                        outStandingAmt = outStandingAmt.add(invScheDetail.getAmount())
                                                .add(invScheDetail.getWriteoffAmount());
                                        paymentScheduleDetail.setCanceled(true);
                                    }
                                    invoiceDocNos.add(paymentScheduleDetail.getInvoicePaymentSchedule()
                                            .getInvoice().getDocumentNo());
                                }
                                // Create merged Payment Schedule Detail with the pending to be paid amount
                                if (outStandingAmt.compareTo(BigDecimal.ZERO) != 0) {
                                    final FIN_PaymentScheduleDetail mergedScheduleDetail = dao
                                            .getNewPaymentScheduleDetail(payment.getOrganization(),
                                                    outStandingAmt);
                                    mergedScheduleDetail.setInvoicePaymentSchedule(
                                            paymentScheduleDetail.getInvoicePaymentSchedule());
                                    mergedScheduleDetail.setOrderPaymentSchedule(
                                            paymentScheduleDetail.getOrderPaymentSchedule());
                                    OBDal.getInstance().save(mergedScheduleDetail);
                                }
                            } else if (paymentScheduleDetail.getOrderPaymentSchedule() != null) {
                                // Related to orders
                                for (final FIN_PaymentScheduleDetail ordScheDetail : paymentScheduleDetail
                                        .getOrderPaymentSchedule()
                                        .getFINPaymentScheduleDetailOrderPaymentScheduleList()) {
                                    if (ordScheDetail.isCanceled()) {
                                        continue;
                                    }
                                    if (ordScheDetail.getPaymentDetails() == null) {
                                        outStandingAmt = outStandingAmt.add(ordScheDetail.getAmount())
                                                .add(ordScheDetail.getWriteoffAmount());
                                        removedPDS.add(ordScheDetail);
                                    } else if (ordScheDetail.equals(paymentScheduleDetail)) {
                                        outStandingAmt = outStandingAmt.add(ordScheDetail.getAmount())
                                                .add(ordScheDetail.getWriteoffAmount());
                                        paymentScheduleDetail.setCanceled(true);
                                    }
                                }
                                // Create merged Payment Schedule Detail with the pending to be paid amount
                                if (outStandingAmt.compareTo(BigDecimal.ZERO) != 0) {
                                    final FIN_PaymentScheduleDetail mergedScheduleDetail = dao
                                            .getNewPaymentScheduleDetail(payment.getOrganization(),
                                                    outStandingAmt);
                                    mergedScheduleDetail.setOrderPaymentSchedule(
                                            paymentScheduleDetail.getOrderPaymentSchedule());
                                    OBDal.getInstance().save(mergedScheduleDetail);
                                }
                            } else if (paymentDetail.getGLItem() != null) {
                                paymentScheduleDetail.setCanceled(true);
                            } else if (paymentScheduleDetail.getOrderPaymentSchedule() == null
                                    && paymentScheduleDetail.getInvoicePaymentSchedule() == null) {
                                // Credit payment
                                payment.setGeneratedCredit(payment.getGeneratedCredit()
                                        .subtract(paymentScheduleDetail.getAmount()));
                                removedPDS.add(paymentScheduleDetail);
                            }

                            OBDal.getInstance().save(payment);
                            OBDal.getInstance().flush();
                        }
                        paymentDetail.getFINPaymentScheduleDetailList().removeAll(removedPDS);
                        for (FIN_PaymentScheduleDetail removedPD : removedPDS) {
                            if (removedPD.getOrderPaymentSchedule() != null) {
                                removedPD.getOrderPaymentSchedule()
                                        .getFINPaymentScheduleDetailOrderPaymentScheduleList()
                                        .remove(removedPD);
                                OBDal.getInstance().save(removedPD.getOrderPaymentSchedule());
                            }
                            if (removedPD.getInvoicePaymentSchedule() != null) {
                                removedPD.getInvoicePaymentSchedule()
                                        .getFINPaymentScheduleDetailInvoicePaymentScheduleList()
                                        .remove(removedPD);
                                OBDal.getInstance().save(removedPD.getInvoicePaymentSchedule());
                            }
                            OBDal.getInstance().remove(removedPD);
                        }
                        OBDal.getInstance().flush();
                        removedPDS.clear();

                    }
                    if (payment.getGeneratedCredit().compareTo(BigDecimal.ZERO) == 0
                            && payment.getUsedCredit().compareTo(BigDecimal.ZERO) == 1) {
                        undoUsedCredit(payment, invoiceDocNos);
                    }
                    payment.getFINPaymentCreditList().clear();
                    payment.setUsedCredit(BigDecimal.ZERO);
                }
                OBDal.getInstance().flush();
            } finally {
                OBContext.restorePreviousMode();
            }
        }
    } catch (final Exception e) {
        log4j.error(e.getMessage());
        msg = OBMessageUtils.translateError(FIN_Utility.getExceptionMessage(e)).getMessage();
        throw new OBException(msg);
    }
}

From source file:org.openbravo.common.actionhandler.SetNewBPCurrency.java

@Override
protected JSONObject doExecute(Map<String, Object> parameters, String content) {

    JSONObject jsonRequest = null;//from ww w .  ja v  a2s.com
    OBContext.setAdminMode(true);
    try {
        jsonRequest = new JSONObject(content);
        JSONObject params = jsonRequest.getJSONObject("_params");
        final String strOrgId = jsonRequest.getString("inpadOrgId");
        final String strFromCurrencyId = jsonRequest.getString("inpbpCurrencyId");
        final String strToCurrencyId = params.getString("C_Currency_ID");
        final String strRate = params.getString("Rate");
        final String strAmount = params.getString("Foreign_Amount");
        final boolean strSetAmount = params.getBoolean("Amount");
        final boolean strUseDefaultConversion = params.getBoolean("Default_Conversion_Rate");
        final String strBpartnerId = jsonRequest.getString("C_BPartner_ID");
        final String glItemId = params.getString("c_glitem_id");
        BigDecimal creditUsed = BigDecimal.ZERO;
        BigDecimal rate = BigDecimal.ZERO;
        Double amount = new Double(0);
        if (strSetAmount && !"null".equals(strAmount)) {
            amount = Double.parseDouble(strAmount);
        }

        if (strUseDefaultConversion && !strSetAmount) {
            rate = getConversionRate(strOrgId, strFromCurrencyId, strToCurrencyId);
            if (rate == BigDecimal.ZERO && !strFromCurrencyId.equals(strToCurrencyId)) {
                try {
                    jsonRequest = new JSONObject();
                    String message = OBMessageUtils.messageBD("NoCurrencyConversion");
                    JSONObject errorMessage = new JSONObject();
                    errorMessage.put("severity", "error");
                    errorMessage.put("text", message);
                    jsonRequest.put("message", errorMessage);
                } catch (Exception e) {
                    OBDal.getInstance().rollbackAndClose();
                    log.error(e.getMessage(), e);
                }
                return jsonRequest;
            }
        } else {
            rate = "null".equals(strRate) ? BigDecimal.ZERO : BigDecimal.valueOf(Double.parseDouble(strRate));
        }
        BusinessPartner businessPartner = OBDal.getInstance().get(BusinessPartner.class, strBpartnerId);
        creditUsed = businessPartner.getCreditUsed();

        ScrollableResults scroll = null;
        GLItem glItem = OBDal.getInstance().get(GLItem.class, glItemId);
        Currency currency = OBDal.getInstance().get(Currency.class, strToCurrencyId);
        BigDecimal creditAmount = BigDecimal.ZERO;
        BigDecimal creditRate = BigDecimal.ONE;

        // Convert available credit automatically
        if (!StringUtils.equals(strFromCurrencyId, strToCurrencyId) && !StringUtils.isEmpty(glItemId)
                && !StringUtils.equals(glItemId, "null")) {

            // Get the rate
            if (!strSetAmount) {
                creditRate = rate;
            } else if (creditUsed.compareTo(BigDecimal.ZERO) != 0) {
                creditRate = BigDecimal.valueOf(amount).divide(creditUsed,
                        FIN_Utility.getConversionRatePrecision(RequestContext.get().getVariablesSecureApp()),
                        RoundingMode.HALF_UP);
            }

            // Loop through all payment documents which generate credit
            scroll = FinancialUtils.getPaymentsWithCredit(businessPartner.getId(), strFromCurrencyId);
            int i = 0;
            try {
                while (scroll.next()) {
                    final String paymentCreditId = (String) scroll.get()[0];
                    final FIN_Payment paymentCredit = OBDal.getInstance().get(FIN_Payment.class,
                            paymentCreditId);
                    creditAmount = paymentCredit.getGeneratedCredit().subtract(paymentCredit.getUsedCredit());

                    // Create a payment to consume the credit with a glitem
                    FIN_Payment payment1 = (FIN_Payment) DalUtil.copy(paymentCredit, false);
                    payment1.setPaymentDate(new Date());
                    payment1.setAmount(creditAmount);
                    payment1.setDocumentNo(FIN_Utility.getDocumentNo(payment1.getOrganization(),
                            payment1.getDocumentType().getDocumentCategory(), "DocumentNo_FIN_Payment"));
                    payment1.setProcessed(false);
                    payment1.setPosted("N");
                    payment1.setDescription(null);
                    payment1.setGeneratedCredit(BigDecimal.ZERO);
                    payment1.setUsedCredit(BigDecimal.ZERO);

                    // Create a payment detail to consume the credit with a glitem
                    FIN_PaymentDetail paymentDetail1 = OBProvider.getInstance().get(FIN_PaymentDetail.class);
                    paymentDetail1.setClient(paymentCredit.getClient());
                    paymentDetail1.setOrganization(paymentCredit.getOrganization());
                    paymentDetail1.setFinPayment(payment1);
                    paymentDetail1.setAmount(creditAmount);
                    paymentDetail1.setRefund(false);
                    paymentDetail1.setGLItem(glItem);
                    paymentDetail1.setPrepayment(false);

                    // Create a payment schedule detail to consume the credit with a glitem
                    FIN_PaymentScheduleDetail paymentScheduleDetail1 = OBProvider.getInstance()
                            .get(FIN_PaymentScheduleDetail.class);
                    paymentScheduleDetail1.setClient(paymentCredit.getClient());
                    paymentScheduleDetail1.setOrganization(paymentCredit.getOrganization());
                    paymentScheduleDetail1.setPaymentDetails(paymentDetail1);
                    paymentScheduleDetail1.setAmount(creditAmount);

                    // Process the payment
                    paymentDetail1.getFINPaymentScheduleDetailList().add(paymentScheduleDetail1);
                    payment1.getFINPaymentDetailList().add(paymentDetail1);
                    OBDal.getInstance().save(payment1);
                    OBDal.getInstance().save(paymentDetail1);
                    OBDal.getInstance().save(paymentScheduleDetail1);
                    FIN_PaymentProcess.doProcessPayment(payment1, "D", false, null, null);

                    // Modify description of original credit payment
                    String paymentCreditDesc = paymentCredit.getDescription() + "\n" + String.format(
                            OBMessageUtils.messageBD("APRM_CreditUsedPayment"), payment1.getDocumentNo());
                    paymentCredit.setDescription((paymentCreditDesc.length() > 255)
                            ? paymentCreditDesc.substring(0, 251).concat("...").toString()
                            : paymentCreditDesc.toString());

                    // Create a payment to refund the credit
                    FIN_Payment payment2 = (FIN_Payment) DalUtil.copy(paymentCredit, false);
                    payment2.setPaymentDate(new Date());
                    payment2.setAmount(creditAmount.negate());
                    payment2.setDocumentNo(FIN_Utility.getDocumentNo(payment2.getOrganization(),
                            payment2.getDocumentType().getDocumentCategory(), "DocumentNo_FIN_Payment"));
                    payment2.setProcessed(false);
                    payment2.setPosted("N");
                    payment2.setDescription(
                            OBMessageUtils.messageBD("APRM_RefundPayment") + ": " + payment1.getDocumentNo());
                    payment2.setGeneratedCredit(BigDecimal.ZERO);
                    payment2.setUsedCredit(creditAmount);

                    // Create a payment credit to refund the credit
                    FIN_Payment_Credit paymentCredit2 = OBProvider.getInstance().get(FIN_Payment_Credit.class);
                    paymentCredit2.setClient(paymentCredit.getClient());
                    paymentCredit2.setOrganization(paymentCredit.getOrganization());
                    paymentCredit2.setPayment(payment2);
                    paymentCredit2.setCreditPaymentUsed(paymentCredit);
                    paymentCredit2.setAmount(creditAmount);
                    paymentCredit2.setCurrency(paymentCredit.getCurrency());

                    // Create a payment detail to refund the credit
                    FIN_PaymentDetail paymentDetail2 = OBProvider.getInstance().get(FIN_PaymentDetail.class);
                    paymentDetail2.setClient(paymentCredit.getClient());
                    paymentDetail2.setOrganization(paymentCredit.getOrganization());
                    paymentDetail2.setFinPayment(payment2);
                    paymentDetail2.setAmount(creditAmount.negate());
                    paymentDetail2.setRefund(true);
                    paymentDetail2.setPrepayment(true);

                    // Create a payment schedule detail to refund the credit
                    FIN_PaymentScheduleDetail paymentScheduleDetail2 = OBProvider.getInstance()
                            .get(FIN_PaymentScheduleDetail.class);
                    paymentScheduleDetail2.setClient(paymentCredit.getClient());
                    paymentScheduleDetail2.setOrganization(paymentCredit.getOrganization());
                    paymentScheduleDetail2.setPaymentDetails(paymentDetail2);
                    paymentScheduleDetail2.setAmount(creditAmount.negate());

                    // Process the payment
                    paymentDetail2.getFINPaymentScheduleDetailList().add(paymentScheduleDetail2);
                    payment2.getFINPaymentDetailList().add(paymentDetail2);
                    payment2.getFINPaymentCreditList().add(paymentCredit2);
                    paymentCredit.setUsedCredit(creditAmount);
                    OBDal.getInstance().save(paymentCredit);
                    OBDal.getInstance().save(payment2);
                    OBDal.getInstance().save(paymentCredit2);
                    OBDal.getInstance().save(paymentDetail2);
                    OBDal.getInstance().save(paymentScheduleDetail2);
                    FIN_PaymentProcess.doProcessPayment(payment2, "D", false, null, null);

                    i++;
                    if (i % 100 == 0) {
                        OBDal.getInstance().flush();
                        OBDal.getInstance().getSession().clear();
                    }
                }

                // Set the new currency
                businessPartner.setCurrency(currency);

                // Loop through all payment documents which generate credit
                scroll.beforeFirst();
                i = 0;
                while (scroll.next()) {
                    final String paymentCreditId = (String) scroll.get()[0];
                    final FIN_Payment paymentCredit = OBDal.getInstance().get(FIN_Payment.class,
                            paymentCreditId);

                    // Create a payment to create the credit with a glitem
                    FIN_Payment payment3 = (FIN_Payment) DalUtil.copy(paymentCredit, false);
                    payment3.setPaymentDate(new Date());
                    payment3.setCurrency(currency);
                    payment3.setAmount(BigDecimal.ZERO);
                    payment3.setDocumentNo(FIN_Utility.getDocumentNo(payment3.getOrganization(),
                            payment3.getDocumentType().getDocumentCategory(), "DocumentNo_FIN_Payment"));
                    payment3.setProcessed(false);
                    payment3.setPosted("N");
                    payment3.setDescription(null);
                    final BigDecimal generatedCredit = creditAmount.multiply(creditRate)
                            .setScale(currency.getStandardPrecision().intValue(), RoundingMode.HALF_UP);
                    payment3.setGeneratedCredit(generatedCredit);
                    payment3.setUsedCredit(BigDecimal.ZERO);

                    // Create a payment detail to create the credit with a glitem
                    FIN_PaymentDetail paymentDetail3 = OBProvider.getInstance().get(FIN_PaymentDetail.class);
                    paymentDetail3.setClient(paymentCredit.getClient());
                    paymentDetail3.setOrganization(paymentCredit.getOrganization());
                    paymentDetail3.setFinPayment(payment3);
                    paymentDetail3.setAmount(generatedCredit);
                    paymentDetail3.setRefund(false);
                    paymentDetail3.setPrepayment(true);

                    // Create a payment detail to create the credit with a glitem
                    FIN_PaymentDetail paymentDetail4 = OBProvider.getInstance().get(FIN_PaymentDetail.class);
                    paymentDetail4.setClient(paymentCredit.getClient());
                    paymentDetail4.setOrganization(paymentCredit.getOrganization());
                    paymentDetail4.setFinPayment(payment3);
                    paymentDetail4.setAmount(generatedCredit.negate());
                    paymentDetail4.setGLItem(glItem);
                    paymentDetail4.setRefund(false);
                    paymentDetail4.setPrepayment(false);

                    // Create a payment schedule detail to create the credit with a glitem
                    FIN_PaymentScheduleDetail paymentScheduleDetail3 = OBProvider.getInstance()
                            .get(FIN_PaymentScheduleDetail.class);
                    paymentScheduleDetail3.setClient(paymentCredit.getClient());
                    paymentScheduleDetail3.setOrganization(paymentCredit.getOrganization());
                    paymentScheduleDetail3.setPaymentDetails(paymentDetail3);
                    paymentScheduleDetail3.setAmount(generatedCredit);

                    // Create a payment schedule detail to create the credit with a glitem
                    FIN_PaymentScheduleDetail paymentScheduleDetail4 = OBProvider.getInstance()
                            .get(FIN_PaymentScheduleDetail.class);
                    paymentScheduleDetail4.setClient(paymentCredit.getClient());
                    paymentScheduleDetail4.setOrganization(paymentCredit.getOrganization());
                    paymentScheduleDetail4.setPaymentDetails(paymentDetail4);
                    paymentScheduleDetail4.setAmount(generatedCredit.negate());

                    // Process the payment
                    paymentDetail3.getFINPaymentScheduleDetailList().add(paymentScheduleDetail3);
                    paymentDetail4.getFINPaymentScheduleDetailList().add(paymentScheduleDetail4);
                    payment3.getFINPaymentDetailList().add(paymentDetail3);
                    payment3.getFINPaymentDetailList().add(paymentDetail4);
                    OBDal.getInstance().save(payment3);
                    OBDal.getInstance().save(paymentDetail3);
                    OBDal.getInstance().save(paymentDetail4);
                    OBDal.getInstance().save(paymentScheduleDetail3);
                    OBDal.getInstance().save(paymentScheduleDetail4);
                    OBDal.getInstance().save(paymentCredit);
                    FIN_PaymentProcess.doProcessPayment(payment3, "D", false, null, null);

                    i++;
                    if (i % 100 == 0) {
                        OBDal.getInstance().flush();
                        OBDal.getInstance().getSession().clear();
                    }
                }
            } finally {
                scroll.close();
            }
        }

        if (strSetAmount && creditUsed.compareTo(BigDecimal.valueOf(amount)) != 0) {
            businessPartner.setCreditUsed(BigDecimal.valueOf(amount));
        }
        if (!strToCurrencyId.equals(strFromCurrencyId) && strToCurrencyId != null
                && !"null".equals(strToCurrencyId)) {
            businessPartner.setCurrency(OBDal.getInstance().get(Currency.class, strToCurrencyId));
            if (rate.compareTo(BigDecimal.ZERO) != 0 && creditUsed.compareTo(BigDecimal.ZERO) != 0
                    && !strSetAmount) {
                businessPartner.setCreditUsed(creditUsed.multiply(rate));
            }
        }

        String messageText = OBMessageUtils.messageBD("CurrencyUpdated");
        JSONObject msg = new JSONObject();
        msg.put("severity", "success");
        msg.put("text", OBMessageUtils.parseTranslation(messageText));
        jsonRequest.put("message", msg);

    } catch (Exception e) {
        OBDal.getInstance().rollbackAndClose();
        log.error("Error in set new currency Action Handler", e);

        try {
            jsonRequest = new JSONObject();
            Throwable ex = DbUtility.getUnderlyingSQLException(e);
            String message = OBMessageUtils.translateError(ex.getMessage()).getMessage();
            JSONObject errorMessage = new JSONObject();
            errorMessage.put("severity", "error");
            errorMessage.put("text", message);
            jsonRequest.put("message", errorMessage);
        } catch (Exception e2) {
            log.error(e.getMessage(), e2);
            // do nothing, give up
        }
    } finally {
        OBContext.restorePreviousMode();
    }
    return jsonRequest;
}

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

/**
 * Create Facts (the accounting logic) for MMS, MMR.
 * //from   ww  w  .  jav a 2 s .  co m
 * <pre>
 *  Shipment
 *      CoGS            DR
 *      Inventory               CR
 *  Shipment of Project Issue
 *      CoGS            DR
 *      Project                 CR
 *  Receipt
 *      Inventory       DR
 *      NotInvoicedReceipt      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 (StringUtils.isEmpty(strClassname)) {
        strClassname = AcctServerData.selectTemplate(conn, as.m_C_AcctSchema_ID, AD_Table_ID);
    } else {
        try {
            DocCostAdjustmentTemplate newTemplate = (DocCostAdjustmentTemplate) Class.forName(strClassname)
                    .newInstance();
            return newTemplate.createFact(this, as, conn, con, vars);
        } catch (Exception e) {
            log4j.error("Error while creating new instance for DocCostAdjustmentTemplate - ", e);
        }
    }
    C_Currency_ID = as.getC_Currency_ID();
    // create Fact Header
    Fact fact = new Fact(this, as, Fact.POST_Actual);
    String Fact_Acct_Group_ID = SequenceIdData.getUUID();
    String amtDebit = "0";
    String amtCredit = "0";

    // Lines
    for (int i = 0; p_lines != null && i < p_lines.length; i++) {
        DocLine_CostAdjustment line = (DocLine_CostAdjustment) p_lines[i];
        String transactionType = line.getTransactionType();

        BigDecimal amount = new BigDecimal(line.getAmount());
        ProductInfo p = new ProductInfo(line.m_M_Product_ID, conn);

        log4jDocCostAdjustment.debug("antes del creteline, line.getAmount(): " + line.getAmount()
                + " - TransactionType: " + transactionType);
        if (transactionType.equals(DocLine_CostAdjustment.TRXTYPE_SHIPMENT)) {
            // Cogs DR
            // Inventory Asset CR
            log4jDocCostAdjustment.debug("********** DocCostAdjustment - factAcct - account - "
                    + p.getAccount(ProductInfo.ACCTTYPE_P_Cogs, as, conn).C_ValidCombination_ID);

            if (line.isTransactionNegative()) {
                amtDebit = "";
                amtCredit = amount.toPlainString();
            } else {
                amtDebit = amount.toPlainString();
                amtCredit = "";
            }
            fact.createLine(line, p.getAccount(ProductInfo.ACCTTYPE_P_Cogs, as, conn), line.m_C_Currency_ID,
                    amtDebit, amtCredit, Fact_Acct_Group_ID, nextSeqNo(SeqNo), DocumentType, line.m_DateAcct,
                    null, conn);
            fact.createLine(line, p.getAccount(ProductInfo.ACCTTYPE_P_Asset, as, conn), line.m_C_Currency_ID,
                    amtCredit, amtDebit, Fact_Acct_Group_ID, nextSeqNo(SeqNo), DocumentType, line.m_DateAcct,
                    null, conn);
        } else if (transactionType.equals(DocLine_CostAdjustment.TRXTYPE_RECEIPT)) {
            Account acct = null;
            // Inventory Asset DR
            if (line.getIsSource() && ("PDC").equals(line.getSourceProcess())) { // Price Diff
                // Correction
                // Invoice Price Variance CR
                acct = p.getAccount(ProductInfo.ACCTTYPE_P_IPV, as, conn);
            } else if (line.getIsSource() && ("LC").equals(line.getSourceProcess())) {
                throw new IllegalStateException(OBMessageUtils.messageBD("LCNotAccounting"));
            } else {
                // Product Exp CR
                acct = getAccountByWarehouse(AcctServer.ACCTTYPE_InvDifferences, as, line.getWarehouseId(),
                        conn);
            }
            log4jDocCostAdjustment.debug("********** DocCostAdjustment - factAcct - account - "
                    + p.getAccount(ProductInfo.ACCTTYPE_P_Expense, as, conn).C_ValidCombination_ID);
            if (line.isTransactionNegative()) {
                amtDebit = amount.toPlainString();
                amtCredit = "";
            } else {
                amtDebit = "";
                amtCredit = amount.toPlainString();
            }
            fact.createLine(line, acct, line.m_C_Currency_ID, amtDebit, amtCredit, Fact_Acct_Group_ID,
                    nextSeqNo(SeqNo), DocumentType, line.m_DateAcct, null, conn);
            fact.createLine(line, p.getAccount(ProductInfo.ACCTTYPE_P_Asset, as, conn), line.m_C_Currency_ID,
                    amtCredit, amtDebit, Fact_Acct_Group_ID, nextSeqNo(SeqNo), DocumentType, line.m_DateAcct,
                    null, conn);
        } else if (transactionType.equals(DocLine_CostAdjustment.TRXTYPE_INVENTORY)) {
            // Inventory Asset DR
            // Inventory Adjustment CR
            log4jDocCostAdjustment.debug("********** DocCostAdjustment - factAcct - account - "
                    + getAccountByWarehouse(AcctServer.ACCTTYPE_InvDifferences, as, line.getWarehouseId(),
                            conn).C_ValidCombination_ID);
            if (line.isTransactionNegative()) {
                amtDebit = amount.toPlainString();
                amtCredit = "";
            } else {
                amtDebit = "";
                amtCredit = amount.toPlainString();
            }
            fact.createLine(line,
                    getAccountByWarehouse(AcctServer.ACCTTYPE_InvDifferences, as, line.getWarehouseId(), conn),
                    line.m_C_Currency_ID, amtDebit, amtCredit, Fact_Acct_Group_ID, nextSeqNo(SeqNo),
                    DocumentType, line.m_DateAcct, null, conn);
            fact.createLine(line, p.getAccount(ProductInfo.ACCTTYPE_P_Asset, as, conn), line.m_C_Currency_ID,
                    amtCredit, amtDebit, Fact_Acct_Group_ID, nextSeqNo(SeqNo), DocumentType, line.m_DateAcct,
                    null, conn);
        } else if (transactionType.equals(DocLine_CostAdjustment.TRXTYPE_INTERNALMOVEMENTFROM)) {
            // Inventory Asset DR
            // Inventory Adjustment CR
            M_Warehouse_ID = line.getWarehouseId();
            log4jDocCostAdjustment.debug("********** DocCostAdjustment - factAcct - account - "
                    + getAccountByWarehouse(AcctServer.ACCTTYPE_InvDifferences, as, line.getWarehouseId(),
                            conn).C_ValidCombination_ID);
            if (line.isTransactionNegative()) {
                amtDebit = amount.negate().toPlainString();
                amtCredit = "";
            } else {
                amtDebit = "";
                amtCredit = amount.negate().toPlainString();
            }
            fact.createLine(line, p.getAccount(ProductInfo.ACCTTYPE_P_Asset, as, conn), line.m_C_Currency_ID,
                    amtDebit, amtCredit, Fact_Acct_Group_ID, nextSeqNo(SeqNo), DocumentType, line.m_DateAcct,
                    null, conn);

            fact.createLine(line,
                    getAccountByWarehouse(AcctServer.ACCTTYPE_InvDifferences, as, line.getWarehouseId(), conn),
                    line.m_C_Currency_ID, amtCredit, amtDebit, Fact_Acct_Group_ID, nextSeqNo(SeqNo),
                    DocumentType, line.m_DateAcct, null, conn);
        } else if (transactionType.equals(DocLine_CostAdjustment.TRXTYPE_INTERNALMOVEMENTTO)) {
            // Inventory Asset DR
            // Inventory Adjustment CR
            M_Warehouse_ID = line.getWarehouseId();
            log4jDocCostAdjustment.debug("********** DocCostAdjustment - factAcct - account - "
                    + getAccountByWarehouse(AcctServer.ACCTTYPE_InvDifferences, as, line.getWarehouseId(),
                            conn).C_ValidCombination_ID);
            if (line.isTransactionNegative()) {
                amtDebit = amount.toPlainString();
                amtCredit = "";
            } else {
                amtDebit = "";
                amtCredit = amount.toPlainString();
            }
            fact.createLine(line,
                    getAccountByWarehouse(AcctServer.ACCTTYPE_InvDifferences, as, line.getWarehouseId(), conn),
                    line.m_C_Currency_ID, amtDebit, amtCredit, Fact_Acct_Group_ID, nextSeqNo(SeqNo),
                    DocumentType, line.m_DateAcct, null, conn);
            fact.createLine(line, p.getAccount(ProductInfo.ACCTTYPE_P_Asset, as, conn), line.m_C_Currency_ID,
                    amtCredit, amtDebit, Fact_Acct_Group_ID, nextSeqNo(SeqNo), DocumentType, line.m_DateAcct,
                    null, conn);
        } else if (transactionType.equals(DocLine_CostAdjustment.TRXTYPE_INTERNALCONSUMPTION)) {
            // Inventory Asset DR
            // Inventory Adjustment CR
            M_Warehouse_ID = line.getWarehouseId();
            log4jDocCostAdjustment.debug("********** DocCostAdjustment - factAcct - account - "
                    + getAccountByWarehouse(AcctServer.ACCTTYPE_InvDifferences, as, line.getWarehouseId(),
                            conn).C_ValidCombination_ID);
            if (line.isTransactionNegative()) {
                amtDebit = amount.toPlainString();
                amtCredit = "";
            } else {
                amtDebit = "";
                amtCredit = amount.toPlainString();
            }
            fact.createLine(line, p.getAccount(ProductInfo.ACCTTYPE_P_Asset, as, conn), line.m_C_Currency_ID,
                    amtDebit, amtCredit, Fact_Acct_Group_ID, nextSeqNo(SeqNo), DocumentType, line.m_DateAcct,
                    null, conn);

            fact.createLine(line,
                    getAccountByWarehouse(AcctServer.ACCTTYPE_InvDifferences, as, line.getWarehouseId(), conn),
                    line.m_C_Currency_ID, amtCredit, amtDebit, Fact_Acct_Group_ID, nextSeqNo(SeqNo),
                    DocumentType, line.m_DateAcct, null, conn);
        } else if (transactionType.equals(DocLine_CostAdjustment.TRXTYPE_BOM)) {
            // Inventory Asset DR
            // Inventory Adjustment CR
            M_Warehouse_ID = line.getWarehouseId();
            log4jDocCostAdjustment.debug("********** DocCostAdjustment - factAcct - account - "
                    + getAccountByWarehouse(AcctServer.ACCTTYPE_InvDifferences, as, line.getWarehouseId(),
                            conn).C_ValidCombination_ID);
            if (line.isTransactionNegative()) {
                amtDebit = amount.toPlainString();
                amtCredit = "";
            } else {
                amtDebit = "";
                amtCredit = amount.toPlainString();
            }
            fact.createLine(line,
                    getAccountByWarehouse(AcctServer.ACCTTYPE_InvDifferences, as, line.getWarehouseId(), conn),
                    line.m_C_Currency_ID, amtDebit, amtCredit, Fact_Acct_Group_ID, nextSeqNo(SeqNo),
                    DocumentType, line.m_DateAcct, null, conn);

            fact.createLine(line, p.getAccount(ProductInfo.ACCTTYPE_P_Asset, as, conn), line.m_C_Currency_ID,
                    amtCredit, amtDebit, Fact_Acct_Group_ID, nextSeqNo(SeqNo), DocumentType, line.m_DateAcct,
                    null, conn);
        } else if (transactionType.equals(DocLine_CostAdjustment.TRXTYPE_MANUFACTURING)) {
            // Inventory Asset DR
            // Inventory Adjustment CR
            M_Warehouse_ID = line.getWarehouseId();
            log4jDocCostAdjustment.debug("********** DocCostAdjustment - factAcct - account - "
                    + getAccountByWarehouse(AcctServer.ACCTTYPE_InvDifferences, as, line.getWarehouseId(),
                            conn).C_ValidCombination_ID);
            if (line.isTransactionNegative()) {
                amtDebit = amount.toPlainString();
                amtCredit = "";
            } else {
                amtDebit = "";
                amtCredit = amount.toPlainString();
            }
            fact.createLine(line,
                    getAccountByWarehouse(AcctServer.ACCTTYPE_InvDifferences, as, line.getWarehouseId(), conn),
                    line.m_C_Currency_ID, amtDebit, amtCredit, Fact_Acct_Group_ID, nextSeqNo(SeqNo),
                    DocumentType, line.m_DateAcct, null, conn);

            fact.createLine(line, p.getAccount(ProductInfo.ACCTTYPE_P_Asset, as, conn), line.m_C_Currency_ID,
                    amtCredit, amtDebit, Fact_Acct_Group_ID, nextSeqNo(SeqNo), DocumentType, line.m_DateAcct,
                    null, conn);
        }
    } // lines

    SeqNo = "0";
    return fact;
}

From source file:org.kuali.kpme.tklm.leave.summary.service.LeaveSummaryServiceImpl.java

private void assignApprovedValuesToRow(LeaveSummaryRow lsr, String accrualCategory,
        List<LeaveBlock> approvedLeaveBlocks, LeavePlan lp, LocalDate ytdEarnedEffectiveDate,
        LocalDate effectiveDate) {

    SortedMap<String, BigDecimal> yearlyAccrued = new TreeMap<String, BigDecimal>();
    SortedMap<String, BigDecimal> yearlyUsage = new TreeMap<String, BigDecimal>();
    BigDecimal accrualedBalance = BigDecimal.ZERO.setScale(2);
    BigDecimal approvedUsage = BigDecimal.ZERO.setScale(2);
    BigDecimal fmlaUsage = BigDecimal.ZERO.setScale(2);

    LocalDate cutOffDateToCheck = ytdEarnedEffectiveDate != null ? ytdEarnedEffectiveDate : effectiveDate;
    DateTime cutOffDate = HrServiceLocator.getLeavePlanService()
            .getFirstDayOfLeavePlan(lp.getLeavePlan(), cutOffDateToCheck).minus(1);

    if (CollectionUtils.isNotEmpty(approvedLeaveBlocks)) {
        // create it here so we don't need to get instance every loop iteration
        for (LeaveBlock aLeaveBlock : approvedLeaveBlocks) {
            // check if leave date is before the next calendar start.
            if (!aLeaveBlock.getLeaveBlockType().equals(LMConstants.LEAVE_BLOCK_TYPE.CARRY_OVER)
                    && aLeaveBlock.getLeaveDateTime().getMillis() < effectiveDate.toDate().getTime()) {
                if ((StringUtils.isBlank(accrualCategory)
                        && StringUtils.isBlank(aLeaveBlock.getAccrualCategory()))
                        || (StringUtils.isNotBlank(aLeaveBlock.getAccrualCategory())
                                && StringUtils.equals(aLeaveBlock.getAccrualCategory(), accrualCategory))) {
                    // disapproved/deferred leave blocks should not be calculated into the approved values
                    if (!(StringUtils.equals(HrConstants.REQUEST_STATUS.DISAPPROVED,
                            aLeaveBlock.getRequestStatus())
                            || StringUtils.equals(HrConstants.REQUEST_STATUS.DEFERRED,
                                    aLeaveBlock.getRequestStatus()))) {

                        String leveBlockType = aLeaveBlock.getLeaveBlockType();
                        EarnCodeContract ec = HrServiceLocator.getEarnCodeService()
                                .getEarnCode(aLeaveBlock.getEarnCode(), aLeaveBlock.getLeaveLocalDate());
                        boolean adjustmentYtd = ec != null
                                && StringUtils.equals(ec.getAccrualBalanceAction(),
                                        HrConstants.ACCRUAL_BALANCE_ACTION.ADJUSTMENT)
                                && LMConstants.ADJUSTMENT_YTD_EARNED_LEAVE_BLOCK_TYPES.contains(leveBlockType);

                        // YTD earned
                        if (LMConstants.YTD_EARNED_LEAVE_BLOCK_TYPES.contains(leveBlockType) || adjustmentYtd) {
                            if (aLeaveBlock.getLeaveLocalDate().toDate().getTime() <= cutOffDate.toDate()
                                    .getTime()) {
                                String yearKey = getYearKey(aLeaveBlock.getLeaveLocalDate(), lp);
                                BigDecimal co = yearlyAccrued.get(yearKey);
                                if (co == null) {
                                    co = BigDecimal.ZERO.setScale(2);
                                }/* www .  j a v  a2 s.com*/
                                co = co.add(aLeaveBlock.getLeaveAmount());
                                yearlyAccrued.put(yearKey, co);
                            } else if (aLeaveBlock.getLeaveDateTime().getMillis() < ytdEarnedEffectiveDate
                                    .toDate().getTime()) {
                                accrualedBalance = accrualedBalance.add(aLeaveBlock.getLeaveAmount());
                            }
                        }

                        // YTD usage
                        if (ec != null
                                && StringUtils.equals(ec.getAccrualBalanceAction(),
                                        HrConstants.ACCRUAL_BALANCE_ACTION.USAGE)
                                && LMConstants.USAGE_LEAVE_BLOCK_TYPES.contains(leveBlockType)) {
                            if (aLeaveBlock.getLeaveDateTime().getMillis() > cutOffDate.toDate().getTime()) {
                                approvedUsage = approvedUsage.add(aLeaveBlock.getLeaveAmount());
                                if (ec.getFmla().equals("Y")) {
                                    fmlaUsage = fmlaUsage.add(aLeaveBlock.getLeaveAmount());
                                }
                            } else {
                                //these usages are for previous years, to help figure out correct carry over values
                                String yearKey = getYearKey(aLeaveBlock.getLeaveLocalDate(), lp);
                                BigDecimal use = yearlyUsage.get(yearKey);
                                if (use == null) {
                                    use = BigDecimal.ZERO.setScale(2);
                                }
                                use = use.add(aLeaveBlock.getLeaveAmount());
                                yearlyUsage.put(yearKey, use);
                            }
                        }
                    }
                }
            } else {
                //we can actually use the carry over block!!

            }
        }
    }

    lsr.setPriorYearsTotalAccrued(yearlyAccrued);
    lsr.setPriorYearsUsage(yearlyUsage);
    lsr.setYtdAccruedBalance(accrualedBalance);
    lsr.setYtdApprovedUsage(approvedUsage.negate());
    lsr.setFmlaUsage(fmlaUsage.negate());

    //lsr.setLeaveBalance(lsr.getYtdAccruedBalance().add(approvedUsage));
}

From source file:com.turborep.turbotracker.banking.service.BankingServiceImpl.java

@SuppressWarnings("unchecked")
@Override//from w ww. ja  v  a  2 s.  c  o m
public PrintCheckBean printCheck(Motransaction theMotransaction, Integer checkNumber, Integer yearID,
        Integer periodID, String userName, Integer userID) throws BankingException {
    PrintCheckBean aPrintBean = new PrintCheckBean();
    Session aSession = itsSessionFactory.openSession();
    Transaction aTransaction = null;
    String deletetemCheck = null, billArrayQuery = null, rxAddressIDQuery = null, vendorPayBeanQuery = null;
    StringBuffer totalAmountQuery = null;
    Molinkage aMolinkage = new Molinkage();
    Integer moLinkageId = null;
    Integer moTransactionId = null;
    Integer moLinkageDetailID = null;
    Integer[] rxMasterID = null;
    ArrayList<Integer> rxMasterID1 = new ArrayList<Integer>();
    ArrayList<BigDecimal> creditAmtUsed = new ArrayList<BigDecimal>();
    BigDecimal[] totalAmount = new BigDecimal[0];
    BigDecimal[] totalAmount1 = null;
    BigDecimal balAmount = new BigDecimal(0);
    BigDecimal balcalculationAmount = new BigDecimal(0);
    MoAccount aMoaccount = new MoAccount();
    checkDate = theMotransaction.getTransactionDate();
    int i = 0;
    int j = 0;
    try {
        aTransaction = aSession.beginTransaction();
        aTransaction.begin();

        deletetemCheck = "DELETE FROM moVendorCheckTemp";
        aSession.createSQLQuery(deletetemCheck).executeUpdate();

        billArrayQuery = "select veBillID from veBillPay where moAccountId=" + theMotransaction.getMoAccountId()
                + " and userID =" + userID;
        Query aQuery = aSession.createSQLQuery(billArrayQuery);
        List<?> billIds = aQuery.list();
        billId = new Integer[aQuery.list().size()];
        for (i = 0; i < billIds.size(); i++)
            billId[i] = (Integer) billIds.get(i);
        String rxMasterList = "SELECT BillPayUniqueIDs.rxMasterID FROM (SELECT rxMasterID FROM (SELECT veBill.rxMasterID FROM veBill LEFT JOIN veBillPay ON veBill.veBillID = veBillPay.veBillID WHERE veBillPay.ApplyingAmount<>0 and veBillPay.moAccountId="
                + theMotransaction.getMoAccountId() + " and veBillPay.userID = " + userID
                + ") AS BillPayIDs GROUP BY rxMasterID) AS BillPayUniqueIDs "
                + "INNER JOIN rxMaster ON BillPayUniqueIDs.rxMasterID = rxMaster.rxMasterID ORDER BY Name;";
        Query aQuery1 = aSession.createSQLQuery(rxMasterList);
        itsLogger.info(aQuery1.toString());
        List<?> rxMasterLists = aQuery1.list();
        rxMasterID = new Integer[aQuery1.list().size()];
        for (i = 0; i < rxMasterLists.size(); i++) {
            rxMasterID[i] = (Integer) rxMasterLists.get(i);
        }

        int counting = 0;
        totalAmount1 = new BigDecimal[rxMasterID.length];
        for (i = 0; i < rxMasterID.length; i++) {

            totalAmountQuery = new StringBuffer(
                    "SELECT SUM(P.ApplyingAmount) AS CheckAmount FROM veBillPay AS P INNER JOIN veBill AS B ON P.veBillID = B.veBillID Where P.moAccountId="
                            + theMotransaction.getMoAccountId() + " and P.userID = " + userID
                            + " and (B.rxMasterID =").append(rxMasterID[i]).append(")");
            Query aQuery2 = aSession.createSQLQuery(totalAmountQuery.toString());
            List<?> totalList = aQuery2.list();
            for (j = 0; j < totalList.size(); j++) {
                if ((BigDecimal) totalList.get(j) != null) {
                    BigDecimal amt = (BigDecimal) totalList.get(j);

                    if (amt.signum() < 0) {
                        rxMasterID1.add(rxMasterID[i]);
                        creditAmtUsed.add((BigDecimal) totalList.get(j));
                    } else {
                        totalAmount1[counting] = (BigDecimal) totalList.get(j);
                        counting++;
                    }
                }
            }
        }

        for (int t = 0; t < rxMasterID1.size(); t++) {
            rxMasterID = (Integer[]) ArrayUtils.removeElement(rxMasterID, rxMasterID1.get(t));
            itsLogger.info("rxMasterID::" + rxMasterID1.get(t));
        }

        if (rxMasterID.length > 0) {
            //Get rxAddress Information from normal payment
            rxAddressID = new Integer[rxMasterID.length];
            for (i = 0; i < rxMasterID.length; i++) {
                rxAddressIDQuery = "SELECT rxAddressID FROM rxAddress WHERE rxMasterID= " + rxMasterID[i]
                        + " and IsRemitTo = 1";
                Query aQuery3 = aSession.createSQLQuery(rxAddressIDQuery);
                List<?> rxAddressList = aQuery3.list();

                if (rxAddressList.size() > 0) {
                    rxAddressID[i] = (Integer) rxAddressList.get(0);
                } else {
                    rxAddressIDQuery = "SELECT rxAddressID FROM rxAddress WHERE rxMasterID= " + rxMasterID[i]
                            + " limit 1";
                    aQuery3 = aSession.createSQLQuery(rxAddressIDQuery);
                    rxAddressList = aQuery3.list();
                    rxAddressID[i] = (Integer) rxAddressList.get(0);
                }

            }
        } else {
            //Get rxAddress Information from credit payment
            rxAddressID = new Integer[rxMasterID1.size()];
            for (i = 0; i < rxMasterID1.size(); i++) {
                rxAddressIDQuery = "SELECT rxAddressID FROM rxAddress WHERE rxMasterID= " + rxMasterID1.get(i)
                        + " limit 1";
                Query aQuery3 = aSession.createSQLQuery(rxAddressIDQuery);
                itsLogger.info("Query2 " + aQuery3.toString());
                List<?> rxAddressList = aQuery3.list();
                for (j = 0; j < rxAddressList.size(); j++) {
                    if ((Integer) rxAddressList.get(j) != null)
                        rxAddressID[i] = (Integer) rxAddressList.get(j);
                }
            }
        }

        aMolinkage.setDummyVal(true);
        moLinkageId = (Integer) aSession.save(aMolinkage);
        int chkno = 0;
        chkno = checkNumber;
        if (counting != 0) // Normal Payment 
        {
            totalAmount = new BigDecimal[counting];
            for (int t = 0; t < counting; t++) {
                totalAmount[t] = totalAmount1[t];
            }
            for (i = 0; i < rxMasterID.length; i++) {

                List<VendorPayBean> payBeanlist = new ArrayList<VendorPayBean>();

                vendorPayBeanQuery = "SELECT veBillPay.veBillPayID, veBillPay.veBillID, veBillPay.ApplyingAmount, veBillPay.DiscountAmount,"
                        + "veBill.BillDate,veBill.InvoiceNumber,veBill.BillAmount,veBill.AppliedAmount,vePO.PONumber FROM veBill "
                        + "LEFT JOIN veBillPay ON veBill.veBillID = veBillPay.veBillID  LEFT JOIN vePO ON veBill.vePOID = vePO.vePOID "
                        + "WHERE veBillPay.ApplyingAmount<>0 AND veBillPay.moAccountId="
                        + theMotransaction.getMoAccountId() + " AND veBillPay.userID = " + userID
                        + " AND  veBill.rxMasterID= " + rxMasterID[i]
                        + " ORDER BY veBill.InvoiceNumber, veBill.BillDate";

                Query aQuery4 = aSession.createSQLQuery(vendorPayBeanQuery);
                payBeanlist = aQuery4.list();

                if (payBeanlist.size() <= 25) // pick invoice count less than 25 for particular vendor
                {
                    balAmount = new BigDecimal(0);
                    ArrayList<VendorPayBean> payBean = new ArrayList<VendorPayBean>();
                    balAmount = balAmount.add(totalAmount[i].negate());
                    Motransaction aMotransaction = new Motransaction();
                    aMotransaction.setRxMasterId(rxMasterID[i]);
                    aMotransaction.setRxAddressId(rxAddressID[i]);
                    aMotransaction.setCheckType(theMotransaction.getCheckType());
                    aMotransaction.setTransactionDate(theMotransaction.getTransactionDate());
                    aMotransaction.setMoAccountId(theMotransaction.getMoAccountId());
                    aMotransaction.setPrinted(theMotransaction.getPrinted());
                    aMotransaction.setAmount(totalAmount[i].negate());
                    balcalculationAmount = balcalculationAmount.add(balAmount); // for each Amount
                    aMotransaction.setBalance(theMotransaction.getBalance().add(balcalculationAmount));
                    aMotransaction.setCoAccountId(theMotransaction.getCoAccountId());
                    aMotransaction.setReference("" + chkno);
                    aMotransaction.setUniquechkRef("" + chkno);
                    aMotransaction.setMoTransactionTypeId(theMotransaction.getMoTransactionTypeId());

                    aMotransaction.setDescription("Vendor Write Checks");
                    aMotransaction.setVoid_((byte) 0);
                    aMotransaction.setReconciled((byte) 0);
                    aMotransaction.setDirectDeposit((byte) 0);
                    aMotransaction.setTempRec((byte) 0);
                    aMotransaction.setPageflagVoid(false);
                    moTransactionId = (Integer) aSession.save(aMotransaction);

                    Iterator<?> aIterator = aQuery4.list().iterator();
                    while (aIterator.hasNext()) {
                        Object[] aObj = (Object[]) aIterator.next();
                        VendorPayBean aPayBean = new VendorPayBean();
                        aPayBean.setVebillpayId((Integer) aObj[0]);
                        aPayBean.setVebillID((Integer) aObj[1]);
                        aPayBean.setApplyingAmount((BigDecimal) aObj[2]);
                        aPayBean.setDiscountAmount((BigDecimal) aObj[3]);
                        payBean.add(aPayBean);

                        WritecheckDetails wcObj = new WritecheckDetails();
                        wcObj.setWcDetailsID(1);
                        wcObj.setMoAccountID(theMotransaction.getMoAccountId());
                        wcObj.setMoTransactionId(moTransactionId);
                        wcObj.setMoTransactionDate(theMotransaction.getTransactionDate());
                        wcObj.setMoTransAmount(totalAmount[i].negate());
                        wcObj.setMoLinkappliedAmount((BigDecimal) aObj[2]);
                        wcObj.setMoLinkdiscount((BigDecimal) aObj[3]);
                        wcObj.setCheckno("" + chkno);
                        wcObj.setUserID(userID);
                        wcObj.setRxMasterID(rxMasterID[i]);
                        wcObj.setRxAddressID(rxAddressID[i]);
                        wcObj.setVeBillID((Integer) aObj[1]);
                        wcObj.setVeBillDate((Date) aObj[4]);
                        wcObj.setInvoiceNumber((String) aObj[5]);
                        wcObj.setVeBillAmount((BigDecimal) aObj[6]);
                        wcObj.setVeBillAppliedAmt((BigDecimal) aObj[7]);
                        wcObj.setPoNumber((String) aObj[8]);
                        wcObj.setVoidStatus(0);
                        wcObj.setVeBillBalance(((BigDecimal) aObj[6] != null ? (BigDecimal) aObj[6]
                                : BigDecimal.ZERO).subtract(
                                        ((BigDecimal) aObj[2] != null ? (BigDecimal) aObj[2] : BigDecimal.ZERO)
                                                .add((BigDecimal) aObj[3] != null ? (BigDecimal) aObj[3]
                                                        : BigDecimal.ZERO)));
                        aSession.save(wcObj);

                    }
                    /*String billtoRxmasterQuery = "SELECT vb.veBillID FROM veBillPay as vp INNER JOIN veBill as vb on vp.veBillID = vb.veBillID WHERE  vb.rxMasterID ="+rxMasterID[i]+";";
                    List<?> billList = aSession.createSQLQuery(billtoRxmasterQuery).list();*/
                    for (j = 0; j < payBean.size(); j++) {

                        Molinkagedetail aMolinkagedetail = new Molinkagedetail();
                        aMolinkagedetail.setVeBillId(payBean.get(j).getVebillID());
                        aMolinkagedetail.setAmount(payBean.get(j).getApplyingAmount());
                        aMolinkagedetail.setMoLinkageId(moLinkageId);
                        aMolinkagedetail.setDiscount(payBean.get(j).getDiscountAmount());
                        aMolinkagedetail.setMoTransactionId(moTransactionId);
                        moLinkageDetailID = (Integer) aSession.save(aMolinkagedetail);

                        Vebill aVebill = new Vebill();
                        aVebill = (Vebill) aSession.get(Vebill.class, payBean.get(j).getVebillID());
                        BigDecimal appliedAmount = aVebill.getAppliedAmount();
                        BigDecimal billAmount = aVebill.getBillAmount();
                        appliedAmount = appliedAmount.add(payBean.get(j).getApplyingAmount())
                                .add(payBean.get(j).getDiscountAmount());
                        aVebill.setAppliedAmount(appliedAmount);
                        aVebill.setCreditUsed("0");

                        if (appliedAmount.compareTo(billAmount) == 0)
                            aVebill.setTransactionStatus(2);
                        else
                            aVebill.setTransactionStatus(1);

                        aSession.update(aVebill);

                        /**Created by: Leo  ID:110 
                         * Date:04/07/2015
                         * Purpose: To store payment history */

                        if (payBean.get(j).getApplyingAmount().signum() > 0) {
                            VeBillPaymentHistory aVeBillPaymentHistory = new VeBillPaymentHistory();
                            aVeBillPaymentHistory.setVeBillID(payBean.get(j).getVebillID());
                            aVeBillPaymentHistory.setCheckNo("" + chkno);
                            aVeBillPaymentHistory.setDatePaid(theMotransaction.getTransactionDate());
                            aVeBillPaymentHistory.setAmountVal(payBean.get(j).getApplyingAmount());
                            aSession.save(aVeBillPaymentHistory);
                        }

                        //added by prasant 
                        if (payBean.get(j).getApplyingAmount().signum() < 0) {

                            System.out.println(
                                    "=======================================================================================================");
                            System.out.println(
                                    "Normal  Payment To store payment history when amount is credit chk:"
                                            + chkno + "Amount" + payBean.get(j).getApplyingAmount());
                            System.out.println(
                                    "=======================================================================================================");

                            VeBillPaymentHistory aVeBillPaymentHistory = new VeBillPaymentHistory();
                            aVeBillPaymentHistory.setVeBillID(payBean.get(j).getVebillID());
                            aVeBillPaymentHistory.setCheckNo("" + chkno);
                            aVeBillPaymentHistory.setDatePaid(theMotransaction.getTransactionDate());
                            aVeBillPaymentHistory.setAmountVal(payBean.get(j).getApplyingAmount());
                            aSession.save(aVeBillPaymentHistory);
                        }

                        //end

                    }
                    Movendorchecktemp amoVendorCheckTemp = new Movendorchecktemp();
                    amoVendorCheckTemp.setMoTransactionId(moTransactionId);
                    aSession.save(amoVendorCheckTemp);
                    chkno++;

                } else {
                    int veBilllistCount = payBeanlist.size() / 25; // "segment spliting" for pdf and generate new check no for each page

                    if ((payBeanlist.size() % 25) > 0) // add 1 segment if remainder comes
                        veBilllistCount += 1;

                    int valSublist = 0;
                    for (int cb = 1; cb <= veBilllistCount; cb++) {
                        valSublist = (cb - 1) * 25; // calculation part for picking data from arralist.
                        balAmount = new BigDecimal(0);
                        ArrayList<VendorPayBean> payBean = new ArrayList<VendorPayBean>();
                        balAmount = balAmount.add(totalAmount[i].negate());
                        Motransaction aMotransaction = new Motransaction();
                        aMotransaction.setRxMasterId(rxMasterID[i]);
                        aMotransaction.setRxAddressId(rxAddressID[i]);
                        aMotransaction.setTransactionDate(theMotransaction.getTransactionDate());
                        aMotransaction.setMoAccountId(theMotransaction.getMoAccountId());
                        aMotransaction.setPrinted(theMotransaction.getPrinted());
                        aMotransaction.setCoAccountId(theMotransaction.getCoAccountId());
                        aMotransaction.setReference("" + chkno);
                        aMotransaction.setMoTransactionTypeId(theMotransaction.getMoTransactionTypeId());

                        if (cb == 1) {
                            aMotransaction.setUniquechkRef("" + chkno);
                            aMotransaction.setDescription("Vendor Write Checks");
                            aMotransaction.setCheckType(theMotransaction.getCheckType());
                            aMotransaction.setAmount(totalAmount[i].negate());
                            balcalculationAmount = balcalculationAmount.add(balAmount); // for each Amount
                            aMotransaction.setBalance(theMotransaction.getBalance().add(balcalculationAmount));
                            aMotransaction.setVoid_((byte) 0);
                            aMotransaction.setPageflagVoid(false);
                        } else {
                            aMotransaction.setUniquechkRef("" + (chkno - (cb - 1)));
                            aMotransaction.setDescription("***VOID***");
                            aMotransaction.setStatus(true);
                            aMotransaction.setAmount(BigDecimal.ZERO);
                            aMotransaction.setVoid_((byte) 0);
                            aMotransaction.setPageflagVoid(true);
                            balcalculationAmount = balcalculationAmount.add(BigDecimal.ZERO); // for each Amount
                            aMotransaction.setBalance(theMotransaction.getBalance().add(balcalculationAmount));
                        }

                        aMotransaction.setReconciled((byte) 0);
                        aMotransaction.setDirectDeposit((byte) 0);
                        aMotransaction.setTempRec((byte) 0);
                        moTransactionId = (Integer) aSession.save(aMotransaction);

                        Iterator<?> aIterator = null;

                        if (cb * 25 < payBeanlist.size()) // pick data from list using index
                            aIterator = aQuery4.list().subList(valSublist, cb * 25).iterator();
                        else
                            aIterator = aQuery4.list().subList(valSublist, payBeanlist.size()).iterator();

                        while (aIterator.hasNext()) {
                            Object[] aObj = (Object[]) aIterator.next();
                            VendorPayBean aPayBean = new VendorPayBean();
                            aPayBean.setVebillpayId((Integer) aObj[0]);
                            aPayBean.setVebillID((Integer) aObj[1]);
                            aPayBean.setApplyingAmount((BigDecimal) aObj[2]);
                            aPayBean.setDiscountAmount((BigDecimal) aObj[3]);
                            payBean.add(aPayBean);

                            WritecheckDetails wcObj = new WritecheckDetails();
                            wcObj.setWcDetailsID(1);
                            wcObj.setMoAccountID(theMotransaction.getMoAccountId());
                            wcObj.setMoTransactionId(moTransactionId);
                            wcObj.setMoTransactionDate(theMotransaction.getTransactionDate());
                            wcObj.setMoTransAmount(totalAmount[i].negate());
                            wcObj.setMoLinkappliedAmount((BigDecimal) aObj[2]);
                            wcObj.setMoLinkdiscount((BigDecimal) aObj[3]);
                            wcObj.setCheckno("" + chkno);
                            wcObj.setUserID(userID);
                            wcObj.setRxMasterID(rxMasterID[i]);
                            wcObj.setRxAddressID(rxAddressID[i]);
                            wcObj.setVeBillID((Integer) aObj[1]);
                            wcObj.setVeBillDate((Date) aObj[4]);
                            wcObj.setInvoiceNumber((String) aObj[5]);
                            wcObj.setVeBillAmount((BigDecimal) aObj[6]);
                            wcObj.setVeBillAppliedAmt((BigDecimal) aObj[7]);
                            wcObj.setPoNumber((String) aObj[8]);
                            wcObj.setVeBillBalance(
                                    ((BigDecimal) aObj[6] != null ? (BigDecimal) aObj[6] : BigDecimal.ZERO)
                                            .subtract(((BigDecimal) aObj[2] != null ? (BigDecimal) aObj[2]
                                                    : BigDecimal.ZERO).add(
                                                            (BigDecimal) aObj[3] != null ? (BigDecimal) aObj[3]
                                                                    : BigDecimal.ZERO)));
                            if (valSublist > 0)
                                wcObj.setVoidStatus(1);
                            else
                                wcObj.setVoidStatus(0);
                            aSession.save(wcObj);

                        }
                        /*String billtoRxmasterQuery = "SELECT vb.veBillID FROM veBillPay as vp INNER JOIN veBill as vb on vp.veBillID = vb.veBillID WHERE  vb.rxMasterID ="+rxMasterID[i]+";";
                        List<?> billList = aSession.createSQLQuery(billtoRxmasterQuery).list();*/
                        for (j = 0; j < payBean.size(); j++) {

                            Molinkagedetail aMolinkagedetail = new Molinkagedetail();
                            aMolinkagedetail.setVeBillId(payBean.get(j).getVebillID());
                            aMolinkagedetail.setAmount(payBean.get(j).getApplyingAmount());
                            aMolinkagedetail.setMoLinkageId(moLinkageId);
                            aMolinkagedetail.setDiscount(payBean.get(j).getDiscountAmount());
                            aMolinkagedetail.setMoTransactionId(moTransactionId);
                            moLinkageDetailID = (Integer) aSession.save(aMolinkagedetail);

                            Vebill aVebill = new Vebill();
                            aVebill = (Vebill) aSession.get(Vebill.class, payBean.get(j).getVebillID());
                            BigDecimal appliedAmount = aVebill.getAppliedAmount();
                            BigDecimal billAmount = aVebill.getBillAmount();
                            appliedAmount = appliedAmount.add(payBean.get(j).getApplyingAmount())
                                    .add(payBean.get(j).getDiscountAmount());
                            aVebill.setAppliedAmount(appliedAmount);
                            aVebill.setCreditUsed("0");

                            if (appliedAmount.compareTo(billAmount) == 0)
                                aVebill.setTransactionStatus(2);
                            else
                                aVebill.setTransactionStatus(1);

                            aSession.update(aVebill);

                            /**Created by: Leo  ID:110 
                             * Date:04/07/2015
                             * Purpose: To store payment history */

                            if (payBean.get(j).getApplyingAmount().signum() > 0) {
                                VeBillPaymentHistory aVeBillPaymentHistory = new VeBillPaymentHistory();
                                aVeBillPaymentHistory.setVeBillID(payBean.get(j).getVebillID());
                                aVeBillPaymentHistory.setCheckNo("" + chkno);
                                aVeBillPaymentHistory.setDatePaid(theMotransaction.getTransactionDate());
                                aVeBillPaymentHistory.setAmountVal(payBean.get(j).getApplyingAmount());
                                aSession.save(aVeBillPaymentHistory);
                            }
                        }
                        Movendorchecktemp amoVendorCheckTemp = new Movendorchecktemp();
                        amoVendorCheckTemp.setMoTransactionId(moTransactionId);
                        aSession.save(amoVendorCheckTemp);
                        chkno++;
                    }

                }
            }
            /**Inserting GlTransaction*/
            payingVendorBillDiscount1(theMotransaction.getMoAccountId(), checkNumber, yearID, periodID,
                    userName, theMotransaction.getTransactionDate(), userID);

            /** Delete VeBillPay **/
            String rxMasterIds = StringUtils.join(rxMasterID, ',');
            if (rxMasterID.length > 0) {
                vendorPayBeanQuery = "DELETE FROM veBillPay WHERE veBillPayID IN (SELECT * FROM (SELECT vP.veBillPayID FROM veBillPay vP,veBill v WHERE vP.moAccountId="
                        + theMotransaction.getMoAccountId() + " AND vP.userID = " + userID
                        + "  AND vP.veBillID = v.veBillID AND v.rxMasterID IN (" + rxMasterIds
                        + ")) AS subQuery)";
                aSession.createSQLQuery(vendorPayBeanQuery).executeUpdate();
            }
            BigDecimal totalamount = new BigDecimal(0);
            for (i = 0; i < totalAmount.length; i++) {
                if (totalAmount[i] != null)
                    totalamount = totalamount.add(totalAmount[i]);
            }

            aMoaccount = (MoAccount) aSession.get(MoAccount.class, theMotransaction.getMoAccountId());
            aMoaccount.setNextCheckNumber(chkno);

            //BigDecimal openBalance = aMoaccount.getOpenBalance();
            /*openBalance = openBalance.subtract(totalamount);
            aMoaccount.setOpenBalance(openBalance);*/
            BigDecimal substractions = aMoaccount.getSubtractions();
            substractions = substractions.add(totalamount);
            aMoaccount.setSubtractions(substractions);
            aSession.update(aMoaccount);
            aTransaction.commit();

        } else // Credit Payment 
        {
            /**Created by: Leo  ID:110 
             * Date:04/06/2015
             * Purpose: for credit payments */

            String creditVeBillID = "";

            for (i = 0; i < rxMasterID1.size(); i++) { // iterate credit rxMasterIDs
                balAmount = new BigDecimal(0);
                ArrayList<VendorPayBean> payBean = new ArrayList<VendorPayBean>();
                BigDecimal pickNegativeAmt = new BigDecimal(0);

                vendorPayBeanQuery = "SELECT veBillPay.veBillPayID, veBillPay.veBillID, veBillPay.ApplyingAmount, veBillPay.DiscountAmount "
                        + "FROM veBill LEFT JOIN veBillPay ON veBill.veBillID = veBillPay.veBillID "
                        + "WHERE veBillPay.ApplyingAmount<>0 AND veBillPay.moAccountId="
                        + theMotransaction.getMoAccountId() + " and veBillPay.userID = " + userID
                        + " And  veBill.rxMasterID= " + rxMasterID1.get(i)
                        + " ORDER BY veBill.InvoiceNumber, veBill.BillDate;";
                Query aQuery4 = aSession.createSQLQuery(vendorPayBeanQuery); // get All veBillPay Details
                Iterator<?> aIterator = aQuery4.list().iterator();
                while (aIterator.hasNext()) {
                    Object[] aObj = (Object[]) aIterator.next();
                    VendorPayBean aPayBean = new VendorPayBean();
                    aPayBean.setVebillpayId((Integer) aObj[0]);
                    aPayBean.setVebillID((Integer) aObj[1]);
                    aPayBean.setApplyingAmount((BigDecimal) aObj[2]);
                    aPayBean.setDiscountAmount((BigDecimal) aObj[3]);
                    if (aPayBean.getApplyingAmount().signum() < 0) {
                        pickNegativeAmt = pickNegativeAmt.add(aPayBean.getApplyingAmount()); //sum of negative Amount only
                        if (creditVeBillID.equals("")) // Get All veBill IDs
                            creditVeBillID = "" + (Integer) aObj[1];
                        else
                            creditVeBillID = creditVeBillID + "," + (Integer) aObj[1];
                    }
                    payBean.add(aPayBean);
                }

                balAmount = balAmount.add(pickNegativeAmt.negate().add(creditAmtUsed.get(i))); // sum of all applying amt without credit Amount

                for (j = 0; j < payBean.size(); j++) { // Iterate veBill IDs

                    Vebill aVebill = new Vebill();
                    aVebill = (Vebill) aSession.get(Vebill.class, payBean.get(j).getVebillID());
                    BigDecimal appliedAmount = aVebill.getAppliedAmount();
                    BigDecimal billAmount = aVebill.getBillAmount();
                    itsLogger.info(payBean.get(j).getApplyingAmount());
                    /**
                     * Note: Credit bill don't update check no. credit used bills only need check no.
                     */

                    if (payBean.get(j).getApplyingAmount().signum() < 0) // check whether Applying Amt is in negative value
                    {

                        if (payBean.get(j).getApplyingAmount().negate().compareTo(balAmount) == 1) // check credit amount is greater or not
                        {
                            appliedAmount = appliedAmount.add(balAmount.negate())
                                    .add(payBean.get(j).getDiscountAmount());
                            aVebill.setAppliedAmount(appliedAmount);
                        } else {
                            appliedAmount = appliedAmount.add(payBean.get(j).getApplyingAmount())
                                    .add(payBean.get(j).getDiscountAmount());
                            aVebill.setAppliedAmount(appliedAmount);
                            balAmount = balAmount.add(payBean.get(j).getApplyingAmount());
                        }
                        aVebill.setCreditUsed("0");
                        itsLogger.info(balAmount);
                    } else {
                        /**Created by: Leo  ID:110 
                         * Date:04/07/2015
                         * Purpose: To store payment history */

                        appliedAmount = appliedAmount.add(payBean.get(j).getApplyingAmount())
                                .add(payBean.get(j).getDiscountAmount());

                        VeBillPaymentHistory aVeBillPaymentHistory = new VeBillPaymentHistory();
                        aVeBillPaymentHistory.setVeBillID(payBean.get(j).getVebillID());
                        aVeBillPaymentHistory.setCheckNo("" + chkno);
                        aVeBillPaymentHistory.setDatePaid(theMotransaction.getTransactionDate());
                        aVeBillPaymentHistory.setAmountVal(appliedAmount);
                        aSession.save(aVeBillPaymentHistory);

                        aVebill.setAppliedAmount(appliedAmount);
                        if (aVebill.getCreditUsed() != null && !aVebill.getCreditUsed().equals("0"))
                            aVebill.setCreditUsed(aVebill.getCreditUsed() + "," + creditVeBillID);
                        else
                            aVebill.setCreditUsed("" + creditVeBillID);

                        itsLogger.info(appliedAmount);
                    }

                    if (appliedAmount.compareTo(billAmount) == 0)
                        aVebill.setTransactionStatus(2);
                    else
                        aVebill.setTransactionStatus(1);
                    aSession.update(aVebill);
                }
                Movendorchecktemp amoVendorCheckTemp = new Movendorchecktemp();
                amoVendorCheckTemp.setMoTransactionId(moTransactionId);
                aSession.save(amoVendorCheckTemp);
                chkno++;
            }

            aMoaccount = (MoAccount) aSession.get(MoAccount.class, theMotransaction.getMoAccountId());
            aMoaccount.setNextCheckNumber(chkno);
            aSession.update(aMoaccount);

            aTransaction.commit();
        }

        if (rxMasterID.length > 0) {
            aPrintBean.setReference("Success");
        } else {
            aPrintBean.setReference("Error");
        }

    } catch (Exception e) {
        itsLogger.error(e.getMessage(), e);

        aTransaction.rollback();

        if (rxMasterID.length > 0) {
            aPrintBean.setReference("Success");
        } else {
            aPrintBean.setReference("Error");
        }

        BankingException aBankingException = new BankingException(e.getMessage(), e);
        throw aBankingException;
    } finally {
        aSession.flush();
        aSession.close();
        deletetemCheck = null;
        billArrayQuery = null;
        rxAddressIDQuery = null;
        vendorPayBeanQuery = null;
        totalAmountQuery = null;
    }
    return aPrintBean;
}

From source file:org.ofbiz.order.order.OrderServices.java

public static BigDecimal calculatePurchaseOrderTermValue(DispatchContext ctx,
        Map<String, ? extends Object> context) {
    BigDecimal termAmount = BigDecimal.ZERO;
    BigDecimal basicAmount = (BigDecimal) context.get("basicAmount");
    BigDecimal poValue = (BigDecimal) context.get("poValue");
    BigDecimal exciseDuty = (BigDecimal) context.get("exciseDuty");
    String termTypeId = (String) context.get("termTypeId");
    String uomId = (String) context.get("uomId");
    BigDecimal termValue = (BigDecimal) context.get("termValue");

    if (UtilValidate.isEmpty(termTypeId)) {
        return termAmount;
    }//from ww  w.  jav  a 2  s .com
    //this to handle non derived terms
    termAmount = termValue;

    //Discount Before ED
    if (termTypeId.equals("COGS_DISC")) {
        if (UtilValidate.isNotEmpty(uomId) && uomId.equals("PERCENT")) {
            termAmount = ((basicAmount.add(exciseDuty)).multiply(termValue)).divide(new BigDecimal("100"),
                    taxRounding);
            termAmount = termAmount.negate();
        } else {
            termAmount = termValue.negate();
        }
    }

    //Discount  After Tax
    if (termTypeId.equals("COGS_DISC_ATR")) {
        if (UtilValidate.isNotEmpty(uomId) && uomId.equals("PERCENT")) {
            Debug.log("poValue========" + poValue);
            termAmount = (poValue.multiply(termValue)).divide(new BigDecimal("100"), taxRounding);
            termAmount = termAmount.negate();
        } else {
            termAmount = termValue.negate();
        }
    }
    //Packing And Forwarding Charges Before Tax
    if (termTypeId.equals("COGS_PCK_FWD")) {
        if (UtilValidate.isNotEmpty(uomId) && uomId.equals("PERCENT")) {
            termAmount = ((basicAmount.add(exciseDuty)).multiply(termValue)).divide(new BigDecimal("100"),
                    taxRounding);
        } else {
            termAmount = termValue;
        }
    }
    //Packing And Forwarding Charges After Tax
    if (termTypeId.equals("COGS_PCK_FWD_ATR")) {
        if (UtilValidate.isNotEmpty(uomId) && uomId.equals("PERCENT")) {
            Debug.log("poValue========" + poValue);
            termAmount = (poValue.multiply(termValue)).divide(new BigDecimal("100"), taxRounding);
        } else {
            termAmount = termValue;
        }
    }
    if (termTypeId.equals("COGS_INSURANCE")) {
        if (UtilValidate.isNotEmpty(uomId) && uomId.equals("PERCENT")) {
            termAmount = ((basicAmount.add(exciseDuty)).multiply(termValue)).divide(new BigDecimal("100"),
                    taxRounding);
        } else {
            termAmount = termValue;
        }
    }

    return termAmount;
}