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.allowance.PnlAllowance.java

private JPanel createContentPanel4(final Resident resident, LocalDate month) {
    final String key = getKey(resident, month);

    if (!contentmap.containsKey(key)) {

        JPanel pnlMonth = new JPanel(new VerticalLayout());

        pnlMonth.setBackground(getBG(resident, 11));
        pnlMonth.setOpaque(false);/*from ww w.  j  a v  a2s . c  o m*/

        //            final String prevKey = resident.getRID() + "-" + SYSCalendar.eom(month.minusMonths(1)).getYear() + "-" + SYSCalendar.eom(month.minusMonths(1)).getMonthOfYear();
        if (!carrySums.containsKey(key)) {
            carrySums.put(key, AllowanceTools.getSUM(resident, SYSCalendar.eom(month.minusMonths(1))));
        }

        BigDecimal rowsum = carrySums.get(key);

        if (!cashmap.containsKey(key)) {
            cashmap.put(key, AllowanceTools.getMonth(resident, month.toDate()));
        }

        JLabel lblEOM = new JLabel("<html><table border=\"0\">" + "<tr>" + "<td width=\"130\" align=\"left\">"
                + DateFormat.getDateInstance().format(month.dayOfMonth().withMaximumValue().toDate()) + "</td>"
                + "<td width=\"400\" align=\"left\">" + SYSTools.xx("admin.residents.cash.endofmonth") + "</td>"
                + "<td width=\"100\" align=\"right\"></td>" + "<td width=\"100\" align=\"right\">"
                + (rowsum.compareTo(BigDecimal.ZERO) < 0 ? "<font color=\"red\">" : "") + cf.format(rowsum)
                + (rowsum.compareTo(BigDecimal.ZERO) < 0 ? "</font>" : "") + "</td>" + "</tr>" + "</table>" +

                "</font></html>");
        pnlMonth.add(lblEOM);

        for (final Allowance allowance : cashmap.get(key)) {

            String title = "<html><table border=\"0\">" + "<tr>" + "<td width=\"130\" align=\"left\">"
                    + DateFormat.getDateInstance().format(allowance.getPit()) + "</td>"
                    + "<td width=\"400\" align=\"left\">" + allowance.getText() + "</td>"
                    + "<td width=\"100\" align=\"right\">"
                    + (allowance.getAmount().compareTo(BigDecimal.ZERO) < 0 ? "<font color=\"red\">" : "")
                    + cf.format(allowance.getAmount())
                    + (allowance.getAmount().compareTo(BigDecimal.ZERO) < 0 ? "</font>" : "") + "</td>"
                    + "<td width=\"100\" align=\"right\">"
                    + (rowsum.compareTo(BigDecimal.ZERO) < 0 ? "<font color=\"red\">" : "") + cf.format(rowsum)
                    + (rowsum.compareTo(BigDecimal.ZERO) < 0 ? "</font>" : "") + "</td>" + "</tr>" + "</table>"
                    +

                    "</font></html>";

            DefaultCPTitle cptitle = new DefaultCPTitle(title, new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {

                }
            });
            cptitle.getButton().setIcon(
                    allowance.isReplaced() || allowance.isReplacement() ? SYSConst.icon22eraser : null);

            if (OPDE.getAppInfo().isAllowedTo(InternalClassACL.UPDATE, internalClassID)) {
                /***
                 *      _____    _ _ _
                 *     | ____|__| (_) |_
                 *     |  _| / _` | | __|
                 *     | |__| (_| | | |_
                 *     |_____\__,_|_|\__|
                 *
                 */
                final JButton btnEdit = new JButton(SYSConst.icon22edit3);
                btnEdit.setPressedIcon(SYSConst.icon22edit3Pressed);
                btnEdit.setAlignmentX(Component.RIGHT_ALIGNMENT);
                btnEdit.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
                btnEdit.setContentAreaFilled(false);
                btnEdit.setBorder(null);
                btnEdit.setToolTipText(SYSTools.xx("admin.residents.cash.btnedit.tooltip"));
                btnEdit.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent actionEvent) {

                        final JidePopup popupTX = new JidePopup();
                        popupTX.setMovable(false);
                        PnlTX pnlTX = getPnlTX(resident, allowance);
                        popupTX.setContentPane(pnlTX);
                        popupTX.removeExcludedComponent(pnlTX);
                        popupTX.setDefaultFocusComponent(pnlTX);

                        popupTX.setOwner(btnEdit);
                        GUITools.showPopup(popupTX, SwingConstants.WEST);

                    }
                });
                cptitle.getRight().add(btnEdit);
                // you can edit your own entries or you are a manager. once they are replaced or a replacement record, its over.
                btnEdit.setEnabled((OPDE.getAppInfo().isAllowedTo(InternalClassACL.MANAGER, internalClassID)
                        || allowance.getUser().equals(OPDE.getLogin().getUser())) && !allowance.isReplaced()
                        && !allowance.isReplacement());

                /***
                 *      _   _           _         _______  __
                 *     | | | |_ __   __| | ___   |_   _\ \/ /
                 *     | | | | '_ \ / _` |/ _ \    | |  \  /
                 *     | |_| | | | | (_| | (_) |   | |  /  \
                 *      \___/|_| |_|\__,_|\___/    |_| /_/\_\
                 *
                 */
                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("admin.residents.cash.btnundotx.tooltip"));
                btnUndoTX.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent actionEvent) {

                        new DlgYesNo(
                                SYSTools.xx("misc.questions.undo1") + "<br/><i>" + "<br/><i>"
                                        + allowance.getText() + "&nbsp;" + cf.format(allowance.getAmount())
                                        + "</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();

                                                Allowance myOldAllowance = em.merge(allowance);
                                                Allowance myCancelAllowance = em
                                                        .merge(new Allowance(myOldAllowance));
                                                em.lock(em.merge(myOldAllowance.getResident()),
                                                        LockModeType.OPTIMISTIC);
                                                em.lock(myOldAllowance, LockModeType.OPTIMISTIC);
                                                myOldAllowance.setReplacedBy(myCancelAllowance,
                                                        em.merge(OPDE.getLogin().getUser()));

                                                em.getTransaction().commit();

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

                                                final String keyMonth = myCancelAllowance.getResident().getRID()
                                                        + "-" + txDate.getYear() + "-"
                                                        + txDate.getMonthOfYear();
                                                contentmap.remove(keyMonth);
                                                cpMap.remove(keyMonth);
                                                cashmap.get(keyMonth).remove(allowance);
                                                cashmap.get(keyMonth).add(myOldAllowance);
                                                cashmap.get(keyMonth).add(myCancelAllowance);
                                                Collections.sort(cashmap.get(keyMonth));

                                                updateCarrySums(myCancelAllowance);

                                                createCP4(myCancelAllowance.getResident());

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

                                                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();
                                            }
                                        }
                                    }
                                });
                    }
                });
                cptitle.getRight().add(btnUndoTX);
                btnUndoTX.setEnabled(!allowance.isReplaced() && !allowance.isReplacement());
            }

            if (OPDE.getAppInfo().isAllowedTo(InternalClassACL.DELETE, internalClassID)) {
                /***
                 *      ____       _      _
                 *     |  _ \  ___| | ___| |_ ___
                 *     | | | |/ _ \ |/ _ \ __/ _ \
                 *     | |_| |  __/ |  __/ ||  __/
                 *     |____/ \___|_|\___|\__\___|
                 *
                 */
                final JButton btnDelete = new JButton(SYSConst.icon22delete);
                btnDelete.setPressedIcon(SYSConst.icon22deletePressed);
                btnDelete.setAlignmentX(Component.RIGHT_ALIGNMENT);
                btnDelete.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
                btnDelete.setContentAreaFilled(false);
                btnDelete.setBorder(null);
                btnDelete.setToolTipText(SYSTools.xx("admin.residents.cash.btndelete.tooltip"));
                btnDelete.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent actionEvent) {
                        new DlgYesNo(
                                SYSTools.xx("misc.questions.delete1") + "<br/><i>" + allowance.getText()
                                        + "&nbsp;" + cf.format(allowance.getAmount()) + "</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();
                                                Allowance myAllowance = em.merge(allowance);
                                                em.lock(em.merge(myAllowance.getResident()),
                                                        LockModeType.OPTIMISTIC);

                                                Allowance theOtherOne = null;
                                                // Check for special cases
                                                if (myAllowance.isReplacement()) {
                                                    theOtherOne = em.merge(myAllowance.getReplacementFor());
                                                    theOtherOne.setReplacedBy(null);
                                                    theOtherOne.setEditedBy(null);
                                                    myAllowance.setEditPit(null);
                                                }
                                                if (myAllowance.isReplaced()) {
                                                    theOtherOne = em.merge(myAllowance.getReplacedBy());
                                                    theOtherOne.setReplacementFor(null);
                                                }

                                                em.remove(myAllowance);
                                                em.getTransaction().commit();

                                                DateTime txDate = new DateTime(myAllowance.getPit());
                                                final String keyMonth = myAllowance.getResident().getRID() + "-"
                                                        + txDate.getYear() + "-" + txDate.getMonthOfYear();

                                                cpMap.remove(keyMonth);
                                                cashmap.get(keyMonth).remove(myAllowance);
                                                if (theOtherOne != null) {
                                                    cashmap.get(keyMonth).remove(theOtherOne);
                                                    cashmap.get(keyMonth).add(theOtherOne);
                                                    Collections.sort(cashmap.get(keyMonth));
                                                }

                                                // only to update the carrysums. myAllowance will be discarded soon.
                                                myAllowance.setAmount(myAllowance.getAmount().negate());
                                                updateCarrySums(myAllowance);

                                                createCP4(myAllowance.getResident());

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

                                                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();
                                            }
                                        }
                                    }
                                });
                    }
                });
                cptitle.getRight().add(btnDelete);
            }
            pnlMonth.add(cptitle.getMain());
            linemap.put(allowance, cptitle.getMain());

            rowsum = rowsum.subtract(allowance.getAmount());
        }

        JLabel lblBOM = new JLabel("<html><table border=\"0\">" + "<tr>" + "<td width=\"130\" align=\"left\">"
                + DateFormat.getDateInstance().format(month.dayOfMonth().withMinimumValue().toDate()) + "</td>"
                + "<td width=\"400\" align=\"left\">" + SYSTools.xx("admin.residents.cash.startofmonth")
                + "</td>" + "<td width=\"100\" align=\"right\"></td>" + "<td width=\"100\" align=\"right\">"
                + (rowsum.compareTo(BigDecimal.ZERO) < 0 ? "<font color=\"red\">" : "") + cf.format(rowsum)
                + (rowsum.compareTo(BigDecimal.ZERO) < 0 ? "</font>" : "") + "</td>" + "</tr>" + "</table>" +

                "</font></html>");
        lblBOM.setBackground(getBG(resident, 11));
        pnlMonth.add(lblBOM);
        contentmap.put(key, pnlMonth);
    }

    return contentmap.get(key);
}

