Example usage for java.math BigDecimal compareTo

List of usage examples for java.math BigDecimal compareTo

Introduction

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

Prototype

@Override
public int compareTo(BigDecimal val) 

Source Link

Document

Compares this BigDecimal with the specified BigDecimal .

Usage

From source file:op.care.med.inventory.PnlInventory.java

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

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

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

    pnlTX.setOpaque(true);//from w  ww  .  ja  va2 s .  c om
    //        pnlTX.setBackground(Color.white);
    synchronized (lstInventories) {
        pnlTX.setBackground(getColor(SYSConst.light2, lstInventories.indexOf(stock.getInventory()) % 2 != 0));
    }

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

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

                                            createCP4(myStock.getInventory());

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

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

    SwingWorker worker = new SwingWorker() {

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

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

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

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

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

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

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

                        "</font></html>";

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

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

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

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

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

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

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

                                                    createCP4(myStock.getInventory());

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

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

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

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

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

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

                                                em.getTransaction().commit();

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

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

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

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

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

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

                                            em.getTransaction().commit();

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

                                        }

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

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

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

            return null;
        }

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

    return pnlTX;
}

From source file:org.egov.dao.budget.BudgetDetailsHibernateDAO.java

private BigDecimal getDetails(final Map<String, Object> detailsMap) {
    Long financialyearid = null;/*  w w w. ja v  a  2s.c o m*/
    Integer moduleid = null;
    String referencenumber = null;
    Integer departmentid = null;
    Long functionid = null;
    Integer functionaryid = null;
    Integer schemeid = null;
    Integer subschemeid = null;
    Integer boundaryid = null;
    List<Long> budgetheadid = null;
    Integer fundid = null;
    double amount = 0.0d;
    String appropriationnumber = null;
    Boolean consumeOrRelease = null;

    if (detailsMap.containsKey(Constants.FINANCIALYEARID))
        financialyearid = (Long) detailsMap.get(Constants.FINANCIALYEARID);
    if (detailsMap.containsKey(Constants.MODULEID))
        moduleid = (Integer) detailsMap.get(Constants.MODULEID);
    if (detailsMap.containsKey(Constants.REFERENCENUMBER))
        referencenumber = (String) detailsMap.get(Constants.REFERENCENUMBER);
    if (detailsMap.containsKey(Constants.DEPARTMENTID))
        departmentid = (Integer) detailsMap.get(Constants.DEPARTMENTID);
    if (detailsMap.containsKey(Constants.FUNCTIONID))
        functionid = (Long) detailsMap.get(Constants.FUNCTIONID);
    if (detailsMap.containsKey(Constants.FUNCTIONARYID))
        functionaryid = (Integer) detailsMap.get(Constants.FUNCTIONARYID);
    if (detailsMap.containsKey(Constants.SCHEMEID))
        schemeid = (Integer) detailsMap.get(Constants.SCHEMEID);
    if (detailsMap.containsKey(Constants.SUBSCHEMEID))
        subschemeid = (Integer) detailsMap.get(Constants.SUBSCHEMEID);
    if (detailsMap.containsKey(Constants.BOUNDARYID))
        boundaryid = (Integer) detailsMap.get(Constants.BOUNDARYID);
    if (detailsMap.containsKey(Constants.BUDGETHEAD))
        budgetheadid = (List<Long>) detailsMap.get(Constants.BUDGETHEAD);
    if (detailsMap.containsKey(Constants.FUNDID))
        fundid = (Integer) detailsMap.get(Constants.FUNDID);
    if (detailsMap.containsKey(Constants.AMOUNT))
        amount = (Double) detailsMap.get(Constants.AMOUNT);
    if (detailsMap.containsKey(Constants.APPROPRIATIONNUMBER))
        appropriationnumber = (String) detailsMap.get(Constants.APPROPRIATIONNUMBER);
    if (detailsMap.containsKey(Constants.CONSUMEORRELEASE))
        consumeOrRelease = (Boolean) detailsMap.get(Constants.CONSUMEORRELEASE);

    try {
        if (LOGGER.isDebugEnabled())
            LOGGER.debug("financialyearid==" + financialyearid + ",moduleid==" + moduleid + ",referencenumber=="
                    + referencenumber + ",departmentid==" + departmentid + ",functionid==" + functionid
                    + ",functionaryid==" + functionaryid + ",schemeid==" + schemeid + ",subschemeid=="
                    + subschemeid + ",boundaryid==" + boundaryid + ",budgetheadid==" + budgetheadid
                    + ",amount==" + amount);

        validateMandatoryParameters(moduleid, referencenumber);
        BigDecimal amtavailable = getPlanningBudgetAvailable(financialyearid, departmentid, functionid,
                functionaryid, schemeid, subschemeid, boundaryid, budgetheadid, fundid);

        if (consumeOrRelease)
            amtavailable = amtavailable.subtract(BigDecimal.valueOf(amount));
        else
            amtavailable = amtavailable.add(BigDecimal.valueOf(amount));
        if (LOGGER.isDebugEnabled())
            LOGGER.debug("budget available after consuming/releasing=" + amtavailable);

        if (amtavailable != null && amtavailable.compareTo(BigDecimal.ZERO) >= 0) {
            // need to update budget details
            final String query = prepareQuery(departmentid, functionid, functionaryid, schemeid, subschemeid,
                    boundaryid, fundid);
            final Query q = getCurrentSession().createQuery(
                    " from BudgetDetail bd where  bd.budget.financialYear.id=:finYearId and bd.budget.isbere=:type and bd.budgetGroup.id in (:bgId)"
                            + query);
            if (budgetService.hasApprovedReForYear(financialyearid))
                q.setParameter("type", "RE");
            else
                q.setParameter("type", "BE");
            q.setParameter("finYearId", financialyearid);
            q.setParameterList("bgId", budgetheadid);
            final List<BudgetDetail> bdList = q.list();
            if (bdList == null || bdList.size() == 0) {
                if (LOGGER.isDebugEnabled())
                    LOGGER.debug(
                            "IN consumeEncumbranceBudget()-getDetail() - No budget detail item defined for RE or BE for this combination!!");
                if (LOGGER.isDebugEnabled())
                    LOGGER.debug("financial year id - " + financialyearid.toString() + " Budget Group -  "
                            + budgetheadid.toString() + " Query - " + query);
                throw new ValidationException(EMPTY_STRING, "Budgetary Check Failed");
            }
            final BudgetDetail bd = bdList.get(0);
            bd.setBudgetAvailable(amtavailable);
            update(bd);

            final BudgetUsage budgetUsage = new BudgetUsage();
            budgetUsage.setFinancialYearId(financialyearid.intValue());
            budgetUsage.setModuleId(moduleid);
            budgetUsage.setReferenceNumber(referencenumber);
            budgetUsage.setBudgetDetail(bd);
            budgetUsage.setAppropriationnumber(appropriationnumber);
            if (consumeOrRelease) {
                budgetUsage.setConsumedAmount(amount);
                budgetUsage.setReleasedAmount(0.0);
            } else {
                budgetUsage.setConsumedAmount(0.0);
                budgetUsage.setReleasedAmount(amount);
            }
            budgetUsage.setCreatedby(ApplicationThreadLocals.getUserId().intValue());
            budgetUsageService.create(budgetUsage);
            return BigDecimal.ONE;
        } else
            return BigDecimal.ZERO;
    } catch (final ValidationException v) {
        LOGGER.error("Exp in consumeEncumbranceBudget API()===" + v.getErrors());
        throw new ValidationException(v.getErrors());
    } catch (final Exception e) {
        LOGGER.error("Exception in consumeEncumbranceBudget API()=" + e.getMessage());
        throw new ValidationException(EMPTY_STRING, e.getMessage());
    }
}

