Example usage for java.math BigDecimal subtract

List of usage examples for java.math BigDecimal subtract

Introduction

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

Prototype

public BigDecimal subtract(BigDecimal subtrahend) 

Source Link

Document

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

Usage

From source file:org.egov.ptis.client.util.PropertyTaxUtil.java

/**
 * API returns the percentage of tax difference between GIS survey tax and application tax Current second half taxes, exluding
 * UAC penalty will be considered for the comparison
 * @param propertyImpl/*from   w  ww . j  a  v  a  2 s. co m*/
 * @return BigDecimal
 */
public BigDecimal getTaxDifferenceForGIS(PropertyImpl propertyImpl) {
    BigDecimal taxDiffPerc = BigDecimal.ZERO;
    BigDecimal gisHalfYrTax = BigDecimal.ZERO;
    BigDecimal applHalfYrTax = BigDecimal.ZERO;
    Map<String, Installment> currYearInstMap = getInstallmentsForCurrYear(new Date());
    PropertyImpl gisProperty = (PropertyImpl) propertyDAO
            .getLatestGISPropertyForBasicProperty(propertyImpl.getBasicProperty());
    if (gisProperty != null) {
        Ptdemand gisPtdemand = gisProperty.getPtDemandSet().iterator().next();
        if (gisPtdemand != null) {
            for (EgDemandDetails demandDetails : gisPtdemand.getEgDemandDetails()) {
                if (gisPtdemand.getEgInstallmentMaster().getFromDate()
                        .equals(demandDetails.getInstallmentStartDate())
                        && !PropertyTaxConstants.DEMANDRSN_CODE_UNAUTHORIZED_PENALTY.equalsIgnoreCase(
                                demandDetails.getEgDemandReason().getEgDemandReasonMaster().getCode()))
                    gisHalfYrTax = gisHalfYrTax.add(demandDetails.getAmount());
            }
        }
    }
    Ptdemand ptdemand = propertyImpl.getPtDemandSet().iterator().next();
    if (ptdemand != null) {
        for (EgDemandDetails demandDetails : ptdemand.getEgDemandDetails()) {
            if (currYearInstMap.get(CURRENTYEAR_SECOND_HALF).getFromDate()
                    .equals(demandDetails.getInstallmentStartDate())
                    && !PropertyTaxConstants.DEMANDRSN_CODE_UNAUTHORIZED_PENALTY.equalsIgnoreCase(
                            demandDetails.getEgDemandReason().getEgDemandReasonMaster().getCode()))
                applHalfYrTax = applHalfYrTax.add(demandDetails.getAmount());
        }
    }
    if (gisHalfYrTax.compareTo(BigDecimal.ZERO) > 0)
        taxDiffPerc = ((gisHalfYrTax.subtract(applHalfYrTax)).multiply(BIGDECIMAL_100)).divide(gisHalfYrTax,
                BigDecimal.ROUND_HALF_UP);

    if (gisProperty != null)
        gisProperty.setSurveyVariance(taxDiffPerc);
    return taxDiffPerc;
}

From source file:och.front.service.FrontAppTest.java

private void test_billing_promoStartBonus() throws Exception {

     long userId = userId1;
     BigDecimal initBalance = null;

     pushToSecurityContext_SYSTEM_USER();
     try {/*  w  ww .j a  v a  2  s .co  m*/
         initBalance = billing.getUserBalance(userId);
     } finally {
         popUserFromSecurityContext();
     }

     assertFalse(universal.selectOne(new GetStartBonusByUserId(userId)).startBonusAdded);

     //first call
     {
         assertTrue(billing.addStartBonus(userId));
         assertTrue(universal.selectOne(new GetStartBonusByUserId(userId)).startBonusAdded);
     }

     //second call
     {
         assertFalse(billing.addStartBonus(userId));
         assertTrue(universal.selectOne(new GetStartBonusByUserId(userId)).startBonusAdded);
     }

     lastFrom(asyncFutures).get();

     //check balance
     pushToSecurityContext_SYSTEM_USER();
     try {
         BigDecimal curBalance = billing.getUserBalance(userId);
         int deltaVal = promo_startBonus.bigDecimalDefVal().intValue();
         assertEquals(deltaVal, curBalance.subtract(initBalance).intValue());

         BigDecimal cacheVal = tryParseBigDecimal(cacheClient.tryGetVal(getBalanceCacheKey(userId)), null);
         assertEquals(deltaVal, cacheVal.subtract(initBalance).intValue());

     } finally {
         popUserFromSecurityContext();
     }
 }

From source file:org.mifos.application.servicefacade.LoanAccountServiceFacadeWebTier.java

private void checkScheduleForMembers(LoanSchedule loanSchedule, LoanBO loan,
        List<GroupMemberLoanDetail> individualMembersOfGroupLoan, List<BigDecimal> radio) {

    for (int i = 0; i < loan.getNoOfInstallments(); ++i) {
        BigDecimal principal = loanSchedule.getRoundedLoanSchedules().get(i).getPrincipal().getAmount();
        BigDecimal interest = loanSchedule.getRoundedLoanSchedules().get(i).getInterest().getAmount();
        BigDecimal miscFee = loanSchedule.getRoundedLoanSchedules().get(i).getMiscFee().getAmount();
        BigDecimal miscPenalty = loanSchedule.getRoundedLoanSchedules().get(i).getMiscPenalty().getAmount();

        for (GroupMemberLoanDetail groupMemberLoanDetail : individualMembersOfGroupLoan) {
            LoanScheduleEntity loanScheduleEntity = groupMemberLoanDetail.getMemberSchedule()
                    .getRoundedLoanSchedules().get(i);

            principal = principal.subtract(loanScheduleEntity.getPrincipal().getAmount());
            interest = interest.subtract(loanScheduleEntity.getInterest().getAmount());
            miscFee = miscFee.subtract(loanScheduleEntity.getMiscFee().getAmount());
            miscPenalty = miscPenalty.subtract(loanScheduleEntity.getMiscPenalty().getAmount());
        }/*ww w . j a  v  a2 s.  c  om*/

        if (principal.compareTo(BigDecimal.ZERO) != 0) {
            for (int j = 0; j < individualMembersOfGroupLoan.size(); ++j) {
                Money oldPrincipal = individualMembersOfGroupLoan.get(j).getMemberSchedule()
                        .getRoundedLoanSchedules().get(i).getPrincipal();
                Money newPrincipal = oldPrincipal
                        .add(new Money(loan.getCurrency(), principal.multiply(radio.get(j))));

                individualMembersOfGroupLoan.get(j).getMemberSchedule().getRoundedLoanSchedules().get(i)
                        .setPrincipal(newPrincipal);
            }
        }

        if (interest.compareTo(BigDecimal.ZERO) != 0) {
            for (int j = 0; j < individualMembersOfGroupLoan.size(); ++j) {
                Money oldinterest = individualMembersOfGroupLoan.get(j).getMemberSchedule()
                        .getRoundedLoanSchedules().get(i).getInterest();
                Money newInterest = oldinterest
                        .add(new Money(loan.getCurrency(), interest.multiply(radio.get(j))));

                individualMembersOfGroupLoan.get(j).getMemberSchedule().getRoundedLoanSchedules().get(i)
                        .setInterest(newInterest);
            }
        }

        if (miscFee.compareTo(BigDecimal.ZERO) != 0) {
            for (int j = 0; j < individualMembersOfGroupLoan.size(); ++j) {
                Money oldMiscFee = individualMembersOfGroupLoan.get(j).getMemberSchedule()
                        .getRoundedLoanSchedules().get(i).getMiscFee();
                Money newMiscFee = oldMiscFee
                        .add(new Money(loan.getCurrency(), miscFee.multiply(radio.get(j))));

                individualMembersOfGroupLoan.get(j).getMemberSchedule().getRoundedLoanSchedules().get(i)
                        .setMiscFee(newMiscFee);
            }
        }

        if (miscPenalty.compareTo(BigDecimal.ZERO) != 0) {
            for (int j = 0; j < individualMembersOfGroupLoan.size(); ++j) {
                Money oldMiscPenalty = individualMembersOfGroupLoan.get(j).getMemberSchedule()
                        .getRoundedLoanSchedules().get(i).getMiscPenalty();
                Money newMiscPenalty = oldMiscPenalty
                        .add(new Money(loan.getCurrency(), miscPenalty.multiply(radio.get(j))));

                individualMembersOfGroupLoan.get(j).getMemberSchedule().getRoundedLoanSchedules().get(i)
                        .setMiscPenalty(newMiscPenalty);
            }
        }
    }
}