From source file:org.apache.fineract.portfolio.loanaccount.domain.LoanCharge.java

public Map<String, Object> update(final JsonCommand command, final BigDecimal amount) {

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

    final String dateFormatAsInput = command.dateFormat();
    final String localeAsInput = command.locale();

    final String dueDateParamName = "dueDate";
    if (command.isChangeInLocalDateParameterNamed(dueDateParamName, getDueLocalDate())) {
        final String valueAsInput = command.stringValueOfParameterNamed(dueDateParamName);
        actualChanges.put(dueDateParamName, valueAsInput);
        actualChanges.put("dateFormat", dateFormatAsInput);
        actualChanges.put("locale", localeAsInput);

        final LocalDate newValue = command.localDateValueOfParameterNamed(dueDateParamName);
        this.dueDate = newValue.toDate();
    }//from  w  w w .  jav a  2  s  .com

    final String amountParamName = "amount";
    if (command.isChangeInBigDecimalParameterNamed(amountParamName, this.amount)) {
        final BigDecimal newValue = command.bigDecimalValueOfParameterNamed(amountParamName);
        BigDecimal loanCharge = null;
        actualChanges.put(amountParamName, newValue);
        actualChanges.put("locale", localeAsInput);
        switch (ChargeCalculationType.fromInt(this.chargeCalculation)) {
        case INVALID:
            break;
        case FLAT:
            if (isInstalmentFee()) {
                this.amount = newValue
                        .multiply(BigDecimal.valueOf(this.loan.fetchNumberOfInstallmensAfterExceptions()));
            } else {
                this.amount = newValue;
            }
            this.amountOutstanding = calculateOutstanding();
            break;
        case PERCENT_OF_AMOUNT:
        case PERCENT_OF_AMOUNT_AND_INTEREST:
        case PERCENT_OF_INTEREST:
        case PERCENT_OF_DISBURSEMENT_AMOUNT:
            this.percentage = newValue;
            this.amountPercentageAppliedTo = amount;
            loanCharge = BigDecimal.ZERO;
            if (isInstalmentFee()) {
                loanCharge = this.loan.calculatePerInstallmentChargeAmount(
                        ChargeCalculationType.fromInt(this.chargeCalculation), this.percentage);
            }
            if (loanCharge.compareTo(BigDecimal.ZERO) == 0) {
                loanCharge = percentageOf(this.amountPercentageAppliedTo);
            }
            this.amount = minimumAndMaximumCap(loanCharge);
            this.amountOutstanding = calculateOutstanding();
            break;
        }
        this.amountOrPercentage = newValue;
        if (isInstalmentFee()) {
            updateInstallmentCharges();
        }
    }
    return actualChanges;
}

From source file:com.visionet.platform.cooperation.service.OrderService.java

public void noticeDriver(String orderNo, String partnerOrderNo, BigDecimal amount) {
    if (orderNo == null) {
        throw new BizException("?orderNo");
    }//  w ww  .j av a  2 s  .  com
    Order order = orderMapper.selectByPrimaryKey(orderNo);
    if (order == null) {
        throw new BizException("??");
    }
    if (partnerOrderNo == null) {
        throw new BizException("?partnerOrderNo");
    }
    if (amount == null) {
        throw new BizException("?amount");
    }
    if (amount.compareTo(BigDecimal.valueOf(0)) != 1) {//-1? 0 1  ???0??
        throw new BizException("??0");
    }
    ThirdPartyOrder thirdPartyOrder = thirdPartyOrderMapper.selectByOrderIdAndPartnerOrderNo(orderNo,
            partnerOrderNo);
    if (thirdPartyOrder == null) {
        throw new BizException("??");
    }
    thirdPartyOrder.setPayAmount(amount);
    thirdPartyOrder.setPayType(2);
    thirdPartyOrder.setPayStatus(1);
    if (!(thirdPartyOrderMapper.updateByPrimaryKeySelective(thirdPartyOrder) > 0)) {
        throw new BizException("??update");
    }
}

From source file:net.shopxx.controller.shop.OrderController.java

@RequestMapping(value = "/create", params = "type=exchange", method = RequestMethod.POST)
public @ResponseBody Map<String, Object> create(Long productId, Integer quantity, Long receiverId,
        Long paymentMethodId, Long shippingMethodId, BigDecimal balance, String memo) {
    Map<String, Object> data = new HashMap<String, Object>();
    if (quantity == null || quantity < 1) {
        data.put("message", ERROR_MESSAGE);
        return data;
    }//from www .  j  a  v a2  s .c  o m
    Product product = productService.find(productId);
    if (product == null) {
        data.put("message", ERROR_MESSAGE);
        return data;
    }
    if (!Goods.Type.exchange.equals(product.getType())) {
        data.put("message", ERROR_MESSAGE);
        return data;
    }
    if (!product.getIsMarketable()) {
        data.put("message", Message.warn("shop.order.productNotMarketable"));
        return data;
    }
    if (quantity > product.getAvailableStock()) {
        data.put("message", Message.warn("shop.order.productLowStock"));
        return data;
    }
    Member member = memberService.getCurrent();
    Receiver receiver = null;
    ShippingMethod shippingMethod = null;
    PaymentMethod paymentMethod = paymentMethodService.find(paymentMethodId);
    if (product.getIsDelivery()) {
        receiver = receiverService.find(receiverId);
        if (receiver == null || !member.equals(receiver.getMember())) {
            data.put("message", ERROR_MESSAGE);
            return data;
        }
        shippingMethod = shippingMethodService.find(shippingMethodId);
        if (shippingMethod == null) {
            data.put("message", ERROR_MESSAGE);
            return data;
        }
    }
    if (member.getPoint() < product.getExchangePoint() * quantity) {
        data.put("message", Message.warn("shop.order.lowPoint"));
        return data;
    }
    if (balance != null && balance.compareTo(member.getBalance()) > 0) {
        data.put("message", Message.warn("shop.order.insufficientBalance"));
        return data;
    }
    Set<CartItem> cartItems = new HashSet<CartItem>();
    CartItem cartItem = new CartItem();
    cartItem.setProduct(product);
    cartItem.setQuantity(quantity);
    cartItems.add(cartItem);
    Cart cart = new Cart();
    cart.setMember(member);
    cart.setCartItems(cartItems);

    Order order = orderService.create(Order.Type.exchange, cart, receiver, paymentMethod, shippingMethod, null,
            null, balance, memo);

    data.put("message", SUCCESS_MESSAGE);
    data.put("sn", order.getSn());
    return data;
}

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

