Example usage for java.math BigDecimal add

List of usage examples for java.math BigDecimal add

Introduction

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

Prototype

public BigDecimal add(BigDecimal augend) 

Source Link

Document

Returns a BigDecimal whose value is (this + augend) , and whose scale is max(this.scale(), augend.scale()) .

Usage

From source file:com.axelor.apps.account.service.MoveLineExportService.java

public BigDecimal getTotalAmount(List<MoveLine> moveLinelst) {

    BigDecimal totDebit = BigDecimal.ZERO;
    BigDecimal totCredit = BigDecimal.ZERO;

    for (MoveLine moveLine : moveLinelst) {
        totDebit = totDebit.add(moveLine.getDebit());
        totCredit = totCredit.add(moveLine.getCredit());
    }//from w ww  .  j a va  2  s.c om

    return totCredit.subtract(totDebit);
}

From source file:churashima.action.manage.WorkingAction.java

@Execute(input = "workEntry.jsp")
public String entryExecute() {

    WorkDao workDao = SingletonS2Container.getComponent(WorkDao.class);
    UserInfoDao userInfoDao = SingletonS2Container.getComponent(UserInfoDao.class);
    SubjectDao subjectDao = SingletonS2Container.getComponent(SubjectDao.class);

    // ??/*  w  w  w  .j  ava2 s .  co m*/
    workingForm.userInfoList = userInfoDao.selectForSearch(null, null);
    workingForm.subjectList = subjectDao.selectForSearch(null, null);

    //      List<Work> workList = workDao.selectForSearch(workingForm.name);
    //      
    //      if (workList != null && workList.size() >= 1) {
    //         ActionMessages errors = new ActionMessages();
    //         errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(
    //            "errors.already.entried", //??????
    //            new Object[] { workingForm.name }));
    //         ActionMessagesUtil.addErrors(RequestUtil.getRequest(), errors);
    //         return "workEntry.jsp";
    //      }

    Work work = new Work();
    try {
        work.date = new SimpleDateFormat("yyyy/MM/dd").parse(workingForm.date);
    } catch (ParseException e) {
        e.printStackTrace();
    }

    work.userId = Long.valueOf(workingForm.userId);

    Timestamp now = new Timestamp(System.currentTimeMillis());
    work.deleted = false;
    work.insDate = now;
    work.insId = Long.valueOf(0);
    work.updDate = now;
    work.updId = Long.valueOf(0);

    List<String> subjectIdList = workingForm.subjectIdList;
    List<String> startHourList = workingForm.startHour;
    List<String> endHourList = workingForm.endHour;
    List<String> startMinuteList = workingForm.startMinute;
    List<String> endMinuteList = workingForm.endMinute;
    List<String> kindList = workingForm.kind;

    String subjectId = null;
    String startHour = null;
    String startMinute = null;
    String endHour = null;
    String endMinute = null;
    String kind = null;

    int endHourBefore = -1;
    int endMinuteBefore = -1;

    for (int index = 0; index < subjectIdList.size(); index++) {
        subjectId = subjectIdList.get(index);
        startHour = startHourList.get(index);
        startMinute = startMinuteList.get(index);
        endHour = endHourList.get(index);
        endMinute = endMinuteList.get(index);
        kind = kindList.get(index);

        if (StringUtils.isEmpty(subjectId)) {
            // subjectId??????
            continue;
        }

        /*** ? start ***/
        if (StringUtils.isEmpty(startHour) || StringUtils.isEmpty(startMinute) || StringUtils.isEmpty(endHour)
                || StringUtils.isEmpty(endMinute)) {

            // ??????
            Subject subject = subjectDao.selectById(Long.valueOf(subjectId));
            ActionMessages errors = new ActionMessages();
            errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("errors.empty.work.time", //??????
                    new Object[] { subject.name }));
            ActionMessagesUtil.addErrors(RequestUtil.getRequest(), errors);
            return "workEntry.jsp";
        }
        int startHourInt = Integer.parseInt(startHour);
        int startMinuteInt = Integer.parseInt(startMinute);
        int endHourInt = Integer.parseInt(endHour);
        int endMinuteInt = Integer.parseInt(endMinute);

        if (startHourInt > endHourInt || (startHourInt == endHourInt && startMinuteInt >= endMinuteInt)) {
            // ????????
            ActionMessages errors = new ActionMessages();
            errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("errors.not.correct.work.time", //??????
                    new Object[] { index + 1 }));
            ActionMessagesUtil.addErrors(RequestUtil.getRequest(), errors);
            return "workEntry.jsp";
        }

        // 2????
        if (endHourBefore >= 0) {

            if (endHourBefore > startHourInt
                    || (endHourBefore == startHourInt && endMinuteBefore > startMinuteInt)) {
                // ????????
                ActionMessages errors = new ActionMessages();
                errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("errors.overlap.work.time", //??????
                        new Object[] { index + 1 }));
                ActionMessagesUtil.addErrors(RequestUtil.getRequest(), errors);
                return "workEntry.jsp";
            }
        }
        /*** ? end ***/

        // 
        Calendar startCal = Calendar.getInstance();
        startCal.setTime(work.date);
        startCal.set(Calendar.HOUR_OF_DAY, Integer.parseInt(startHour));
        startCal.set(Calendar.MINUTE, Integer.parseInt(startMinute));
        work.startTime = new Timestamp(startCal.getTimeInMillis());

        // 
        Calendar endCal = Calendar.getInstance();
        endCal.setTime(work.date);
        endCal.set(Calendar.HOUR_OF_DAY, Integer.parseInt(endHour));
        endCal.set(Calendar.MINUTE, Integer.parseInt(endMinute));
        work.endTime = new Timestamp(endCal.getTimeInMillis());

        // 
        double diff = endCal.getTimeInMillis() - startCal.getTimeInMillis();

        // 12:0013:00
        BigDecimal lunchRestHour = WorkUtil.getHour(startCal, endCal, Const.REST_HOUR, Const.REST_MINUTE,
                Const.REST_TERM);

        // ?15:0015:30
        BigDecimal retHour = WorkUtil.getHour(startCal, endCal, Const.LUNCH_REST_HOUR, Const.LUNCH_REST_MINUTE,
                Const.LUNCH_REST_TERM);

        work.workHour = (new BigDecimal(diff / 1000 / 60 / 60)).subtract(lunchRestHour);
        work.workHour = work.workHour.subtract(retHour);

        // ?
        BigDecimal morningHour = WorkUtil.getHour(startCal, endCal, Const.MORNING_OVER_HOUR,
                Const.MORNING_OVER_MINUTE, Const.MORNING_OVER_TERM);

        // 
        BigDecimal eveningHour = WorkUtil.getHour(startCal, endCal, Const.EVENING_OVER_HOUR,
                Const.EVENING_OVER_MINUTE, Const.EVENING_OVER_TERM);

        // 
        BigDecimal nightHour = WorkUtil.getHour(startCal, endCal, Const.NIGHT_OVER_HOUR,
                Const.NIGHT_OVER_MINUTE, Const.NIGHT_OVER_TERM);

        work.overHourMorning = morningHour;
        work.overHourEvening = eveningHour;
        work.overHourNight = nightHour;
        work.overHour = morningHour.add(eveningHour).add(nightHour);

        work.subjectId = Long.valueOf(subjectId);
        work.kind = kind;

        workDao.insert(work);

        endHourBefore = endHourInt;
        endMinuteBefore = endMinuteInt;
    }

    return "search";
}

