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:com.esd.cs.audit.AuditsController.java

/**
 * ??/*  www  . j a  v  a  2 s.c o  m*/
 * 
 * @param companyCode
 * @return
 */
private BigDecimal getSectionPaid(String year, Integer companyId, List<AccountModel> sb) {
    BigDecimal amount = new BigDecimal(0.00);
    // List<Accounts> audits =
    // accountsService.getUnauditByCompany(companyId, year,
    // Constants.PROCESS_STATIC_BFJK);
    List<Accounts> accounts = accountsService.getByYearAndCompany(year, companyId,
            Constants.PROCESS_STATIC_BFJK);
    Map<String, Accounts> map = new HashMap<>();
    for (Accounts group : accounts) {
        Object obj = map.get(group.getYear());
        if (obj == null) {
            map.put(group.getYear(), group);
        } else {
            Accounts a = (Accounts) obj;
            a.setTotalMoney(a.getTotalMoney().add(group.getTotalMoney()));
        }
    }
    for (Accounts a : map.values()) {
        BigDecimal paymentTotal = paymentService.getEffPaid(null, a.getYear(), companyId);// 
        BigDecimal qj = a.getTotalMoney().subtract(paymentTotal);
        AuditParameter auditParameter = auditParameterService.getByYear(a.getYear());
        Date auditDelayDate = auditParameter.getAuditDelayDate();
        int days = CalendarUtil.getDaySub(auditDelayDate, new Date());
        BigDecimal penalty = qj.multiply(auditParameter.getAuditDelayRate()).multiply(new BigDecimal(days));
        BigDecimal total = qj.add(penalty);
        AccountModel am = new AccountModel();
        am.setYear(a.getYear());
        am.setDays(String.valueOf(days));
        am.setMoney(df.format(qj));
        am.setPenalty(df.format(penalty));
        am.setProp(df4.format(auditParameter.getAuditDelayRate()));
        am.setTotal(df.format(total));
        sb.add(am);
        amount = amount.add(total);
    }
    if (amount.compareTo(new BigDecimal(0.00)) != 0) {
        AccountModel am = new AccountModel();
        am.setTotal(df.format(amount));
        sb.add(am);
    }
    return amount;
}

From source file:net.groupbuy.controller.shop.PaymentController.java

/**
 * ??/*from  www.  j  av a  2 s .  co m*/
 */
@RequestMapping(value = "/submit", method = RequestMethod.POST)
public String submit(Type type, String paymentPluginId, String sn, BigDecimal amount,
        HttpServletRequest request, HttpServletResponse response, ModelMap model) {
    Member member = memberService.getCurrent();
    if (member == null) {
        return ERROR_VIEW;
    }
    PaymentPlugin paymentPlugin = pluginService.getPaymentPlugin(paymentPluginId);
    if (paymentPlugin == null || !paymentPlugin.getIsEnabled()) {
        return ERROR_VIEW;
    }
    Payment payment = new Payment();
    String description = null;
    if (type == Type.payment) {
        Order order = orderService.findBySn(sn);
        if (order == null || !member.equals(order.getMember()) || order.isExpired() || order.isLocked(null)) {
            return ERROR_VIEW;
        }
        if (order.getPaymentMethod() == null
                || order.getPaymentMethod().getMethod() != PaymentMethod.Method.online) {
            return ERROR_VIEW;
        }
        if (order.getPaymentStatus() != PaymentStatus.unpaid
                && order.getPaymentStatus() != PaymentStatus.partialPayment) {
            return ERROR_VIEW;
        }
        if (order.getAmountPayable().compareTo(new BigDecimal(0)) <= 0) {
            return ERROR_VIEW;
        }
        payment.setSn(snService.generate(Sn.Type.payment));
        payment.setType(Type.payment);
        payment.setMethod(Method.online);
        payment.setStatus(Status.wait);
        payment.setPaymentMethod(order.getPaymentMethodName() + Payment.PAYMENT_METHOD_SEPARATOR
                + paymentPlugin.getPaymentName());
        payment.setFee(paymentPlugin.calculateFee(order.getAmountPayable()));
        payment.setAmount(paymentPlugin.calculateAmount(order.getAmountPayable()));
        payment.setPaymentPluginId(paymentPluginId);
        payment.setExpire(paymentPlugin.getTimeout() != null
                ? DateUtils.addMinutes(new Date(), paymentPlugin.getTimeout())
                : null);
        payment.setOrder(order);
        paymentService.save(payment);
        description = order.getName();
    } else if (type == Type.recharge) {
        Setting setting = SettingUtils.get();
        if (amount == null || amount.compareTo(new BigDecimal(0)) <= 0 || amount.precision() > 15
                || amount.scale() > setting.getPriceScale()) {
            return ERROR_VIEW;
        }
        payment.setSn(snService.generate(Sn.Type.payment));
        payment.setType(Type.recharge);
        payment.setMethod(Method.online);
        payment.setStatus(Status.wait);
        payment.setPaymentMethod(paymentPlugin.getPaymentName());
        payment.setFee(paymentPlugin.calculateFee(amount));
        payment.setAmount(paymentPlugin.calculateAmount(amount));
        payment.setPaymentPluginId(paymentPluginId);
        payment.setExpire(paymentPlugin.getTimeout() != null
                ? DateUtils.addMinutes(new Date(), paymentPlugin.getTimeout())
                : null);
        payment.setMember(member);
        paymentService.save(payment);
        description = message("shop.member.deposit.recharge");
    } else {
        return ERROR_VIEW;
    }
    model.addAttribute("requestUrl", paymentPlugin.getRequestUrl());
    model.addAttribute("requestMethod", paymentPlugin.getRequestMethod());
    model.addAttribute("requestCharset", paymentPlugin.getRequestCharset());
    model.addAttribute("parameterMap", paymentPlugin.getParameterMap(payment.getSn(), description, request));
    if (StringUtils.isNotEmpty(paymentPlugin.getRequestCharset())) {
        response.setContentType("text/html; charset=" + paymentPlugin.getRequestCharset());
    }
    return "shop/payment/submit";
}