@Transactional
@Override/*  ww  w. ja va 2 s. c  om*/
public CommandProcessingResult modifyApplication(final Long loanId, final JsonCommand command) {

    try {
        AppUser currentUser = getAppUserIfPresent();
        final Loan existingLoanApplication = retrieveLoanBy(loanId);
        if (!existingLoanApplication.isSubmittedAndPendingApproval()) {
            throw new LoanApplicationNotInSubmittedAndPendingApprovalStateCannotBeModified(loanId);
        }

        final String productIdParamName = "productId";
        LoanProduct newLoanProduct = null;
        if (command.isChangeInLongParameterNamed(productIdParamName,
                existingLoanApplication.loanProduct().getId())) {
            final Long productId = command.longValueOfParameterNamed(productIdParamName);
            newLoanProduct = this.loanProductRepository.findOne(productId);
            if (newLoanProduct == null) {
                throw new LoanProductNotFoundException(productId);
            }
        }

        LoanProduct loanProductForValidations = newLoanProduct == null ? existingLoanApplication.loanProduct()
                : newLoanProduct;

        this.fromApiJsonDeserializer.validateForModify(command.json(), loanProductForValidations,
                existingLoanApplication);

        checkClientOrGroupActive(existingLoanApplication);

        final Set<LoanCharge> existingCharges = existingLoanApplication.charges();
        Map<Long, LoanChargeData> chargesMap = new HashMap<>();
        for (LoanCharge charge : existingCharges) {
            LoanChargeData chargeData = new LoanChargeData(charge.getId(), charge.getDueLocalDate(),
                    charge.amountOrPercentage());
            chargesMap.put(charge.getId(), chargeData);
        }
        List<LoanDisbursementDetails> disbursementDetails = this.loanUtilService
                .fetchDisbursementData(command.parsedJson().getAsJsonObject());

        /**
         * Stores all charges which are passed in during modify loan
         * application
         **/
        final Set<LoanCharge> possiblyModifedLoanCharges = this.loanChargeAssembler
                .fromParsedJson(command.parsedJson(), disbursementDetails);
        /** Boolean determines if any charge has been modified **/
        boolean isChargeModified = false;

        Set<Charge> newTrancheChages = this.loanChargeAssembler.getNewLoanTrancheCharges(command.parsedJson());
        for (Charge charge : newTrancheChages) {
            existingLoanApplication.addTrancheLoanCharge(charge);
        }

        /**
         * If there are any charges already present, which are now not
         * passed in as a part of the request, deem the charges as modified
         **/
        if (!possiblyModifedLoanCharges.isEmpty()) {
            if (!possiblyModifedLoanCharges.containsAll(existingCharges)) {
                isChargeModified = true;
            }
        }

        /**
         * If any new charges are added or values of existing charges are
         * modified
         **/
        for (LoanCharge loanCharge : possiblyModifedLoanCharges) {
            if (loanCharge.getId() == null) {
                isChargeModified = true;
            } else {
                LoanChargeData chargeData = chargesMap.get(loanCharge.getId());
                if (loanCharge.amountOrPercentage().compareTo(chargeData.amountOrPercentage()) != 0
                        || (loanCharge.isSpecifiedDueDate()
                                && !loanCharge.getDueLocalDate().equals(chargeData.getDueDate()))) {
                    isChargeModified = true;
                }
            }
        }

        final Set<LoanCollateral> possiblyModifedLoanCollateralItems = this.loanCollateralAssembler
                .fromParsedJson(command.parsedJson());

        final Map<String, Object> changes = existingLoanApplication.loanApplicationModification(command,
                possiblyModifedLoanCharges, possiblyModifedLoanCollateralItems, this.aprCalculator,
                isChargeModified);

        if (changes.containsKey("expectedDisbursementDate")) {
            this.loanAssembler.validateExpectedDisbursementForHolidayAndNonWorkingDay(existingLoanApplication);
        }

        final String clientIdParamName = "clientId";
        if (changes.containsKey(clientIdParamName)) {
            final Long clientId = command.longValueOfParameterNamed(clientIdParamName);
            final Client client = this.clientRepository.findOneWithNotFoundDetection(clientId);
            if (client.isNotActive()) {
                throw new ClientNotActiveException(clientId);
            }

            existingLoanApplication.updateClient(client);
        }

        final String groupIdParamName = "groupId";
        if (changes.containsKey(groupIdParamName)) {
            final Long groupId = command.longValueOfParameterNamed(groupIdParamName);
            final Group group = this.groupRepository.findOneWithNotFoundDetection(groupId);
            if (group.isNotActive()) {
                throw new GroupNotActiveException(groupId);
            }

            existingLoanApplication.updateGroup(group);
        }

        if (newLoanProduct != null) {
            existingLoanApplication.updateLoanProduct(newLoanProduct);
            if (!changes.containsKey("interestRateFrequencyType")) {
                existingLoanApplication.updateInterestRateFrequencyType();
            }
            final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
            final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors)
                    .resource("loan");
            if (newLoanProduct.useBorrowerCycle()) {
                final Long clientId = this.fromJsonHelper.extractLongNamed("clientId", command.parsedJson());
                final Long groupId = this.fromJsonHelper.extractLongNamed("groupId", command.parsedJson());
                Integer cycleNumber = 0;
                if (clientId != null) {
                    cycleNumber = this.loanReadPlatformService.retriveLoanCounter(clientId,
                            newLoanProduct.getId());
                } else if (groupId != null) {
                    cycleNumber = this.loanReadPlatformService.retriveLoanCounter(groupId,
                            AccountType.GROUP.getValue(), newLoanProduct.getId());
                }
                this.loanProductCommandFromApiJsonDeserializer.validateMinMaxConstraints(command.parsedJson(),
                        baseDataValidator, newLoanProduct, cycleNumber);
            } else {
                this.loanProductCommandFromApiJsonDeserializer.validateMinMaxConstraints(command.parsedJson(),
                        baseDataValidator, newLoanProduct);
            }
            if (newLoanProduct.isLinkedToFloatingInterestRate()) {
                existingLoanApplication.getLoanProductRelatedDetail().updateForFloatingInterestRates();
            } else {
                existingLoanApplication.setInterestRateDifferential(null);
                existingLoanApplication.setIsFloatingInterestRate(null);
            }
            if (!dataValidationErrors.isEmpty()) {
                throw new PlatformApiDataValidationException(dataValidationErrors);
            }
        }

        existingLoanApplication.updateIsInterestRecalculationEnabled();
        validateSubmittedOnDate(existingLoanApplication);

        final LoanProductRelatedDetail productRelatedDetail = existingLoanApplication.repaymentScheduleDetail();
        if (existingLoanApplication.loanProduct().getLoanProductConfigurableAttributes() != null) {
            updateProductRelatedDetails(productRelatedDetail, existingLoanApplication);
        }

        if (existingLoanApplication.getLoanProduct().canUseForTopup()
                && existingLoanApplication.getClientId() != null) {
            final Boolean isTopup = command.booleanObjectValueOfParameterNamed(LoanApiConstants.isTopup);
            if (command.isChangeInBooleanParameterNamed(LoanApiConstants.isTopup,
                    existingLoanApplication.isTopup())) {
                existingLoanApplication.setIsTopup(isTopup);
                changes.put(LoanApiConstants.isTopup, isTopup);
            }

            if (existingLoanApplication.isTopup()) {
                final Long loanIdToClose = command.longValueOfParameterNamed(LoanApiConstants.loanIdToClose);
                LoanTopupDetails existingLoanTopupDetails = existingLoanApplication.getTopupLoanDetails();
                if (existingLoanTopupDetails == null
                        || (existingLoanTopupDetails != null
                                && existingLoanTopupDetails.getLoanIdToClose() != loanIdToClose)
                        || changes.containsKey("submittedOnDate")
                        || changes.containsKey("expectedDisbursementDate") || changes.containsKey("principal")
                        || changes.containsKey(LoanApiConstants.disbursementDataParameterName)) {
                    Long existingLoanIdToClose = null;
                    if (existingLoanTopupDetails != null) {
                        existingLoanIdToClose = existingLoanTopupDetails.getLoanIdToClose();
                    }
                    final Loan loanToClose = this.loanRepositoryWrapper.findNonClosedLoanThatBelongsToClient(
                            loanIdToClose, existingLoanApplication.getClientId());
                    if (loanToClose == null) {
                        throw new GeneralPlatformDomainRuleException(
                                "error.msg.loan.loanIdToClose.no.active.loan.associated.to.client.found",
                                "loanIdToClose is invalid, No Active Loan associated with the given Client ID found.");
                    }
                    if (loanToClose.isMultiDisburmentLoan()
                            && !loanToClose.isInterestRecalculationEnabledForProduct()) {
                        throw new GeneralPlatformDomainRuleException(
                                "error.msg.loan.topup.on.multi.tranche.loan.without.interest.recalculation.not.supported",
                                "Topup on loan with multi-tranche disbursal and without interest recalculation is not supported.");
                    }
                    final LocalDate disbursalDateOfLoanToClose = loanToClose.getDisbursementDate();
                    if (!existingLoanApplication.getSubmittedOnDate().isAfter(disbursalDateOfLoanToClose)) {
                        throw new GeneralPlatformDomainRuleException(
                                "error.msg.loan.submitted.date.should.be.after.topup.loan.disbursal.date",
                                "Submitted date of this loan application "
                                        + existingLoanApplication.getSubmittedOnDate()
                                        + " should be after the disbursed date of loan to be closed "
                                        + disbursalDateOfLoanToClose);
                    }
                    if (!loanToClose.getCurrencyCode().equals(existingLoanApplication.getCurrencyCode())) {
                        throw new GeneralPlatformDomainRuleException(
                                "error.msg.loan.to.be.closed.has.different.currency",
                                "loanIdToClose is invalid, Currency code is different.");
                    }
                    final LocalDate lastUserTransactionOnLoanToClose = loanToClose.getLastUserTransactionDate();
                    if (!existingLoanApplication.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 "
                                        + existingLoanApplication.getDisbursementDate()
                                        + " should be after last transaction date of loan to be closed "
                                        + lastUserTransactionOnLoanToClose);
                    }
                    BigDecimal loanOutstanding = this.loanReadPlatformService.retrieveLoanPrePaymentTemplate(
                            loanIdToClose, existingLoanApplication.getDisbursementDate()).getAmount();
                    final BigDecimal firstDisbursalAmount = existingLoanApplication.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.");
                    }

                    if (existingLoanIdToClose != loanIdToClose) {
                        final LoanTopupDetails topupDetails = new LoanTopupDetails(existingLoanApplication,
                                loanIdToClose);
                        existingLoanApplication.setTopupLoanDetails(topupDetails);
                        changes.put(LoanApiConstants.loanIdToClose, loanIdToClose);
                    }
                }
            } else {
                existingLoanApplication.setTopupLoanDetails(null);
            }
        } else {
            if (existingLoanApplication.isTopup()) {
                existingLoanApplication.setIsTopup(false);
                existingLoanApplication.setTopupLoanDetails(null);
                changes.put(LoanApiConstants.isTopup, false);
            }
        }

        final String fundIdParamName = "fundId";
        if (changes.containsKey(fundIdParamName)) {
            final Long fundId = command.longValueOfParameterNamed(fundIdParamName);
            final Fund fund = this.loanAssembler.findFundByIdIfProvided(fundId);

            existingLoanApplication.updateFund(fund);
        }

        final String loanPurposeIdParamName = "loanPurposeId";
        if (changes.containsKey(loanPurposeIdParamName)) {
            final Long loanPurposeId = command.longValueOfParameterNamed(loanPurposeIdParamName);
            final CodeValue loanPurpose = this.loanAssembler.findCodeValueByIdIfProvided(loanPurposeId);
            existingLoanApplication.updateLoanPurpose(loanPurpose);
        }

        final String loanOfficerIdParamName = "loanOfficerId";
        if (changes.containsKey(loanOfficerIdParamName)) {
            final Long loanOfficerId = command.longValueOfParameterNamed(loanOfficerIdParamName);
            final Staff newValue = this.loanAssembler.findLoanOfficerByIdIfProvided(loanOfficerId);
            existingLoanApplication.updateLoanOfficerOnLoanApplication(newValue);
        }

        final String strategyIdParamName = "transactionProcessingStrategyId";
        if (changes.containsKey(strategyIdParamName)) {
            final Long strategyId = command.longValueOfParameterNamed(strategyIdParamName);
            final LoanTransactionProcessingStrategy strategy = this.loanAssembler
                    .findStrategyByIdIfProvided(strategyId);

            existingLoanApplication.updateTransactionProcessingStrategy(strategy);
        }

        final String collateralParamName = "collateral";
        if (changes.containsKey(collateralParamName)) {
            final Set<LoanCollateral> loanCollateral = this.loanCollateralAssembler
                    .fromParsedJson(command.parsedJson());
            existingLoanApplication.updateLoanCollateral(loanCollateral);
        }

        final String chargesParamName = "charges";
        if (changes.containsKey(chargesParamName)) {
            existingLoanApplication.updateLoanCharges(possiblyModifedLoanCharges);
        }

        if (changes.containsKey("recalculateLoanSchedule")) {
            changes.remove("recalculateLoanSchedule");

            final JsonElement parsedQuery = this.fromJsonHelper.parse(command.json());
            final JsonQuery query = JsonQuery.from(command.json(), parsedQuery, this.fromJsonHelper);

            final LoanScheduleModel loanSchedule = this.calculationPlatformService.calculateLoanSchedule(query,
                    false);
            existingLoanApplication.updateLoanSchedule(loanSchedule, currentUser);
            existingLoanApplication.recalculateAllCharges();
        }

        this.fromApiJsonDeserializer.validateLoanTermAndRepaidEveryValues(
                existingLoanApplication.getTermFrequency(),
                existingLoanApplication.getTermPeriodFrequencyType(),
                productRelatedDetail.getNumberOfRepayments(), productRelatedDetail.getRepayEvery(),
                productRelatedDetail.getRepaymentPeriodFrequencyType().getValue(), existingLoanApplication);

        saveAndFlushLoanWithDataIntegrityViolationChecks(existingLoanApplication);

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

        final Long calendarId = command.longValueOfParameterNamed("calendarId");
        Calendar calendar = null;
        if (calendarId != null && calendarId != 0) {
            calendar = this.calendarRepository.findOne(calendarId);
            if (calendar == null) {
                throw new CalendarNotFoundException(calendarId);
            }
        }

        final List<CalendarInstance> ciList = (List<CalendarInstance>) this.calendarInstanceRepository
                .findByEntityIdAndEntityTypeId(loanId, CalendarEntityType.LOANS.getValue());
        if (calendar != null) {

            // For loans, allow to attach only one calendar instance per
            // loan
            if (ciList != null && !ciList.isEmpty()) {
                final CalendarInstance calendarInstance = ciList.get(0);
                final boolean isCalendarAssociatedWithEntity = this.calendarReadPlatformService
                        .isCalendarAssociatedWithEntity(calendarInstance.getEntityId(),
                                calendarInstance.getCalendar().getId(),
                                CalendarEntityType.LOANS.getValue().longValue());
                if (isCalendarAssociatedWithEntity) {
                    this.calendarRepository.delete(calendarInstance.getCalendar());
                }
                if (calendarInstance.getCalendar().getId() != calendar.getId()) {
                    calendarInstance.updateCalendar(calendar);
                    this.calendarInstanceRepository.saveAndFlush(calendarInstance);
                }
            } else {
                // attaching new calendar
                final CalendarInstance calendarInstance = new CalendarInstance(calendar,
                        existingLoanApplication.getId(), CalendarEntityType.LOANS.getValue());
                this.calendarInstanceRepository.save(calendarInstance);
            }

        } else {
            if (ciList != null && !ciList.isEmpty()) {
                final CalendarInstance existingCalendarInstance = ciList.get(0);
                final boolean isCalendarAssociatedWithEntity = this.calendarReadPlatformService
                        .isCalendarAssociatedWithEntity(existingCalendarInstance.getEntityId(),
                                existingCalendarInstance.getCalendar().getId(),
                                CalendarEntityType.GROUPS.getValue().longValue());
                if (isCalendarAssociatedWithEntity) {
                    this.calendarInstanceRepository.delete(existingCalendarInstance);
                }
            }
            if (changes.containsKey("repaymentFrequencyNthDayType")
                    || changes.containsKey("repaymentFrequencyDayOfWeekType")) {
                if (changes.get("repaymentFrequencyNthDayType") == null) {
                    if (ciList != null && !ciList.isEmpty()) {
                        final CalendarInstance calendarInstance = ciList.get(0);
                        final boolean isCalendarAssociatedWithEntity = this.calendarReadPlatformService
                                .isCalendarAssociatedWithEntity(calendarInstance.getEntityId(),
                                        calendarInstance.getCalendar().getId(),
                                        CalendarEntityType.LOANS.getValue().longValue());
                        if (isCalendarAssociatedWithEntity) {
                            this.calendarInstanceRepository.delete(calendarInstance);
                            this.calendarRepository.delete(calendarInstance.getCalendar());
                        }
                    }
                } else {
                    Integer repaymentFrequencyTypeInt = command
                            .integerValueOfParameterNamed("repaymentFrequencyType");
                    if (repaymentFrequencyTypeInt != null) {
                        if (PeriodFrequencyType
                                .fromInt(repaymentFrequencyTypeInt) == PeriodFrequencyType.MONTHS) {
                            final String title = "loan_schedule_" + existingLoanApplication.getId();
                            final Integer typeId = CalendarType.COLLECTION.getValue();
                            final CalendarFrequencyType repaymentFrequencyType = CalendarFrequencyType.MONTHLY;
                            final Integer interval = command.integerValueOfParameterNamed("repaymentEvery");
                            LocalDate startDate = command
                                    .localDateValueOfParameterNamed("repaymentsStartingFromDate");
                            if (startDate == null)
                                startDate = command.localDateValueOfParameterNamed("expectedDisbursementDate");
                            final Calendar newCalendar = Calendar.createRepeatingCalendar(title, startDate,
                                    typeId, repaymentFrequencyType, interval,
                                    (Integer) changes.get("repaymentFrequencyDayOfWeekType"),
                                    (Integer) changes.get("repaymentFrequencyNthDayType"));
                            if (ciList != null && !ciList.isEmpty()) {
                                final CalendarInstance calendarInstance = ciList.get(0);
                                final boolean isCalendarAssociatedWithEntity = this.calendarReadPlatformService
                                        .isCalendarAssociatedWithEntity(calendarInstance.getEntityId(),
                                                calendarInstance.getCalendar().getId(),
                                                CalendarEntityType.LOANS.getValue().longValue());
                                if (isCalendarAssociatedWithEntity) {
                                    final Calendar existingCalendar = calendarInstance.getCalendar();
                                    if (existingCalendar != null) {
                                        String existingRecurrence = existingCalendar.getRecurrence();
                                        if (!existingRecurrence.equals(newCalendar.getRecurrence())) {
                                            existingCalendar.setRecurrence(newCalendar.getRecurrence());
                                            this.calendarRepository.save(existingCalendar);
                                        }
                                    }
                                }
                            } else {
                                this.calendarRepository.save(newCalendar);
                                final Integer calendarEntityType = CalendarEntityType.LOANS.getValue();
                                final CalendarInstance calendarInstance = new CalendarInstance(newCalendar,
                                        existingLoanApplication.getId(), calendarEntityType);
                                this.calendarInstanceRepository.save(calendarInstance);
                            }
                        }
                    }
                }
            }
        }

        // Save linked account information
        final String linkAccountIdParamName = "linkAccountId";
        final Long savingsAccountId = command.longValueOfParameterNamed(linkAccountIdParamName);
        AccountAssociations accountAssociations = this.accountAssociationsRepository.findByLoanIdAndType(loanId,
                AccountAssociationType.LINKED_ACCOUNT_ASSOCIATION.getValue());
        boolean isLinkedAccPresent = false;
        if (savingsAccountId == null) {
            if (accountAssociations != null) {
                if (this.fromJsonHelper.parameterExists(linkAccountIdParamName, command.parsedJson())) {
                    this.accountAssociationsRepository.delete(accountAssociations);
                    changes.put(linkAccountIdParamName, null);
                } else {
                    isLinkedAccPresent = true;
                }
            }
        } else {
            isLinkedAccPresent = true;
            boolean isModified = false;
            if (accountAssociations == null) {
                isModified = true;
            } else {
                final SavingsAccount savingsAccount = accountAssociations.linkedSavingsAccount();
                if (savingsAccount == null || !savingsAccount.getId().equals(savingsAccountId)) {
                    isModified = true;
                }
            }
            if (isModified) {
                final SavingsAccount savingsAccount = this.savingsAccountAssembler
                        .assembleFrom(savingsAccountId);
                this.fromApiJsonDeserializer.validatelinkedSavingsAccount(savingsAccount,
                        existingLoanApplication);
                if (accountAssociations == null) {
                    boolean isActive = true;
                    accountAssociations = AccountAssociations.associateSavingsAccount(existingLoanApplication,
                            savingsAccount, AccountAssociationType.LINKED_ACCOUNT_ASSOCIATION.getValue(),
                            isActive);
                } else {
                    accountAssociations.updateLinkedSavingsAccount(savingsAccount);
                }
                changes.put(linkAccountIdParamName, savingsAccountId);
                this.accountAssociationsRepository.save(accountAssociations);
            }
        }

        if (!isLinkedAccPresent) {
            final Set<LoanCharge> charges = existingLoanApplication.charges();
            for (final LoanCharge loanCharge : charges) {
                if (loanCharge.getChargePaymentMode().isPaymentModeAccountTransfer()) {
                    final String errorMessage = "one of the charges requires linked savings account for payment";
                    throw new LinkedAccountRequiredException("loanCharge", errorMessage);
                }
            }
        }

        if ((command.longValueOfParameterNamed(productIdParamName) != null)
                || (command.longValueOfParameterNamed(clientIdParamName) != null)
                || (command.longValueOfParameterNamed(groupIdParamName) != null)) {
            Long OfficeId = null;
            if (existingLoanApplication.getClient() != null) {
                OfficeId = existingLoanApplication.getClient().getOffice().getId();
            } else if (existingLoanApplication.getGroup() != null) {
                OfficeId = existingLoanApplication.getGroup().getOffice().getId();
            }
            officeSpecificLoanProductValidation(existingLoanApplication.getLoanProduct().getId(), OfficeId);
        }

        // updating loan interest recalculation details throwing null
        // pointer exception after saveAndFlush
        // http://stackoverflow.com/questions/17151757/hibernate-cascade-update-gives-null-pointer/17334374#17334374
        this.loanRepositoryWrapper.save(existingLoanApplication);

        if (productRelatedDetail.isInterestRecalculationEnabled()) {
            this.fromApiJsonDeserializer.validateLoanForInterestRecalculation(existingLoanApplication);
            if (changes.containsKey(LoanProductConstants.isInterestRecalculationEnabledParameterName)) {
                createAndPersistCalendarInstanceForInterestRecalculation(existingLoanApplication);

            }

        }

        return new CommandProcessingResultBuilder() //
                .withEntityId(loanId) //
                .withOfficeId(existingLoanApplication.getOfficeId()) //
                .withClientId(existingLoanApplication.getClientId()) //
                .withGroupId(existingLoanApplication.getGroupId()) //
                .withLoanId(existingLoanApplication.getId()) //
                .with(changes).build();
    } catch (final DataIntegrityViolationException dve) {
        handleDataIntegrityIssues(command, dve.getMostSpecificCause(), dve);
        return CommandProcessingResult.empty();
    } catch (final PersistenceException dve) {
        Throwable throwable = ExceptionUtils.getRootCause(dve.getCause());
        handleDataIntegrityIssues(command, throwable, dve);
        return CommandProcessingResult.empty();
    }
}