From source file:org.egov.dao.budget.BudgetDetailsHibernateDAO.java

@Deprecated
@Transactional//from   w  w  w .jav  a 2  s. c o  m
private BudgetUsage getBudgetUsageDetails(final Long financialyearid, final Integer moduleid,
        final String referencenumber, final Integer departmentid, final Long functionid,
        final Integer functionaryid, final Integer schemeid, final Integer subschemeid,
        final Integer boundaryid, final List<Long> budgetheadid, final Integer fundid, final double amount,
        final boolean consumeOrRelease, final String appropriationnumber) {
    try {
        if (LOGGER.isDebugEnabled())
            LOGGER.debug("financialyearid==" + financialyearid + ",moduleid==" + moduleid + ",referencenumber=="
                    + referencenumber + ",departmentid==" + departmentid + ",functionid==" + functionid
                    + ",functionaryid==" + functionaryid + ",schemeid==" + schemeid + ",subschemeid=="
                    + subschemeid + ",boundaryid==" + boundaryid + ",budgetheadid==" + budgetheadid
                    + ",amount==" + amount);

        validateMandatoryParameters(moduleid, referencenumber);
        BigDecimal amtavailable = getPlanningBudgetAvailable(financialyearid, departmentid, functionid,
                functionaryid, schemeid, subschemeid, boundaryid, budgetheadid, fundid);

        if (consumeOrRelease)
            amtavailable = amtavailable.subtract(BigDecimal.valueOf(amount));
        else
            amtavailable = amtavailable.add(BigDecimal.valueOf(amount));
        if (LOGGER.isDebugEnabled())
            LOGGER.debug("budget available after consuming/releasing=" + amtavailable);
        if (BudgetControlType.BudgetCheckOption.MANDATORY.toString()
                .equals(budgetCheckConfigService.getConfigValue())) {
            if (amtavailable.compareTo(BigDecimal.ZERO) < 0)
                return null;
        }

        // need to update budget details
        final String query = prepareQuery(departmentid, functionid, functionaryid, schemeid, subschemeid,
                boundaryid, fundid);
        final Query q = persistenceService.getSession().createQuery(
                " from BudgetDetail bd where  bd.budget.financialYear.id=:finYearId  and  bd.budget.isbere=:type and bd.budgetGroup.id in (:bgId)"
                        + query);
        if (budgetService.hasApprovedReForYear(financialyearid))
            q.setParameter("type", "RE");
        else
            q.setParameter("type", "BE");
        q.setParameter("finYearId", financialyearid);
        q.setParameterList("bgId", budgetheadid);
        final List<BudgetDetail> bdList = q.list();

        if (bdList == null || bdList.size() == 0) {
            if (LOGGER.isDebugEnabled())
                LOGGER.debug(
                        "IN consumeEncumbranceBudget()-getDetail() - No budget detail item defined for RE or BE for this combination!!");
            if (LOGGER.isDebugEnabled())
                LOGGER.debug("financial year id - " + financialyearid.toString() + " Budget Group -  "
                        + budgetheadid.toString() + " Query - " + query);
            throw new ValidationException(EMPTY_STRING, "Budgetary Check Failed");
        }
        final BudgetDetail bd = bdList.get(0);
        bd.setBudgetAvailable(amtavailable);
        budgetDetailService.update(bd);

        final BudgetUsage budgetUsage = new BudgetUsage();
        budgetUsage.setFinancialYearId(financialyearid.intValue());
        budgetUsage.setModuleId(moduleid);
        budgetUsage.setReferenceNumber(referencenumber);
        budgetUsage.setBudgetDetail(bd);
        budgetUsage.setAppropriationnumber(appropriationnumber);
        if (consumeOrRelease) {
            budgetUsage.setConsumedAmount(amount);
            budgetUsage.setReleasedAmount(0.0);
        } else {
            budgetUsage.setConsumedAmount(0.0);
            budgetUsage.setReleasedAmount(amount);
        }
        budgetUsage.setCreatedby(ApplicationThreadLocals.getUserId().intValue());
        budgetUsageService.create(budgetUsage);
        return budgetUsage;

    } catch (final ValidationException v) {
        throw v;
    } catch (final Exception e) {
        LOGGER.error("Exception in consumeEncumbranceBudget API()=" + e.getMessage());
        throw new ValidationException(EMPTY_STRING, e.getMessage());
    }
}