From source file:com.nkapps.billing.dao.OverpaymentDaoImpl.java

@Override
public void returnStateCommit(Session session, BankStatement bs, BigDecimal returnSum, Long issuerSerialNumber,
        String issuerIp, LocalDateTime dateTime) throws Exception {
    if (!bs.getBankStatementPayments().isEmpty()) { // if bankstatement has payments
        String q = " SELECT p.id AS id, p.tin AS tin, p.paymentNum AS paymentNum, p.paymentDate AS paymentDate,"
                + "  p.paymentSum AS paymentSum, p.sourceCode AS sourceCode,"
                + " p.state AS state, p.tinDebtor as tinDebtor,p.claim as claim, p.issuerSerialNumber as issuerSerialNumber,"
                + " p.issuerIp as issuerIp,p.dateCreated AS dateCreated, p.dateUpdated as dateUpdated, "
                + " p.paymentSum - COALESCE((SELECT SUM(paidSum) FROM KeyPayment kp WHERE kp.payment = p),0) AS overSum "
                + " FROM Payment p JOIN p.bankStatementPayment bsp "
                + " WHERE p.state IN (1,2) AND p.claim = 0 " + " AND bsp.id.bankStatement = :bs"
                + " ORDER BY p.paymentDate, p.paymentNum ";
        Query query = session.createQuery(q);
        query.setParameter("bs", bs);
        query.setResultTransformer(Transformers.aliasToBean(Payment.class));
        List<Payment> paymentList = query.list();

        for (Payment payment : paymentList) {
            if (payment.getOverSum().compareTo(returnSum) <= 0) {

                payment.setPaymentSum(payment.getPaymentSum().subtract(payment.getOverSum()));
                payment.setState((short) 3); //
                payment.setIssuerSerialNumber(issuerSerialNumber);
                payment.setIssuerIp(issuerIp);
                payment.setDateUpdated(dateTime);

                session.update(payment);

                returnSum = returnSum.subtract(payment.getOverSum());
            } else {

                payment.setPaymentSum(payment.getPaymentSum().subtract(returnSum));
                payment.setIssuerSerialNumber(issuerSerialNumber);
                payment.setIssuerIp(issuerIp);
                payment.setDateUpdated(dateTime);

                session.update(payment);

                returnSum = BigDecimal.ZERO;

            }/*from  ww w  .  j av  a  2s .c o  m*/
            if (returnSum.compareTo(BigDecimal.ZERO) <= 0) {
                break;
            }
        }
    }
}

From source file:org.impotch.calcul.impot.cantonal.ge.pp.avant2010.BaremePrestationCapital2009Test.java

private void test(int revenu, String tauxEnPourcent) {
    RecepteurMultipleImpot recepteur = recepteur("IBR", "RIBR", "CAR", "RCAR", "ADR", "COR");
    FournisseurAssiettePeriodique fournisseur = this.creerAssiettes(2009, revenu);
    producteur2009.produireImpot(situationCelibataire, fournisseur, recepteur);

    BigDecimal valeurImpot = getValeur(recepteur, "TOTAL");

    // On prend les bornes Sup et Inf
    BigDecimal borneSup = valeurImpot.add(deltaSurMontantImpotCalcule);
    BigDecimal borneInf = valeurImpot.subtract(deltaSurMontantImpotCalcule);

    BigDecimal tauxCalculeSup = borneSup.multiply(new BigDecimal(20)).divide(new BigDecimal(revenu), 5,
            BigDecimal.ROUND_HALF_UP);
    BigDecimal tauxCalculeInf = borneInf.multiply(new BigDecimal(20)).divide(new BigDecimal(revenu), 5,
            BigDecimal.ROUND_HALF_UP);
    BigDecimal tauxAttendu = new BigDecimal(tauxEnPourcent);

    assertTrue("Comparaison taux attendu : " + tauxEnPourcent + ", tauxSup " + tauxCalculeSup,
            0 >= tauxAttendu.compareTo(tauxCalculeSup));
    assertTrue("Comparaison taux attendu : " + tauxEnPourcent + ", tauxInf " + tauxCalculeInf,
            0 >= tauxCalculeInf.compareTo(tauxAttendu));
}

From source file:com.esd.cs.audit.AuditsController.java

/**
 * ?//from  w  w w .  jav  a2s.  c  om
 * 
 * @param year
 * @param companyCode
 * @param total
 * @return
 */
private BigDecimal getUnAudits(String year, Integer companyId, BigDecimal total, List<AccountModel> sb) {
    BigDecimal amount = new BigDecimal(0.00);
    // ??
    AuditParameter auditParameter = auditParameterService.getByYear(year);
    BigDecimal averageSalary = auditParameter.getAverageSalary();
    // ?
    // 
    BigDecimal putScale = auditParameter.getPutScale();
    // ??*(?*)?? 
    BigDecimal payableAmount = averageSalary.multiply(total.multiply(putScale));
    String[] unAudits = companyService.getUnauditYearByCompany(companyId, year);
    if (unAudits != null) {
        for (String unYear : unAudits) {
            AuditParameter oldAuditParameter = auditParameterService.getByYear(unYear);
            Date auditDelayDate = oldAuditParameter.getAuditDelayDate();
            int days = CalendarUtil.getDaySub(auditDelayDate, new Date());
            // =?**
            BigDecimal penalty = payableAmount.multiply(oldAuditParameter.getAuditDelayRate())
                    .multiply(new BigDecimal(days));
            BigDecimal unYearTotal = payableAmount.add(penalty);
            logger.debug("payableAmount:{},year:{} date:{} penalty:{} unYearTotal:{}", payableAmount, unYear,
                    days, penalty, unYearTotal);
            AccountModel am = new AccountModel();
            am.setYear(unYear);
            am.setDays(String.valueOf(days));
            am.setMoney(df.format(payableAmount));
            am.setPenalty(df.format(penalty));
            am.setProp(df4.format(oldAuditParameter.getAuditDelayRate()));
            am.setTotal(df.format(unYearTotal));
            sb.add(am);
            amount = amount.add(unYearTotal);
        }
    }
    if (amount.compareTo(new BigDecimal(0.00)) != 0) {
        AccountModel am = new AccountModel();
        am.setTotal(df.format(amount));
        sb.add(am);
    }
    return amount;
}