From source file:com.healthmarketscience.jackcess.Column.java

/**
 * Writes a numeric value./* ww  w  .j a  va2  s  .  co m*/
 */
private void writeNumericValue(ByteBuffer buffer, Object value) throws IOException {
    Object inValue = value;
    try {
        BigDecimal decVal = toBigDecimal(value);
        inValue = decVal;

        boolean negative = (decVal.compareTo(BigDecimal.ZERO) < 0);
        if (negative) {
            decVal = decVal.negate();
        }

        // write sign byte
        buffer.put(negative ? (byte) 0x80 : (byte) 0);

        // adjust scale according to this column type (will cause the an
        // ArithmeticException if number has too many decimal places)
        decVal = decVal.setScale(getScale());

        // check precision
        if (decVal.precision() > getPrecision()) {
            throw new IOException(
                    "Numeric value is too big for specified precision " + getPrecision() + ": " + decVal);
        }

        // convert to unscaled BigInteger, big-endian bytes
        byte[] intValBytes = decVal.unscaledValue().toByteArray();
        int maxByteLen = getType().getFixedSize() - 1;
        if (intValBytes.length > maxByteLen) {
            throw new IOException("Too many bytes for valid BigInteger?");
        }
        if (intValBytes.length < maxByteLen) {
            byte[] tmpBytes = new byte[maxByteLen];
            System.arraycopy(intValBytes, 0, tmpBytes, (maxByteLen - intValBytes.length), intValBytes.length);
            intValBytes = tmpBytes;
        }
        if (buffer.order() != ByteOrder.BIG_ENDIAN) {
            fixNumericByteOrder(intValBytes);
        }
        buffer.put(intValBytes);
    } catch (ArithmeticException e) {
        throw (IOException) new IOException("Numeric value '" + inValue + "' out of range").initCause(e);
    }
}