From source file:ca.uhn.fhir.jpa.dao.BaseFhirResourceDao.java

private Set<Long> addPredicateQuantity(String theParamName, Set<Long> thePids,
        List<? extends IQueryParameterType> theList) {
    if (theList == null || theList.isEmpty()) {
        return thePids;
    }/*from  ww w.ja v  a 2s . c  om*/

    CriteriaBuilder builder = myEntityManager.getCriteriaBuilder();
    CriteriaQuery<Long> cq = builder.createQuery(Long.class);
    Root<ResourceIndexedSearchParamQuantity> from = cq.from(ResourceIndexedSearchParamQuantity.class);
    cq.select(from.get("myResourcePid").as(Long.class));

    List<Predicate> codePredicates = new ArrayList<Predicate>();
    for (IQueryParameterType nextOr : theList) {
        IQueryParameterType params = nextOr;

        String systemValue;
        String unitsValue;
        QuantityCompararatorEnum cmpValue;
        BigDecimal valueValue;
        boolean approx = false;

        if (params instanceof BaseQuantityDt) {
            BaseQuantityDt param = (BaseQuantityDt) params;
            systemValue = param.getSystemElement().getValueAsString();
            unitsValue = param.getUnitsElement().getValueAsString();
            cmpValue = QuantityCompararatorEnum.VALUESET_BINDER
                    .fromCodeString(param.getComparatorElement().getValueAsString());
            valueValue = param.getValueElement().getValue();
        } else if (params instanceof QuantityParam) {
            QuantityParam param = (QuantityParam) params;
            systemValue = param.getSystem().getValueAsString();
            unitsValue = param.getUnits();
            cmpValue = param.getComparator();
            valueValue = param.getValue().getValue();
            approx = param.isApproximate();
        } else {
            throw new IllegalArgumentException("Invalid quantity type: " + params.getClass());
        }

        Predicate system = null;
        if (!isBlank(systemValue)) {
            system = builder.equal(from.get("mySystem"), systemValue);
        }

        Predicate code = null;
        if (!isBlank(unitsValue)) {
            code = builder.equal(from.get("myUnits"), unitsValue);
        }

        Predicate num;
        if (cmpValue == null) {
            BigDecimal mul = approx ? new BigDecimal(0.1) : new BigDecimal(0.01);
            BigDecimal low = valueValue.subtract(valueValue.multiply(mul));
            BigDecimal high = valueValue.add(valueValue.multiply(mul));
            Predicate lowPred = builder.gt(from.get("myValue").as(BigDecimal.class), low);
            Predicate highPred = builder.lt(from.get("myValue").as(BigDecimal.class), high);
            num = builder.and(lowPred, highPred);
        } else {
            switch (cmpValue) {
            case GREATERTHAN:
                Expression<Number> path = from.get("myValue");
                num = builder.gt(path, valueValue);
                break;
            case GREATERTHAN_OR_EQUALS:
                path = from.get("myValue");
                num = builder.ge(path, valueValue);
                break;
            case LESSTHAN:
                path = from.get("myValue");
                num = builder.lt(path, valueValue);
                break;
            case LESSTHAN_OR_EQUALS:
                path = from.get("myValue");
                num = builder.le(path, valueValue);
                break;
            default:
                throw new IllegalStateException(cmpValue.getCode());
            }
        }

        if (system == null && code == null) {
            codePredicates.add(num);
        } else if (system == null) {
            Predicate singleCode = builder.and(code, num);
            codePredicates.add(singleCode);
        } else if (code == null) {
            Predicate singleCode = builder.and(system, num);
            codePredicates.add(singleCode);
        } else {
            Predicate singleCode = builder.and(system, code, num);
            codePredicates.add(singleCode);
        }
    }

    Predicate masterCodePredicate = builder.or(codePredicates.toArray(new Predicate[0]));

    Predicate type = builder.equal(from.get("myResourceType"), myResourceName);
    Predicate name = builder.equal(from.get("myParamName"), theParamName);
    if (thePids.size() > 0) {
        Predicate inPids = (from.get("myResourcePid").in(thePids));
        cq.where(builder.and(type, name, masterCodePredicate, inPids));
    } else {
        cq.where(builder.and(type, name, masterCodePredicate));
    }

    TypedQuery<Long> q = myEntityManager.createQuery(cq);
    return new HashSet<Long>(q.getResultList());
}

From source file:org.ofbiz.order.shoppingcart.ShoppingCartEvents.java

/**
 * Add agreement order term */*w  w  w  .  java  2s . c  o m*/
 */