From source file:churashima.action.manage.WorkingAction.java

@Execute(validator = false)
public String editExecute() {

    // ?/*from  ww  w  .ja  v  a2s . c o m*/
    UserInfoDao userInfoDao = SingletonS2Container.getComponent(UserInfoDao.class);
    SubjectDao subjectDao = SingletonS2Container.getComponent(SubjectDao.class);
    WorkDao workDao = SingletonS2Container.getComponent(WorkDao.class);

    workingForm.userInfoList = userInfoDao.selectForSearch(null, null);
    workingForm.subjectList = subjectDao.selectForSearch(null, null);

    //      List<Work> workList = workDao.selectForSearch(workingForm.name);
    //      
    //      if (workList != null && workList.size() >= 1) {
    //         ActionMessages errors = new ActionMessages();
    //         errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(
    //            "errors.already.entried", //??????
    //            new Object[] { workingForm.name }));
    //         ActionMessagesUtil.addErrors(RequestUtil.getRequest(), errors);
    //         return "workEntry.jsp";
    //      }
    Work work = workDao.selectById(Long.valueOf(workingForm.workId));

    try {
        work.date = new SimpleDateFormat("yyyy/MM/dd").parse(workingForm.date);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    work.userId = Long.valueOf(workingForm.userId);

    Timestamp now = new Timestamp(System.currentTimeMillis());
    work.updDate = now;
    work.updId = Long.valueOf(0);

    List<Work> workDeleteList = workDao.selectForSearch(work.userId, null, null, null, null, null, work.date);

    // 
    for (Work workDel : workDeleteList) {
        workDao.delete(workDel);
    }

    // ?
    work.deleted = false;
    work.insDate = now;
    work.insId = Long.valueOf(0);
    work.updDate = now;
    work.updId = Long.valueOf(0);

    List<String> subjectIdList = workingForm.subjectIdList;
    List<String> startHourList = workingForm.startHour;
    List<String> endHourList = workingForm.endHour;
    List<String> startMinuteList = workingForm.startMinute;
    List<String> endMinuteList = workingForm.endMinute;
    List<String> kindList = workingForm.kind;

    String subjectId = null;
    String startHour = null;
    String startMinute = null;
    String endHour = null;
    String endMinute = null;
    String kind = null;

    int endHourBefore = -1;
    int endMinuteBefore = -1;

    for (int index = 0; index < subjectIdList.size(); index++) {
        subjectId = subjectIdList.get(index);
        startHour = startHourList.get(index);
        startMinute = startMinuteList.get(index);
        endHour = endHourList.get(index);
        endMinute = endMinuteList.get(index);
        kind = kindList.get(index);

        if (StringUtils.isEmpty(subjectId)) {
            // subjectId??????
            continue;
        }

        /*** ? start ***/
        if (StringUtils.isEmpty(startHour) || StringUtils.isEmpty(startMinute) || StringUtils.isEmpty(endHour)
                || StringUtils.isEmpty(endMinute)) {

            // ??????
            Subject subject = subjectDao.selectById(Long.valueOf(subjectId));
            ActionMessages errors = new ActionMessages();
            errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("errors.empty.work.time", //??????
                    new Object[] { subject.name }));
            ActionMessagesUtil.addErrors(RequestUtil.getRequest(), errors);
            return "workEdit.jsp";
        }
        int startHourInt = Integer.parseInt(startHour);
        int startMinuteInt = Integer.parseInt(startMinute);
        int endHourInt = Integer.parseInt(endHour);
        int endMinuteInt = Integer.parseInt(endMinute);

        if (startHourInt > endHourInt || (startHourInt == endHourInt && startMinuteInt >= endMinuteInt)) {
            // ????????
            ActionMessages errors = new ActionMessages();
            errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("errors.not.correct.work.time", //??????
                    new Object[] { index + 1 }));
            ActionMessagesUtil.addErrors(RequestUtil.getRequest(), errors);
            return "workEdit.jsp";
        }

        // 2????
        if (endHourBefore >= 0) {

            if (endHourBefore > startHourInt
                    || (endHourBefore == startHourInt && endMinuteBefore > startMinuteInt)) {
                // ????????
                ActionMessages errors = new ActionMessages();
                errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("errors.overlap.work.time", //??????
                        new Object[] { index + 1 }));
                ActionMessagesUtil.addErrors(RequestUtil.getRequest(), errors);
                return "workEdit.jsp";
            }
        }
        /*** ? end ***/

        // 
        Calendar startCal = Calendar.getInstance();
        startCal.setTime(work.date);
        startCal.set(Calendar.HOUR_OF_DAY, Integer.parseInt(startHour));
        startCal.set(Calendar.MINUTE, Integer.parseInt(startMinute));
        work.startTime = new Timestamp(startCal.getTimeInMillis());

        // 
        Calendar endCal = Calendar.getInstance();
        endCal.setTime(work.date);
        endCal.set(Calendar.HOUR_OF_DAY, Integer.parseInt(endHour));
        endCal.set(Calendar.MINUTE, Integer.parseInt(endMinute));
        work.endTime = new Timestamp(endCal.getTimeInMillis());

        // 
        double diff = endCal.getTimeInMillis() - startCal.getTimeInMillis();

        // 12:0013:00
        BigDecimal lunchRestHour = WorkUtil.getHour(startCal, endCal, Const.REST_HOUR, Const.REST_MINUTE,
                Const.REST_TERM);

        // ?15:0015:30
        BigDecimal retHour = WorkUtil.getHour(startCal, endCal, Const.LUNCH_REST_HOUR, Const.LUNCH_REST_MINUTE,
                Const.LUNCH_REST_TERM);

        work.workHour = (new BigDecimal(diff / 1000 / 60 / 60)).subtract(lunchRestHour);
        work.workHour = work.workHour.subtract(retHour);

        // ?
        BigDecimal morningHour = WorkUtil.getHour(startCal, endCal, Const.MORNING_OVER_HOUR,
                Const.MORNING_OVER_MINUTE, Const.MORNING_OVER_TERM);

        // 
        BigDecimal eveningHour = WorkUtil.getHour(startCal, endCal, Const.EVENING_OVER_HOUR,
                Const.EVENING_OVER_MINUTE, Const.EVENING_OVER_TERM);

        // 
        BigDecimal nightHour = WorkUtil.getHour(startCal, endCal, Const.NIGHT_OVER_HOUR,
                Const.NIGHT_OVER_MINUTE, Const.NIGHT_OVER_TERM);

        work.overHourMorning = morningHour;
        work.overHourEvening = eveningHour;
        work.overHourNight = nightHour;
        work.overHour = morningHour.add(eveningHour).add(nightHour);

        work.subjectId = Long.valueOf(subjectId);
        work.kind = kind;

        workDao.insert(work);
    }

    return "search";
}