From source file:op.care.bhp.PnlBHP.java

private CollapsiblePane createCP4(final BHP bhp) {
    final CollapsiblePane bhpPane = new CollapsiblePane();
    bhpPane.setCollapseOnTitleClick(false);

    ActionListener applyActionListener = new ActionListener() {
        @Override/*  w  w w  .  j  a  v  a2s.c  o  m*/
        public void actionPerformed(ActionEvent actionEvent) {
            if (bhp.getState() != BHPTools.STATE_OPEN) {
                return;
            }
            if (bhp.getPrescription().isClosed()) {
                return;
            }

            if (BHPTools.isChangeable(bhp)) {
                outcomeText = null;
                if (bhp.getNeedsText()) {
                    new DlgYesNo(SYSConst.icon48comment, new Closure() {
                        @Override
                        public void execute(Object o) {
                            if (SYSTools.catchNull(o).isEmpty()) {
                                outcomeText = null;
                            } else {
                                outcomeText = o.toString();
                            }
                        }
                    }, "nursingrecords.bhp.describe.outcome", null, null);

                }

                if (bhp.getNeedsText() && outcomeText == null) {
                    OPDE.getDisplayManager().addSubMessage(
                            new DisplayMessage("nursingrecords.bhp.notext.nooutcome", DisplayMessage.WARNING));
                    return;
                }

                if (bhp.getPrescription().isWeightControlled()) {
                    new DlgYesNo(SYSConst.icon48scales, new Closure() {
                        @Override
                        public void execute(Object o) {
                            if (SYSTools.catchNull(o).isEmpty()) {
                                weight = null;
                            } else {
                                weight = (BigDecimal) o;
                            }
                        }
                    }, "nursingrecords.bhp.weight", null, 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);
                        }
                    });

                }

                if (bhp.getPrescription().isWeightControlled() && weight == null) {
                    OPDE.getDisplayManager().addSubMessage(new DisplayMessage(
                            "nursingrecords.bhp.noweight.nosuccess", DisplayMessage.WARNING));
                    return;
                }

                EntityManager em = OPDE.createEM();
                try {
                    em.getTransaction().begin();

                    em.lock(em.merge(resident), LockModeType.OPTIMISTIC);
                    BHP myBHP = em.merge(bhp);
                    em.lock(myBHP, LockModeType.OPTIMISTIC);

                    if (myBHP.isOnDemand()) {
                        em.lock(myBHP.getPrescriptionSchedule(), LockModeType.OPTIMISTIC_FORCE_INCREMENT);
                        em.lock(myBHP.getPrescription(), LockModeType.OPTIMISTIC_FORCE_INCREMENT);
                    } else {
                        em.lock(myBHP.getPrescriptionSchedule(), LockModeType.OPTIMISTIC);
                        em.lock(myBHP.getPrescription(), LockModeType.OPTIMISTIC);
                    }

                    myBHP.setState(BHPTools.STATE_DONE);
                    myBHP.setUser(em.merge(OPDE.getLogin().getUser()));
                    myBHP.setIst(new Date());
                    myBHP.setiZeit(SYSCalendar.whatTimeIDIs(new Date()));
                    myBHP.setMDate(new Date());
                    myBHP.setText(outcomeText);

                    Prescription involvedPresciption = null;
                    if (myBHP.shouldBeCalculated()) {
                        MedInventory inventory = TradeFormTools.getInventory4TradeForm(resident,
                                myBHP.getTradeForm());
                        MedInventoryTools.withdraw(em, em.merge(inventory), myBHP.getDose(), weight, myBHP);
                        // Was the prescription closed during this withdraw ?
                        involvedPresciption = em.find(Prescription.class, myBHP.getPrescription().getID());
                    }

                    BHP outcomeBHP = null;
                    // add outcome check BHP if necessary
                    if (!myBHP.isOutcomeText()
                            && myBHP.getPrescriptionSchedule().getCheckAfterHours() != null) {
                        outcomeBHP = em.merge(new BHP(myBHP));
                        mapShift2BHP.get(BHPTools.SHIFT_ON_DEMAND).add(outcomeBHP);
                    }

                    em.getTransaction().commit();

                    if (myBHP.shouldBeCalculated() && involvedPresciption.isClosed()) { // &&
                        reload();
                    } else if (outcomeBHP != null) {
                        reload();
                    } else {
                        mapBHP2Pane.put(myBHP, createCP4(myBHP));
                        int position = mapShift2BHP.get(myBHP.getShift()).indexOf(bhp);
                        mapShift2BHP.get(myBHP.getShift()).remove(position);
                        mapShift2BHP.get(myBHP.getShift()).add(position, myBHP);
                        if (myBHP.isOnDemand()) {
                            // This whole thing here is only to handle the BPHs on Demand
                            // Fix the other BHPs on demand. If not, you will get locking exceptions,
                            // we FORCED INCREMENTED LOCKS on the Schedule and the Prescription.
                            ArrayList<BHP> changeList = new ArrayList<BHP>();
                            for (BHP bhp : mapShift2BHP.get(BHPTools.SHIFT_ON_DEMAND)) {
                                if (bhp.getPrescription().getID() == myBHP.getPrescription().getID()
                                        && bhp.getBHPid() != myBHP.getBHPid()) {
                                    bhp.setPrescription(myBHP.getPrescription());
                                    bhp.setPrescriptionSchedule(myBHP.getPrescriptionSchedule());
                                    changeList.add(bhp);
                                }
                            }
                            for (BHP bhp : changeList) {
                                mapBHP2Pane.put(bhp, createCP4(myBHP));
                                position = mapShift2BHP.get(bhp.getShift()).indexOf(bhp);
                                mapShift2BHP.get(myBHP.getShift()).remove(position);
                                mapShift2BHP.get(myBHP.getShift()).add(position, bhp);
                            }

                            Collections.sort(mapShift2BHP.get(myBHP.getShift()),
                                    BHPTools.getOnDemandComparator());
                        } else {
                            Collections.sort(mapShift2BHP.get(myBHP.getShift()));
                        }

                        mapShift2Pane.put(myBHP.getShift(), createCP4(myBHP.getShift()));
                        buildPanel(false);
                    }
                } 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 (RollbackException 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();
                }

            } else {
                OPDE.getDisplayManager()
                        .addSubMessage(new DisplayMessage(SYSTools.xx("nursingrecords.bhp.notchangeable")));
            }
        }
    };

    //        JPanel titlePanelleft = new JPanel();
    //        titlePanelleft.setLayout(new BoxLayout(titlePanelleft, BoxLayout.LINE_AXIS));

    MedStock stock = mapPrescription2Stock.get(bhp.getPrescription());
    if (bhp.hasMed() && stock == null) {
        stock = MedStockTools
                .getStockInUse(TradeFormTools.getInventory4TradeForm(resident, bhp.getTradeForm()));
        mapPrescription2Stock.put(bhp.getPrescription(), stock);
    }

    String title;

    if (bhp.isOutcomeText()) {
        title = "<html><font size=+1>"
                + SYSConst.html_italic(SYSTools
                        .left("&ldquo;" + PrescriptionTools.getShortDescriptionAsCompactText(
                                bhp.getPrescriptionSchedule().getPrescription()), MAX_TEXT_LENGTH)
                        + BHPTools.getScheduleText(bhp.getOutcome4(), "&rdquo;, ", ""))
                + " [" + bhp.getPrescriptionSchedule().getCheckAfterHours() + " "
                + SYSTools.xx("misc.msg.Hour(s)") + "] " + BHPTools.getScheduleText(bhp, ", ", "")
                + (bhp.getPrescription().isWeightControlled()
                        ? " " + SYSConst.html_16x16_scales_internal + (bhp.isOpen() ? ""
                                : (bhp.getStockTransaction().isEmpty() ? " "
                                        : NumberFormat.getNumberInstance()
                                                .format(bhp.getStockTransaction().get(0).getWeight()) + "g "))
                        : "")
                + (bhp.getUser() != null ? ", <i>" + SYSTools.anonymizeUser(bhp.getUser().getUID()) + "</i>"
                        : "")
                +

                "</font></html>";
    } else {
        title = "<html><font size=+1>"
                + SYSTools.left(PrescriptionTools.getShortDescriptionAsCompactText(
                        bhp.getPrescriptionSchedule().getPrescription()), MAX_TEXT_LENGTH)
                + (bhp.hasMed()
                        ? ", <b>" + SYSTools.getAsHTML(bhp.getDose()) + " "
                                + DosageFormTools.getUsageText(
                                        bhp.getPrescription().getTradeForm().getDosageForm())
                                + "</b>"
                        : "")
                + BHPTools.getScheduleText(bhp, ", ", "")
                + (bhp.getPrescription().isWeightControlled()
                        ? " " + SYSConst.html_16x16_scales_internal + (bhp.isOpen() ? ""
                                : (bhp.getStockTransaction().isEmpty() ? " "
                                        : NumberFormat.getNumberInstance()
                                                .format(bhp.getStockTransaction().get(0).getWeight()) + "g "))
                        : "")
                + (bhp.getUser() != null ? ", <i>" + SYSTools.anonymizeUser(bhp.getUser().getUID()) + "</i>"
                        : "")
                + "</font></html>";
    }

    DefaultCPTitle cptitle = new DefaultCPTitle(title,
            OPDE.getAppInfo().isAllowedTo(InternalClassACL.UPDATE, internalClassID) ? applyActionListener
                    : null);

    JLabel icon1 = new JLabel(BHPTools.getIcon(bhp));
    icon1.setOpaque(false);
    if (!bhp.isOpen()) {
        icon1.setToolTipText(DateFormat.getDateTimeInstance().format(bhp.getIst()));
    }

    JLabel icon2 = new JLabel(BHPTools.getWarningIcon(bhp, stock));
    icon2.setOpaque(false);

    cptitle.getAdditionalIconPanel().add(icon1);
    cptitle.getAdditionalIconPanel().add(icon2);

    if (bhp.getPrescription().isClosed()) {
        JLabel icon3 = new JLabel(SYSConst.icon22stopSign);
        icon3.setOpaque(false);
        cptitle.getAdditionalIconPanel().add(icon3);
    }

    if (bhp.isOutcomeText()) {
        JLabel icon4 = new JLabel(SYSConst.icon22comment);
        icon4.setOpaque(false);
        cptitle.getAdditionalIconPanel().add(icon4);
    }

    if (!bhp.isOutcomeText() && bhp.getPrescriptionSchedule().getCheckAfterHours() != null) {
        JLabel icon4 = new JLabel(SYSConst.icon22intervalBySecond);
        icon4.setOpaque(false);
        cptitle.getAdditionalIconPanel().add(icon4);
    }

    if (OPDE.getAppInfo().isAllowedTo(InternalClassACL.UPDATE, internalClassID)) {
        if (!bhp.getPrescription().isClosed()) {

            /***
             *      _     _            _                _
             *     | |__ | |_ _ __    / \   _ __  _ __ | |_   _
             *     | '_ \| __| '_ \  / _ \ | '_ \| '_ \| | | | |
             *     | |_) | |_| | | |/ ___ \| |_) | |_) | | |_| |
             *     |_.__/ \__|_| |_/_/   \_\ .__/| .__/|_|\__, |
             *                             |_|   |_|      |___/
             */
            JButton btnApply = new JButton(SYSConst.icon22apply);
            btnApply.setPressedIcon(SYSConst.icon22applyPressed);
            btnApply.setAlignmentX(Component.RIGHT_ALIGNMENT);
            btnApply.setToolTipText(SYSTools.xx("nursingrecords.bhp.btnApply.tooltip"));
            btnApply.addActionListener(applyActionListener);
            btnApply.setContentAreaFilled(false);
            btnApply.setBorder(null);
            btnApply.setEnabled(bhp.isOpen()
                    && (!bhp.hasMed() || mapPrescription2Stock.containsKey(bhp.getPrescription())));
            cptitle.getRight().add(btnApply);

            /***
             *                             ____  _             _
             *       ___  _ __   ___ _ __ / ___|| |_ ___   ___| | __
             *      / _ \| '_ \ / _ \ '_ \\___ \| __/ _ \ / __| |/ /
             *     | (_) | |_) |  __/ | | |___) | || (_) | (__|   <
             *      \___/| .__/ \___|_| |_|____/ \__\___/ \___|_|\_\
             *           |_|
             */
            if (bhp.hasMed() && stock == null && MedInventoryTools.getNextToOpen(
                    TradeFormTools.getInventory4TradeForm(resident, bhp.getTradeForm())) != null) {
                final JButton btnOpenStock = new JButton(SYSConst.icon22ledGreenOn);
                btnOpenStock.setPressedIcon(SYSConst.icon22ledGreenOff);
                btnOpenStock.setAlignmentX(Component.RIGHT_ALIGNMENT);
                btnOpenStock.setContentAreaFilled(false);
                btnOpenStock.setBorder(null);
                btnOpenStock.setToolTipText(SYSTools
                        .toHTMLForScreen(SYSTools.xx("nursingrecords.inventory.stock.btnopen.tooltip")));
                btnOpenStock.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent actionEvent) {

                        EntityManager em = OPDE.createEM();
                        try {
                            em.getTransaction().begin();
                            em.lock(em.merge(resident), LockModeType.OPTIMISTIC);
                            BHP myBHP = em.merge(bhp);
                            em.lock(myBHP, LockModeType.OPTIMISTIC);
                            em.lock(myBHP.getPrescriptionSchedule(), LockModeType.OPTIMISTIC);
                            em.lock(myBHP.getPrescription(), LockModeType.OPTIMISTIC);

                            MedStock myStock = em.merge(MedInventoryTools.openNext(
                                    TradeFormTools.getInventory4TradeForm(resident, myBHP.getTradeForm())));
                            em.lock(myStock, LockModeType.OPTIMISTIC);
                            em.getTransaction().commit();

                            OPDE.getDisplayManager()
                                    .addSubMessage(new DisplayMessage(
                                            String.format(SYSTools.xx("newstocks.stock.has.been.opened"),
                                                    myStock.getID().toString())));
                            reload();

                        } 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();
                        }

                    }

                });
                cptitle.getRight().add(btnOpenStock);
            }

            if (!bhp.isOutcomeText()) {
                /***
                 *      _     _         ____       __
                 *     | |__ | |_ _ __ |  _ \ ___ / _|_   _ ___  ___
                 *     | '_ \| __| '_ \| |_) / _ \ |_| | | / __|/ _ \
                 *     | |_) | |_| | | |  _ <  __/  _| |_| \__ \  __/
                 *     |_.__/ \__|_| |_|_| \_\___|_|  \__,_|___/\___|
                 *
                 */
                final JButton btnRefuse = new JButton(SYSConst.icon22cancel);
                btnRefuse.setPressedIcon(SYSConst.icon22cancelPressed);
                btnRefuse.setAlignmentX(Component.RIGHT_ALIGNMENT);
                btnRefuse.setContentAreaFilled(false);
                btnRefuse.setBorder(null);
                btnRefuse.setToolTipText(
                        SYSTools.toHTMLForScreen(SYSTools.xx("nursingrecords.bhp.btnRefuse.tooltip")));
                btnRefuse.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent actionEvent) {
                        if (bhp.getState() != BHPTools.STATE_OPEN) {
                            return;
                        }

                        if (BHPTools.isChangeable(bhp)) {
                            EntityManager em = OPDE.createEM();
                            try {
                                em.getTransaction().begin();

                                em.lock(em.merge(resident), LockModeType.OPTIMISTIC);
                                BHP myBHP = em.merge(bhp);
                                em.lock(myBHP, LockModeType.OPTIMISTIC);
                                em.lock(myBHP.getPrescriptionSchedule(), LockModeType.OPTIMISTIC);
                                em.lock(myBHP.getPrescription(), LockModeType.OPTIMISTIC);

                                myBHP.setState(BHPTools.STATE_REFUSED);
                                myBHP.setUser(em.merge(OPDE.getLogin().getUser()));
                                myBHP.setIst(new Date());
                                myBHP.setiZeit(SYSCalendar.whatTimeIDIs(new Date()));
                                myBHP.setMDate(new Date());

                                mapBHP2Pane.put(myBHP, createCP4(myBHP));
                                int position = mapShift2BHP.get(myBHP.getShift()).indexOf(bhp);
                                mapShift2BHP.get(bhp.getShift()).remove(position);
                                mapShift2BHP.get(bhp.getShift()).add(position, myBHP);
                                if (myBHP.isOnDemand()) {
                                    Collections.sort(mapShift2BHP.get(myBHP.getShift()),
                                            BHPTools.getOnDemandComparator());
                                } else {
                                    Collections.sort(mapShift2BHP.get(myBHP.getShift()));
                                }

                                em.getTransaction().commit();
                                mapShift2Pane.put(myBHP.getShift(), createCP4(myBHP.getShift()));
                                buildPanel(false);
                            } 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();
                            }

                        } else {
                            OPDE.getDisplayManager().addSubMessage(
                                    new DisplayMessage(SYSTools.xx("nursingrecords.bhp.notchangeable")));
                        }
                    }
                });
                btnRefuse.setEnabled(!bhp.isOnDemand() && bhp.isOpen());
                cptitle.getRight().add(btnRefuse);

                /***
                 *      _     _         ____       __                ____  _                       _
                 *     | |__ | |_ _ __ |  _ \ ___ / _|_   _ ___  ___|  _ \(_)___  ___ __ _ _ __ __| |
                 *     | '_ \| __| '_ \| |_) / _ \ |_| | | / __|/ _ \ | | | / __|/ __/ _` | '__/ _` |
                 *     | |_) | |_| | | |  _ <  __/  _| |_| \__ \  __/ |_| | \__ \ (_| (_| | | | (_| |
                 *     |_.__/ \__|_| |_|_| \_\___|_|  \__,_|___/\___|____/|_|___/\___\__,_|_|  \__,_|
                 *
                 */
                final JButton btnRefuseDiscard = new JButton(SYSConst.icon22deleteall);
                btnRefuseDiscard.setPressedIcon(SYSConst.icon22deleteallPressed);
                btnRefuseDiscard.setAlignmentX(Component.RIGHT_ALIGNMENT);
                btnRefuseDiscard.setContentAreaFilled(false);
                btnRefuseDiscard.setBorder(null);
                btnRefuseDiscard.setToolTipText(
                        SYSTools.toHTMLForScreen(SYSTools.xx("nursingrecords.bhp.btnRefuseDiscard.tooltip")));
                btnRefuseDiscard.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent actionEvent) {
                        if (bhp.getState() != BHPTools.STATE_OPEN) {
                            return;
                        }

                        if (BHPTools.isChangeable(bhp)) {

                            if (bhp.getPrescription().isWeightControlled()) {
                                new DlgYesNo(SYSConst.icon48scales, new Closure() {
                                    @Override
                                    public void execute(Object o) {
                                        if (SYSTools.catchNull(o).isEmpty()) {
                                            weight = null;
                                        } else {
                                            weight = (BigDecimal) o;
                                        }
                                    }
                                }, "nursingrecords.bhp.weight", null, 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);
                                    }
                                });

                            }

                            if (bhp.getPrescription().isWeightControlled() && weight == null) {
                                OPDE.getDisplayManager().addSubMessage(new DisplayMessage(
                                        "nursingrecords.bhp.noweight.nosuccess", DisplayMessage.WARNING));
                                return;
                            }

                            EntityManager em = OPDE.createEM();
                            try {
                                em.getTransaction().begin();

                                em.lock(em.merge(resident), LockModeType.OPTIMISTIC);
                                BHP myBHP = em.merge(bhp);
                                em.lock(myBHP, LockModeType.OPTIMISTIC);
                                em.lock(myBHP.getPrescriptionSchedule(), LockModeType.OPTIMISTIC);
                                em.lock(myBHP.getPrescription(), LockModeType.OPTIMISTIC);

                                myBHP.setState(BHPTools.STATE_REFUSED_DISCARDED);
                                myBHP.setUser(em.merge(OPDE.getLogin().getUser()));
                                myBHP.setIst(new Date());
                                myBHP.setiZeit(SYSCalendar.whatTimeIDIs(new Date()));
                                myBHP.setMDate(new Date());

                                if (myBHP.shouldBeCalculated()) {
                                    MedInventory inventory = TradeFormTools.getInventory4TradeForm(resident,
                                            myBHP.getTradeForm());
                                    if (inventory != null) {
                                        MedInventoryTools.withdraw(em, em.merge(inventory), myBHP.getDose(),
                                                weight, myBHP);
                                    } else {
                                        OPDE.getDisplayManager().addSubMessage(
                                                new DisplayMessage("nursingrecords.bhp.NoInventory"));
                                    }
                                }

                                mapBHP2Pane.put(myBHP, createCP4(myBHP));
                                int position = mapShift2BHP.get(myBHP.getShift()).indexOf(bhp);
                                mapShift2BHP.get(bhp.getShift()).remove(position);
                                mapShift2BHP.get(bhp.getShift()).add(position, myBHP);
                                if (myBHP.isOnDemand()) {
                                    Collections.sort(mapShift2BHP.get(myBHP.getShift()),
                                            BHPTools.getOnDemandComparator());
                                } else {
                                    Collections.sort(mapShift2BHP.get(myBHP.getShift()));
                                }

                                em.getTransaction().commit();
                                mapShift2Pane.put(myBHP.getShift(), createCP4(myBHP.getShift()));
                                buildPanel(false);
                            } 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();
                            }

                        } else {
                            OPDE.getDisplayManager().addSubMessage(
                                    new DisplayMessage(SYSTools.xx("nursingrecords.bhp.notchangeable")));
                        }
                    }
                });

                btnRefuseDiscard.setEnabled(
                        !bhp.isOnDemand() && bhp.hasMed() && bhp.shouldBeCalculated() && bhp.isOpen());
                cptitle.getRight().add(btnRefuseDiscard);
            }

            /***
             *      _     _         _____                 _
             *     | |__ | |_ _ __ | ____|_ __ ___  _ __ | |_ _   _
             *     | '_ \| __| '_ \|  _| | '_ ` _ \| '_ \| __| | | |
             *     | |_) | |_| | | | |___| | | | | | |_) | |_| |_| |
             *     |_.__/ \__|_| |_|_____|_| |_| |_| .__/ \__|\__, |
             *                                     |_|        |___/
             */
            final JButton btnEmpty = new JButton(SYSConst.icon22empty);
            btnEmpty.setPressedIcon(SYSConst.icon22emptyPressed);
            btnEmpty.setAlignmentX(Component.RIGHT_ALIGNMENT);
            btnEmpty.setContentAreaFilled(false);
            btnEmpty.setBorder(null);
            btnEmpty.setToolTipText(SYSTools.xx("nursingrecords.bhp.btnEmpty.tooltip"));
            btnEmpty.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent actionEvent) {
                    if (bhp.getState() == BHPTools.STATE_OPEN) {
                        return;
                    }

                    BHP outcomeBHP = BHPTools.getComment(bhp);

                    if (outcomeBHP != null && !outcomeBHP.isOpen()) {
                        // already commented
                        return;
                    }

                    if (BHPTools.isChangeable(bhp)) {
                        EntityManager em = OPDE.createEM();
                        try {
                            em.getTransaction().begin();

                            em.lock(em.merge(resident), LockModeType.OPTIMISTIC);
                            BHP myBHP = em.merge(bhp);

                            em.lock(myBHP, LockModeType.OPTIMISTIC);
                            em.lock(myBHP.getPrescriptionSchedule(), LockModeType.OPTIMISTIC);
                            em.lock(myBHP.getPrescription(), LockModeType.OPTIMISTIC);

                            // the normal BHPs (those assigned to a NursingProcess) are reset to the OPEN state.
                            // TXs are deleted
                            myBHP.setState(BHPTools.STATE_OPEN);
                            myBHP.setUser(null);
                            myBHP.setIst(null);
                            myBHP.setiZeit(null);
                            myBHP.setMDate(new Date());
                            myBHP.setText(null);

                            if (myBHP.shouldBeCalculated()) {
                                for (MedStockTransaction tx : myBHP.getStockTransaction()) {
                                    em.remove(tx);
                                }
                                myBHP.getStockTransaction().clear();
                            }

                            if (outcomeBHP != null) {
                                BHP myOutcomeBHP = em.merge(outcomeBHP);
                                em.remove(myOutcomeBHP);
                            }

                            if (myBHP.isOnDemand()) {
                                em.remove(myBHP);
                            }

                            em.getTransaction().commit();

                            if (myBHP.isOnDemand()) {
                                reload();
                            } else {

                                mapBHP2Pane.put(myBHP, createCP4(myBHP));
                                int position = mapShift2BHP.get(myBHP.getShift()).indexOf(bhp);
                                mapShift2BHP.get(bhp.getShift()).remove(position);
                                mapShift2BHP.get(bhp.getShift()).add(position, myBHP);
                                if (myBHP.isOnDemand()) {
                                    Collections.sort(mapShift2BHP.get(myBHP.getShift()),
                                            BHPTools.getOnDemandComparator());
                                } else {
                                    Collections.sort(mapShift2BHP.get(myBHP.getShift()));
                                }

                                mapShift2Pane.put(myBHP.getShift(), createCP4(myBHP.getShift()));
                                buildPanel(false);
                            }
                        } 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();
                        }

                    } else {
                        OPDE.getDisplayManager().addSubMessage(
                                new DisplayMessage(SYSTools.xx("nursingrecords.bhp.notchangeable")));
                    }
                }
            });
            btnEmpty.setEnabled(!bhp.isOpen());
            cptitle.getRight().add(btnEmpty);
        }

        /***
         *      _     _         ___        __
         *     | |__ | |_ _ __ |_ _|_ __  / _| ___
         *     | '_ \| __| '_ \ | || '_ \| |_ / _ \
         *     | |_) | |_| | | || || | | |  _| (_) |
         *     |_.__/ \__|_| |_|___|_| |_|_|  \___/
         *
         */
        final JButton btnInfo = new JButton(SYSConst.icon22info);

        btnInfo.setPressedIcon(SYSConst.icon22infoPressed);
        btnInfo.setAlignmentX(Component.RIGHT_ALIGNMENT);
        btnInfo.setContentAreaFilled(false);
        btnInfo.setBorder(null);
        btnInfo.setToolTipText(SYSTools.xx("nursingrecords.bhp.btnInfo.tooltip"));
        final JTextPane txt = new JTextPane();
        txt.setContentType("text/html");
        txt.setEditable(false);
        final JidePopup popupInfo = new JidePopup();
        popupInfo.setMovable(false);
        popupInfo.setContentPane(new JScrollPane(txt));
        popupInfo.removeExcludedComponent(txt);
        popupInfo.setDefaultFocusComponent(txt);

        btnInfo.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                popupInfo.setOwner(btnInfo);

                if (bhp.isOutcomeText() && !bhp.isOpen()) {
                    txt.setText(SYSTools.toHTML(SYSConst.html_div(bhp.getText())));
                } else {
                    txt.setText(SYSTools.toHTML(SYSConst.html_div(bhp.getPrescription().getText())));
                }

                //                    txt.setText(SYSTools.toHTML(SYSConst.html_div(bhp.getPrescription().getText())));
                GUITools.showPopup(popupInfo, SwingConstants.SOUTH_WEST);
            }
        });

        if (bhp.isOutcomeText() && !bhp.isOpen()) {
            btnInfo.setEnabled(true);
        } else {
            btnInfo.setEnabled(!SYSTools.catchNull(bhp.getPrescription().getText()).isEmpty());
        }

        cptitle.getRight().add(btnInfo);

    }

    bhpPane.setTitleLabelComponent(cptitle.getMain());
    bhpPane.setSlidingDirection(SwingConstants.SOUTH);

    final JTextPane contentPane = new JTextPane();
    contentPane.setEditable(false);
    contentPane.setContentType("text/html");
    bhpPane.setContentPane(contentPane);
    bhpPane.setBackground(bhp.getBG());
    bhpPane.setForeground(bhp.getFG());

    try {
        bhpPane.setCollapsed(true);
    } catch (PropertyVetoException e) {
        OPDE.error(e);
    }

    bhpPane.addCollapsiblePaneListener(new CollapsiblePaneAdapter() {
        @Override
        public void paneExpanded(CollapsiblePaneEvent collapsiblePaneEvent) {
            contentPane.setText(SYSTools.toHTML(
                    PrescriptionTools.getPrescriptionAsHTML(bhp.getPrescription(), false, false, true, false)));
        }
    });

    bhpPane.setHorizontalAlignment(SwingConstants.LEADING);
    bhpPane.setOpaque(false);
    return bhpPane;
}