public static String addAgreementOrderTerm(HttpServletRequest request, HttpServletResponse response) {

    ShoppingCart cart = getCartObject(request);
    Locale locale = UtilHttp.getLocale(request);

    cart.removeOrderTerms();

    String termTypeId = request.getParameter("termTypeId");
    String termValueStr = request.getParameter("termValue");
    String termDaysStr = request.getParameter("termDays");
    String textValue = request.getParameter("textValue");

    String textValueCodeudor = request.getParameter("textValueCodeudor");
    String termValueAnticipo = request.getParameter("termValueAnticipo");
    String termValueCuotas = request.getParameter("termValueCuotas");
    String textValueDate = request.getParameter("textValueDate");
    String termValueVencimiento = request.getParameter("termValueVencimiento");
    String textValueRefNom1 = request.getParameter("textValueRefNom1");
    String termValueRefTel1 = request.getParameter("termValueRefTel1");
    String textValueRefNom2 = request.getParameter("textValueRefNom2");
    String termValueRefTel2 = request.getParameter("termValueRefTel2");

    // ANTICIPO

    termTypeId = "CRD_ANTICIPO";
    termValueStr = termValueAnticipo;

    GenericValue termType = null;
    Delegator delegator = (Delegator) request.getAttribute("delegator");

    BigDecimal termValue = null;
    Long termDays = null;
    Long DiaVencimiento = null;

    Timestamp termDate = null;

    Timestamp termDateIni = null;

    Long termSec = Long.valueOf(0);

    termSec++;

    if (UtilValidate.isNotEmpty(termValueStr)) {

        //           if (UtilValidate.isEmpty(termTypeId)) {
        //               request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resource_error, "OrderOrderTermTypeIsRequired", locale));
        //               return "error";
        //           }

        try {
            termType = delegator.findOne("TermType", UtilMisc.toMap("termTypeId", termTypeId), false);
        } catch (GenericEntityException gee) {
            request.setAttribute("_ERROR_MESSAGE_", gee.getMessage());
            return "error";
        }

        //           if (("FIN_PAYMENT_TERM".equals(termTypeId) && UtilValidate.isEmpty(termDaysStr)) || (UtilValidate.isNotEmpty(termType) && "FIN_PAYMENT_TERM".equals(termType.get("parentTypeId")) && UtilValidate.isEmpty(termDaysStr))) {
        //               request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resource_error, "OrderOrderTermDaysIsRequired", locale));
        //               return "error";
        //           }
        //   
        if (UtilValidate.isNotEmpty(termValueStr)) {
            try {
                termValue = new BigDecimal(termValueStr);
            } catch (NumberFormatException e) {
                request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resource_error,
                        "OrderOrderTermValueError", UtilMisc.toMap("orderTermValue", termValueStr), locale));
                return "error";
            }
        }

        if (UtilValidate.isNotEmpty(termDaysStr)) {
            try {
                termDays = Long.valueOf(termDaysStr);
            } catch (NumberFormatException e) {
                request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resource_error,
                        "OrderOrderTermDaysError", UtilMisc.toMap("orderTermDays", termDaysStr), locale));
                return "error";
            }
        }

        //removeOrderTerm(request, response);

        cart.addOrderTerm(termTypeId, termValue, termDays, textValue, termDate, termSec);
    }
    //

    //----------------------------------------------------//

    termTypeId = null;
    termValueStr = null;
    termDaysStr = null;
    textValue = null;

    termTypeId = "CRD_CODEUDOR";
    textValue = textValueCodeudor;

    termType = null;
    termValue = null;
    termDays = null;

    termSec++;

    if (UtilValidate.isNotEmpty(textValueCodeudor)) {
        //           if (UtilValidate.isEmpty(termTypeId)) {
        //               request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resource_error, "OrderOrderTermTypeIsRequired", locale));
        //               return "error";
        //           }

        try {
            termType = delegator.findOne("TermType", UtilMisc.toMap("termTypeId", termTypeId), false);
        } catch (GenericEntityException gee) {
            request.setAttribute("_ERROR_MESSAGE_", gee.getMessage());
            return "error";
        }

        if (("FIN_PAYMENT_TERM".equals(termTypeId) && UtilValidate.isEmpty(termDaysStr))
                || (UtilValidate.isNotEmpty(termType) && "FIN_PAYMENT_TERM".equals(termType.get("parentTypeId"))
                        && UtilValidate.isEmpty(termDaysStr))) {
            request.setAttribute("_ERROR_MESSAGE_",
                    UtilProperties.getMessage(resource_error, "OrderOrderTermDaysIsRequired", locale));
            return "error";
        }

        if (UtilValidate.isNotEmpty(termValueStr)) {
            try {
                termValue = new BigDecimal(termValueStr);
            } catch (NumberFormatException e) {
                request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resource_error,
                        "OrderOrderTermValueError", UtilMisc.toMap("orderTermValue", termValueStr), locale));
                return "error";
            }
        }

        if (UtilValidate.isNotEmpty(termDaysStr)) {
            try {
                termDays = Long.valueOf(termDaysStr);
            } catch (NumberFormatException e) {
                request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resource_error,
                        "OrderOrderTermDaysError", UtilMisc.toMap("orderTermDays", termDaysStr), locale));
                return "error";
            }
        }

        //removeOrderTerm(request, response);

        cart.addOrderTerm(termTypeId, termValue, termDays, textValue, termDate, termSec);
    }

    //----------------------------------------------------//

    termTypeId = null;
    termValueStr = null;
    termDaysStr = null;
    textValue = null;

    termTypeId = "CRD_REFERENCIA";
    textValue = textValueRefNom1.toUpperCase();
    termValueStr = termValueRefTel1;

    termType = null;
    termValue = null;
    termDays = null;

    termSec++;

    if (UtilValidate.isNotEmpty(textValueRefNom1)) {

        //        if (UtilValidate.isEmpty(termTypeId)) {
        //            request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resource_error, "OrderOrderTermTypeIsRequired", locale));
        //            return "error";
        //        }

        try {
            termType = delegator.findOne("TermType", UtilMisc.toMap("termTypeId", termTypeId), false);
        } catch (GenericEntityException gee) {
            request.setAttribute("_ERROR_MESSAGE_", gee.getMessage());
            return "error";
        }

        if (("FIN_PAYMENT_TERM".equals(termTypeId) && UtilValidate.isEmpty(termDaysStr))
                || (UtilValidate.isNotEmpty(termType) && "FIN_PAYMENT_TERM".equals(termType.get("parentTypeId"))
                        && UtilValidate.isEmpty(termDaysStr))) {
            request.setAttribute("_ERROR_MESSAGE_",
                    UtilProperties.getMessage(resource_error, "OrderOrderTermDaysIsRequired", locale));
            return "error";
        }

        if (UtilValidate.isNotEmpty(termValueStr)) {
            try {
                termValue = new BigDecimal(termValueStr);
            } catch (NumberFormatException e) {
                request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resource_error,
                        "OrderOrderTermValueError", UtilMisc.toMap("orderTermValue", termValueStr), locale));
                return "error";
            }
        }

        if (UtilValidate.isNotEmpty(termDaysStr)) {
            try {
                termDays = Long.valueOf(termDaysStr);
            } catch (NumberFormatException e) {
                request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resource_error,
                        "OrderOrderTermDaysError", UtilMisc.toMap("orderTermDays", termDaysStr), locale));
                return "error";
            }
        }

        //removeOrderTerm(request, response);

        cart.addOrderTerm(termTypeId, termValue, termDays, textValue, termDate, termSec);

    }

    //----------------------------------------------------//

    termTypeId = null;
    termValueStr = null;
    termDaysStr = null;
    textValue = null;

    termTypeId = "CRD_REFERENCIA";
    textValue = textValueRefNom2.toUpperCase();
    termValueStr = termValueRefTel2;

    termType = null;
    termValue = null;
    termDays = null;

    termSec++;

    if (UtilValidate.isNotEmpty(textValueRefNom2))

    {
        //        if (UtilValidate.isEmpty(termTypeId)) {
        //            request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resource_error, "OrderOrderTermTypeIsRequired", locale));
        //            return "error";
        //        }

        try {
            termType = delegator.findOne("TermType", UtilMisc.toMap("termTypeId", termTypeId), false);
        } catch (GenericEntityException gee) {
            request.setAttribute("_ERROR_MESSAGE_", gee.getMessage());
            return "error";
        }

        if (("FIN_PAYMENT_TERM".equals(termTypeId) && UtilValidate.isEmpty(termDaysStr))
                || (UtilValidate.isNotEmpty(termType) && "FIN_PAYMENT_TERM".equals(termType.get("parentTypeId"))
                        && UtilValidate.isEmpty(termDaysStr))) {
            request.setAttribute("_ERROR_MESSAGE_",
                    UtilProperties.getMessage(resource_error, "OrderOrderTermDaysIsRequired", locale));
            return "error";
        }

        if (UtilValidate.isNotEmpty(termValueStr)) {
            try {
                termValue = new BigDecimal(termValueStr);
            } catch (NumberFormatException e) {
                request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resource_error,
                        "OrderOrderTermValueError", UtilMisc.toMap("orderTermValue", termValueStr), locale));
                return "error";
            }
        }

        if (UtilValidate.isNotEmpty(termDaysStr)) {
            try {
                termDays = Long.valueOf(termDaysStr);
            } catch (NumberFormatException e) {
                request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resource_error,
                        "OrderOrderTermDaysError", UtilMisc.toMap("orderTermDays", termDaysStr), locale));
                return "error";
            }
        }

        //removeOrderTerm(request, response);

        cart.addOrderTerm(termTypeId, termValue, termDays, textValue, termDate, termSec);

    }

    //----------------------------------------------------//

    termTypeId = null;
    termValueStr = null;
    termDaysStr = null;
    textValue = null;

    termTypeId = "CRD_FECHA_INI";
    textValue = textValueDate;

    termType = null;
    termValue = null;
    termDays = null;

    termSec++;

    if (UtilValidate.isNotEmpty(textValueDate)) {

        //        if (UtilValidate.isEmpty(termTypeId)) {
        //            request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resource_error, "OrderOrderTermTypeIsRequired", locale));
        //            return "error";
        //        }

        textValueDate = textValueDate + " 00:00:00";
        termDate = Timestamp.valueOf(textValueDate);
        termDateIni = termDate;

        try {
            termType = delegator.findOne("TermType", UtilMisc.toMap("termTypeId", termTypeId), false);
        } catch (GenericEntityException gee) {
            request.setAttribute("_ERROR_MESSAGE_", gee.getMessage());
            return "error";
        }

        //        if (("FIN_PAYMENT_TERM".equals(termTypeId) && UtilValidate.isEmpty(termDaysStr)) || (UtilValidate.isNotEmpty(termType) && "FIN_PAYMENT_TERM".equals(termType.get("parentTypeId")) && UtilValidate.isEmpty(termDaysStr))) {
        //            request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resource_error, "OrderOrderTermDaysIsRequired", locale));
        //            return "error";
        //        }

        if (UtilValidate.isNotEmpty(termValueStr)) {
            try {
                termValue = new BigDecimal(termValueStr);
            } catch (NumberFormatException e) {
                request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resource_error,
                        "OrderOrderTermValueError", UtilMisc.toMap("orderTermValue", termValueStr), locale));
                return "error";
            }
        }

        if (UtilValidate.isNotEmpty(termDaysStr)) {
            try {
                termDays = Long.valueOf(termDaysStr);
            } catch (NumberFormatException e) {
                request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resource_error,
                        "OrderOrderTermDaysError", UtilMisc.toMap("orderTermDays", termDaysStr), locale));
                return "error";
            }
        }

        //removeOrderTerm(request, response);

        //cart.addOrderTerm(termTypeId, termValue, termDays, textValue, termDate, termSec);

    } else {
        request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resource_error, "Debe Cargar Fecha",
                UtilMisc.toMap("textValueDate", textValueDate), locale));
        return "error";
    }
    //

    //---------------------------------------------------------------//

    termTypeId = null;
    termValueStr = null;
    termDaysStr = null;
    textValue = null;

    termTypeId = "CRD_DIA_VENCIMIENTO";
    termDaysStr = termValueVencimiento;

    termType = null;
    termValue = null;
    termDays = null;
    termDate = null;

    termSec++;

    if (UtilValidate.isNotEmpty(termValueVencimiento)) {

        //        if (UtilValidate.isEmpty(termTypeId)) {
        //            request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resource_error, "OrderOrderTermTypeIsRequired", locale));
        //            return "error";
        //        }

        try {
            termType = delegator.findOne("TermType", UtilMisc.toMap("termTypeId", termTypeId), false);
        } catch (GenericEntityException gee) {
            request.setAttribute("_ERROR_MESSAGE_", gee.getMessage());
            return "error";
        }

        //        if (("FIN_PAYMENT_TERM".equals(termTypeId) && UtilValidate.isEmpty(termDaysStr)) || (UtilValidate.isNotEmpty(termType) && "FIN_PAYMENT_TERM".equals(termType.get("parentTypeId")) && UtilValidate.isEmpty(termDaysStr))) {
        //            request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resource_error, "OrderOrderTermDaysIsRequired", locale));
        //            return "error";
        //        }

        if (UtilValidate.isNotEmpty(termValueStr)) {
            try {
                termValue = new BigDecimal(termValueStr);
            } catch (NumberFormatException e) {
                request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resource_error,
                        "OrderOrderTermValueError", UtilMisc.toMap("orderTermValue", termValueStr), locale));
                return "error";
            }
        }

        if (UtilValidate.isNotEmpty(termDaysStr)) {
            try {
                termDays = Long.valueOf(termDaysStr);
                DiaVencimiento = termDays;
            } catch (NumberFormatException e) {
                request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resource_error,
                        "OrderOrderTermDaysError", UtilMisc.toMap("orderTermDays", termDaysStr), locale));
                return "error";
            }
        }

        //removeOrderTerm(request, response);

        //cart.addOrderTerm(termTypeId, termValue, termDays, textValue, termDate, termSec);

    } else {
        request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resource_error,
                "Debe Cargar Vencimiento", UtilMisc.toMap("textValueDate", textValueDate), locale));
        return "error";
    }
    //

    //---------------------------------------------------------------//

    int Cuotas = 0;
    BigDecimal MtTotal = null;
    BigDecimal MtAnticipo = null;
    BigDecimal MtCuota = null;
    BigDecimal CantCuotas = null;

    if (cart.getOrderType().equals("PURCHASE_ORDER")) {
        MtTotal = cart.getDisplayGrandTotal();// Para tomar el que tiene IVA
    } else {
        MtTotal = cart.getGrandTotal();
    }

    if (UtilValidate.isNotEmpty(termValueCuotas)) {
        //           if (UtilValidate.isNotEmpty(termValueCuotas)) {
        try {
            CantCuotas = new BigDecimal(termValueCuotas);
        } catch (NumberFormatException e) {
            request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resource_error,
                    "OrderOrderTermValueError", UtilMisc.toMap("orderTermValue", termValueStr), locale));
            return "error";
        }
        //           }

        if (UtilValidate.isNotEmpty(termValueAnticipo)) {
            try {
                MtAnticipo = new BigDecimal(termValueAnticipo);
            } catch (NumberFormatException e) {
                request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resource_error,
                        "OrderOrderTermValueError", UtilMisc.toMap("orderTermValue", termValueStr), locale));
                return "error";
            }

            MtTotal = MtTotal.subtract(MtAnticipo);
        }

        //CODIGOLINUX Redondea sin decimal
        MtCuota = MtTotal.divide(CantCuotas, generalRounding).setScale(0, ROUNDING);

        if (UtilValidate.isNotEmpty(termValueCuotas)) {
            try {
                Cuotas = Integer.parseInt(termValueCuotas);
            } catch (NumberFormatException e) {
                request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resource_error,
                        "OrderOrderTermValueError", UtilMisc.toMap("orderTermValue", termValueStr), locale));
                return "error";
            }
        }

        termTypeId = "CRD_CUOTA";
        if (UtilValidate.isEmpty(termTypeId)) {
            request.setAttribute("_ERROR_MESSAGE_",
                    UtilProperties.getMessage(resource_error, "OrderOrderTermTypeIsRequired", locale));
            return "error";
        }
        try {
            termType = delegator.findOne("TermType", UtilMisc.toMap("termTypeId", termTypeId), false);
        } catch (GenericEntityException gee) {
            request.setAttribute("_ERROR_MESSAGE_", gee.getMessage());
            return "error";
        }

        termValueStr = null;
        termDaysStr = null;
        textValue = null;

        termType = null;
        termValue = null;
        termDays = null;

        // termValue = BigDecimal.valueOf(x);

        //CODIGOLINUX
        TimeZone timeZone = UtilHttp.getTimeZone(request);

        termValue = MtCuota;

        termDate = termDateIni;

        int ultimoDiaProximoMes = 0;
        int sumar_dias = 1;
        Timestamp proximoMes = null;

        proximoMes = UtilDateTime.nowTimestamp();

        for (int x = 1; x <= Cuotas; x++) {

            textValue = textValueDate;

            textValue = "Nro." + String.valueOf(x);

            termDays = (long) x;

            termSec++;

            //removeOrderTerm(request, response);

            cart.addOrderTerm(termTypeId, termValue, termDays, textValue, termDate, termSec);

            termDate = UtilDateTime.getMonthEnd(termDate, timeZone, locale);

            proximoMes = UtilDateTime.addDaysToTimestamp(termDate, sumar_dias);

            termDate = UtilDateTime.getMonthEnd(proximoMes, timeZone, locale);

            ultimoDiaProximoMes = UtilDateTime.getDayOfMonth(termDate, timeZone, locale);

            if (ultimoDiaProximoMes > DiaVencimiento) {
                //termDate=UtilDateTime.adjustTimestamp(termDate, Calendar.DAY_OF_MONTH, DiaVencimiento.intValue(), timeZone, locale);
                //termDate=UtilDateTime.adjustTimestamp(termDate, Calendar.DAY_OF_MONTH, DiaVencimiento.intValue());

                termDate = UtilDateTime.toTimestamp(UtilDateTime.getMonth(proximoMes, timeZone, locale) + 1,
                        DiaVencimiento.intValue(), UtilDateTime.getYear(termDate, timeZone, locale), 0, 0, 0);
            } else {
                termDate = UtilDateTime.toTimestamp(UtilDateTime.getMonth(proximoMes, timeZone, locale) + 1,
                        ultimoDiaProximoMes, UtilDateTime.getYear(termDate, timeZone, locale), 0, 0, 0);
            }
        }
    } else {
        request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resource_error,
                "Debe Ingresar Numero de Cuotas", UtilMisc.toMap("termValueCuotas", termValueCuotas), locale));
        return "error";
    }

    //---------------------------------------------------------------//

    return "success";
}