From source file:logic.EntityCar.java

private void freeStaticCount() throws Exception {

    //getAllStaticOptions();
    BigDecimal bestRel = BigDecimal.valueOf(0);
    BigDecimal one = BigDecimal.valueOf(1);
    ///*from   w w w.  j  a  v  a 2 s  . c  o  m*/
    int k = 0;
    //suplog+="; bplistS="+bpList.size()+"; ";
    //suplog += "stat1: cols=" + car.getCarColorValues().size() + "; ";
    for (CarColorValue ccv : car.getCarColorValues()) {
        k++;
        Color col = ccv.getColor();
        String suid = col.getUid().trim();
        //suplog+="!! suid="+suid.trim()+"; ";
        BaseParam bp = getBaseParam(allParams, suid);
        //suplog+=""+k+"."+ccv.getTitle()+" - "+ccv.getColor().getName()+"; ";
        if (bp != null && StaticType.STATIC.equals(bp.getStaticType())) {
            List<String> colorRadList = ConvertSupport.getRadicalList(col.getRadical());
            if (!colorRadList.isEmpty()) {
                String attrToxRad = "";
                BigDecimal attrToxRate = BigDecimal.valueOf(-100);
                for (String colorRad : colorRadList) {
                    BigDecimal ToxRate = BigDecimal
                            .valueOf(getToxicRate(radCore.trim(), radColor.trim(), colorRad));
                    if (ToxRate.compareTo(attrToxRate) > 0) {
                        attrToxRate = ToxRate;
                        attrToxRad = colorRad;
                    }
                }
                if (attrToxRad != null && !attrToxRad.equals("")) {
                    BigDecimal attrModalRate = BigDecimal.valueOf(0);
                    if (percType.equals(Perception.AUDIAL)) {
                        if (col.getAudial() != null) {
                            attrModalRate = BigDecimal.valueOf(col.getAudial());
                        }
                    } else if (percType.equals(Perception.KINESTETIC)) {
                        if (col.getKinestet() != null) {
                            attrModalRate = BigDecimal.valueOf(col.getKinestet());
                        }
                    } else if (percType.equals(Perception.VISUAL)) {
                        if (col.getVisual() != null) {
                            attrModalRate = BigDecimal.valueOf(col.getVisual());
                        }
                    }
                    //BigDecimal rel = attrToxRate.divide(BigDecimal.valueOf(100), 2, RoundingMode.HALF_UP);
                    if (attrToxRate.compareTo(one) >= 0) {
                        EntityProperty ep = new EntityProperty("", ccv.getTitle(), suid, attrToxRate,
                                attrToxRad, attrModalRate, (double) 0, PropertyType.OPTION,
                                " ??");
                        List<EntityProperty> availEps = staticProps.get(suid);
                        if (availEps == null || availEps.isEmpty()) {
                            availEps = new ArrayList();
                            availEps.add(ep);
                            staticProps.put(suid, availEps);
                        } else {
                            EntityProperty availEp = availEps.get(0);
                            if (attrToxRate.compareTo(availEp.value) == 0) {
                                BigDecimal availModVal = availEp.modalValue;
                                if (attrModalRate.compareTo(availModVal) > 0) {
                                    availEps = new ArrayList();
                                    availEps.add(ep);
                                    staticProps.put(suid, availEps);
                                } else if (attrModalRate.compareTo(availModVal) == 0) {
                                    availEps.add(ep);
                                    staticProps.put(suid, availEps);
                                }
                            } else if (attrToxRate.compareTo(availEp.getValue()) > 0) {
                                availEps = new ArrayList();
                                availEps.add(ep);
                                staticProps.put(suid, availEps);
                            }
                        }
                        //suplog+="COLOR: atr="+attrToxRate+"; am="+attrModalRate+"; etr="+essToxRate+"; statrate="+rel.toString()+"; ";
                    }
                }
            }
        }
    }
    //suplog+="statics: "+staticProps.keySet().size()+"; ";

    int i = 0;
    int m = 0;
    int n = 0;
    //suplog += "stat1: covs=" + car.getCarOptionValues().size() + "; ";
    for (CarOptionValue cov : car.getCarOptionValues()) {
        i++;
        CarCompletionOption cco = cov.getCCO();
        String suid = cco.getUid().trim();
        //BaseParam bp = baseParamService.getBaseParam(suid.trim());
        BaseParam bp = getBaseParam(allParams, suid);
        if (bp != null && StaticType.STATIC.equals(bp.getStaticType())
                && cov.getPrice().compareTo(Double.valueOf(0)) == 0) {
            m++;
            //String colorRad = cco.getRadical();
            //suplog+="rc:"+radCore.trim()+"; rad:"+colorRad.toString().trim()+"; ";

            List<String> colorRadList = ConvertSupport.getRadicalList(cov.getRadical());
            if (!colorRadList.isEmpty()) {
                n++;
                String attrToxRad = "";
                BigDecimal attrToxRate = BigDecimal.valueOf(-100);
                for (String colorRad : colorRadList) {
                    BigDecimal ToxRate = BigDecimal
                            .valueOf(getToxicRate(radCore.trim(), radColor.trim(), colorRad));
                    if (ToxRate.compareTo(attrToxRate) > 0) {
                        attrToxRate = ToxRate;
                        attrToxRad = colorRad;
                    }
                }
                if (attrToxRad != null && !attrToxRad.equals("")) {
                    //String essRad = bp.getRadical().trim();

                    //BigDecimal essModalRate = BigDecimal.valueOf(0);
                    BigDecimal attrModalRate = BigDecimal.valueOf(0);
                    if (percType.equals(Perception.AUDIAL)) {
                        if (cov.getAudial() != null) {
                            attrModalRate = BigDecimal.valueOf(cov.getAudial());
                        }
                    } else if (percType.equals(Perception.KINESTETIC)) {
                        if (cov.getKinestet() != null) {
                            attrModalRate = BigDecimal.valueOf(cov.getKinestet());
                        }
                    } else if (percType.equals(Perception.VISUAL)) {
                        if (cov.getVisual() != null) {
                            attrModalRate = BigDecimal.valueOf(cov.getVisual());
                        }
                    }

                    if (attrToxRate.compareTo(one) >= 0) {
                        EntityProperty ep = new EntityProperty(bp.getName(), cco.getTitle(),
                                cov.getDescription(), suid, attrToxRate, attrToxRad, attrModalRate, (double) 0,
                                PropertyType.OPTION, " ??");
                        List<EntityProperty> availEps = staticProps.get(suid);
                        if (availEps == null || availEps.isEmpty()) {
                            availEps = new ArrayList();
                            availEps.add(ep);
                            staticProps.put(suid, availEps);
                        } else {
                            EntityProperty availEp = availEps.get(0);
                            if (attrToxRate.compareTo(availEp.value) == 0) {
                                BigDecimal availModVal = availEp.modalValue;
                                if (attrModalRate.compareTo(availModVal) > 0) {
                                    availEps = new ArrayList();
                                    availEps.add(ep);
                                    staticProps.put(suid, availEps);
                                } else if (attrModalRate.compareTo(availModVal) == 0) {
                                    availEps.add(ep);
                                    staticProps.put(suid, availEps);
                                }
                            } else if (attrToxRate.compareTo(availEp.getValue()) > 0) {
                                availEps = new ArrayList();
                                availEps.add(ep);
                                staticProps.put(suid, availEps);
                            }
                        }
                    }

                    /*if (attrToxRate.compareTo(one) >= 0) {
                     EntityProperty availEp = staticProps.get(suid);
                     if (availEp == null) {
                     staticProps.put(suid, new EntityProperty(bp.getName(), cco.getTitle(), cov.getDescription(), suid, attrToxRate, attrToxRad, attrModalRate, (double) 0, PropertyType.OPTION));
                     } else {
                     if (attrToxRate.compareTo(availEp.getValue()) == 0) {
                     BigDecimal availModVal = staticProps.get(suid).modalValue;
                     if (attrModalRate.compareTo(availModVal) > 0) {
                     staticProps.put(suid, new EntityProperty(bp.getName(), cco.getTitle(), cov.getDescription(), suid, attrToxRate, attrToxRad, attrModalRate, (double) 0, PropertyType.OPTION));
                     }
                     } else if (attrToxRate.compareTo(availEp.getValue()) > 0) {
                     staticProps.put(suid, new EntityProperty(bp.getName(), cco.getTitle(), cov.getDescription(), suid, attrToxRate, attrToxRad, attrModalRate, (double) 0, PropertyType.OPTION));
                     }
                     }
                     //suplog+="COLOR: atr="+attrToxRate+"; am="+attrModalRate+"; etr="+essToxRate+"; statrate="+rel.toString()+"; ";
                     }*/
                }
            }
        }

    }

    //suplog += "? ?.: " + i + ", ?  : " + m + " ? ? : " + n + "; " + "minToxLvl=" + minParamToxic1 + "; ";
    for (FreeOption fo : car.getFreeOptions()) {
        String suid = fo.getUid().trim();
        Boolean pricep = PropertyType.STATICBASIS.equals(fo.getType());

        //suplog+="!! suid="+suid.trim()+"; ";
        BaseParam bp = getBaseParam(allParams, suid);
        //suplog+=""+k+"."+ccv.getTitle()+" - "+ccv.getColor().getName()+"; ";
        if (bp != null && StaticType.STATIC.equals(bp.getStaticType())
                && fo.getPrice().compareTo(Double.valueOf(0)) == 0) {
            List<String> colorRadList = ConvertSupport.getRadicalList(fo.getRadical());

            if (!colorRadList.isEmpty()) {
                String attrToxRad = "";
                BigDecimal attrToxRate = BigDecimal.valueOf(-100);
                for (String colorRad : colorRadList) {
                    BigDecimal ToxRate = BigDecimal
                            .valueOf(getToxicRate(radCore.trim(), radColor.trim(), colorRad));
                    if (ToxRate.compareTo(attrToxRate) >= 0) {
                        attrToxRate = ToxRate;
                        attrToxRad = colorRad;
                    }
                }
                if (attrToxRad != null && !attrToxRad.equals("")) {
                    BigDecimal attrModalRate = BigDecimal.valueOf(0);
                    if (percType.equals(Perception.AUDIAL)) {
                        if (fo.getAudial() != null) {
                            attrModalRate = BigDecimal.valueOf(fo.getAudial());
                        }
                    } else if (percType.equals(Perception.KINESTETIC)) {
                        if (fo.getKinestetic() != null) {
                            attrModalRate = BigDecimal.valueOf(fo.getKinestetic());
                        }
                    } else if (percType.equals(Perception.VISUAL)) {
                        if (fo.getVisual() != null) {
                            attrModalRate = BigDecimal.valueOf(fo.getVisual());
                        }
                    }

                    if ((attrToxRate.compareTo(one) >= 0 && !pricep) || (pricep)) {
                        String statType = " ??";
                        if (pricep) {
                            statType = " ";
                        }
                        EntityProperty ep = new EntityProperty(bp.getName(), fo.getTitle(), suid, attrToxRate,
                                attrToxRad, attrModalRate, fo.getPrice(), fo.getType(), statType);
                        List<EntityProperty> availEps = staticProps.get(suid);
                        if (availEps == null || availEps.isEmpty()) {
                            availEps = new ArrayList();
                            availEps.add(ep);
                            staticProps.put(suid, availEps);
                        } else {
                            EntityProperty availEp = availEps.get(0);
                            if ((!PropertyType.STATICBASIS.equals(availEp.type))
                                    || (PropertyType.STATICBASIS.equals(availEp.type) && pricep)) {
                                if (attrToxRate.compareTo(availEp.value) == 0) {
                                    BigDecimal availModVal = availEp.modalValue;
                                    if (attrModalRate.compareTo(availModVal) > 0) {
                                        availEps = new ArrayList();
                                        availEps.add(ep);
                                        staticProps.put(suid, availEps);
                                    } else if (attrModalRate.compareTo(availModVal) == 0) {
                                        availEps.add(ep);
                                        staticProps.put(suid, availEps);
                                    }
                                } else if (attrToxRate.compareTo(availEp.getValue()) > 0) {
                                    availEps = new ArrayList();
                                    availEps.add(ep);
                                    staticProps.put(suid, availEps);
                                }
                            } else if (pricep) {
                                availEps = new ArrayList();
                                availEps.add(ep);
                                staticProps.put(suid, availEps);
                            }
                        }
                    }

                    /* if (attrToxRate.compareTo(one) >= 0) {
                     EntityProperty availEp = staticProps.get(suid);
                     if (availEp == null) {
                     staticProps.put(suid, new EntityProperty(bp.getName(), fo.getTitle(), suid, attrToxRate, attrToxRad, attrModalRate, fo.getPrice(), fo.getType()));
                     } else {
                     if (attrToxRate.compareTo(availEp.getValue()) == 0) {
                     BigDecimal availModVal = availEp.modalValue;
                     if (attrModalRate.compareTo(availModVal) > 0) {
                     staticProps.put(suid, new EntityProperty(bp.getName(), fo.getTitle(), suid, attrToxRate, attrToxRad, attrModalRate, fo.getPrice(), fo.getType()));
                     }
                     } else if (attrToxRate.compareTo(availEp.getValue()) > 0) {
                     staticProps.put(suid, new EntityProperty(bp.getName(), fo.getTitle(), suid, attrToxRate, attrToxRad, attrModalRate, fo.getPrice(), fo.getType()));
                     }
                     }
                     //suplog+="COLOR: atr="+attrToxRate+"; am="+attrModalRate+"; etr="+essToxRate+"; statrate="+rel.toString()+"; ";
                     }*/
                }
            }
        }
    }
    for (Feature f : car.getFeatures()) {
        String suid = f.getUid().trim();
        //suplog+="!! suid="+suid.trim()+"; ";
        BaseParam bp = getBaseParam(allParams, suid);
        //suplog+=""+k+"."+ccv.getTitle()+" - "+ccv.getColor().getName()+"; ";
        if (bp != null && StaticType.STATIC.equals(bp.getStaticType())) {
            List<String> colorRadList = ConvertSupport.getRadicalList(f.getRadical());
            if (!colorRadList.isEmpty()) {
                String attrToxRad = "";
                BigDecimal attrToxRate = BigDecimal.valueOf(-100);
                for (String colorRad : colorRadList) {
                    BigDecimal ToxRate = BigDecimal
                            .valueOf(getToxicRate(radCore.trim(), radColor.trim(), colorRad));
                    if (ToxRate.compareTo(attrToxRate) > 0) {
                        attrToxRate = ToxRate;
                        attrToxRad = colorRad;
                    }
                }
                if (attrToxRad != null && !attrToxRad.equals("")) {
                    BigDecimal attrModalRate = BigDecimal.valueOf(0);
                    if (percType.equals(Perception.AUDIAL)) {
                        if (f.getAudial() != null) {
                            attrModalRate = BigDecimal.valueOf(f.getAudial());
                        }
                    } else if (percType.equals(Perception.KINESTETIC)) {
                        if (f.getKinestet() != null) {
                            attrModalRate = BigDecimal.valueOf(f.getKinestet());
                        }
                    } else if (percType.equals(Perception.VISUAL)) {
                        if (f.getVisual() != null) {
                            attrModalRate = BigDecimal.valueOf(f.getVisual());
                        }
                    }

                    if (attrToxRate.compareTo(one) >= 0) {
                        EntityProperty ep = new EntityProperty(bp.getName(), f.getTitle(), suid, attrToxRate,
                                attrToxRad, attrModalRate, (double) 0, PropertyType.FEATURE,
                                " ??");
                        List<EntityProperty> availEps = staticProps.get(suid);
                        if (availEps == null || availEps.isEmpty()) {
                            availEps = new ArrayList();
                            availEps.add(ep);
                            staticProps.put(suid, availEps);
                        } else {
                            EntityProperty availEp = availEps.get(0);
                            if (attrToxRate.compareTo(availEp.value) == 0) {
                                BigDecimal availModVal = availEp.modalValue;
                                if (attrModalRate.compareTo(availModVal) > 0) {
                                    availEps = new ArrayList();
                                    availEps.add(ep);
                                    staticProps.put(suid, availEps);
                                } else if (attrModalRate.compareTo(availModVal) == 0) {
                                    availEps.add(ep);
                                    staticProps.put(suid, availEps);
                                }
                            } else if (attrToxRate.compareTo(availEp.getValue()) > 0) {
                                availEps = new ArrayList();
                                availEps.add(ep);
                                staticProps.put(suid, availEps);
                            }
                        }
                    }

                    /*if (attrToxRate.compareTo(one) >= 0) {
                     EntityProperty availEp = staticProps.get(suid);
                     if (availEp == null) {
                     staticProps.put(suid, new EntityProperty(bp.getName(), f.getTitle(), suid, attrToxRate, attrToxRad, attrModalRate, (double) 0, PropertyType.FEATURE));
                     } else {
                     if (attrToxRate.compareTo(availEp.getValue()) == 0) {
                     BigDecimal availModVal = staticProps.get(suid).modalValue;
                     if (attrModalRate.compareTo(availModVal) > 0) {
                     staticProps.put(suid, new EntityProperty(bp.getName(), f.getTitle(), suid, attrToxRate, attrToxRad, attrModalRate, (double) 0, PropertyType.FEATURE));
                     }
                     } else if (attrToxRate.compareTo(availEp.getValue()) > 0) {
                     staticProps.put(suid, new EntityProperty(bp.getName(), f.getTitle(), suid, attrToxRate, attrToxRad, attrModalRate, (double) 0, PropertyType.FEATURE));
                     }
                     }
                     //suplog+="COLOR: atr="+attrToxRate+"; am="+attrModalRate+"; etr="+essToxRate+"; statrate="+rel.toString()+"; ";
                     }*/
                }
            }
        }
    }

}