From source file:org.kuali.coeus.s2sgen.impl.generate.support.RRBudgetV1_1Generator.java

/**
 * This method gets BudgetYearDataType details like
 * BudgetPeriodStartDate,BudgetPeriodEndDate,BudgetPeriod
 * KeyPersons,OtherPersonnel,TotalCompensation,Equipment,ParticipantTraineeSupportCosts,Travel,OtherDirectCosts
 * DirectCosts,IndirectCosts,CognizantFederalAgency,TotalCosts based on
 * BudgetPeriodInfo for the RRBudget./*from w w w .  j a  v  a  2s  .  c  o  m*/
 * 
 * @param periodInfo
 *            (BudgetPeriodInfo) budget period entry.
 * @return BudgetYear1DataType corresponding to the BudgetSummaryInfo
 *         object.
 */
private BudgetYearDataType getBudgetYearDataType(BudgetPeriodDto periodInfo) {

    BudgetYearDataType budgetYear = BudgetYearDataType.Factory.newInstance();
    if (periodInfo != null) {
        budgetYear
                .setBudgetPeriodStartDate(s2SDateTimeService.convertDateToCalendar(periodInfo.getStartDate()));
        budgetYear.setBudgetPeriodEndDate(s2SDateTimeService.convertDateToCalendar(periodInfo.getEndDate()));
        BudgetPeriod.Enum budgetPeriod = BudgetPeriod.Enum.forInt(periodInfo.getBudgetPeriod());
        budgetYear.setBudgetPeriod(budgetPeriod);
        budgetYear.setKeyPersons(getKeyPersons(periodInfo));
        budgetYear.setOtherPersonnel(getOtherPersonnel(periodInfo));
        if (periodInfo.getTotalCompensation() != null) {
            budgetYear.setTotalCompensation(periodInfo.getTotalCompensation().bigDecimalValue());
        }
        budgetYear.setEquipment(getEquipment(periodInfo));
        budgetYear.setTravel(getTravel(periodInfo));
        budgetYear.setParticipantTraineeSupportCosts(getParticipantTraineeSupportCosts(periodInfo));
        budgetYear.setOtherDirectCosts(getOtherDirectCosts(periodInfo));
        BigDecimal directCosts = periodInfo.getDirectCostsTotal().bigDecimalValue();
        budgetYear.setDirectCosts(directCosts);
        IndirectCosts indirectCosts = getIndirectCosts(periodInfo);
        budgetYear.setIndirectCosts(indirectCosts);
        budgetYear.setCognizantFederalAgency(periodInfo.getCognizantFedAgency());
        if (indirectCosts != null) {
            budgetYear.setTotalCosts(directCosts.add(indirectCosts.getTotalIndirectCosts()));
        } else {
            budgetYear.setTotalCosts(periodInfo.getTotalCosts().bigDecimalValue());
        }
    }
    return budgetYear;
}