From source file:nl.strohalm.cyclos.services.transactions.PaymentServiceImpl.java

@Override
public StatisticalResultDTO getSimulateConversionGraph(final ConversionSimulationDTO input) {
    final LocalSettings localSettings = settingsService.getLocalSettings();
    final byte precision = (byte) localSettings.getPrecision().getValue();

    // get series
    final TransactionFeePreviewForRatesDTO temp = simulateConversion(input);
    final int series = temp.getFees().size();
    // get range of points, but without values for A < 0
    BigDecimal initialARate = null;
    RatesResultDTO rates = new RatesResultDTO();
    if (input.isUseActualRates()) {
        rates = rateService.getRatesForTransferFrom(input.getAccount(), input.getAmount(), null);
        rates.setDate(input.getDate());//from  ww  w. j  a v a 2  s  .  c o m
        initialARate = rates.getaRate();
    } else {
        initialARate = input.getArate();
    }

    // lowerlimit takes care that values for A < 0 are left out of the graph
    final Double lowerLimit = (initialARate == null) ? null : initialARate.negate().doubleValue();
    final Number[] xRange = GraphHelper.getOptimalRangeAround(0, 33, 0, 0.8, lowerLimit);

    // Data structure to build the table
    final Number[][] tableCells = new Number[xRange.length][series];
    // initialize series names and x labels
    final String[] seriesNames = new String[series];
    final byte[] seriesOrder = new byte[series];
    final Calendar[] xPointDates = new Calendar[xRange.length];
    final Calendar now = Calendar.getInstance();
    BigDecimal inputARate = temp.getARate();
    BigDecimal inputDRate = temp.getDRate();
    // assign data
    for (int i = 0; i < xRange.length; i++) {
        final ConversionSimulationDTO inputPointX = (ConversionSimulationDTO) input.clone();
        final Calendar date = (Calendar) ((input.isUseActualRates()) ? input.getDate().clone() : now.clone());
        date.add(Calendar.DAY_OF_YEAR, xRange[i].intValue());
        xPointDates[i] = date;
        // Set useActualRates for this input to false, otherwise simulateConversion will use the account's the balance and rates of that date, and
        // we don't want that.
        inputPointX.setUseActualRates(false);
        if (inputARate != null) {
            final BigDecimal aRate = inputARate.add(new BigDecimal(xRange[i].doubleValue()));
            inputPointX.setArate(aRate);
        }
        if (inputDRate != null) {
            final BigDecimal dRate = inputDRate.subtract(new BigDecimal(xRange[i].doubleValue()));
            inputPointX.setDrate(dRate);
        }

        final TransactionFeePreviewDTO tempResult = simulateConversion(inputPointX);
        int j = 0;
        for (final TransactionFee fee : tempResult.getFees().keySet()) {
            tableCells[i][j] = new StatisticalNumber(tempResult.getFees().get(fee).doubleValue(), precision);
            byte index;
            switch (fee.getChargeType()) {
            case D_RATE:
                index = 2;
                break;
            case A_RATE:
            case MIXED_A_D_RATES:
                index = 3;
                break;
            default:
                index = 1;
                break;
            }
            seriesOrder[j] = index;
            seriesNames[j++] = fee.getName();
        }
    }

    // create the graph object
    final StatisticalResultDTO result = new StatisticalResultDTO(tableCells);
    result.setBaseKey("conversionSimulation.result.graph");
    result.setHelpFile("account_management");
    // date labels along x-axis
    final String[] rowKeys = new String[xRange.length];
    Arrays.fill(rowKeys, "");
    result.setRowKeys(rowKeys);
    for (int i = 0; i < rowKeys.length; i++) {
        final String rowHeader = localSettings.getDateConverterForGraphs().toString(xPointDates[i]);
        result.setRowHeader(rowHeader, i);
    }
    // mark the actual date upon which the x-axis is based as a vertical line
    final Calendar baseDate = (input.isUseActualRates()) ? (Calendar) input.getDate().clone() : now;
    final String baseDateString = localSettings.getDateConverterForGraphs().toString(baseDate);
    final Marker[] markers = new Marker[1];
    markers[0] = new CategoryMarker(baseDateString);
    markers[0].setPaint(Color.ORANGE);
    final String todayString = localSettings.getDateConverterForGraphs().toString(now);
    if (todayString.equals(baseDateString)) {
        markers[0].setLabel("global.today");
    }
    result.setDomainMarkers(markers);

    // Series labels indicate fee names
    final String[] columnKeys = new String[series];
    Arrays.fill(columnKeys, "");
    result.setColumnKeys(columnKeys);
    for (int j = 0; j < columnKeys.length; j++) {
        result.setColumnHeader(seriesNames[j], j);
    }

    // order the series
    result.orderSeries(seriesOrder);

    final TransferType tt = fetchService.fetch(input.getTransferType(),
            RelationshipHelper.nested(TransferType.Relationships.FROM, AccountType.Relationships.CURRENCY));
    result.setYAxisUnits(tt.getCurrency().getSymbol());
    result.setShowTable(false);
    result.setGraphType(StatisticalResultDTO.GraphType.STACKED_AREA);
    return result;
}

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