From source file:com.genscript.gsscm.order.web.OrderAction.java

/**
 * confirm??/*  w  w w  . j a va2 s .co m*/
 * 
 * @return
 */
public String checkConfirm() {
    if (!StringUtils.isNumeric(sessOrderNo)) {
        Struts2Util.renderText("The order are not available to be confirmed.");
        return null;
    }
    order = (OrderMainDTO) SessionUtil.getRow(SessionConstant.Order.value(), sessOrderNo);
    if (order.getOrderCurrency() == null || "".equals(order.getOrderCurrency())) {
        Struts2Util.renderText("The order currency is null, couldn't comfirm.");
        return null;
    }
    // }else if (!order.getOrderCurrency().equals(order.getBaseCurrency()))
    // {
    // Struts2Util.renderText("The order base currency '" +
    // order.getBaseCurrency() + "' is not same as order currency '" +
    // order.getOrderCurrency() + ", so can't to be confirmed.");
    // return null;
    // }
    String oldStatus = order.getStatus();
    if (status.equalsIgnoreCase("CC") && !oldStatus.equalsIgnoreCase("NW")
            && !oldStatus.equalsIgnoreCase("RV")) {
        Struts2Util.renderText("The order are not available to be confirmed.");
        return null;
    }
    if (order.getWarehouseId() == null) {
        Struts2Util.renderText("Order's WarehouseId is null, couldn't comfirm.");
        return null;
    }
    if (internalOrderFlag != 1) {
        if (orderService.isPoCCexixt(Integer.parseInt(sessOrderNo)).booleanValue() == false) {
            Struts2Util.renderText("Please add the payment method!");
            return null;
        }
        // customer-confirm email???
        if (orderService.isCustMailSent(Integer.parseInt(sessOrderNo), Constants.CUST_CONFIRM_EMAIL)
                .booleanValue() == false) {
            Struts2Util.renderText("The customer-confirm email has not been sent yet.");
            return null;
        }
    }
    // Add Order Change Notification???
    if (orderService.isCustMailSent(Integer.parseInt(sessOrderNo), Constants.ORDER_CHANGE_NOTIFICATION)
            .booleanValue() == false) {
        Struts2Util.renderText("The 'Add Order Change Notification' email has not been sent yet.");
        return null;
    }
    // order total < creit limit
    BigDecimal orderTotal = quoteOrderService.getTotal(order.getAmount(), order.getDiscount(), order.getTax(),
            order.getShipAmt(), order.getOrderCurrency());
    if (!"USD".equalsIgnoreCase(order.getOrderCurrency())) {
        orderTotal = quoteOrderService.changeTotalCurrency(orderTotal, order.getOrderCurrency(), "USD");
    }
    Double creditLimit = customerService.getCreditLimit(order.getCustNo(), order.getOrderCurrency());
    if (creditLimit == null || orderTotal.compareTo(new BigDecimal(creditLimit)) == 1) {
        Struts2Util.renderText("The customer's credit limit is less than order total.");
        return null;
    }
    Struts2Util.renderText("SUCCESS");
    return null;
}