From source file:com.selfsoft.business.action.TbFixEntrustAction.java

public String statisticsTbFixEntrust() throws Exception {

    ActionContext.getContext().put("tmUserMap", tmUserService.findAllTmUserMap());

    if (null == tbFixEntrust) {

        tbFixEntrust = new TbFixEntrust();

        tbFixEntrust.setIsvalid(Constants.ISVALIDVALUE);

        Date d = new Date();

        Date s = CommonMethod.parseStringToDate(
                CommonMethod.getYear(d) + "-" + CommonMethod.getMonth(d) + "-01", "yyyy-MM-dd");

        Date e = CommonMethod.parseStringToDate(
                CommonMethod.getYear(d) + "-" + CommonMethod.getMonth(d) + "-"
                        + CommonMethod.getMonthDays(CommonMethod.getYear(d), CommonMethod.getMonth(d)),
                "yyyy-MM-dd");

        tbFixEntrust.setFixDateStart(s);

        tbFixEntrust.setFixDateEnd(e);//w  w w. java2s.c  om
    }

    List<TbFixEntrust> tbFixEntrustList = tbFixEntrustService.findByTbFixEntrust(tbFixEntrust);

    ActionContext.getContext().put("tbFixEntrustList", tbFixEntrustList);

    if (null != tbFixEntrustList && tbFixEntrustList.size() > 0) {

        BigDecimal d_fixHourAll = new BigDecimal("0.00");

        for (TbFixEntrust tbFixEntrust : tbFixEntrustList) {

            Double fixHourAll = tbFixEntrustContentService
                    .countTbFixEnTrustContentByTbFixEntrustId(tbFixEntrust.getId());

            d_fixHourAll = d_fixHourAll
                    .add(new BigDecimal(String.valueOf(fixHourAll == null ? 0.00d : fixHourAll)))
                    .setScale(2, BigDecimal.ROUND_HALF_UP);
        }

        ActionContext.getContext().put("fixHourAll", d_fixHourAll);
    }

    //ActionContext.getContext().put("sellPriceAll",new BigDecimal(tbFixEntrustService.getTotalSellPriceByEntrustList(tbFixEntrustList)).setScale(2));

    //ActionContext.getContext().put("costPriceAll",new BigDecimal(tbFixEntrustService.getTotalCostPriceByEntrustList(tbFixEntrustList)).setScale(2));

    ActionContext.getContext().put("sellPriceAll",
            tbFixEntrustService.getTotalSellPriceByEntrustList(tbFixEntrustList));

    ActionContext.getContext().put("costPriceAll",
            tbFixEntrustService.getTotalCostPriceByEntrustList(tbFixEntrustList));

    List<StatisticsTbFixBusinessVo> statisticsTbFixBusinessVoList = tbFixEntrustService
            .statisticsTbFixEntrust(tbFixEntrust);

    ActionContext.getContext().put("statisticsTbFixBusinessVoList", statisticsTbFixBusinessVoList);

    return Constants.SUCCESS;

}

From source file:com.mg.merp.planning.support.MPSProcessorServiceBean.java

private List<ProductDemandItem> loadCurrentQuantityOnHandFromWarehouse(Date planningStartDate) {
    List<GenericItem> giList = ormTemplate.findByCriteria(
            OrmTemplate.createCriteria(GenericItem.class).add(Restrictions.eq("PlanningItemFlag", true)));
    List<ProductDemandItem> result = new ArrayList<ProductDemandItem>();
    CurrentStockSituation currentStockSituation = CurrentStockSituationLocator.locate();
    for (GenericItem genericItem : giList) {
        BigDecimal quan = BigDecimal.ZERO;
        List<StockSituationValues> stockSituationValuesList = currentStockSituation
                .getSituation(genericItem.getCatalog());
        if (stockSituationValuesList == null)
            continue;
        for (StockSituationValues stockSituationValues : stockSituationValuesList)
            quan = quan.add(stockSituationValues.getLocated1());

        if (genericItem.getMeasure().getId() != genericItem.getCatalog().getMeasure1().getId())
            quan = getMeasureConversionService().conversion(genericItem.getCatalog().getMeasure1(),
                    genericItem.getMeasure(), genericItem.getCatalog(), planningStartDate, quan);
        result.add(new ProductDemandItem(genericItem, genericItem.getCatalog(), genericItem.getMeasure(),
                planningStartDate, quan, (short) 0, null));
    }//from ww w .  java2 s.  c o m
    return result;
}

From source file:com.salesmanager.core.service.tax.TaxService.java

/**
 * Calculates tax on an OrderTotalSummary object (products applicable,
 * shipping...), creates and set the shopping cart lines. Returns the amount
 * with tax// w  w  w.j av a  2  s  . co m
 * 
 * @param summary
 * @param amount
 * @param customer
 * @param merchantId
 * @return
 * @throws Exception
 */