From source file:com.gst.portfolio.loanproduct.serialization.LoanProductDataValidator.java

private void validateBorrowerCycleVariations(final JsonElement element,
        final DataValidatorBuilder baseDataValidator, final String variationParameterName,
        final String defaultParameterName, final String minParameterName, final String maxParameterName,
        final String valueUsageConditionParamName, final String cycleNumbersParamName) {
    final JsonObject topLevelJsonElement = element.getAsJsonObject();
    final Locale locale = this.fromApiJsonHelper.extractLocaleParameter(topLevelJsonElement);
    Integer lastCycleNumber = 0;//w  w w  .  j  a  v  a 2  s  . com
    LoanProductValueConditionType lastConditionType = LoanProductValueConditionType.EQUAL;
    if (this.fromApiJsonHelper.parameterExists(variationParameterName, element)) {
        final JsonArray variationArray = this.fromApiJsonHelper.extractJsonArrayNamed(variationParameterName,
                element);
        if (variationArray != null && variationArray.size() > 0) {
            int i = 0;
            do {
                final JsonObject jsonObject = variationArray.get(i).getAsJsonObject();

                BigDecimal defaultValue = this.fromApiJsonHelper.extractBigDecimalNamed(
                        LoanProductConstants.defaultValueParameterName, jsonObject, locale);
                BigDecimal minValue = this.fromApiJsonHelper
                        .extractBigDecimalNamed(LoanProductConstants.minValueParameterName, jsonObject, locale);
                BigDecimal maxValue = this.fromApiJsonHelper
                        .extractBigDecimalNamed(LoanProductConstants.maxValueParameterName, jsonObject, locale);
                Integer cycleNumber = this.fromApiJsonHelper.extractIntegerNamed(
                        LoanProductConstants.borrowerCycleNumberParamName, jsonObject, locale);
                Integer valueUsageCondition = this.fromApiJsonHelper.extractIntegerNamed(
                        LoanProductConstants.valueConditionTypeParamName, jsonObject, locale);

                baseDataValidator.reset().parameter(defaultParameterName).value(defaultValue).notBlank();
                if (minValue != null) {
                    baseDataValidator.reset().parameter(minParameterName).value(minValue)
                            .notGreaterThanMax(maxValue);
                }

                if (maxValue != null) {
                    baseDataValidator.reset().parameter(maxParameterName).value(maxValue)
                            .notLessThanMin(minValue);
                }
                if ((minValue != null && minValue.compareTo(BigDecimal.ZERO) == 1)
                        && (maxValue != null && maxValue.compareTo(BigDecimal.ZERO) == 1)) {
                    baseDataValidator.reset().parameter(defaultParameterName).value(defaultValue)
                            .inMinAndMaxAmountRange(minValue, maxValue);
                } else {
                    if (minValue != null && minValue.compareTo(BigDecimal.ZERO) == 1) {
                        baseDataValidator.reset().parameter(defaultParameterName).value(defaultValue)
                                .notLessThanMin(minValue);
                    } else if (maxValue != null && maxValue.compareTo(BigDecimal.ZERO) == 1) {
                        baseDataValidator.reset().parameter(defaultParameterName).value(defaultValue)
                                .notGreaterThanMax(maxValue);
                    }
                }

                LoanProductValueConditionType conditionType = LoanProductValueConditionType.INVALID;
                if (valueUsageCondition != null) {
                    conditionType = LoanProductValueConditionType.fromInt(valueUsageCondition);
                }
                baseDataValidator.reset().parameter(valueUsageConditionParamName).value(valueUsageCondition)
                        .notNull().inMinMaxRange(LoanProductValueConditionType.EQUAL.getValue(),
                                LoanProductValueConditionType.GREATERTHAN.getValue());
                if (lastConditionType.equals(LoanProductValueConditionType.EQUAL)
                        && conditionType.equals(LoanProductValueConditionType.GREATERTHAN)) {
                    if (lastCycleNumber == 0) {
                        baseDataValidator.reset().parameter(cycleNumbersParamName)
                                .failWithCode(LoanProductConstants.VALUE_CONDITION_START_WITH_ERROR);
                        lastCycleNumber = 1;
                    }
                    baseDataValidator.reset().parameter(cycleNumbersParamName).value(cycleNumber).notNull()
                            .integerSameAsNumber(lastCycleNumber);
                } else if (lastConditionType.equals(LoanProductValueConditionType.EQUAL)) {
                    baseDataValidator.reset().parameter(cycleNumbersParamName).value(cycleNumber).notNull()
                            .integerSameAsNumber(lastCycleNumber + 1);
                } else if (lastConditionType.equals(LoanProductValueConditionType.GREATERTHAN)) {
                    baseDataValidator.reset().parameter(cycleNumbersParamName).value(cycleNumber).notNull()
                            .integerGreaterThanNumber(lastCycleNumber);
                }
                if (conditionType != null) {
                    lastConditionType = conditionType;
                }
                if (cycleNumber != null) {
                    lastCycleNumber = cycleNumber;
                }
                i++;
            } while (i < variationArray.size());
            if (!lastConditionType.equals(LoanProductValueConditionType.GREATERTHAN)) {
                baseDataValidator.reset().parameter(cycleNumbersParamName)
                        .failWithCode(LoanProductConstants.VALUE_CONDITION_END_WITH_ERROR);
            }
        }

    }

}