/**
 * This API is handling the budget checking
 * //  w  w w. j  a va 2s .c o m
 * @param paramMap
 *            paramMap contains 1. debitAmt (mandatory) 2. creditAmt
 *            (mandatory) 3. deptid (optional) 4. functionid (optional) 5.
 *            functionaryid (optional) 6. schemeid (optional) 7. subschemeid
 *            (optional) 8. boundaryid (optional) 9. glcode (mandatory) -
 *            based on the glcode, we can get the budgetheadid 10. asondate
 *            (manadtory) - to get the actuals, we need asondate
 *            11.mis.budgetcheckreq-Boolean-(optional) set to false if
 *            budget check not to be done for this bill default is True.
 * @return @
 */
@Override
public boolean budgetaryCheckForBill(final Map<String, Object> paramMap) {
    String cashbasedbudgetType = EMPTY_STRING, txnType = EMPTY_STRING;
    BigDecimal debitAmt = null;
    BigDecimal creditAmt = null;
    BigDecimal txnAmt = null;
    String glCode = "";
    Date asondate = null;
    Date fromdate = null;
    try {
        String budgetCheckConfig = budgetCheckConfigService.getConfigValue();
        if (budgetCheckConfig.equals(BudgetControlType.BudgetCheckOption.NONE.toString())) {
            if (LOGGER.isDebugEnabled())
                LOGGER.debug("Application Level budget check disabled skipping budget check.");
            return true;
        }
        if (paramMap.get("mis.budgetcheckreq") != null
                && ((Boolean) paramMap.get("mis.budgetcheckreq")).equals(false)) {
            if (LOGGER.isDebugEnabled())
                LOGGER.debug("voucher Level budget check disabled  so skipping budget check.");
            return true;
        }
        if (paramMap.get("debitAmt") != null)
            debitAmt = (BigDecimal) paramMap.get("debitAmt");
        if (paramMap.get("creditAmt") != null)
            creditAmt = (BigDecimal) paramMap.get("creditAmt");

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

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

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

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

        cashbasedbudgetType = list.get(0).getValue();
        if (cashbasedbudgetType.equalsIgnoreCase("Y")) // cash based budget
        {
            if (LOGGER.isDebugEnabled())
                LOGGER.debug("cashbasedbudgetType==" + cashbasedbudgetType);
        } else // Accural based budgeting
        {
            if (debitAmt != null && debitAmt.compareTo(BigDecimal.ZERO) > 0) {
                txnType = "debit";
                txnAmt = debitAmt;
            } else {
                txnType = "credit";
                txnAmt = creditAmt;
            }

            if (paramMap.get("glcode") != null)
                glCode = paramMap.get("glcode").toString();
            if (paramMap.get(Constants.ASONDATE) != null)
                asondate = (Date) paramMap.get(Constants.ASONDATE);

            if (glCode == null)
                throw new ValidationException(EMPTY_STRING, "glcode is null");
            if (txnAmt == null)
                throw new ValidationException(EMPTY_STRING, "txnAmt is null");
            if (txnType == null)
                throw new ValidationException(EMPTY_STRING, "txnType is null");
            if (asondate == null)
                throw new ValidationException(EMPTY_STRING, "As On Date is null");

            // check the account code needs budget checking
            final CChartOfAccounts coa = chartOfAccountsHibernateDAO.getCChartOfAccountsByGlCode(glCode);
            if (coa.getBudgetCheckReq() != null && coa.getBudgetCheckReq()) {
                // get budgethead for the glcode
                final List<BudgetGroup> budgetHeadListByGlcode = getBudgetHeadByGlcode(coa);

                if (!isBudgetCheckingRequiredForType(txnType,
                        budgetHeadListByGlcode.get(0).getBudgetingType().toString())) {
                    if (LOGGER.isDebugEnabled())
                        LOGGER.debug("No need to check budget for :" + glCode + " as the transaction type is "
                                + txnType + "so skipping budget check");
                    return true;
                }

                // get the financialyear from asondate
                final CFinancialYear finyear = financialYearHibDAO.getFinancialYearByDate(asondate);
                final SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy", Constants.LOCALE);
                if (finyear == null)
                    throw new ValidationException(EMPTY_STRING,
                            "Financial year is not defined for this date [" + sdf.format(asondate) + "]");
                fromdate = finyear.getStartingDate();

                paramMap.put("financialyearid", Long.valueOf(finyear.getId()));
                paramMap.put(BUDGETHEADID, budgetHeadListByGlcode);
                paramMap.put("fromdate", fromdate);
                paramMap.put(Constants.ASONDATE, finyear.getEndingDate());

                paramMap.put(GLCODEID, coa.getId());
                if (LOGGER.isDebugEnabled())
                    LOGGER.debug("************ BudgetCheck Details For bill *********************");
                final BigDecimal budgetedAmt = getBudgetedAmtForYear(paramMap); // get
                // the
                // budgetedamount

                if (LOGGER.isDebugEnabled())
                    LOGGER.debug(".................Budgeted amount......................" + budgetedAmt);
                if (budgetCheckConfigService.getConfigValue()
                        .equalsIgnoreCase(BudgetControlType.BudgetCheckOption.MANDATORY.toString()))
                    if (budgetedAmt.compareTo(BigDecimal.ZERO) == 0) {
                        if (LOGGER.isDebugEnabled())
                            LOGGER.debug(
                                    "Budget check failed Because of  Budgeted not allocated for the combination");
                        return false;
                    }

                final BigDecimal actualAmt = getActualBudgetUtilizedForBudgetaryCheck(paramMap); // get
                // actual
                // amount
                // only
                // Generalledger
                if (LOGGER.isDebugEnabled())
                    LOGGER.debug("..................Voucher Actual amount......................." + actualAmt);

                BigDecimal billAmt = getBillAmountForBudgetCheck(paramMap); // get
                // actual
                // amount
                // of
                // Bill
                EgBillregister bill = null;

                if (paramMap.get("bill") != null)
                    bill = (EgBillregister) paramMap.get("bill");
                if (bill != null && bill.getEgBillregistermis().getBudgetaryAppnumber() != null) {
                    if (LOGGER.isDebugEnabled())
                        LOGGER.debug(".............Found BillId so subtracting txn amount......................"
                                + txnAmt);
                    billAmt = billAmt.subtract(txnAmt);
                }

                if (LOGGER.isDebugEnabled())
                    LOGGER.debug(
                            "........................Bill Actual amount ........................" + billAmt);

                final BigDecimal diff = budgetedAmt.subtract(actualAmt).subtract(billAmt); // get
                // diff
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug("......................diff amount......................" + diff);
                }
                if (LOGGER.isDebugEnabled())
                    LOGGER.debug("************ BudgetCheck Details For bill End *********************");

                if (budgetCheckConfigService.getConfigValue()
                        .equalsIgnoreCase(BudgetControlType.BudgetCheckOption.MANDATORY.toString())) {
                    if (txnAmt.compareTo(diff) <= 0) {
                        if (paramMap.get("bill") != null)
                            getAppNumberForBill(paramMap);
                        return true;
                    } else
                        return false;
                }
                if (budgetCheckConfigService.getConfigValue()
                        .equalsIgnoreCase(BudgetControlType.BudgetCheckOption.ANTICIPATORY.toString())) {
                    getAppNumberForBill(paramMap);
                    return true;
                }

            } else
                return true;

        }
    } catch (final ValidationException v) {
        LOGGER.error("Exp in budgetary check API()=" + v.getErrors());
        throw v;
    } catch (final Exception e) {
        LOGGER.error("Exp in budgetary check API()=" + e.getMessage());
        throw e;
    }
    return true;
}