@Transactional
public OrderTotalSummary calculateTax(OrderTotalSummary summary, Collection<OrderProduct> products,
        Customer customer, int merchantId, Locale locale, String currency) throws Exception {

    MerchantService mservice = (MerchantService) ServiceFactory.getService(ServiceFactory.MerchantService);
    MerchantStore store = mservice.getMerchantStore(merchantId);

    Map productsTax = new HashMap();

    //rounding definition
    BigDecimal totalTaxAmount = new BigDecimal(0);
    //totalTaxAmount.setScale(2, BigDecimal.ROUND_DOWN);

    // check if tax is applicable and build a map
    // of tax class - product
    if (products != null) {
        Iterator prodIt = products.iterator();
        while (prodIt.hasNext()) {
            OrderProduct prod = (OrderProduct) prodIt.next();
            if (prod.getTaxClassId() > -1) {

                BigDecimal groupBeforeTaxAmount = (BigDecimal) productsTax.get(prod.getTaxClassId());

                if (groupBeforeTaxAmount == null) {
                    groupBeforeTaxAmount = new BigDecimal("0");
                }

                BigDecimal finalPrice = prod.getFinalPrice();// unit price +
                // attribute
                // * qty
                // finalPrice = finalPrice.multiply(new
                // BigDecimal(prod.getProductQuantity()));

                groupBeforeTaxAmount = groupBeforeTaxAmount.add(finalPrice);

                // getPrices
                Set prices = prod.getPrices();
                // List prices = prod.getRelatedPrices();
                if (prices != null) {
                    Iterator ppriceIter = prices.iterator();
                    while (ppriceIter.hasNext()) {
                        OrderProductPrice pprice = (OrderProductPrice) ppriceIter.next();
                        if (!pprice.isDefaultPrice()) {// related price
                            // activation...
                            // PriceModule module =
                            // (PriceModule)SpringUtil.getBean(pprice.getProductPriceModuleName());
                            // if(module.isTaxApplicable()) {//related price
                            // becomes taxeable
                            // if(pprice.isProductHasTax()) {
                            // groupBeforeTaxAmount =
                            // groupBeforeTaxAmount.add(ProductUtil.determinePrice(pprice));

                            BigDecimal ppPrice = pprice.getProductPriceAmount();
                            ppPrice = ppPrice.multiply(new BigDecimal(prod.getProductQuantity()));

                            groupBeforeTaxAmount = groupBeforeTaxAmount.add(ppPrice);
                            // }
                        }
                    }
                }

                BigDecimal credits = prod.getApplicableCreditOneTimeCharge();
                groupBeforeTaxAmount = groupBeforeTaxAmount.subtract(credits);

                productsTax.put(prod.getTaxClassId(), groupBeforeTaxAmount);

            }
        }
    }

    if (productsTax.size() == 0) {
        return summary;
    }

    // determine if tax applies on billing or shipping address

    // get shipping & tax informations
    ConfigurationRequest request = new ConfigurationRequest(merchantId);
    ConfigurationResponse response = mservice.getConfiguration(request);

    String taxBasis = TaxConstants.SHIPPING_TAX_BASIS;

    // get tax basis
    MerchantConfiguration taxConf = response.getMerchantConfiguration(TaxConstants.MODULE_TAX_BASIS);
    if (taxConf != null && !StringUtils.isBlank(taxConf.getConfigurationValue())) {// tax
        // basis
        taxBasis = taxConf.getConfigurationValue();
    }

    // tax on shipping
    if (summary.getShippingTotal() != null && summary.getShippingTotal().floatValue() > 0) {
        MerchantConfiguration shippingTaxConf = response
                .getMerchantConfiguration(ShippingConstants.MODULE_SHIPPING_TAX_CLASS);
        if (shippingTaxConf != null && !StringUtils.isBlank(shippingTaxConf.getConfigurationValue())) {// tax on shipping

            long taxClass = Long.parseLong(shippingTaxConf.getConfigurationValue());
            BigDecimal groupSubTotal = (BigDecimal) productsTax.get(taxClass);
            if (groupSubTotal == null) {
                groupSubTotal = new BigDecimal("0");
                productsTax.put(taxClass, groupSubTotal);
            }
            groupSubTotal = groupSubTotal.add(summary.getShippingTotal());
            productsTax.put(taxClass, groupSubTotal);
        }
    }

    Map taxDescriptionsHolder = new TreeMap();

    Iterator taxMapIter = productsTax.keySet().iterator();
    while (taxMapIter.hasNext()) {// get each tax class

        long key = (Long) taxMapIter.next();
        // List taxClassGroup = (List)productsTax.get(key);

        int countryId = 0;

        Collection taxCollection = null;
        if (taxBasis.equals(TaxConstants.SHIPPING_TAX_BASIS)) {

            if (store.getCountry() != customer.getCustomerCountryId()) {
                return summary;
            }

            taxCollection = taxRateDao.findByCountryIdZoneIdAndClassId(customer.getCustomerCountryId(),
                    customer.getCustomerZoneId(), key, merchantId);
            countryId = customer.getCustomerCountryId();
        } else { // BILLING

            if (store.getCountry() != customer.getCustomerBillingCountryId()) {
                return summary;
            }

            taxCollection = taxRateDao.findByCountryIdZoneIdAndClassId(customer.getCustomerBillingCountryId(),
                    customer.getCustomerBillingZoneId(), key, merchantId);
            countryId = customer.getCustomerBillingCountryId();
        }

        if (taxCollection == null || taxCollection.size() == 0) {// no tax
            continue;
        }

        Map countries = RefCache.getCountriesMap();
        Country c = (Country) countries.get(countryId);

        if (c != null) {// tax adjustment rules
            TaxModule module = (TaxModule) SpringUtil.getBean(c.getCountryIsoCode2());
            if (module != null) {
                taxCollection = module.adjustTaxRate(taxCollection, store);
            }
        }

        //BigDecimal beforeTaxAmount = new BigDecimal("0");
        //beforeTaxAmount.setScale(2, BigDecimal.ROUND_HALF_UP);
        BigDecimal groupSubTotal = (BigDecimal) productsTax.get(key);

        //beforeTaxAmount = beforeTaxAmount.add(groupSubTotal);
        BigDecimal beforeTaxAmount = groupSubTotal;
        beforeTaxAmount.setScale(2, BigDecimal.ROUND_HALF_UP);

        // iterate through tax collection and calculate tax lines
        if (taxCollection != null) {

            Iterator i = taxCollection.iterator();
            while (i.hasNext()) {

                TaxRate trv = (TaxRate) i.next();
                // double value = ((trv.getTaxRate().doubleValue() *
                // beforeTaxAmount.doubleValue())/100)+beforeTaxAmount.doubleValue();
                double trDouble = trv.getTaxRate().doubleValue();

                // if piggy back, add tax to subtotal
                BigDecimal amount = beforeTaxAmount;
                if (trv.isPiggyback()) {
                    // add previous calculated tax on top of subtotal
                    amount = amount.add(totalTaxAmount);
                }

                // commented for piggyback
                // double beforeTaxDouble = beforeTaxAmount.doubleValue();
                double beforeTaxDouble = amount.doubleValue();

                double value = ((trDouble * beforeTaxDouble) / 100);

                BigDecimal nValue = BigDecimal.valueOf(value);

                //BigDecimal nValue = new BigDecimal(value);
                nValue.setScale(2, BigDecimal.ROUND_HALF_UP);

                //nValue = nValue.add(new BigDecimal(value));

                // commented for piggyback
                // beforeTaxAmount = beforeTaxAmount.add(nValue);

                //BigDecimal bdValue = nValue;
                String am = CurrencyUtil.getAmount(nValue, store.getCurrency());

                /** this one **/
                totalTaxAmount = totalTaxAmount.add(new BigDecimal(am));

                String name = LabelUtil.getInstance().getText(locale, "label.generic.tax");

                OrderTotalLine line = (OrderTotalLine) taxDescriptionsHolder
                        .get(trv.getZoneToGeoZone().getGeoZoneId());

                if (line == null) {
                    // tax description
                    line = new OrderTotalLine();
                    Set descriptionsSet = trv.getDescriptions();
                    if (descriptionsSet != null) {
                        Iterator li = descriptionsSet.iterator();
                        while (li.hasNext()) {
                            TaxRateDescription description = (TaxRateDescription) li.next();
                            if (description.getId().getLanguageId() == LanguageUtil
                                    .getLanguageNumberCode(locale.getLanguage())) {
                                name = description.getTaxDescription();
                                break;
                            }
                        }
                    }

                    line.setText(name);
                    line.setCost(nValue);
                    line.setCostFormated(CurrencyUtil.displayFormatedAmountWithCurrency(nValue, currency));
                    taxDescriptionsHolder.put(trv.getZoneToGeoZone().getGeoZoneId(), line);
                } else {// needs to re-use the same shopping cart line
                    BigDecimal cost = line.getCost();
                    cost = cost.add(nValue);
                    line.setCostFormated(CurrencyUtil.displayFormatedAmountWithCurrency(cost, currency));
                }

                // now set tax on producs
                Iterator prodIt = products.iterator();
                while (prodIt.hasNext()) {
                    OrderProduct prod = (OrderProduct) prodIt.next();
                    if (prod.getTaxClassId() == key) {
                        // calculate tax for this product
                        BigDecimal price = prod.getProductPrice();
                        BigDecimal productTax = prod.getProductTax();
                        if (productTax == null) {
                            productTax = new BigDecimal("0");
                        }
                        price = price.add(productTax);
                        double pTax = ((trDouble * price.doubleValue()) / 100);

                        prod.setProductTax(new BigDecimal(pTax));

                    }
                }

            } // end while

        }

        Iterator titer = taxDescriptionsHolder.keySet().iterator();
        while (titer.hasNext()) {
            long lineKey = (Long) titer.next();
            OrderTotalLine line = (OrderTotalLine) taxDescriptionsHolder.get(lineKey);
            summary.addTaxPrice(line);
        }

    }

    summary.setTaxTotal(totalTaxAmount);

    return summary;

}