From source file:com.gst.accounting.journalentry.service.AccountingProcessorHelper.java

/**
 * Convenience method that creates a pair of related Debits and Credits for
 * Accrual Based accounting./*from   www .  ja  v a  2s.c o m*/
 * 
 * The target accounts for debits and credits are switched in case of a
 * reversal
 * 
 * @param office
 * @param accountTypeToBeDebited
 *            Enum of the placeholder GLAccount to be debited
 * @param accountTypeToBeCredited
 *            Enum of the placeholder of the GLAccount to be credited
 * @param loanProductId
 * @param paymentTypeId
 * @param loanId
 * @param transactionId
 * @param transactionDate
 * @param amount
 * @param isReversal
 */
public void createAccrualBasedJournalEntriesAndReversalsForLoanCharges(final Office office,
        final String currencyCode, final Integer accountTypeToBeDebited, final Integer accountTypeToBeCredited,
        final Long loanProductId, final Long loanId, final String transactionId, final Date transactionDate,
        final BigDecimal totalAmount, final Boolean isReversal,
        final List<ChargePaymentDTO> chargePaymentDTOs) {

    GLAccount receivableAccount = getLinkedGLAccountForLoanCharges(loanProductId, accountTypeToBeDebited, null);
    final Map<GLAccount, BigDecimal> creditDetailsMap = new LinkedHashMap<>();
    for (final ChargePaymentDTO chargePaymentDTO : chargePaymentDTOs) {
        final Long chargeId = chargePaymentDTO.getChargeId();
        final GLAccount chargeSpecificAccount = getLinkedGLAccountForLoanCharges(loanProductId,
                accountTypeToBeCredited, chargeId);
        BigDecimal chargeSpecificAmount = chargePaymentDTO.getAmount();

        // adjust net credit amount if the account is already present in the
        // map
        if (creditDetailsMap.containsKey(chargeSpecificAccount)) {
            final BigDecimal existingAmount = creditDetailsMap.get(chargeSpecificAccount);
            chargeSpecificAmount = chargeSpecificAmount.add(existingAmount);
        }
        creditDetailsMap.put(chargeSpecificAccount, chargeSpecificAmount);
    }

    BigDecimal totalCreditedAmount = BigDecimal.ZERO;
    for (final Map.Entry<GLAccount, BigDecimal> entry : creditDetailsMap.entrySet()) {
        final GLAccount account = entry.getKey();
        final BigDecimal amount = entry.getValue();
        totalCreditedAmount = totalCreditedAmount.add(amount);
        if (isReversal) {
            createDebitJournalEntryForLoan(office, currencyCode, account, loanId, transactionId,
                    transactionDate, amount);
            createCreditJournalEntryForLoan(office, currencyCode, receivableAccount, loanId, transactionId,
                    transactionDate, amount);
        } else {
            createDebitJournalEntryForLoan(office, currencyCode, receivableAccount, loanId, transactionId,
                    transactionDate, amount);
            createCreditJournalEntryForLoan(office, currencyCode, account, loanId, transactionId,
                    transactionDate, amount);
        }
    }

    if (totalAmount.compareTo(totalCreditedAmount) != 0) {
        throw new PlatformDataIntegrityException(
                "Meltdown in advanced accounting...sum of all charges is not equal to the fee charge for a transaction",
                "Meltdown in advanced accounting...sum of all charges is not equal to the fee charge for a transaction",
                totalCreditedAmount, totalAmount);
    }
}

From source file:com.gst.portfolio.loanaccount.service.LoanWritePlatformServiceJpaRepositoryImpl.java

private void validateForAddAndDeleteTranche(final Loan loan) {

    BigDecimal totalDisbursedAmount = BigDecimal.ZERO;
    Collection<LoanDisbursementDetails> loanDisburseDetails = loan.getDisbursementDetails();
    for (LoanDisbursementDetails disbursementDetails : loanDisburseDetails) {
        if (disbursementDetails.actualDisbursementDate() != null) {
            totalDisbursedAmount = totalDisbursedAmount.add(disbursementDetails.principal());
        }//  ww  w.  j  a  v  a2 s .  c o  m
    }
    if (totalDisbursedAmount.compareTo(loan.getApprovedPrincipal()) == 0) {
        final String errorMessage = "loan.disbursement.cannot.be.a.edited";
        throw new LoanMultiDisbursementException(errorMessage);
    }
}