From source file:org.apache.fineract.portfolio.loanaccount.domain.LoanCharge.java

private void populateDerivedFields(final BigDecimal amountPercentageAppliedTo, final BigDecimal chargeAmount,
        Integer numberOfRepayments, BigDecimal loanCharge) {

    switch (ChargeCalculationType.fromInt(this.chargeCalculation)) {
    case INVALID:
        this.percentage = null;
        this.amount = null;
        this.amountPercentageAppliedTo = null;
        this.amountPaid = null;
        this.amountOutstanding = BigDecimal.ZERO;
        this.amountWaived = null;
        this.amountWrittenOff = null;
        break;/*from  ww  w .  ja v a2s. c  om*/
    case FLAT:
        this.percentage = null;
        this.amountPercentageAppliedTo = null;
        this.amountPaid = null;
        if (isInstalmentFee()) {
            if (numberOfRepayments == null) {
                numberOfRepayments = this.loan.fetchNumberOfInstallmensAfterExceptions();
            }
            this.amount = chargeAmount.multiply(BigDecimal.valueOf(numberOfRepayments));
        } else {
            this.amount = chargeAmount;
        }
        this.amountOutstanding = this.amount;
        this.amountWaived = null;
        this.amountWrittenOff = null;
        break;
    case PERCENT_OF_AMOUNT:
    case PERCENT_OF_AMOUNT_AND_INTEREST:
    case PERCENT_OF_INTEREST:
    case PERCENT_OF_DISBURSEMENT_AMOUNT:
        this.percentage = chargeAmount;
        this.amountPercentageAppliedTo = amountPercentageAppliedTo;
        if (loanCharge.compareTo(BigDecimal.ZERO) == 0) {
            loanCharge = percentageOf(this.amountPercentageAppliedTo);
        }
        this.amount = minimumAndMaximumCap(loanCharge);
        this.amountPaid = null;
        this.amountOutstanding = calculateOutstanding();
        this.amountWaived = null;
        this.amountWrittenOff = null;
        break;
    }
    this.amountOrPercentage = chargeAmount;
    if (this.loan != null && isInstalmentFee()) {
        updateInstallmentCharges();
    }
}