From source file:com.citrix.cpbm.portal.fragment.controllers.AbstractTenantController.java

/**
 * Add credit method.//from w w  w.j  a  va  2 s.  c o m
 * 
 * @param tenantParam the tenant param.
 * @param credit the Credit Amount
 * @param comment
 * @param request {@link HttpServletRequest}
 * @param response {@link HttpServletResponse}
 * @return
 */
@RequestMapping(value = "/{tenantParam}/add_credit", method = RequestMethod.POST)
@ResponseBody
public String issueCredit(@PathVariable String tenantParam,
        @RequestParam(value = "credit", required = true) String credit,
        @RequestParam(value = "comment", required = true) String comment, HttpServletRequest request,
        HttpServletResponse response) {
    logger.debug("###Entering in issueCredit(tenantId,credit,comment,response) method @POST");
    try {
        Tenant tenant = tenantService.get(tenantParam);
        JSONObject result = new JSONObject();
        BigDecimal creditDecimal = billingPostProcessor.setScaleByCurrency(new BigDecimal(credit),
                tenant.getCurrency());
        if (creditDecimal.compareTo(new BigDecimal(0)) < 0) {// negative credit
            response.setStatus(HttpStatus.PRECONDITION_FAILED.value());
        } else {

            SalesLedgerRecord creditSLR = billingAdminService.addPaymentOrCredit(tenant, creditDecimal,
                    Type.SERVICE_CREDIT, comment, null);

            AccountStatement accountStatement = creditSLR.getAccountStatement();
            response.setStatus(HttpStatus.OK.value());
            String message = messageSource.getMessage("tenant.credit.confirmation", null,
                    getSessionLocale(request));
            result.put("creditBalance", accountStatement.getFinalCharges().negate()) // toConfirm
                    .put("message", StringEscapeUtils.escapeHtml(message))
                    .put("creditamount", accountStatement.getCredits());
        }
        logger.debug(result.toString());
        logger.debug("###Exiting issueCredit(tenantId,credit,comment,response) method @POST");
        return result.toString();
    } catch (Exception ex) {
        response.setStatus(HttpStatus.PRECONDITION_FAILED.value());
        logger.error(ex);
        return null;
    }
}

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