From source file:com.gst.portfolio.loanaccount.service.LoanWritePlatformServiceJpaRepositoryImpl.java

@Transactional
@Override//from   w w w .  ja va2 s . c om
public CommandProcessingResult disburseLoan(final Long loanId, final JsonCommand command,
        Boolean isAccountTransfer) {

    final AppUser currentUser = getAppUserIfPresent();

    this.loanEventApiJsonValidator.validateDisbursement(command.json(), isAccountTransfer);

    final Loan loan = this.loanAssembler.assembleFrom(loanId);

    final LocalDate actualDisbursementDate = command.localDateValueOfParameterNamed("actualDisbursementDate");
    // validate ActualDisbursement Date Against Expected Disbursement Date
    LoanProduct loanProduct = loan.loanProduct();
    if (loanProduct.syncExpectedWithDisbursementDate()) {
        syncExpectedDateWithActualDisbursementDate(loan, actualDisbursementDate);
    }
    checkClientOrGroupActive(loan);

    final LocalDate nextPossibleRepaymentDate = loan.getNextPossibleRepaymentDateForRescheduling();
    final Date rescheduledRepaymentDate = command.DateValueOfParameterNamed("adjustRepaymentDate");

    entityDatatableChecksWritePlatformService.runTheCheckForProduct(loanId, EntityTables.LOAN.getName(),
            StatusEnum.DISBURSE.getCode().longValue(), EntityTables.LOAN.getForeignKeyColumnNameOnDatatable(),
            loan.productId());

    // check for product mix validations
    checkForProductMixRestrictions(loan);

    LocalDate recalculateFrom = null;
    ScheduleGeneratorDTO scheduleGeneratorDTO = this.loanUtilService.buildScheduleGeneratorDTO(loan,
            recalculateFrom);

    // validate actual disbursement date against meeting date
    final CalendarInstance calendarInstance = this.calendarInstanceRepository
            .findCalendarInstaneByEntityId(loan.getId(), CalendarEntityType.LOANS.getValue());
    if (loan.isSyncDisbursementWithMeeting()) {
        this.loanEventApiJsonValidator.validateDisbursementDateWithMeetingDate(actualDisbursementDate,
                calendarInstance, scheduleGeneratorDTO.isSkipRepaymentOnFirstDayofMonth(),
                scheduleGeneratorDTO.getNumberOfdays());
    }

    this.businessEventNotifierService.notifyBusinessEventToBeExecuted(BUSINESS_EVENTS.LOAN_DISBURSAL,
            constructEntityMap(BUSINESS_ENTITY.LOAN, loan));

    final List<Long> existingTransactionIds = new ArrayList<>();
    final List<Long> existingReversedTransactionIds = new ArrayList<>();

    final Map<String, Object> changes = new LinkedHashMap<>();

    final PaymentDetail paymentDetail = this.paymentDetailWritePlatformService
            .createAndPersistPaymentDetail(command, changes);

    final Boolean isPaymnetypeApplicableforDisbursementCharge = configurationDomainService
            .isPaymnetypeApplicableforDisbursementCharge();

    // Recalculate first repayment date based in actual disbursement date.
    updateLoanCounters(loan, actualDisbursementDate);
    Money amountBeforeAdjust = loan.getPrincpal();
    loan.validateAccountStatus(LoanEvent.LOAN_DISBURSED);
    boolean canDisburse = loan.canDisburse(actualDisbursementDate);
    ChangedTransactionDetail changedTransactionDetail = null;
    if (canDisburse) {
        Money disburseAmount = loan.adjustDisburseAmount(command, actualDisbursementDate);
        Money amountToDisburse = disburseAmount.copy();
        boolean recalculateSchedule = amountBeforeAdjust.isNotEqualTo(loan.getPrincpal());
        final String txnExternalId = command.stringValueOfParameterNamedAllowingNull("externalId");

        if (loan.isTopup() && loan.getClientId() != null) {
            final Long loanIdToClose = loan.getTopupLoanDetails().getLoanIdToClose();
            final Loan loanToClose = this.loanRepositoryWrapper
                    .findNonClosedLoanThatBelongsToClient(loanIdToClose, loan.getClientId());
            if (loanToClose == null) {
                throw new GeneralPlatformDomainRuleException(
                        "error.msg.loan.to.be.closed.with.topup.is.not.active",
                        "Loan to be closed with this topup is not active.");
            }
            final LocalDate lastUserTransactionOnLoanToClose = loanToClose.getLastUserTransactionDate();
            if (!loan.getDisbursementDate().isAfter(lastUserTransactionOnLoanToClose)) {
                throw new GeneralPlatformDomainRuleException(
                        "error.msg.loan.disbursal.date.should.be.after.last.transaction.date.of.loan.to.be.closed",
                        "Disbursal date of this loan application " + loan.getDisbursementDate()
                                + " should be after last transaction date of loan to be closed "
                                + lastUserTransactionOnLoanToClose);
            }

            BigDecimal loanOutstanding = this.loanReadPlatformService
                    .retrieveLoanPrePaymentTemplate(loanIdToClose, actualDisbursementDate).getAmount();
            final BigDecimal firstDisbursalAmount = loan.getFirstDisbursalAmount();
            if (loanOutstanding.compareTo(firstDisbursalAmount) > 0) {
                throw new GeneralPlatformDomainRuleException(
                        "error.msg.loan.amount.less.than.outstanding.of.loan.to.be.closed",
                        "Topup loan amount should be greater than outstanding amount of loan to be closed.");
            }

            amountToDisburse = disburseAmount.minus(loanOutstanding);

            disburseLoanToLoan(loan, command, loanOutstanding);
        }

        if (isAccountTransfer) {
            disburseLoanToSavings(loan, command, amountToDisburse, paymentDetail);
            existingTransactionIds.addAll(loan.findExistingTransactionIds());
            existingReversedTransactionIds.addAll(loan.findExistingReversedTransactionIds());
        } else {
            existingTransactionIds.addAll(loan.findExistingTransactionIds());
            existingReversedTransactionIds.addAll(loan.findExistingReversedTransactionIds());
            LoanTransaction disbursementTransaction = LoanTransaction.disbursement(loan.getOffice(),
                    amountToDisburse, paymentDetail, actualDisbursementDate, txnExternalId,
                    DateUtils.getLocalDateTimeOfTenant(), currentUser);
            disbursementTransaction.updateLoan(loan);
            loan.addLoanTransaction(disbursementTransaction);
        }

        regenerateScheduleOnDisbursement(command, loan, recalculateSchedule, scheduleGeneratorDTO,
                nextPossibleRepaymentDate, rescheduledRepaymentDate);
        if (loan.repaymentScheduleDetail().isInterestRecalculationEnabled()) {
            createAndSaveLoanScheduleArchive(loan, scheduleGeneratorDTO);
        }
        if (isPaymnetypeApplicableforDisbursementCharge) {
            changedTransactionDetail = loan.disburse(currentUser, command, changes, scheduleGeneratorDTO,
                    paymentDetail);
        } else {
            changedTransactionDetail = loan.disburse(currentUser, command, changes, scheduleGeneratorDTO, null);
        }
    }
    if (!changes.isEmpty()) {
        saveAndFlushLoanWithDataIntegrityViolationChecks(loan);

        final String noteText = command.stringValueOfParameterNamed("note");
        if (StringUtils.isNotBlank(noteText)) {
            final Note note = Note.loanNote(loan, noteText);
            this.noteRepository.save(note);
        }

        if (changedTransactionDetail != null) {
            for (final Map.Entry<Long, LoanTransaction> mapEntry : changedTransactionDetail
                    .getNewTransactionMappings().entrySet()) {
                this.loanTransactionRepository.save(mapEntry.getValue());
                this.accountTransfersWritePlatformService.updateLoanTransaction(mapEntry.getKey(),
                        mapEntry.getValue());
            }
        }

        // auto create standing instruction
        createStandingInstruction(loan);

        postJournalEntries(loan, existingTransactionIds, existingReversedTransactionIds);

    }

    final Set<LoanCharge> loanCharges = loan.charges();
    final Map<Long, BigDecimal> disBuLoanCharges = new HashMap<>();
    for (final LoanCharge loanCharge : loanCharges) {
        if (loanCharge.isDueAtDisbursement() && loanCharge.getChargePaymentMode().isPaymentModeAccountTransfer()
                && loanCharge.isChargePending()) {
            disBuLoanCharges.put(loanCharge.getId(), loanCharge.amountOutstanding());
        }
    }

    final Locale locale = command.extractLocale();
    final DateTimeFormatter fmt = DateTimeFormat.forPattern(command.dateFormat()).withLocale(locale);
    for (final Map.Entry<Long, BigDecimal> entrySet : disBuLoanCharges.entrySet()) {
        final PortfolioAccountData savingAccountData = this.accountAssociationsReadPlatformService
                .retriveLoanLinkedAssociation(loanId);
        final SavingsAccount fromSavingsAccount = null;
        final boolean isRegularTransaction = true;
        final boolean isExceptionForBalanceCheck = false;
        final AccountTransferDTO accountTransferDTO = new AccountTransferDTO(actualDisbursementDate,
                entrySet.getValue(), PortfolioAccountType.SAVINGS, PortfolioAccountType.LOAN,
                savingAccountData.accountId(), loanId, "Loan Charge Payment", locale, fmt, null, null,
                LoanTransactionType.REPAYMENT_AT_DISBURSEMENT.getValue(), entrySet.getKey(), null,
                AccountTransferType.CHARGE_PAYMENT.getValue(), null, null, null, null, null, fromSavingsAccount,
                isRegularTransaction, isExceptionForBalanceCheck);
        this.accountTransfersWritePlatformService.transferFunds(accountTransferDTO);
    }

    updateRecurringCalendarDatesForInterestRecalculation(loan);
    this.loanAccountDomainService.recalculateAccruals(loan);
    this.businessEventNotifierService.notifyBusinessEventWasExecuted(BUSINESS_EVENTS.LOAN_DISBURSAL,
            constructEntityMap(BUSINESS_ENTITY.LOAN, loan));
    return new CommandProcessingResultBuilder() //
            .withCommandId(command.commandId()) //
            .withEntityId(loan.getId()) //
            .withOfficeId(loan.getOfficeId()) //
            .withClientId(loan.getClientId()) //
            .withGroupId(loan.getGroupId()) //
            .withLoanId(loanId) //
            .with(changes) //
            .build();
}

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

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

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

    String invoiceId = (String) context.get("invoiceId");
    GenericValue invoice = null;
    try {
        invoice = EntityQuery.use(delegator).from("Invoice").where("invoiceId", invoiceId).queryOne();
    } catch (GenericEntityException e) {
        Debug.logError(e, "Problem getting Invoice for Invoice ID" + invoiceId, module);
        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "AccountingInvoiceNotFound",
                UtilMisc.toMap("invoiceId", invoiceId), locale));
    }

    // Ignore invoices that aren't ready yet
    if (!invoice.getString("statusId").equals("INVOICE_READY")) {
        return ServiceUtil.returnSuccess();
    }

    // Get the payment applications that can be used to pay the invoice
    List<GenericValue> paymentAppl = null;
    try {
        paymentAppl = EntityQuery.use(delegator).from("PaymentAndApplication").where("invoiceId", invoiceId)
                .queryList();
        // For each payment application, select only those that are RECEIVED or SENT based on whether the payment is a RECEIPT or DISBURSEMENT respectively
        for (Iterator<GenericValue> iter = paymentAppl.iterator(); iter.hasNext();) {
            GenericValue payment = iter.next();
            if ("PMNT_RECEIVED".equals(payment.get("statusId")) && UtilAccounting.isReceipt(payment)) {
                continue; // keep
            }
            if ("PMNT_SENT".equals(payment.get("statusId")) && UtilAccounting.isDisbursement(payment)) {
                continue; // keep
            }
            // all other cases, remove the payment application
            iter.remove();
        }
    } catch (GenericEntityException e) {
        Debug.logError(e, "Problem getting PaymentApplication(s) for Invoice ID " + invoiceId, module);
        return ServiceUtil.returnError(UtilProperties.getMessage(resource,
                "AccountingProblemGettingPaymentApplication", UtilMisc.toMap("invoiceId", invoiceId), locale));
    }

    Map<String, BigDecimal> payments = new HashMap<String, BigDecimal>();
    Timestamp paidDate = null;
    for (GenericValue payAppl : paymentAppl) {
        payments.put(payAppl.getString("paymentId"), payAppl.getBigDecimal("amountApplied"));

        // paidDate will be the last date (chronologically) of all the Payments applied to this invoice
        Timestamp paymentDate = payAppl.getTimestamp("effectiveDate");
        if (paymentDate != null) {
            if ((paidDate == null) || (paidDate.before(paymentDate))) {
                paidDate = paymentDate;
            }
        }
    }

    BigDecimal totalPayments = ZERO;
    for (BigDecimal amount : payments.values()) {
        if (amount == null)
            amount = ZERO;
        totalPayments = totalPayments.add(amount).setScale(DECIMALS, ROUNDING);
    }

    if (totalPayments.signum() == 1) {
        BigDecimal invoiceTotal = InvoiceWorker.getInvoiceTotal(delegator, invoiceId);
        if (Debug.verboseOn()) {
            Debug.logVerbose("Invoice #" + invoiceId + " total: " + invoiceTotal, module);
            Debug.logVerbose("Total payments : " + totalPayments, module);
        }
        if (totalPayments.compareTo(invoiceTotal) >= 0) { // this checks that totalPayments is greater than or equal to invoiceTotal
            // this invoice is paid
            Map<String, Object> svcCtx = UtilMisc.toMap("statusId", "INVOICE_PAID", "invoiceId", invoiceId,
                    "paidDate", paidDate, "userLogin", userLogin);
            try {
                dispatcher.runSync("setInvoiceStatus", svcCtx);
            } catch (GenericServiceException e) {
                Debug.logError(e, "Problem changing invoice status to INVOICE_PAID" + svcCtx, module);
                return ServiceUtil.returnError(
                        UtilProperties.getMessage(resource, "AccountingProblemChangingInvoiceStatusTo",
                                UtilMisc.toMap("newStatus", "INVOICE_PAID"), locale));
            }
        }
    } else {
        Debug.logInfo("No payments found for Invoice #" + invoiceId, module);
    }

    return ServiceUtil.returnSuccess();
}