From source file:com.xumpy.thuisadmin.services.implementations.BedragenSrvImpl.java

public Map OverviewRekeningData(List<? extends Bedragen> bedragen) {
    Map overviewRekeningData = new LinkedHashMap();

    BigDecimal rekeningStand;
    if (isRekeningUnique(bedragen)) {
        rekeningStand = getBedragAtDate(bedragen.get(0).getDatum(), bedragen.get(0).getRekening());
    } else {//from   w ww .ja  v a2s. c  om
        rekeningStand = getBedragAtDate(bedragen.get(0).getDatum(), null);
    }
    overviewRekeningData.put(bedragen.get(0).getDatum(), rekeningStand);

    for (Integer i = 1; i < bedragen.size(); i++) {
        if (!bedragen.get(i).getDatum().equals(bedragen.get(0).getDatum())) {
            if (bedragen.get(i).getGroep().getNegatief().equals(1)) {
                rekeningStand = rekeningStand.subtract(bedragen.get(i).getBedrag());
            }
            if (bedragen.get(i).getGroep().getNegatief().equals(0)) {
                rekeningStand = rekeningStand.add(bedragen.get(i).getBedrag());
            }
            overviewRekeningData.put(bedragen.get(i).getDatum(), rekeningStand);
        }
    }

    return overviewRekeningData;
}