/**
 * Resolve the first authorization level for the given payment, if any. When the payment wouldn't be authorizable, return null
 *///from   ww  w . j  a v a 2  s.  c om
private AuthorizationLevel firstAuthorizationLevel(TransferType transferType, final BigDecimal amount,
        AccountOwner from) {
    transferType = fetchService.fetch(transferType, TransferType.Relationships.AUTHORIZATION_LEVELS);
    if (transferType.isRequiresAuthorization()
            && CollectionUtils.isNotEmpty(transferType.getAuthorizationLevels())) {
        if (from == null) {
            from = LoggedUser.accountOwner();
        }
        final Account account = accountService.getAccount(new AccountDTO(from, transferType.getFrom()));
        BigDecimal amountSoFarToday = transferDao.getTransactionedAmountAt(null, account, transferType);
        final AuthorizationLevel authorization = transferType.getAuthorizationLevels().iterator().next();

        // When the amount is greater than the authorization, return true
        final BigDecimal amountToTest = amountSoFarToday.add(amount);
        if (amountToTest.compareTo(authorization.getAmount()) >= 0) {
            return transferType.getAuthorizationLevels().iterator().next();
        }
    }
    return null;
}

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

/**
 * Creates the gain loss4 document account.
 *
 * @param _parameter Parameter as passed by the eFaps API
 * @return the return//from  w  w  w  . jav a 2s  .co  m
 * @throws EFapsException on error
 */