From source file:com.gst.portfolio.loanproduct.serialization.LoanProductDataValidator.java

private void validatePrincipalMinMaxConstraint(final JsonElement element, final LoanProduct loanProduct,
        final DataValidatorBuilder baseDataValidator) {

    boolean principalUpdated = false;
    boolean minPrincipalUpdated = false;
    boolean maxPrincipalUpdated = false;
    final String principalParameterName = "principal";
    BigDecimal principalAmount = null;
    if (this.fromApiJsonHelper.parameterExists(principalParameterName, element)) {
        principalAmount = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed(principalParameterName,
                element);/*from www .j  a  v  a  2  s  . co m*/
        principalUpdated = true;
    } else {
        principalAmount = loanProduct.getPrincipalAmount().getAmount();
    }

    final String minPrincipalParameterName = "minPrincipal";
    BigDecimal minPrincipalAmount = null;
    if (this.fromApiJsonHelper.parameterExists(minPrincipalParameterName, element)) {
        minPrincipalAmount = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed(minPrincipalParameterName,
                element);
        minPrincipalUpdated = true;
    } else {
        minPrincipalAmount = loanProduct.getMinPrincipalAmount().getAmount();
    }

    final String maxPrincipalParameterName = "maxPrincipal";
    BigDecimal maxPrincipalAmount = null;
    if (this.fromApiJsonHelper.parameterExists(maxPrincipalParameterName, element)) {
        maxPrincipalAmount = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed(maxPrincipalParameterName,
                element);
        maxPrincipalUpdated = true;
    } else {
        maxPrincipalAmount = loanProduct.getMaxPrincipalAmount().getAmount();
    }

    if (minPrincipalUpdated) {
        baseDataValidator.reset().parameter(minPrincipalParameterName).value(minPrincipalAmount)
                .notGreaterThanMax(maxPrincipalAmount);
    }

    if (maxPrincipalUpdated) {
        baseDataValidator.reset().parameter(maxPrincipalParameterName).value(maxPrincipalAmount)
                .notLessThanMin(minPrincipalAmount);
    }

    if ((principalUpdated || minPrincipalUpdated || maxPrincipalUpdated)) {

        if ((minPrincipalAmount != null && minPrincipalAmount.compareTo(BigDecimal.ZERO) == 1)
                && (maxPrincipalAmount != null && maxPrincipalAmount.compareTo(BigDecimal.ZERO) == 1)) {
            baseDataValidator.reset().parameter(principalParameterName).value(principalAmount)
                    .inMinAndMaxAmountRange(minPrincipalAmount, maxPrincipalAmount);
        } else {
            if (minPrincipalAmount != null && minPrincipalAmount.compareTo(BigDecimal.ZERO) == 1) {
                baseDataValidator.reset().parameter(principalParameterName).value(principalAmount)
                        .notLessThanMin(minPrincipalAmount);
            } else if (maxPrincipalAmount != null && maxPrincipalAmount.compareTo(BigDecimal.ZERO) == 1) {
                baseDataValidator.reset().parameter(principalParameterName).value(principalAmount)
                        .notGreaterThanMax(maxPrincipalAmount);
            }
        }
    }
}