From source file:com.visionet.platform.cooperation.service.OrderService.java

/**
 * ?? //from  w  w w .  jav a2 s.  c om
 *
 * @param sign
 * @param channel
 * @param orderNo
 * @param partnerOrderNo
 * @param payType
 * @author ?
 */
public void settlementNotice(String sign, String channel, String orderNo, String partnerOrderNo, String payType,
        BigDecimal payAmount) {
    if (StringUtils.isEmpty(orderNo)) {
        throw new BizException("???");
    }
    if (StringUtils.isEmpty(partnerOrderNo)) {
        throw new BizException("????");
    }
    if (StringUtils.isEmpty(payType)) {
        throw new BizException("??");
    }
    if (!ValidateUtils.checkIsInt(payType)) {
        throw new BizException("??");
    }
    if ("2".equals(payType)) {// ?
        int amount = payAmount.compareTo(BigDecimal.ZERO);
        if (amount == 0) {
            throw new BizException("???0");
        }
    }
    // ??
    ThirdPartyOrder tpOrder = new ThirdPartyOrder();
    tpOrder.setOrderId(orderNo);
    tpOrder.setPartnerOrderNo(partnerOrderNo);
    tpOrder.setUpdateDate(new Date());
    if (Integer.valueOf(payType) == 1) {// 
        tpOrder.setPayType(Integer.valueOf(payType));
        tpOrder.setFinishDate(new Date());
        // ????
        Order order = new Order();
        order.setStatus(2);// ?
        order.setFinishDate(new Date());
        order.setOrderId(orderNo);
        order.setUpdateDate(new Date());
        orderMapper.updateByPrimaryKeySelective(order);
    }
    if (Integer.valueOf(payType) == 2) {// ?
        // TODO ?
        tpOrder.setPayType(Integer.valueOf(payType));
        tpOrder.setPayAmount(payAmount);
    }
    thirdPartyOrderMapper.updateBySelective(tpOrder);
}

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