From source file:net.sourceforge.fenixedu.presentationTier.TagLib.GanttDiagramTagLib.java

private StringBuilder generateGanttDiagramInTotalMode(BigDecimal tableWidth) throws JspException {

    StringBuilder builder = new StringBuilder();

    if (!getEvents().isEmpty()) {
        if (isShowPeriod() && isShowObservations()) {
            builder.append("<table style=\"width:")
                    .append(tableWidth.add(BigDecimal.valueOf(FIXED_COLUMNS_SIZE_EM)))
                    .append("em;\" class=\"tcalendar thlight\">");
        } else {/*  ww  w. j a  v  a 2 s.co m*/
            builder.append("<table style=\"width:")
                    .append(tableWidth.add(BigDecimal.valueOf(FIXED_COLUMNS_SIZE_EM - 35)))
                    .append("em;\" class=\"tcalendar thlight\">");
        }
        generateHeaders(builder);

        int scale = getScale();

        String selectedEvent = getRequest().getParameter(getEventParameter());
        Object selectedEventObject = getRequest().getAttribute(getEventParameter());

        for (GanttDiagramEvent event : getEvents()) {

            String eventUrl = getRequest().getContextPath() + getEventUrl() + "&amp;" + getEventParameter()
                    + "=" + event.getGanttDiagramEventIdentifier();
            String eventName = event.getGanttDiagramEventName().getContent(getGanttDiagramObject().getLocale());
            String paddingStyle = "padding-left:" + event.getGanttDiagramEventOffset() * PADDING_LEFT_MULTIPLIER
                    + "px";

            if (event.getGanttDiagramEventIdentifier().equals(selectedEvent) || (selectedEventObject != null
                    && event.getGanttDiagramEventIdentifier().equals(selectedEventObject.toString()))) {
                builder.append("<tr class=\"selected\">");
            } else {
                builder.append("<tr>");
            }

            builder.append("<td class=\"padded\">")
                    .append("<div style=\"overflow:hidden; width: 14.5em;\" class=\"nowrap\">");
            builder.append("<span style=\"").append(paddingStyle).append("\" title=\"").append(eventName)
                    .append("\">");
            builder.append("<a href=\"").append(eventUrl).append("\">").append("*").append(eventName);
            builder.append("</a></span></div></td>");

            for (DateTime month : getGanttDiagramObject().getMonths()) {

                DateTime firstDayOfMonth = (month.getDayOfMonth() != 1) ? month.withDayOfMonth(1) : month;
                DateTime lastDayOfMonth = firstDayOfMonth.plusMonths(1).minusDays(1);
                int monthNumberOfDays = Days.daysBetween(firstDayOfMonth, lastDayOfMonth).getDays() + 1;
                BigDecimal entryDays = EMPTY_UNIT, startDay = EMPTY_UNIT;

                builder.append("<td style=\"width: ").append(convertToEm(monthNumberOfDays * scale))
                        .append("em;\"><div style=\"position: relative;\">");

                for (Interval interval : event.getGanttDiagramEventSortedIntervals()) {

                    DateMidnight intervalStart = interval.getStart().toDateMidnight();
                    DateMidnight intervalEnd = interval.getEnd().toDateMidnight();

                    // Started in this month
                    if (intervalStart.getMonthOfYear() == month.getMonthOfYear()
                            && intervalStart.getYear() == month.getYear()) {

                        // Ended in this month
                        if (interval.getEnd().getMonthOfYear() == month.getMonthOfYear()
                                && intervalEnd.getYear() == month.getYear()) {

                            // Started in first day of this month
                            if (intervalStart.getDayOfMonth() == 1) {

                                // Ended in the last day of this month
                                if (intervalEnd.getDayOfMonth() == monthNumberOfDays) {
                                    entryDays = convertToEm(
                                            (Days.daysBetween(intervalStart, lastDayOfMonth).getDays() + 1)
                                                    * scale);
                                    startDay = convertToEm((intervalStart.getDayOfMonth() - 1) * scale);
                                    addSpecialDiv(builder, entryDays, startDay);
                                }

                                // Ended before last day of this month
                                else {
                                    entryDays = convertToEm(
                                            (Days.daysBetween(intervalStart, intervalEnd).getDays() + 1)
                                                    * scale);
                                    startDay = convertToEm((intervalStart.getDayOfMonth() - 1) * scale);
                                    addSpecialDiv(builder, entryDays, startDay);
                                }
                            }

                            // Started after first day of this month
                            else {

                                // Ended in the last day of this month
                                if (intervalEnd.getDayOfMonth() == monthNumberOfDays) {
                                    entryDays = convertToEm(
                                            (Days.daysBetween(intervalStart, lastDayOfMonth).getDays() + 1)
                                                    * scale);
                                    startDay = convertToEm((intervalStart.getDayOfMonth() - 1) * scale);
                                    addSpecialDiv(builder, entryDays, startDay);
                                }

                                // Ended before last day of this month
                                else {
                                    entryDays = convertToEm(
                                            (Days.daysBetween(intervalStart, intervalEnd).getDays() + 1)
                                                    * scale);
                                    startDay = convertToEm((intervalStart.getDayOfMonth() - 1) * scale);
                                    addSpecialDiv(builder, entryDays, startDay);
                                }
                            }
                        }

                        // Ended after this month
                        else {
                            entryDays = convertToEm(
                                    (Days.daysBetween(intervalStart, lastDayOfMonth).getDays() + 1) * scale);
                            startDay = convertToEm((intervalStart.getDayOfMonth() - 1) * scale);
                            addSpecialDiv(builder, entryDays, startDay);
                        }

                        // Not Started in this month
                    } else {

                        // Started before this month
                        if (intervalStart.getYear() < month.getYear()
                                || (intervalStart.getYear() == month.getYear()
                                        && intervalStart.getMonthOfYear() < month.getMonthOfYear())) {

                            // Ended after this month
                            if (intervalEnd.getYear() > month.getYear()
                                    || (intervalEnd.getYear() == month.getYear()
                                            && intervalEnd.getMonthOfYear() > month.getMonthOfYear())) {

                                entryDays = convertToEm(
                                        (Days.daysBetween(firstDayOfMonth, lastDayOfMonth).getDays() + 1)
                                                * scale);
                                startDay = convertToEm((firstDayOfMonth.getDayOfMonth() - 1) * scale);
                                addSpecialDiv(builder, entryDays, startDay);
                            } else {

                                // Ended in this month
                                if (intervalEnd.getMonthOfYear() == month.getMonthOfYear()
                                        && intervalEnd.getYear() == month.getYear()) {
                                    entryDays = convertToEm(
                                            (Days.daysBetween(firstDayOfMonth, intervalEnd).getDays() + 1)
                                                    * scale);
                                    startDay = convertToEm((firstDayOfMonth.getDayOfMonth() - 1) * scale);
                                    addSpecialDiv(builder, entryDays, startDay);
                                }
                            }
                        }
                    }
                }
                builder.append("</div></td>");
            }
            if (isShowPeriod()) {
                builder.append("<td class=\"padded smalltxt\" title=\"")
                        .append(event.getGanttDiagramEventPeriod())
                        .append("\"><div style=\"overflow:hidden;\" class=\"nowrap\">")
                        .append(event.getGanttDiagramEventPeriod()).append("</div></td>");
            }
            if (isShowObservations()) {
                builder.append("<td class=\"padded smalltxt\">")
                        .append(event.getGanttDiagramEventObservations()).append("</td>");
            }
            builder.append("</tr>");
        }

        insertNextAndBeforeLinks(builder);
        builder.append("</table>");
    }
    return builder;
}