From source file:org.egov.collection.web.actions.receipts.ReceiptAction.java

/**
 * To set the receiptpayee details for misc receipts
 */// w w w  .  ja  va  2s.c om
private boolean setMiscReceiptDetails() {
    if (CollectionConstants.BLANK.equals(payeename))
        payeename = collectionsUtil.getAppConfigValue(CollectionConstants.MODULE_NAME_COLLECTIONS_CONFIG,
                CollectionConstants.APPCONFIG_VALUE_PAYEEFORMISCRECEIPTS);

    ServiceDetails service = (ServiceDetails) getPersistenceService().findByNamedQuery(
            CollectionConstants.QUERY_SERVICE_BY_CODE, CollectionConstants.SERVICE_CODE_COLLECTIONS);
    if (null != serviceId && serviceId != -1)
        service = serviceDetailsService.findById(serviceId, false);
    receiptHeader.setPartPaymentAllowed(false);
    receiptHeader.setService(service);
    final Fund fund = fundDAO.fundById(receiptMisc.getFund().getId(), false);
    Functionary functionary = null;
    Scheme scheme = null;
    SubScheme subscheme = null;
    try {
        if (receiptMisc.getIdFunctionary() != null)
            functionary = functionaryDAO.functionaryById(receiptMisc.getIdFunctionary().getId());
        if (receiptMisc.getScheme() != null && receiptMisc.getScheme().getId() != -1)
            scheme = schemeDAO.getSchemeById(receiptMisc.getScheme().getId());
        if (receiptMisc.getSubscheme() != null && receiptMisc.getSubscheme().getId() != -1)
            subscheme = subSchemeDAO.getSubSchemeById(receiptMisc.getSubscheme().getId());
    } catch (final Exception e) {
        LOGGER.error("Error in getting functionary for id [" + receiptMisc.getIdFunctionary().getId() + "]", e);
    }

    Fundsource fundSource = null;
    if (receiptMisc.getFundsource() != null && receiptMisc.getFundsource().getId() != null)
        fundSource = fundSourceDAO.fundsourceById(receiptMisc.getFundsource().getId().intValue());
    final Department dept = (Department) getPersistenceService()
            .findByNamedQuery(CollectionConstants.QUERY_DEPARTMENT_BY_ID, Long.valueOf(deptId));
    receiptHeader.setReceiptMisc(
            new ReceiptMisc(null, fund, functionary, fundSource, dept, receiptHeader, scheme, subscheme, null));
    totalAmntToBeCollected = BigDecimal.ZERO;
    int m = 0;
    BigDecimal debitamount = BigDecimal.ZERO;
    removeEmptyRows(billCreditDetailslist);
    removeEmptyRows(billRebateDetailslist);
    removeEmptyRows(subLedgerlist);
    if (validateData(billCreditDetailslist, subLedgerlist))
        for (final ReceiptDetailInfo voucherDetails : billCreditDetailslist) {
            final CChartOfAccounts account = chartOfAccountsDAO
                    .getCChartOfAccountsByGlCode(voucherDetails.getGlcodeDetail());
            CFunction function = null;
            if (functionId != null)
                function = functionDAO.getFunctionById(functionId);
            ReceiptDetail receiptDetail = new ReceiptDetail(account, function,
                    voucherDetails.getCreditAmountDetail(), voucherDetails.getDebitAmountDetail(),
                    BigDecimal.ZERO, Long.valueOf(m), null, true, receiptHeader, PURPOSE.OTHERS.toString());

            if (voucherDetails.getCreditAmountDetail() == null)
                receiptDetail.setCramount(BigDecimal.ZERO);
            else
                receiptDetail.setCramount(voucherDetails.getCreditAmountDetail());

            if (voucherDetails.getDebitAmountDetail() == null)
                receiptDetail.setDramount(BigDecimal.ZERO);
            else
                receiptDetail.setDramount(voucherDetails.getDebitAmountDetail());

            receiptDetail = setAccountPayeeDetails(subLedgerlist, receiptDetail);
            receiptHeader.addReceiptDetail(receiptDetail);
            debitamount = debitamount.add(voucherDetails.getCreditAmountDetail());
            debitamount = debitamount.subtract(voucherDetails.getDebitAmountDetail());
            m++;
        }
    else
        return false;
    if (validateRebateData(billRebateDetailslist, subLedgerlist)) {
        for (final ReceiptDetailInfo voucherDetails : billRebateDetailslist)
            if (voucherDetails.getGlcodeDetail() != null
                    && org.apache.commons.lang.StringUtils.isNotBlank(voucherDetails.getGlcodeDetail())) {
                final CChartOfAccounts account = chartOfAccountsDAO
                        .getCChartOfAccountsByGlCode(voucherDetails.getGlcodeDetail());
                CFunction function = null;
                if (voucherDetails.getFunctionIdDetail() != null)
                    function = functionDAO.getFunctionById(voucherDetails.getFunctionIdDetail());
                ReceiptDetail receiptDetail = new ReceiptDetail(account, function,
                        voucherDetails.getCreditAmountDetail(), voucherDetails.getDebitAmountDetail(),
                        BigDecimal.ZERO, Long.valueOf(m), null, true, receiptHeader, PURPOSE.OTHERS.toString());

                if (voucherDetails.getDebitAmountDetail() == null)
                    receiptDetail.setDramount(BigDecimal.ZERO);
                else
                    receiptDetail.setDramount(voucherDetails.getDebitAmountDetail());
                if (voucherDetails.getCreditAmountDetail() == null)
                    receiptDetail.setCramount(BigDecimal.ZERO);
                else
                    receiptDetail.setCramount(voucherDetails.getCreditAmountDetail());

                receiptDetail = setAccountPayeeDetails(subLedgerlist, receiptDetail);
                receiptHeader.addReceiptDetail(receiptDetail);
                debitamount = debitamount.add(voucherDetails.getCreditAmountDetail());
                debitamount = debitamount.subtract(voucherDetails.getDebitAmountDetail());
                m++;
            }
    } else
        return false;
    setTotalDebitAmount(debitamount);
    return true;
}