public Return createGainLoss4DocumentAccount(final Parameter _parameter) throws EFapsException {
    final Set<String> setAccounts = getAccounts4DocumentConfig(_parameter);

    final String[] oidsDoc = (String[]) Context.getThreadContext().getSessionAttribute(
            CIFormAccounting.Accounting_GainLoss4DocumentAccountForm.selectedDocuments.name);
    final DateTime dateTo = new DateTime(_parameter
            .getParameterValue(CIFormAccounting.Accounting_GainLoss4DocumentAccountForm.transactionDate.name));
    for (final String oid : oidsDoc) {
        final Instance instDoc = Instance.get(oid);

        final QueryBuilder attrQuerBldr = new QueryBuilder(CIAccounting.Transaction2SalesDocument);
        attrQuerBldr.addWhereAttrEqValue(CIAccounting.Transaction2SalesDocument.ToLink, instDoc);
        final AttributeQuery attrQuery = attrQuerBldr
                .getAttributeQuery(CIAccounting.Transaction2SalesDocument.FromLink);

        // filter classification Document
        final QueryBuilder attrQueryBldr2 = new QueryBuilder(CIAccounting.Transaction);
        attrQueryBldr2.addWhereAttrEqValue(CIAccounting.Transaction.PeriodLink,
                _parameter.getInstance().getId());
        attrQueryBldr2.addWhereAttrInQuery(CIAccounting.Transaction.ID, attrQuery);
        final AttributeQuery attrQuery2 = attrQuerBldr.getAttributeQuery(CIAccounting.Transaction.ID);

        final QueryBuilder queryBldr = new QueryBuilder(CIAccounting.TransactionPositionAbstract);
        queryBldr.addWhereAttrInQuery(CIAccounting.TransactionPositionAbstract.TransactionLink, attrQuery2);
        final MultiPrintQuery multi = queryBldr.getPrint();
        multi.addAttribute(CIAccounting.TransactionPositionAbstract.Amount,
                CIAccounting.TransactionPositionAbstract.RateAmount,
                CIAccounting.TransactionPositionAbstract.CurrencyLink,
                CIAccounting.TransactionPositionAbstract.RateCurrencyLink);
        final SelectBuilder selAcc = new SelectBuilder()
                .linkto(CIAccounting.TransactionPositionAbstract.AccountLink).oid();
        multi.addSelect(selAcc);
        multi.execute();
        final Map<String, AccountInfo> map = new HashMap<>();
        while (multi.next()) {
            final Instance accountInst = Instance.get(multi.<String>getSelect(selAcc));
            if (setAccounts.contains(accountInst.getOid())) {
                final BigDecimal oldRateAmount = multi
                        .<BigDecimal>getAttribute(CIAccounting.TransactionPositionAbstract.RateAmount);
                final BigDecimal oldAmount = multi
                        .<BigDecimal>getAttribute(CIAccounting.TransactionPositionAbstract.Amount);
                final Instance targetCurrInst = Instance.get(CIERP.Currency.getType(),
                        multi.<Long>getAttribute(CIAccounting.TransactionPositionAbstract.RateCurrencyLink));
                final Instance currentInst = Instance.get(CIERP.Currency.getType(),
                        multi.<Long>getAttribute(CIAccounting.TransactionPositionAbstract.CurrencyLink));

                final PriceUtil priceUtil = new PriceUtil();
                final BigDecimal[] rates = priceUtil.getRates(_parameter, targetCurrInst, currentInst);
                final BigDecimal rate = rates[2];
                final BigDecimal newAmount = oldRateAmount.divide(rate, BigDecimal.ROUND_HALF_UP);

                BigDecimal gainloss = BigDecimal.ZERO;
                if (!currentInst.equals(targetCurrInst)) {
                    gainloss = newAmount.subtract(oldAmount);
                } else {
                    gainloss = newAmount;
                }
                if (map.containsKey(accountInst.getOid())) {
                    final AccountInfo tarAcc = map.get(accountInst.getOid());
                    tarAcc.addAmount(gainloss);
                } else {
                    final AccountInfo tarAcc = new AccountInfo(accountInst, gainloss);
                    tarAcc.setAmountRate(gainloss);
                    tarAcc.setCurrInstance(currentInst);
                    map.put(accountInst.getOid(), tarAcc);
                }
            }
        }

        if (!map.isEmpty()) {
            Insert insert = null;
            CurrencyInst curr = null;
            BigDecimal gainlossSum = BigDecimal.ZERO;
            for (final Entry<String, AccountInfo> entry : map.entrySet()) {
                final AccountInfo tarAcc = entry.getValue();
                final Instance instAcc = Instance.get(entry.getKey());
                final BigDecimal gainloss = tarAcc.getAmount();
                gainlossSum = gainlossSum.add(gainloss);
                final Instance currInstance = tarAcc.getCurrInstance();
                curr = new CurrencyInst(currInstance);
                final Map<String, String[]> mapVal = validateInfo(_parameter, gainloss);
                final String[] accs = mapVal.get("accs");
                final String[] check = mapVal.get("check");

                if (checkAccounts(accs, 0, check).length() > 0) {
                    if (gainloss.compareTo(BigDecimal.ZERO) != 0) {
                        final String[] accOids = mapVal.get("accountOids");
                        if (insert == null) {
                            final DateTimeFormatter formater = DateTimeFormat.mediumDate();
                            final String dateStr = dateTo
                                    .withChronology(Context.getThreadContext().getChronology())
                                    .toString(formater.withLocale(Context.getThreadContext().getLocale()));
                            final StringBuilder description = new StringBuilder();
                            description
                                    .append(DBProperties
                                            .getProperty("Accounting_DocumentAccountForm.TxnRecalculate.Label"))
                                    .append(" ").append(dateStr);
                            insert = new Insert(CIAccounting.Transaction);
                            insert.add(CIAccounting.Transaction.Description, description.toString());
                            insert.add(CIAccounting.Transaction.Date, dateTo);
                            insert.add(CIAccounting.Transaction.PeriodLink, _parameter.getInstance().getId());
                            insert.add(CIAccounting.Transaction.Status,
                                    Status.find(CIAccounting.TransactionStatus.uuid, "Open").getId());
                            insert.execute();
                        }

                        Insert insertPos = new Insert(CIAccounting.TransactionPositionCredit);
                        insertPos.add(CIAccounting.TransactionPositionCredit.TransactionLink, insert.getId());
                        if (gainloss.signum() < 0) {
                            insertPos.add(CIAccounting.TransactionPositionCredit.AccountLink, instAcc.getId());
                        } else {
                            insertPos.add(CIAccounting.TransactionPositionCredit.AccountLink,
                                    Instance.get(accOids[0]).getId());
                        }
                        insertPos.add(CIAccounting.TransactionPositionCredit.Amount, gainloss.abs());
                        insertPos.add(CIAccounting.TransactionPositionCredit.RateAmount, gainloss.abs());
                        insertPos.add(CIAccounting.TransactionPositionCredit.CurrencyLink,
                                currInstance.getId());
                        insertPos.add(CIAccounting.TransactionPositionCredit.RateCurrencyLink,
                                currInstance.getId());
                        insertPos.add(CIAccounting.TransactionPositionCredit.Rate,
                                new Object[] { BigDecimal.ONE, BigDecimal.ONE });
                        insertPos.execute();

                        insertPos = new Insert(CIAccounting.TransactionPositionDebit);
                        insertPos.add(CIAccounting.TransactionPositionDebit.TransactionLink, insert.getId());
                        if (gainloss.signum() < 0) {
                            insertPos.add(CIAccounting.TransactionPositionDebit.AccountLink,
                                    Instance.get(accOids[0]).getId());
                        } else {
                            insertPos.add(CIAccounting.TransactionPositionDebit.AccountLink, instAcc.getId());
                        }
                        insertPos.add(CIAccounting.TransactionPositionDebit.Amount, gainloss.abs().negate());
                        insertPos.add(CIAccounting.TransactionPositionDebit.RateAmount,
                                gainloss.abs().negate());
                        insertPos.add(CIAccounting.TransactionPositionDebit.CurrencyLink, currInstance.getId());
                        insertPos.add(CIAccounting.TransactionPositionDebit.RateCurrencyLink,
                                currInstance.getId());
                        insertPos.add(CIAccounting.TransactionPositionDebit.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.getId());
                relInsert1.add(classification1.getRelTypeAttributeName(), classification1.getId());
                relInsert1.execute();

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

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

                final Insert classInsert = new Insert(classification);
                classInsert.add(classification.getLinkAttributeName(), instance.getId());
                classInsert.add(CIAccounting.TransactionClassGainLoss.Amount, gainlossSum);
                classInsert.add(CIAccounting.TransactionClassGainLoss.RateAmount, gainlossSum);
                classInsert.add(CIAccounting.TransactionClassGainLoss.CurrencyLink, curr.getInstance().getId());
                classInsert.add(CIAccounting.TransactionClassGainLoss.RateCurrencyLink,
                        curr.getInstance().getId());
                classInsert.add(CIAccounting.TransactionClassGainLoss.Rate,
                        new Object[] { BigDecimal.ONE, BigDecimal.ONE });
                classInsert.execute();

                new Create().connectDocs2Transaction(_parameter, instance, instDoc);
            }
        }
    }

    return new Return();
}