From source file:org.openmrs.module.billing.web.controller.main.BillableServiceBillAddController.java

@RequestMapping(method = RequestMethod.POST)
public String onSubmit(Model model, Object command, BindingResult bindingResult, HttpServletRequest request,
        @RequestParam("cons") Integer[] cons, @RequestParam("patientId") Integer patientId) {
    validate(cons, bindingResult, request);
    if (bindingResult.hasErrors()) {
        model.addAttribute("errors", bindingResult.getAllErrors());
        return "module/billing/main/billableServiceBillEdit";
    }/*from w  ww .j  a  va 2 s .c  om*/

    BillingService billingService = Context.getService(BillingService.class);

    PatientService patientService = Context.getPatientService();

    // Get the BillCalculator to calculate the rate of bill item the patient has to pay
    Patient patient = patientService.getPatient(patientId);
    Map<String, String> attributes = PatientUtils.getAttributes(patient);
    BillCalculatorService calculator = new BillCalculatorService();

    PatientServiceBill bill = new PatientServiceBill();
    bill.setCreatedDate(new Date());
    bill.setPatient(patient);
    bill.setCreator(Context.getAuthenticatedUser());

    PatientServiceBillItem item;
    int quantity = 0;
    Money itemAmount;
    Money mUnitPrice;
    Money totalAmount = new Money(BigDecimal.ZERO);
    BigDecimal totalActualAmount = new BigDecimal(0);
    BigDecimal unitPrice;
    String name;
    BillableService service;

    for (int conceptId : cons) {

        unitPrice = NumberUtils.createBigDecimal(request.getParameter(conceptId + "_unitPrice"));
        quantity = NumberUtils.createInteger(request.getParameter(conceptId + "_qty"));
        name = request.getParameter(conceptId + "_name");
        service = billingService.getServiceByConceptId(conceptId);

        mUnitPrice = new Money(unitPrice);
        itemAmount = mUnitPrice.times(quantity);
        totalAmount = totalAmount.plus(itemAmount);

        item = new PatientServiceBillItem();
        item.setCreatedDate(new Date());
        item.setName(name);
        item.setPatientServiceBill(bill);
        item.setQuantity(quantity);
        item.setService(service);
        item.setUnitPrice(unitPrice);

        item.setAmount(itemAmount.getAmount());

        // Get the ratio for each bill item
        Map<String, Object> parameters = HospitalCoreUtils.buildParameters("patient", patient, "attributes",
                attributes, "billItem", item, "request", request);
        BigDecimal rate = calculator.getRate(parameters);
        item.setActualAmount(item.getAmount().multiply(rate));
        totalActualAmount = totalActualAmount.add(item.getActualAmount());

        bill.addBillItem(item);
    }
    bill.setAmount(totalAmount.getAmount());
    bill.setActualAmount(totalActualAmount);

    bill.setFreeBill(calculator.isFreeBill(HospitalCoreUtils.buildParameters("attributes", attributes)));
    logger.info("Is free bill: " + bill.getFreeBill());

    bill.setReceipt(billingService.createReceipt());
    bill = billingService.savePatientServiceBill(bill);
    return "redirect:/module/billing/patientServiceBill.list?patientId=" + patientId + "&billId="
            + bill.getPatientServiceBillId();

}