From source file:com.salesmanager.core.service.order.OrderService.java

@Transactional
private OrderTotalSummary calculateOrderTotal(Order order, Collection<OrderProduct> products, Customer customer,
        Shipping shipping, String currency, Locale locale) throws Exception {

    OrderTotalSummary summary = new OrderTotalSummary(order.getCurrency());

    if (products != null) {
        Iterator i = products.iterator();

        // calculates oneTimeSubTotal
        // BigDecimal oneTimeSubTotal = summary.getOneTimeSubTotal();

        while (i.hasNext()) {
            OrderProduct product = (OrderProduct) i.next();
            product.setApplicableCreditOneTimeCharge(new BigDecimal("0"));
            product.setSoldPrice(new BigDecimal("0"));

            if (product.isShipping()) {
                summary.setShipping(true);
            }/*www  . j a v a  2 s  . c o  m*/

            // get unit price
            BigDecimal price = product.getProductPrice();

            // get the prices for each
            Set productPrices = product.getPrices();
            boolean defaultPriceMet = false;

            if (productPrices != null && productPrices.size() > 0) {
                Iterator it = productPrices.iterator();

                while (it.hasNext()) {
                    OrderProductPrice pp = (OrderProductPrice) it.next();
                    PriceModule priceModule = (PriceModule) SpringUtil.getBean(pp.getProductPriceModuleName());
                    if (priceModule == null) {
                        log.warn("Price Module " + pp.getProductPriceModuleName()
                                + " is not defined in sm-core-beans.xml");
                        continue;
                    }

                    // price module will set the price in order summary
                    summary = priceModule.calculateOrderPrice(order, summary, product, pp, currency, locale);

                    if (pp.isDefaultPrice()) {
                        defaultPriceMet = true;
                        // BigDecimal t = summary.getOneTimeSubTotal();
                        // t = t.add(product.getProductPrice()).multiply(
                        // new BigDecimal(product.getProductQuantity()));
                        // summary.setOneTimeSubTotal(t);
                    }

                }
            } else {// consider the price submited as one time
                if (summary.getOneTimeSubTotal() == null) {

                    BigDecimal oneTimeSubTotal = new BigDecimal(0);
                    //oneTimeSubTotal.setScale(0, BigDecimal.ROUND_DOWN);

                    summary.setOneTimeSubTotal(oneTimeSubTotal);
                }
                BigDecimal t = summary.getOneTimeSubTotal();
                BigDecimal subTotal = price.multiply(new BigDecimal(product.getProductQuantity()));
                t = t.add(subTotal);
                summary.setOneTimeSubTotal(t);
                defaultPriceMet = true;

                // check for regular discount
                // Special sp = product.getBasePriceSpecial();
                java.util.Date spdate = null;
                java.util.Date spenddate = null;
                BigDecimal bddiscountprice = null;
                if (product.getProductSpecialNewPrice() != null) {
                    bddiscountprice = product.getProductSpecialNewPrice();
                    spdate = product.getProductSpecialDateAvailable();
                    spenddate = product.getProductSpecialDateExpire();
                    if (spdate != null && spdate.before(new Date()) && spdate != null
                            && spenddate.after(new Date())) {

                        OrderTotalLine line = new OrderTotalLine();

                        BigDecimal st = product.getOriginalProductPrice()
                                .multiply(new BigDecimal(product.getProductQuantity()));
                        BigDecimal creditSubTotal = bddiscountprice
                                .multiply(new BigDecimal(product.getProductQuantity()));
                        BigDecimal credit = subTotal.subtract(creditSubTotal);

                        // BigDecimal credit =
                        // product.getOriginalProductPrice().subtract(bddiscountprice);

                        StringBuffer spacialNote = new StringBuffer();
                        spacialNote.append("<font color=\"red\">[");
                        spacialNote.append(product.getProductName());
                        spacialNote.append(" ");
                        spacialNote.append(CurrencyUtil.displayFormatedAmountWithCurrency(credit, currency));
                        spacialNote.append("]</font>");

                        line.setCost(credit);
                        line.setText(spacialNote.toString());
                        line.setCostFormated(CurrencyUtil.displayFormatedAmountWithCurrency(credit, currency));
                        summary.addDueNowCredits(line);

                        BigDecimal oneTimeCredit = product.getApplicableCreditOneTimeCharge();
                        oneTimeCredit = oneTimeCredit.add(credit);
                        product.setApplicableCreditOneTimeCharge(oneTimeCredit);

                    }
                }

            }

            if (!defaultPriceMet) {
                BigDecimal t = summary.getOneTimeSubTotal();

                BigDecimal subTotal = price.multiply(new BigDecimal(product.getProductQuantity()));
                t = t.add(subTotal);
                /** t = t.add(price); **/
                summary.setOneTimeSubTotal(t);

                // check for regular discount
                // Special sp = product.getBasePriceSpecial();
                java.util.Date spdate = null;
                java.util.Date spenddate = null;
                BigDecimal bddiscountprice = null;
                if (product.getProductSpecialNewPrice() != null) {
                    bddiscountprice = product.getProductSpecialNewPrice();
                    spdate = product.getProductSpecialDateAvailable();
                    spenddate = product.getProductSpecialDateExpire();
                    if (spdate != null && spdate.before(new Date()) && spdate != null
                            && spenddate.after(new Date())) {

                        OrderTotalLine line = new OrderTotalLine();

                        // BigDecimal credit =
                        // product.getOriginalProductPrice().subtract(bddiscountprice);

                        BigDecimal st = product.getOriginalProductPrice()
                                .multiply(new BigDecimal(product.getProductQuantity()));

                        // BigDecimal attributes =
                        // product.getAttributeAdditionalCost();
                        // if(attributes!=null) {
                        // attributes = attributes.multiply(new
                        // BigDecimal(product.getProductQuantity()));
                        // st = st.subtract(attributes);
                        // }

                        BigDecimal creditSubTotal = bddiscountprice
                                .multiply(new BigDecimal(product.getProductQuantity()));

                        // BigDecimal credit =
                        // subTotal.subtract(creditSubTotal);
                        BigDecimal credit = st.subtract(creditSubTotal);

                        StringBuffer spacialNote = new StringBuffer();
                        spacialNote.append("<font color=\"red\">[");
                        spacialNote.append(product.getProductName());
                        spacialNote.append(" ");
                        spacialNote.append(CurrencyUtil.displayFormatedAmountWithCurrency(credit, currency));
                        spacialNote.append("]</font>");

                        line.setCost(credit);
                        line.setText(spacialNote.toString());
                        line.setCostFormated(CurrencyUtil.displayFormatedAmountWithCurrency(credit, currency));
                        summary.addDueNowCredits(line);

                        BigDecimal oneTimeCredit = product.getApplicableCreditOneTimeCharge();
                        oneTimeCredit = oneTimeCredit.add(credit);
                        product.setApplicableCreditOneTimeCharge(oneTimeCredit);

                    }
                }

            }

        }

        // reajust order total with credits
        Iterator prIterator = products.iterator();
        BigDecimal credit = new BigDecimal("0");
        while (prIterator.hasNext()) {
            OrderProduct op = (OrderProduct) prIterator.next();

            credit = credit.add(op.getApplicableCreditOneTimeCharge());

        }

        BigDecimal otSummary = summary.getOneTimeSubTotal();
        otSummary = otSummary.subtract(credit);
        summary.setOneTimeSubTotal(otSummary);

        // @todo why shipping is not null for subscriptions ?

        if (shipping != null) {
            if (shipping.getShippingCost() != null) {
                BigDecimal totalShipping = shipping.getShippingCost();
                if (shipping.getHandlingCost() != null) {
                    totalShipping = totalShipping.add(shipping.getHandlingCost());
                }
                // shippingInformation.setShippingCost(totalShipping);
                summary.setShippingTotal(totalShipping);
            }
        }

        if (customer != null) {

            // calculate tax on subtotal + shipping if applies
            TaxService tservice = (TaxService) ServiceFactory.getService(ServiceFactory.TaxService);

            summary = tservice.calculateTax(summary, products, customer, order.getMerchantId(), locale,
                    currency);

        }

        // calculate total
        // subtotal + shipping + tax

        BigDecimal total = summary.getOneTimeSubTotal().add(summary.getShippingTotal())
                .add(summary.getTaxTotal());

        summary.setTotal(total);

    }

    return summary;

}

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