From source file:org.egov.dao.budget.BudgetDetailsHibernateDAO.java

/**
 * This API is handling the budget checking
 * //w ww. j  a v  a  2s. c o m
 * @param paramMap
 *            paramMap contains 1. debitAmt (mandatory) 2. creditAmt
 *            (mandatory) 3. deptid (optional) 4. functionid (optional) 5.
 *            functionaryid (optional) 6. schemeid (optional) 7. subschemeid
 *            (optional) 8. boundaryid (optional) 9. glcode (mandatory) -
 *            based on the glcode, we can get the budgetheadid 10. asondate
 *            (manadtory) - to get the actuals, we need asondate 11.
 *            mis.budgetcheckreq-Boolean- (optional) to skip budget check if
 *            set to false.Default is true Budget checking will be enabled
 *            or disabled by these levels and in the order a. Application -
 *            uses set up "Budget Control Type" b. Voucherlevel - uses
 *            budgetcheckreq column of vouchermis table for perticular
 *            voucher c. Debit or Credit level - uses Budgetgroup.budgetting
 *            type for debit side only ,credit side or both d. Glcode level
 *            - Uses chartofaccounts.budgetcheckreq fieled to decide budget
 *            checking .
 * @return @
 */
@Override
public boolean budgetaryCheck(final Map<String, Object> paramMap) {
    String cashbasedbudgetType = EMPTY_STRING, txnType = EMPTY_STRING;
    BigDecimal debitAmt = null;
    BigDecimal creditAmt = null;
    BigDecimal txnAmt = null;

    try {

        String budgetCheckConfig = budgetCheckConfigService.getConfigValue();

        if (budgetCheckConfig.equals("NONE"))
            return true;

        if (paramMap.get("mis.budgetcheckreq") != null
                && ((Boolean) paramMap.get("mis.budgetcheckreq")).equals(false))
            return true;

        if (paramMap.get("debitAmt") != null)
            debitAmt = (BigDecimal) paramMap.get("debitAmt");
        if (paramMap.get("creditAmt") != null)
            creditAmt = (BigDecimal) paramMap.get("creditAmt");

        if (debitAmt == null && creditAmt == null)
            throw new ValidationException(EMPTY_STRING, "Both Debit and Credit amount is null");

        if (debitAmt != null && debitAmt.compareTo(BigDecimal.ZERO) == 0 && creditAmt != null
                && creditAmt.compareTo(BigDecimal.ZERO) == 0)
            throw new ValidationException(EMPTY_STRING, "Both Debit and Credit amount is zero");

        if (debitAmt != null && debitAmt.compareTo(BigDecimal.ZERO) > 0 && creditAmt != null
                && creditAmt.compareTo(BigDecimal.ZERO) > 0)
            throw new ValidationException(EMPTY_STRING, "Both Debit and Credit amount is greater than zero");

        // get the type of budget from appconfig .
        List<AppConfigValues> list;
        list = appConfigValuesService.getConfigValuesByModuleAndKey(EGF, "budgetaryCheck_budgettype_cashbased");
        if (list.isEmpty())
            throw new ValidationException(EMPTY_STRING,
                    "budgetaryCheck_budgettype_cashbased is not defined in AppConfig");

        cashbasedbudgetType = list.get(0).getValue();
        if (cashbasedbudgetType.equalsIgnoreCase("Y")) // cash based budget
        {
            if (LOGGER.isDebugEnabled())
                LOGGER.debug("cashbasedbudgetType==" + cashbasedbudgetType);
        } else // Accural based budgeting
        {
            if (debitAmt != null && debitAmt.compareTo(BigDecimal.ZERO) > 0) {
                txnType = "debit";
                txnAmt = debitAmt;
            } else {
                txnType = "credit";
                txnAmt = creditAmt;
            }
            paramMap.put("txnAmt", txnAmt);
            paramMap.put("txnType", txnType);
            return checkCondition(paramMap);
        }
    } catch (final ValidationException v) {
        throw v;
    } catch (final Exception e) {
        throw new ValidationException(EMPTY_STRING, e.getMessage());
    }
    return true;
}