/**
 * @param _parameter Parameter as passed by the eFasp API
 * @return new Return/*  w ww.  j  ava  2s  .c  o  m*/
 * @throws EFapsException on error
 */
public Return createGainLoss4SimpleAccount(final Parameter _parameter) throws EFapsException {
    final PrintQuery printPer = new PrintQuery(_parameter.getInstance());
    final SelectBuilder selCurrInst = SelectBuilder.get().linkto(CIAccounting.Period.CurrencyLink).instance();
    printPer.addSelect(selCurrInst);
    printPer.addAttribute(CIAccounting.Period.FromDate, CIAccounting.Period.CurrencyLink);
    printPer.execute();
    final DateTime dateFrom = printPer.<DateTime>getAttribute(CIAccounting.Period.FromDate);
    final Instance currencyInst = printPer.<Instance>getSelect(selCurrInst);

    final String[] relOIDs = (String[]) Context.getThreadContext()
            .getSessionAttribute(CIFormAccounting.Accounting_GainLoss4SimpleAccountForm.config2period.name);
    final DateTime dateTo = new DateTime(_parameter
            .getParameterValue(CIFormAccounting.Accounting_GainLoss4SimpleAccountForm.transactionDate.name));
    final DateTime dateEx = new DateTime(_parameter
            .getParameterValue(CIFormAccounting.Accounting_GainLoss4SimpleAccountForm.exchangeDate.name));
    Insert insert = null;
    BigDecimal totalSum = BigDecimal.ZERO;

    for (final String oid : relOIDs) {
        Instance tarCurInst = null;
        final Instance relInst = Instance.get(oid);
        final PrintQuery print = new PrintQuery(relInst);
        final SelectBuilder selAccount = new SelectBuilder()
                .linkto(CIAccounting.AccountConfigSimple2Period.FromLink).oid();
        print.addSelect(selAccount);
        print.addAttribute(CIAccounting.AccountConfigSimple2Period.IsSale);
        if (print.execute()) {
            final Instance instAcc = Instance.get(print.<String>getSelect(selAccount));
            final boolean isSale = print.<Boolean>getAttribute(CIAccounting.AccountConfigSimple2Period.IsSale);
            final QueryBuilder attrQuerBldr = new QueryBuilder(CIAccounting.Transaction);
            attrQuerBldr.addWhereAttrEqValue(CIAccounting.Transaction.PeriodLink, _parameter.getInstance());
            attrQuerBldr.addWhereAttrGreaterValue(CIAccounting.Transaction.Date, dateFrom.minusMinutes(1));
            attrQuerBldr.addWhereAttrLessValue(CIAccounting.Transaction.Date, dateTo.plusDays(1));
            final AttributeQuery attrQuery = attrQuerBldr.getAttributeQuery(CIAccounting.Transaction.ID);

            final QueryBuilder queryBldr = new QueryBuilder(CIAccounting.TransactionPositionAbstract);
            queryBldr.addWhereAttrEqValue(CIAccounting.TransactionPositionAbstract.AccountLink, instAcc);
            queryBldr.addWhereAttrInQuery(CIAccounting.TransactionPositionAbstract.TransactionLink, attrQuery);
            final MultiPrintQuery multi = queryBldr.getPrint();
            final SelectBuilder selTRInst = SelectBuilder.get()
                    .linkto(CIAccounting.TransactionPositionAbstract.RateCurrencyLink).instance();
            multi.addSelect(selTRInst);
            multi.addAttribute(CIAccounting.TransactionPositionAbstract.Amount,
                    CIAccounting.TransactionPositionAbstract.RateAmount);
            BigDecimal gainlossSum = BigDecimal.ZERO;
            multi.execute();
            while (multi.next()) {
                final BigDecimal oldRateAmount = multi
                        .<BigDecimal>getAttribute(CIAccounting.TransactionPositionAbstract.RateAmount);
                final BigDecimal oldAmount = multi
                        .<BigDecimal>getAttribute(CIAccounting.TransactionPositionAbstract.Amount);
                final Instance targetCurrInst = multi.<Instance>getSelect(selTRInst);
                final BigDecimal rate = evaluateRate(_parameter, dateEx, currencyInst, targetCurrInst, isSale);
                final BigDecimal newAmount = oldRateAmount.divide(rate, BigDecimal.ROUND_HALF_UP);

                BigDecimal gainloss = BigDecimal.ZERO;
                if (!currencyInst.equals(targetCurrInst)) {
                    gainloss = newAmount.subtract(oldAmount);
                    tarCurInst = targetCurrInst;
                } else {
                    gainloss = newAmount;
                }
                gainlossSum = gainlossSum.add(gainloss);
            }
            totalSum = totalSum.add(gainlossSum);

            final Map<String, String[]> map = validateInfo(_parameter, gainlossSum);
            final String[] accs = map.get("accs");
            final String[] check = map.get("check");

            if (checkAccounts(accs, 0, check).length() > 0) {
                if (gainlossSum.compareTo(BigDecimal.ZERO) != 0) {
                    final String[] accOids = map.get("accountOids");
                    if (insert == null) {
                        final String descr = DBProperties.getFormatedDBProperty(
                                Recalculate.class.getName() + ".gainLoss4SimpleAccountTransDesc",
                                dateTo.toDate());
                        insert = new Insert(CIAccounting.Transaction);
                        insert.add(CIAccounting.Transaction.Description, descr);
                        insert.add(CIAccounting.Transaction.Date, dateTo);
                        insert.add(CIAccounting.Transaction.PeriodLink, _parameter.getInstance());
                        insert.add(CIAccounting.Transaction.Status,
                                Status.find(CIAccounting.TransactionStatus.Open));
                        insert.execute();
                    }

                    Insert insertPos = new Insert(CIAccounting.TransactionPositionDebit);
                    insertPos.add(CIAccounting.TransactionPositionDebit.TransactionLink, insert.getInstance());
                    if (gainlossSum.signum() > 0) {
                        insertPos.add(CIAccounting.TransactionPositionDebit.AccountLink,
                                Instance.get(accOids[0]));
                    } else {
                        insertPos.add(CIAccounting.TransactionPositionDebit.AccountLink, instAcc);
                    }
                    insertPos.add(CIAccounting.TransactionPositionDebit.Amount, gainlossSum.abs().negate());
                    insertPos.add(CIAccounting.TransactionPositionDebit.RateAmount, BigDecimal.ZERO);
                    insertPos.add(CIAccounting.TransactionPositionDebit.CurrencyLink, currencyInst);
                    insertPos.add(CIAccounting.TransactionPositionDebit.RateCurrencyLink, tarCurInst);
                    insertPos.add(CIAccounting.TransactionPositionDebit.Rate,
                            new Object[] { BigDecimal.ONE, BigDecimal.ONE });
                    insertPos.execute();

                    insertPos = new Insert(CIAccounting.TransactionPositionCredit);
                    insertPos.add(CIAccounting.TransactionPositionCredit.TransactionLink, insert.getInstance());
                    if (gainlossSum.signum() > 0) {
                        insertPos.add(CIAccounting.TransactionPositionCredit.AccountLink, instAcc);
                    } else {
                        insertPos.add(CIAccounting.TransactionPositionCredit.AccountLink,
                                Instance.get(accOids[0]));
                    }
                    insertPos.add(CIAccounting.TransactionPositionCredit.Amount, gainlossSum.abs());
                    insertPos.add(CIAccounting.TransactionPositionCredit.RateAmount, BigDecimal.ZERO);
                    insertPos.add(CIAccounting.TransactionPositionCredit.CurrencyLink, currencyInst);
                    insertPos.add(CIAccounting.TransactionPositionCredit.RateCurrencyLink, tarCurInst);
                    insertPos.add(CIAccounting.TransactionPositionCredit.Rate,
                            new Object[] { BigDecimal.ONE, BigDecimal.ONE });
                    insertPos.execute();
                }
            }
        }
    }
    if (insert != null) {
        final Instance instance = insert.getInstance();
        // create classifications
        final Classification classification1 = (Classification) CIAccounting.TransactionClass.getType();
        final Insert relInsert1 = new Insert(classification1.getClassifyRelationType());
        relInsert1.add(classification1.getRelLinkAttributeName(), instance);
        relInsert1.add(classification1.getRelTypeAttributeName(), classification1.getId());
        relInsert1.execute();

        final Insert classInsert1 = new Insert(classification1);
        classInsert1.add(classification1.getLinkAttributeName(), instance);
        classInsert1.execute();

        final Classification classification = (Classification) CIAccounting.TransactionClassGainLoss.getType();
        final Insert relInsert = new Insert(classification.getClassifyRelationType());
        relInsert.add(classification.getRelLinkAttributeName(), instance);
        relInsert.add(classification.getRelTypeAttributeName(), classification.getId());
        relInsert.execute();

        final Insert classInsert = new Insert(classification);
        classInsert.add(classification.getLinkAttributeName(), instance);
        classInsert.add(CIAccounting.TransactionClassGainLoss.Amount, totalSum);
        classInsert.add(CIAccounting.TransactionClassGainLoss.RateAmount, totalSum);
        classInsert.add(CIAccounting.TransactionClassGainLoss.CurrencyLink, currencyInst);
        classInsert.add(CIAccounting.TransactionClassGainLoss.RateCurrencyLink, currencyInst);
        classInsert.add(CIAccounting.TransactionClassGainLoss.Rate,
                new Object[] { BigDecimal.ONE, BigDecimal.ONE });
        classInsert.execute();
    }
    // clean up
    Context.getThreadContext()
            .removeSessionAttribute(CIFormAccounting.Accounting_GainLoss4SimpleAccountForm.config2period.name);
    return new Return();
}