/**
 * To check budget available for the glcode with other parameters. if txnamt
 * is less than the budget available, it would return true, otherwise false.
 * /*  ww  w .j av  a 2s  .  co  m*/
 * @param paramMap
 * @return @
 */
private boolean checkCondition(final Map<String, Object> paramMap) {
    String txnType = null;
    String glCode = null;
    BigDecimal txnAmt = null;
    java.util.Date asondate = null;
    java.util.Date fromdate = null;

    try {
        if (paramMap.get("txnAmt") != null)
            txnAmt = (BigDecimal) paramMap.get("txnAmt");
        if (paramMap.get("txnType") != null)
            txnType = paramMap.get("txnType").toString();
        if (paramMap.get("glcode") != null)
            glCode = paramMap.get("glcode").toString();
        if (paramMap.get(Constants.ASONDATE) != null)
            asondate = (Date) paramMap.get(Constants.ASONDATE);

        if (glCode == null)
            throw new ValidationException(EMPTY_STRING, "glcode is null");
        if (txnAmt == null)
            throw new ValidationException(EMPTY_STRING, "txnAmt is null");
        if (txnType == null)
            throw new ValidationException(EMPTY_STRING, "txnType is null");
        if (asondate == null)
            throw new ValidationException(EMPTY_STRING, "As On Date is null");

        // check the account code needs budget checking

        final CChartOfAccounts coa = chartOfAccountsHibernateDAO.getCChartOfAccountsByGlCode(glCode);
        if (coa.getBudgetCheckReq() != null && coa.getBudgetCheckReq()) {
            // get budgethead for the glcode
            // BudgetGroup bg = getBudgetHeadByGlcode(coa,paramMap);
            final List<BudgetGroup> budgetHeadListByGlcode = getBudgetHeadByGlcode(coa);
            if (budgetHeadListByGlcode == null || budgetHeadListByGlcode.size() == 0)
                throw new ValidationException(EMPTY_STRING,
                        "Budget Check failed: Budget not defined for the given combination.");
            // get budgettinh type for first BG object
            if (!isBudgetCheckingRequiredForType(txnType,
                    budgetHeadListByGlcode.get(0).getBudgetingType().toString())) {
                if (LOGGER.isDebugEnabled())
                    LOGGER.debug("No need to check budget for :" + glCode + " as the transaction type is "
                            + txnType);
                return true;
            }

            paramMap.put("glcodeid", coa.getId());
            // get the financialyear from asondate

            final CFinancialYear finyear = financialYearHibDAO.getFinancialYearByDate(asondate);
            if (finyear == null)
                throw new ValidationException(EMPTY_STRING, "Financial Year is not defined for-" + asondate);
            new SimpleDateFormat("dd-MMM-yyyy", Constants.LOCALE);
            fromdate = finyear.getStartingDate();

            paramMap.put("fromdate", fromdate);
            // Here as on date is overridden by Financialyear ending date to
            // check all budget appropriation irrespective of
            // date
            paramMap.put(Constants.ASONDATE, finyear.getEndingDate());
            paramMap.put("financialyearid", Long.valueOf(finyear.getId()));

            paramMap.put(BUDGETHEADID, budgetHeadListByGlcode);

            if (LOGGER.isDebugEnabled())
                LOGGER.debug("************ BudgetCheck Details *********************");
            // pass the list of bg to getBudgetedAmtForYear
            final BigDecimal budgetedAmt = getBudgetedAmtForYear(paramMap); // get
            // the
            // budgetedamount
            if (LOGGER.isDebugEnabled())
                LOGGER.debug(".............Budgeted Amount For the year............" + budgetedAmt);

            if (budgetCheckConfigService.getConfigValue()
                    .equalsIgnoreCase(BudgetControlType.BudgetCheckOption.MANDATORY.toString()))
                if (budgetedAmt.compareTo(BigDecimal.ZERO) == 0)
                    return false;

            final BigDecimal actualAmt = getActualBudgetUtilizedForBudgetaryCheck(paramMap); // get
            // actual
            // amount
            if (LOGGER.isDebugEnabled())
                LOGGER.debug(".............Voucher Actual amount............" + actualAmt);

            BigDecimal billAmt = getBillAmountForBudgetCheck(paramMap); // get
            // actual
            // amount
            if (LOGGER.isDebugEnabled())
                LOGGER.debug(".............Bill Actual amount............" + billAmt);
            EgBillregister bill = null;

            if (paramMap.get("bill") != null)
                bill = (EgBillregister) persistenceService.find("from EgBillregister where id=? ",
                        (Long) paramMap.get("bill"));
            if (bill != null && bill.getEgBillregistermis().getBudgetaryAppnumber() != null) {
                if (LOGGER.isDebugEnabled())
                    LOGGER.debug(".............Found BillId so subtracting txn amount......................"
                            + txnAmt);
                billAmt = billAmt.subtract(txnAmt);
            }
            if (LOGGER.isDebugEnabled())
                LOGGER.debug(".......Recalculated Bill Actual amount............" + billAmt);
            final BigDecimal diff = budgetedAmt.subtract(actualAmt).subtract(billAmt); // get
            // bill
            // amt
            if (LOGGER.isDebugEnabled())
                LOGGER.debug(".................diff amount..........................." + diff);

            if (LOGGER.isDebugEnabled())
                LOGGER.debug("************ BudgetCheck Details End****************");
            // BigDecimal diff = budgetedAmt.subtract(actualAmt);

            if (budgetCheckConfigService.getConfigValue()
                    .equalsIgnoreCase(BudgetControlType.BudgetCheckOption.MANDATORY.toString())) {
                if (txnAmt.compareTo(diff) <= 0) {

                    generateBanNumber(paramMap, bill);
                    return true;
                }

                else
                    return false;
            }
            if (budgetCheckConfigService.getConfigValue()
                    .equalsIgnoreCase(BudgetControlType.BudgetCheckOption.ANTICIPATORY.toString())) {
                generateBanNumber(paramMap, bill);
                return true;
            }
        } else // no budget check for coa
            return true;
    } catch (final ValidationException v) {
        throw v;
    } catch (final Exception e) {
        throw new ValidationException(EMPTY_STRING, e.getMessage());
    }
    return true;
}