Example usage for java.math BigDecimal ROUND_HALF_UP

List of usage examples for java.math BigDecimal ROUND_HALF_UP

Introduction

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

Prototype

int ROUND_HALF_UP

To view the source code for java.math BigDecimal ROUND_HALF_UP.

Click Source Link

Document

Rounding mode to round towards "nearest neighbor" unless both neighbors are equidistant, in which case round up.

Usage

From source file:org.egov.ptis.service.es.CollectionIndexElasticSearchService.java

private void prepareCollBreakupMap(StringTerms collBreakup,
        Map<String, Map<String, BigDecimal>> collectionDivisionMap, boolean isForCurrYear) {
    Map<String, BigDecimal> individualCollMap;
    Sum arrearAmt;/*from   w w w  .  java 2  s.co  m*/
    Sum currentAmt;
    Sum arrearCess;
    Sum currentCess;
    Sum penaltyAmt;
    Sum latePaymentPenaltyAmt;
    Sum rebate;
    Sum advance;
    String arrearAmtKey;
    String currentAmtKey;
    String arrearCessKey;
    String currentCessKey;
    String penaltyAmtKey;
    String latePaymentPenaltyAmtKey;
    String rebateAmtKey;
    String advanceAmtKey;
    if (isForCurrYear) {
        arrearAmtKey = CY_ARREAR_AMOUNT;
        currentAmtKey = CY_CURRENT_AMOUNT;
        arrearCessKey = CY_ARREAR_CESS;
        currentCessKey = CY_CURRENT_CESS;
        penaltyAmtKey = CY_PENALTY;
        latePaymentPenaltyAmtKey = CY_LATE_PAYMENT_PENALTY;
        rebateAmtKey = CY_REBATE;
        advanceAmtKey = CY_ADVANCE;
    } else {
        arrearAmtKey = LY_ARREAR_AMOUNT;
        currentAmtKey = LY_CURRENT_AMOUNT;
        arrearCessKey = LY_ARREAR_CESS;
        currentCessKey = LY_CURRENT_CESS;
        penaltyAmtKey = LY_PENALTY;
        latePaymentPenaltyAmtKey = LY_LATE_PAYMENT_PENALTY;
        rebateAmtKey = LY_REBATE;
        advanceAmtKey = LY_ADVANCE;
    }
    for (Terms.Bucket entry : collBreakup.getBuckets()) {
        individualCollMap = new HashMap<>();

        arrearAmt = entry.getAggregations().get(ARREAR_AMOUNT_CONST);
        currentAmt = entry.getAggregations().get(CURR_AMOUNT);
        arrearCess = entry.getAggregations().get(ARREAR_CESS_CONST);
        currentCess = entry.getAggregations().get(CURR_CESS);
        penaltyAmt = entry.getAggregations().get("penalty");
        latePaymentPenaltyAmt = entry.getAggregations().get("latePaymentPenalty");
        rebate = entry.getAggregations().get(REBATE);
        advance = entry.getAggregations().get(ADVANCE);

        individualCollMap.put(arrearAmtKey,
                BigDecimal.valueOf(arrearAmt.getValue()).setScale(0, BigDecimal.ROUND_HALF_UP));
        individualCollMap.put(currentAmtKey,
                BigDecimal.valueOf(currentAmt.getValue()).setScale(0, BigDecimal.ROUND_HALF_UP));
        individualCollMap.put(arrearCessKey,
                BigDecimal.valueOf(arrearCess.getValue()).setScale(0, BigDecimal.ROUND_HALF_UP));
        individualCollMap.put(currentCessKey,
                BigDecimal.valueOf(currentCess.getValue()).setScale(0, BigDecimal.ROUND_HALF_UP));
        individualCollMap.put(penaltyAmtKey,
                BigDecimal.valueOf(penaltyAmt.getValue()).setScale(0, BigDecimal.ROUND_HALF_UP));
        individualCollMap.put(latePaymentPenaltyAmtKey,
                BigDecimal.valueOf(latePaymentPenaltyAmt.getValue()).setScale(0, BigDecimal.ROUND_HALF_UP));
        individualCollMap.put(rebateAmtKey,
                BigDecimal.valueOf(rebate.getValue()).setScale(0, BigDecimal.ROUND_HALF_UP));
        individualCollMap.put(advanceAmtKey,
                BigDecimal.valueOf(advance.getValue()).setScale(0, BigDecimal.ROUND_HALF_UP));

        collectionDivisionMap.put(String.valueOf(entry.getKey()), individualCollMap);
    }
}

From source file:org.egov.ptis.service.es.CollectionIndexElasticSearchService.java

/**
 * Provides collection and demand results
 * //from   w ww . j a v a2s.  c  o m
 * @param collectionDetailsRequest
 * @param fromDate
 * @param toDate
 * @param indexName
 * @param fieldName
 * @param ulbCodeField
 * @param aggregationField
 * @return Map
 */
public Map<String, BigDecimal> getCollectionAndDemandValues(CollectionDetailsRequest collectionDetailsRequest,
        Date fromDate, Date toDate, String indexName, String fieldName, String aggregationField) {
    BoolQueryBuilder boolQuery = prepareWhereClause(collectionDetailsRequest, indexName);
    if (indexName.equals(COLLECTION_INDEX_NAME))
        boolQuery = boolQuery
                .filter(QueryBuilders.rangeQuery(RECEIPT_DATE).gte(DATEFORMATTER_YYYY_MM_DD.format(fromDate))
                        .lte(DATEFORMATTER_YYYY_MM_DD.format(toDate)).includeUpper(false))
                .mustNot(QueryBuilders.matchQuery(STATUS, CANCELLED));
    else
        boolQuery = boolQuery.filter(QueryBuilders.matchQuery(IS_ACTIVE, true))
                .filter(QueryBuilders.matchQuery(IS_EXEMPTED, false));

    AggregationBuilder aggregation = AggregationBuilders.terms(BY_CITY).field(aggregationField).size(120)
            .subAggregation(AggregationBuilders.sum("total").field(fieldName));

    SearchQuery searchQueryColl = new NativeSearchQueryBuilder().withIndices(indexName).withQuery(boolQuery)
            .addAggregation(aggregation).build();

    Aggregations collAggr = elasticsearchTemplate.query(searchQueryColl, new ResultsExtractor<Aggregations>() {
        @Override
        public Aggregations extract(SearchResponse response) {
            return response.getAggregations();
        }
    });

    StringTerms cityAggr = collAggr.get(BY_CITY);
    Map<String, BigDecimal> cytdCollMap = new HashMap<>();
    for (Terms.Bucket entry : cityAggr.getBuckets()) {
        Sum aggr = entry.getAggregations().get("total");
        cytdCollMap.put(String.valueOf(entry.getKey()),
                BigDecimal.valueOf(aggr.getValue()).setScale(0, BigDecimal.ROUND_HALF_UP));
    }
    return cytdCollMap;
}

From source file:com.sentaroh.android.SMBExplorer.FileIo.java

private static String calTransferRate(long tb, long tt) {
    String tfs = null;/*from   w  w  w .j ava2 s .  c o  m*/
    BigDecimal bd_tr;
    if (tb > (1024)) {//KB
        BigDecimal dfs1 = new BigDecimal(tb * 1.000);
        BigDecimal dfs2 = new BigDecimal(1024 * 1.000);
        BigDecimal dfs3 = new BigDecimal("0.000000");
        dfs3 = dfs1.divide(dfs2);
        BigDecimal dft1 = new BigDecimal(tt * 1.000);
        BigDecimal dft2 = new BigDecimal(1000.000);
        BigDecimal dft3 = new BigDecimal("0.000000");
        dft3 = dft1.divide(dft2);
        bd_tr = dfs3.divide(dft3, 2, BigDecimal.ROUND_HALF_UP);
        tfs = bd_tr + "KBytes/sec";
    } else {
        BigDecimal dfs1 = new BigDecimal(tb * 1.000);
        BigDecimal dfs2 = new BigDecimal(1024 * 1.000);
        BigDecimal dfs3 = new BigDecimal("0.000000");
        dfs3 = dfs1.divide(dfs2);
        BigDecimal dft1 = new BigDecimal(tt * 1.000);
        BigDecimal dft2 = new BigDecimal(1000.000);
        BigDecimal dft3 = new BigDecimal("0.000000");
        dft3 = dft1.divide(dft2);
        bd_tr = dfs3.divide(dft3, 2, BigDecimal.ROUND_HALF_UP);
        tfs = bd_tr + "Bytes/sec";
    }

    return tfs;
}

From source file:net.cbtltd.rest.AbstractReservation.java

private static void roundReservationDoubleValues(Reservation reservation) {
    if (reservation == null) {
        throw new ServiceException(Error.parameter_null, "reservation");
    }/* ww  w . jav  a2s  .  com*/
    Double price = reservation.getPrice();
    Double cost = reservation.getCost();
    Double quote = reservation.getQuote();
    Double deposit = reservation.getDeposit();
    Double extra = reservation.getExtra();

    reservation.setPrice(price == null ? 0. : round(price, 2, BigDecimal.ROUND_HALF_UP));
    reservation.setCost(cost == null ? 0. : round(cost, 2, BigDecimal.ROUND_HALF_UP));
    reservation.setQuote(quote == null ? 0. : round(quote, 2, BigDecimal.ROUND_HALF_UP));
    reservation.setDeposit(deposit == null ? 0. : round(deposit, 2, BigDecimal.ROUND_HALF_UP));
    reservation.setExtra(extra == null ? 0. : round(extra, 2, BigDecimal.ROUND_HALF_UP));
    if (reservation.getQuotedetail() != null) {
        for (Price priceItem : reservation.getQuotedetail()) {
            priceItem.setValue(priceItem.getValue() == null ? 0.
                    : round(priceItem.getValue(), 2, BigDecimal.ROUND_HALF_UP));
        }
    }
}

From source file:com.icebreak.p2p.trade.impl.TradeServiceImpl.java

@Transactional(rollbackFor = Exception.class, value = "transactionManager")
@Override/*from   ww w.j a  v a2  s.c om*/
public void createRelativeTrades(Trade trade) throws Exception {

    trade = tradeDao.getByTradeIdWithRowLock(trade.getId());
    // ?
    modifyStatus(trade.getId(), YrdConstants.TradeStatus.GUARANTEE_AUDITING);
    // ???
    tradeDao.updateIsNotifiedLoaner(trade.getId(), YrdConstants.MessageNotifyConstants.ISNOTIFIED_NO);
    LoanDemandDO loan = loanDemandManager.queryLoanDemandByDemandId(trade.getDemandId());
    long divisionTemplateLoanBaseId = loan.getDivisionTemplateId();
    DivisionTemplateLoanDO divisionTemplateLoan = divisionTemplateLoanService
            .getByBaseId(divisionTemplateLoanBaseId);
    List<DivsionRuleRole> investRolelist = divisionService
            .getRuleRole(String.valueOf(divisionTemplateLoan.getInvestTemplateId()));
    // ??
    double countInvestCutAmount = 0;
    if (investRolelist != null && investRolelist.size() > 0) {
        for (DivsionRuleRole roleRule : investRolelist) {
            if (DivisionPhaseEnum.INVESET_PHASE.code().equals(roleRule.getPhase())) {
                BigDecimal bg = new BigDecimal(getDaysRuleRate(roleRule.getRule(), trade));
                double rate = bg.setScale(10, BigDecimal.ROUND_HALF_UP).doubleValue();
                countInvestCutAmount += Math.round(rate * trade.getLoanedAmount());
            }
        }
    }
    tradeDetailDao.addTradeDetail(new TradeDetail(getYrdExchangeUserId(), trade.getId(),
            (long) countInvestCutAmount, SysUserRoleEnum.PLATFORM.getValue(),
            DivisionPhaseEnum.INVESET_TRANSITION_PHASE.code(), null));
    /** ? */
    List<DivsionRuleRole> repayRolelist = divisionService
            .getRuleRole(String.valueOf(divisionTemplateLoan.getRepayTemplateId()));
    double repayCutAmount = 0;
    if (repayRolelist != null && repayRolelist.size() > 0) {
        for (DivsionRuleRole druleRole : repayRolelist) {
            if (DivisionPhaseEnum.REPAY_PHASE.code().equals(druleRole.getPhase())) {
                BigDecimal bg = new BigDecimal(getDaysRuleRate(druleRole.getRule(), trade));
                repayCutAmount += Math.round(
                        trade.getLoanedAmount() * bg.setScale(10, BigDecimal.ROUND_HALF_UP).doubleValue());
            }
        }
    }
    long repayAmount = trade.getLoanedAmount() + (long) repayCutAmount;
    tradeDetailDao.addTradeDetail(new TradeDetail(getYrdExchangeUserId(), trade.getId(), repayAmount,
            SysUserRoleEnum.PLATFORM.getValue(), DivisionPhaseEnum.REPAY_TRANSITION_PHASE.code(), null));
    // ??????
    investRolelist.addAll(repayRolelist);
    if (investRolelist != null && investRolelist.size() > 0) {
        // 
        for (DivsionRuleRole roleRule : investRolelist) {
            logger.info("getGuaranteeRoleId=" + getGuaranteeRoleId() + " roleRule=" + roleRule.getRoleId());
            if (getGuaranteeRoleId().equals(String.valueOf(roleRule.getRoleId()))) {
                BigDecimal bg = new BigDecimal(
                        getDaysRuleRate(roleRule.getRule(), trade) * trade.getLoanedAmount());
                double amount = bg.setScale(10, BigDecimal.ROUND_HALF_UP).doubleValue();
                amount = Math.floor(amount);
                tradeDetailDao.addTradeDetail(new TradeDetail(loan.getGuaranteeId(), trade.getId(),
                        (long) amount, 8, roleRule.getPhase(), "")); // loan.getGuaranteeStatement()
                // //?? ??
            } else if (getSponsorRoleId().equals(String.valueOf(roleRule.getRoleId()))) {
                BigDecimal bg = new BigDecimal(
                        getDaysRuleRate(roleRule.getRule(), trade) * trade.getLoanedAmount());
                double amount = bg.setScale(10, BigDecimal.ROUND_HALF_UP).doubleValue();
                amount = Math.floor(amount);
                tradeDetailDao.addTradeDetail(new TradeDetail(loan.getSponsorId(), trade.getId(), (long) amount,
                        9, roleRule.getPhase(), "")); // loan.getGuaranteeStatement()
                // //?? ??
            } else if (getPlatformRoleId().equals(String.valueOf(roleRule.getRoleId()))) {
                BigDecimal bg = new BigDecimal(
                        getDaysRuleRate(roleRule.getRule(), trade) * trade.getLoanedAmount());
                double amount = bg.setScale(10, BigDecimal.ROUND_HALF_UP).doubleValue();
                amount = Math.round(amount);
                tradeDetailDao.addTradeDetail(new TradeDetail(getYrdUserId(), trade.getId(), (long) amount, 7,
                        roleRule.getPhase(), null));
            }
        }
    }

    // ?
    modifyStatus(trade.getId(), YrdConstants.TradeStatus.GUARANTEE_AUDITING);

    if (sysFunctionConfigService.isTradeFeeCharge()) {
    }

    // ??
    StringBuilder message = new StringBuilder();
    String content = YrdConstants.MessageNotifyConstants.DEMAND_CONFIRMED_NOTIFY;
    UserBaseInfoDO toUser = new UserBaseInfoDO();
    content = content.replace("var1", trade.getName());
    content = content.replace("var2", MoneyUtil.getFormatAmount(trade.getAmount()));
    content = content.replace("var3", MoneyUtil.getFormatAmount(trade.getLoanedAmount()));
    message.append(content);
    setToUserDetail(toUser);
    messageService.notifyUser(toUser, message.toString());
}

From source file:org.egov.ptis.service.es.CollectionIndexElasticSearchService.java

/**
 * Prepares month-wise collections for 3 consecutive years - from current year
 * /*from w w w  .jav  a2  s  .  c  om*/
 * @param collectionDetailsRequest
 * @return List
 */
public List<CollectionTrend> getMonthwiseCollectionDetails(CollectionDetailsRequest collectionDetailsRequest) {
    List<CollectionTrend> collTrendsList = new ArrayList<>();
    Date fromDate;
    Date toDate;
    Date dateForMonth;
    String[] dateArr;
    Integer month;
    Sum aggregateSum;
    String aggregationField = StringUtils.EMPTY;
    CFinancialYear financialYear;
    Map<Integer, String> monthValuesMap = DateUtils.getAllMonthsWithFullNames();
    String monthName;
    List<Map<String, BigDecimal>> yearwiseMonthlyCollList = new ArrayList<>();
    Map<String, BigDecimal> monthwiseColl;
    if (StringUtils.isNotBlank(collectionDetailsRequest.getType()))
        aggregationField = getAggregrationField(collectionDetailsRequest);

    /**
     * For month-wise collections between the date ranges if dates are sent in the request, consider fromDate and toDate+1 ,
     * else calculate from current year start date till current date+1 day
     */
    if (StringUtils.isNotBlank(collectionDetailsRequest.getFromDate())
            && StringUtils.isNotBlank(collectionDetailsRequest.getToDate())) {
        fromDate = DateUtils.getDate(collectionDetailsRequest.getFromDate(), DATE_FORMAT_YYYYMMDD);
        toDate = DateUtils
                .addDays(DateUtils.getDate(collectionDetailsRequest.getToDate(), DATE_FORMAT_YYYYMMDD), 1);
        financialYear = cFinancialYearService.getFinancialYearByDate(fromDate);
    } else {
        financialYear = cFinancialYearService.getFinancialYearByDate(new Date());
        fromDate = DateUtils.startOfDay(financialYear.getStartingDate());
        toDate = DateUtils.addDays(new Date(), 1);
    }

    Date finYearStartDate = financialYear.getStartingDate();
    Date finYearEndDate = financialYear.getEndingDate();
    for (int count = 0; count <= 2; count++) {
        monthwiseColl = new LinkedHashMap<>();
        Aggregations collAggr = getMonthwiseCollectionsForConsecutiveYears(collectionDetailsRequest, fromDate,
                toDate, false, null, aggregationField);
        Histogram dateaggs = collAggr.get(DATE_AGG);

        for (Histogram.Bucket entry : dateaggs.getBuckets()) {
            dateArr = entry.getKeyAsString().split("T");
            dateForMonth = DateUtils.getDate(dateArr[0], DATE_FORMAT_YYYYMMDD);
            month = Integer.valueOf(dateArr[0].split("-", 3)[1]);
            monthName = monthValuesMap.get(month);
            aggregateSum = entry.getAggregations().get(CURRENT_TOTAL);
            // If the total amount is greater than 0 and the month belongs
            // to respective financial year, add values to the map
            if (DateUtils.between(dateForMonth, finYearStartDate, finYearEndDate)
                    && BigDecimal.valueOf(aggregateSum.getValue()).setScale(0, BigDecimal.ROUND_HALF_UP)
                            .compareTo(BigDecimal.ZERO) > 0)
                monthwiseColl.put(monthName,
                        BigDecimal.valueOf(aggregateSum.getValue()).setScale(0, BigDecimal.ROUND_HALF_UP));
        }
        yearwiseMonthlyCollList.add(monthwiseColl);

        /**
         * If dates are passed in request, get result for the date range, else get results for entire financial year
         */
        if (StringUtils.isNotBlank(collectionDetailsRequest.getFromDate())
                && StringUtils.isNotBlank(collectionDetailsRequest.getToDate())) {
            fromDate = DateUtils.addYears(fromDate, -1);
            toDate = DateUtils.addYears(toDate, -1);
        } else {
            fromDate = DateUtils.addYears(finYearStartDate, -1);
            toDate = DateUtils.addYears(DateUtils.addDays(finYearEndDate, 1), -1);
        }
        finYearStartDate = DateUtils.addYears(finYearStartDate, -1);
        finYearEndDate = DateUtils.addYears(finYearEndDate, -1);
    }

    populateCollTrends(collectionDetailsRequest, collTrendsList, yearwiseMonthlyCollList);
    return collTrendsList;
}

From source file:com.selfsoft.business.service.impl.TbBusinessBalanceServiceImpl.java

public List<StatisticsTbFixBusinessVo> statisticsAll(TbBusinessBalance tbBusinessBalance) {

    List<TbBusinessBalance> listAll = this.findTbBusinessBalanceToGroup(tbBusinessBalance);

    List<StatisticsTbFixBusinessVo> statisticsTbFixBusinessVoList = new ArrayList<StatisticsTbFixBusinessVo>();

    StatisticsTbFixBusinessVo statisticsTbFixBusinessVo = new StatisticsTbFixBusinessVo();

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

        statisticsTbFixBusinessVo.setAllBalance(listAll.size());

        BigDecimal d_all = new BigDecimal("0.00");

        BigDecimal d_payed = new BigDecimal("0.00");

        BigDecimal d_owe = new BigDecimal("0.00");

        for (TbBusinessBalance t : listAll) {

            d_all = d_all.add(new BigDecimal(String.valueOf(t.getBalanceTotalAll())));

            d_payed = d_payed.add(new BigDecimal(String.valueOf(t.getShouldPayAmount())));

            d_owe = d_owe.add(new BigDecimal(String.valueOf(t.getOweAmount())));
        }/*  w ww.j  av a2 s  .c o m*/

        statisticsTbFixBusinessVo.setBalanceItemAmount(d_all.doubleValue());

        statisticsTbFixBusinessVo.setBalanceItemPay(d_payed.doubleValue());

        statisticsTbFixBusinessVo.setBalanceItemOweAmount(d_owe.doubleValue());

        StatisticsTbFixBusinessVo st = tbReceiveFreeService.staticsTbReceiveFree(listAll);

        statisticsTbFixBusinessVo.setFreeBalance(st.getFreeBalance());

        statisticsTbFixBusinessVo.setBalanceItemFree(st.getBalanceItemFree());

        StatisticsTbFixBusinessVo reBalance = this.staticsReBalance(tbBusinessBalance);

        statisticsTbFixBusinessVo.setReBalance(reBalance.getCountNum());

        /**
         * ?E3
         */
        StatisticsTbFixBusinessVo s_balanceItemAmount_show = new StatisticsTbFixBusinessVo();

        s_balanceItemAmount_show.setStaticsShow("?");

        s_balanceItemAmount_show.setStaticsVal(statisticsTbFixBusinessVo.getBalanceItemAmount());

        // ?
        ActionContext.getContext().put("totalAll",
                new BigDecimal(statisticsTbFixBusinessVo.getBalanceItemAmount()).setScale(2,
                        BigDecimal.ROUND_HALF_UP));
        // ?
        BigDecimal substract = new BigDecimal(statisticsTbFixBusinessVo.getBalanceItemAmount())
                .divide(new BigDecimal(1.17d), 2, BigDecimal.ROUND_HALF_UP);

        StatisticsTbFixBusinessVo s_allBalance_show = new StatisticsTbFixBusinessVo();

        s_allBalance_show.setStaticsShow("");

        s_allBalance_show.setStaticsVal(statisticsTbFixBusinessVo.getAllBalance() + " " + "");

        StatisticsTbFixBusinessVo s_balanceItemPay_show = new StatisticsTbFixBusinessVo();

        s_balanceItemPay_show.setStaticsShow("?");

        s_balanceItemPay_show.setStaticsVal(statisticsTbFixBusinessVo.getBalanceItemAmount());

        StatisticsTbFixBusinessVo s_balanceItemOweAmount_show = new StatisticsTbFixBusinessVo();

        s_balanceItemOweAmount_show.setStaticsShow("?");

        s_balanceItemOweAmount_show.setStaticsVal(statisticsTbFixBusinessVo.getBalanceItemOweAmount());

        StatisticsTbFixBusinessVo s_freeBalance_show = new StatisticsTbFixBusinessVo();

        s_freeBalance_show.setStaticsShow("??");

        s_freeBalance_show.setStaticsVal(statisticsTbFixBusinessVo.getFreeBalance() + " " + "");

        StatisticsTbFixBusinessVo s_balanceItemFree_show = new StatisticsTbFixBusinessVo();

        s_balanceItemFree_show.setStaticsShow("???");

        s_balanceItemFree_show.setStaticsVal(statisticsTbFixBusinessVo.getBalanceItemFree());

        StatisticsTbFixBusinessVo s_reBalance_show = new StatisticsTbFixBusinessVo();

        s_reBalance_show.setStaticsShow("?");

        s_reBalance_show.setStaticsVal(statisticsTbFixBusinessVo.getReBalance() + " " + "");

        statisticsTbFixBusinessVoList.add(s_balanceItemAmount_show);

        statisticsTbFixBusinessVoList.add(s_allBalance_show);

        statisticsTbFixBusinessVoList.add(s_balanceItemPay_show);

        statisticsTbFixBusinessVoList.add(s_balanceItemOweAmount_show);

        statisticsTbFixBusinessVoList.add(s_freeBalance_show);

        statisticsTbFixBusinessVoList.add(s_balanceItemFree_show);

        statisticsTbFixBusinessVoList.add(s_reBalance_show);
    }

    return statisticsTbFixBusinessVoList;
}

From source file:com.selfsoft.business.service.impl.TbFixEntrustServiceImpl.java

public void printTbFixEntrustTemplateBlank(OutputStream os, String tpl, Long tbFixEntrustId) {

    try {/*from  w  w w  .j a va  2 s .c  o  m*/

        TbFixEntrust tbFixEntrust = this.findById(tbFixEntrustId);

        TbCustomer tbCustomer = tbCustomerService.findById(tbFixEntrust.getTbCustomer().getId());

        TbCarInfo tbCarInfo = tbCarInfoService.findById(tbFixEntrust.getTbCarInfo().getId());

        List<TbFixEntrustContent> tbFixEntrustContentList = tbFixEntrustContentService
                .findTbFixEnTrustContentListByTbFixEntrustId(tbFixEntrustId);

        /*
         * List<TbMaintainPartContent> maintainList =
         * tbMaintainPartContentService
         * .getViewEntrustMaintianContent(tbFixEntrustId);
         * 
         * 
         * List<TmStockOutDetVo> solePartList =
         * tmStockOutService.getSellByEntrustCode
         * (tbFixEntrust.getEntrustCode());
         */

        /**
         * ??
         */
        List<TbMaintianVo> maintianvos = tbMaintainPartContentService
                .getTbMaintianDetailVosByEntrustId(tbFixEntrust.getId(), Constants.BALANCE_ALL);

        /**
         * ?
         */
        List<TmStockOutDetVo> tmStockOutDetVos = tmStockOutService
                .getSellDetailByEntrustCode(tbFixEntrust.getEntrustCode(), Constants.BALANCE_ALL);

        /**
         * ??
         */

        List<TbMaintianVo> partAll = new ArrayList<TbMaintianVo>();

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

            for (TbMaintianVo tbMaintianVo : maintianvos) {

                partAll.add(tbMaintianVo);

            }
        }

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

            for (TmStockOutDetVo tmStockOutDetVo : tmStockOutDetVos) {

                TbMaintianVo tbMaintianVo = new TbMaintianVo();

                tbMaintianVo.setPartId(tmStockOutDetVo.getPartinfoId());

                tbMaintianVo.setHouseName(tmStockOutDetVo.getHouseName());

                tbMaintianVo.setPartCode(tmStockOutDetVo.getPartCode());

                tbMaintianVo.setPartName(tmStockOutDetVo.getPartName());

                tbMaintianVo.setUnitName(tmStockOutDetVo.getUnitName());

                tbMaintianVo.setPrice(tmStockOutDetVo.getPrice());

                tbMaintianVo.setPartQuantity(tmStockOutDetVo.getQuantity());

                tbMaintianVo.setTotal(tmStockOutDetVo.getTotal());

                tbMaintianVo.setIsFree(tmStockOutDetVo.getIsFree());

                tbMaintianVo.setProjectType(tmStockOutDetVo.getProjectType());

                tbMaintianVo.setZl(tmStockOutDetVo.getZl());

                tbMaintianVo.setXmlx(tmStockOutDetVo.getXmlx());

                partAll.add(tbMaintianVo);
            }
        }

        int fixSize = (tbFixEntrustContentList == null ? 0 : tbFixEntrustContentList.size());

        int maintainSize = (maintianvos == null ? 0 : maintianvos.size());

        int solePartSize = (tmStockOutDetVos == null ? 0 : tmStockOutDetVos.size());

        int partAllSize = (partAll == null ? 0 : partAll.size());

        HSSFWorkbook workbook = new HSSFWorkbook(this.getClass().getResourceAsStream(tpl));

        HSSFSheet sheet = workbook.getSheetAt(0);

        HSSFCellStyle style = workbook.createCellStyle();

        style.setWrapText(true);

        style.setAlignment(HSSFCellStyle.ALIGN_LEFT);

        style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

        HSSFFont font = workbook.createFont();

        font.setFontName("");

        font.setFontHeightInPoints((short) 9);

        // style.setFont(font);

        HSSFCellStyle style11 = workbook.createCellStyle();

        style11.setWrapText(true);

        style11.setAlignment(HSSFCellStyle.ALIGN_LEFT);

        style11.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

        HSSFFont font11 = workbook.createFont();

        font11.setFontName("");

        font11.setFontHeightInPoints((short) 11);

        // style11.setFont(font11);

        HSSFCellStyle style10 = workbook.createCellStyle();

        style10.setWrapText(true);

        style10.setAlignment(HSSFCellStyle.ALIGN_LEFT);

        style10.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

        HSSFFont font10 = workbook.createFont();

        font10.setFontName("");

        font10.setFontHeightInPoints((short) 10);

        // style10.setFont(font10);

        HSSFRow row = null;

        HSSFCell cell = null;

        row = sheet.getRow(10);

        cell = row.getCell(0);

        String entrustCode = tbFixEntrust.getEntrustCode();

        String[] es = entrustCode.split("-");

        String newCode = "RO" + es[0].substring(2, 6) + es[1];

        // cell.setCellValue(tbFixEntrust.getEntrustCode());

        cell.setCellValue(newCode);

        row = sheet.getRow(10);

        cell = row.getCell(8);

        cell.setCellValue(tbCarInfo.getPurchaseDate() == null ? ""
                : CommonMethod.parseDateToString(tbCarInfo.getPurchaseDate(), "yyyy-MM-dd"));

        row = sheet.getRow(10);

        cell = row.getCell(14);

        cell.setCellValue(
                tbFixEntrust.getTmUser().getUserRealName() == null ? tbFixEntrust.getTmUser().getUserName()
                        : tbFixEntrust.getTmUser().getUserRealName());

        row = sheet.getRow(10);

        cell = row.getCell(19);

        cell.setCellValue(tbCarInfo.getLicenseCode());

        row = sheet.getRow(10);

        cell = row.getCell(27);

        // cell.setCellStyle(style);

        cell.setCellValue(tbCarInfo.getTmCarModelType().getModelName());

        row = sheet.getRow(10);

        cell = row.getCell(32);

        cell.setCellValue(
                tbFixEntrust.getEnterStationKilo() == null ? ""
                        : new BigDecimal(tbFixEntrust.getEnterStationKilo().toString())
                                .divide(new BigDecimal("1.00"), 0, BigDecimal.ROUND_HALF_UP).toString()
                                + "   Km");

        row = sheet.getRow(10);

        cell = row.getCell(41);

        cell.setCellValue(tbCarInfo.getColor() == null ? "" : tbCarInfo.getColor().toString());

        row = sheet.getRow(10);

        cell = row.getCell(45);

        cell.setCellValue(tbFixEntrust.getFixDate() == null ? ""
                : CommonMethod.parseDateToString(tbFixEntrust.getFixDate(), Constants.TIMEFORMATOFMINUTE));

        row = sheet.getRow(15);

        cell = row.getCell(0);

        cell.setCellValue(tbCustomer.getCustomerName() == null ? "" : tbCustomer.getContractPerson());

        row = sheet.getRow(15);

        cell = row.getCell(8);

        cell.setCellValue(tbCustomer.getTelephone() == null ? "" : tbCustomer.getTelephone());

        row = sheet.getRow(15);

        cell = row.getCell(14);

        cell.setCellValue(tbCustomer.getPhone() == null ? "" : tbCustomer.getPhone());

        row = sheet.getRow(15);

        cell = row.getCell(20);

        cell.setCellValue(tbCarInfo.getChassisCode() == null ? "" : tbCarInfo.getChassisCode());

        row = sheet.getRow(15);

        cell = row.getCell(32);

        // cell.setCellStyle(style);

        cell.setCellValue(tbCarInfo.getEngineCode() == null ? "" : tbCarInfo.getEngineCode());

        row = sheet.getRow(15);

        cell = row.getCell(45);

        // cell.setCellStyle(style);

        cell.setCellValue(tbFixEntrust.getEstimateDate() == null ? ""
                : CommonMethod.parseDateToString(tbFixEntrust.getEstimateDate(), Constants.TIMEFORMATOFMINUTE));

        row = sheet.getRow(18);

        cell = row.getCell(8);

        cell.setCellValue(tbCustomer.getCustomerName() == null ? "" : tbCustomer.getCustomerName());

        row = sheet.getRow(20);

        cell = row.getCell(8);

        // cell.setCellStyle(style);

        cell.setCellValue(tbCustomer.getAddress() == null ? "" : tbCustomer.getAddress());

        row = sheet.getRow(25);

        cell = row.getCell(8);

        cell.setCellValue(tbCustomer.getZipCode() == null ? "" : tbCustomer.getZipCode());

        row = sheet.getRow(20);

        cell = row.getCell(23);

        // cell.setCellStyle(style);

        cell.setCellValue((tbFixEntrust.getWrongDescribe() == null || "".equals(tbFixEntrust.getWrongDescribe())
                ? ""
                : tbFixEntrust.getWrongDescribe() + ";")
                + (tbFixEntrust.getBeforeFixState() == null || "".equals(tbFixEntrust.getBeforeFixState()) ? ""
                        : tbFixEntrust.getBeforeFixState() + ";"));

        Double fixCount = tbFixEntrustContentService.countTbFixEnTrustContentByTbFixEntrustId(tbFixEntrustId);

        row = sheet.getRow(70);

        cell = row.getCell(32);

        // cell.setCellStyle(style);

        cell.setCellValue(new BigDecimal(fixCount).divide(new BigDecimal("1.00"), 2, BigDecimal.ROUND_HALF_UP)
                .toString());

        row = sheet.getRow(70);

        cell = row.getCell(48);

        // cell.setCellStyle(style);

        cell.setCellValue("0.00");

        BigDecimal partPriceAll = new BigDecimal("0.00");

        if (partAllSize > 0) {

            for (int i = 0; i < partAllSize; i++) {

                TbMaintianVo tbMaintianVo = partAll.get(i);

                BigDecimal total = new BigDecimal(tbMaintianVo.getPrice())
                        .multiply(new BigDecimal(tbMaintianVo.getPartQuantity()));

                partPriceAll = partPriceAll.add(total);

            }

        }

        row = sheet.getRow(73);

        cell = row.getCell(34);

        // cell.setCellStyle(style);

        cell.setCellValue(partPriceAll.divide(new BigDecimal("1.00"), 2, BigDecimal.ROUND_HALF_UP).toString());

        BigDecimal total = new BigDecimal(fixCount).add(partPriceAll).divide(new BigDecimal("1.00"), 2,
                BigDecimal.ROUND_HALF_UP);

        row = sheet.getRow(76);

        cell = row.getCell(35);

        // cell.setCellStyle(style);

        cell.setCellValue(total.toString());

        int page = 1;

        if (fixSize / 5 >= (maintainSize + solePartSize) / 13) {

            page = fixSize / 5;

        }

        else {

            page = (maintainSize + solePartSize) / 13;

        }

        for (int i = 0; i < page; i++) {

            int p = 0;

            int k = 0;

            HSSFSheet sheetClone = workbook.cloneSheet(0);

            if (fixSize > 5) {

                int printFixSize = (fixSize > (i + 2) * 5 ? (i + 2) * 5 : fixSize);

                for (int j = 5 * (i + 1); j < printFixSize; j++) {

                    TbFixEntrustContent content = tbFixEntrustContentList.get(j);

                    List<TbFixShare> tbFixShareList = tbFixShareService
                            .findTbFixShareListByTbFixEntrustContentId(content.getId());

                    String fixPersons = "";

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

                        for (TbFixShare tbFixShare : tbFixShareList) {

                            if (null != tbFixShare.getTmUser()) {

                                TmUser tmUser = tmUserService.findById(tbFixShare.getTmUser().getId());

                                fixPersons += (tmUser.getUserRealName() == null
                                        || "".equals(tmUser.getUserRealName()) ? tmUser.getUserName()
                                                : tmUser.getUserRealName())
                                        + " ";
                            }

                        }
                    }

                    row = sheetClone.getRow(31 + p * 6);

                    cell = row.getCell(0);

                    // cell.setCellStyle(style11);

                    cell.setCellValue(content.getStationCode() + "    " + content.getStationName());

                    cell = row.getCell(20);

                    // cell.setCellStyle(style11);

                    cell.setCellValue(content.getWxlx() == null ? "" : content.getWxlx());

                    cell = row.getCell(26);

                    // cell.setCellStyle(style11);

                    cell.setCellValue(fixPersons);

                    p++;

                }

            }

            if (partAllSize > 13) {

                int prinPartSize = (partAllSize > (i + 2) * 13 ? (i + 2) * 13 : partAllSize);

                for (int j = 13 * (i + 1); j < prinPartSize; j++) {

                    TbMaintianVo t = partAll.get(j);

                    row = sheetClone.getRow(31 + k * 3);

                    cell = row.getCell(32);

                    // cell.setCellStyle(style10);

                    cell.setCellValue(t.getPartName());

                    cell = row.getCell(40);

                    // cell.setCellStyle(style10);

                    cell.setCellValue(new BigDecimal(t.getPartQuantity())
                            .divide(new BigDecimal("1.00"), 2, BigDecimal.ROUND_HALF_UP).toString());

                    cell = row.getCell(44);

                    // cell.setCellStyle(style10);

                    cell.setCellValue(new BigDecimal(t.getPrice())
                            .divide(new BigDecimal("1.00"), 2, BigDecimal.ROUND_HALF_UP).toString());

                    k++;

                }
            }

        }

        if (fixSize > 0) {

            int printFixSize = (fixSize > 5 ? 5 : fixSize);

            for (int j = 0; j < printFixSize; j++) {

                TbFixEntrustContent content = tbFixEntrustContentList.get(j);

                List<TbFixShare> tbFixShareList = tbFixShareService
                        .findTbFixShareListByTbFixEntrustContentId(content.getId());

                String fixPersons = "";

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

                    for (TbFixShare tbFixShare : tbFixShareList) {

                        if (null != tbFixShare.getTmUser()) {

                            TmUser tmUser = tmUserService.findById(tbFixShare.getTmUser().getId());

                            fixPersons += (tmUser.getUserRealName() == null
                                    || "".equals(tmUser.getUserRealName()) ? tmUser.getUserName()
                                            : tmUser.getUserRealName())
                                    + " ";
                        }

                    }
                }

                row = sheet.getRow(31 + j * 6);

                cell = row.getCell(0);

                // cell.setCellStyle(style11);

                cell.setCellValue(content.getStationCode() + "    " + content.getStationName());

                cell = row.getCell(20);

                // cell.setCellStyle(style11);

                cell.setCellValue(content.getWxlx() == null ? "" : content.getWxlx());

                cell = row.getCell(26);

                // cell.setCellStyle(style11);

                cell.setCellValue(fixPersons);

            }

        }

        if (partAllSize > 0) {

            int printPartSize = (partAllSize > 13 ? 13 : partAllSize);

            for (int j = 0; j < printPartSize; j++) {

                TbMaintianVo t = partAll.get(j);

                row = sheet.getRow(31 + j * 3);

                cell = row.getCell(32);

                // cell.setCellStyle(style10);

                cell.setCellValue(t.getPartName());

                cell = row.getCell(40);

                // cell.setCellStyle(style10);

                cell.setCellValue(new BigDecimal(t.getPartQuantity())
                        .divide(new BigDecimal("1.00"), 2, BigDecimal.ROUND_HALF_UP).toString());

                cell = row.getCell(44);

                // cell.setCellStyle(style10);

                cell.setCellValue(new BigDecimal(t.getPrice())
                        .divide(new BigDecimal("1.00"), 2, BigDecimal.ROUND_HALF_UP).toString());

            }

        }

        workbook.write(os);

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:org.egov.wtms.service.es.WaterChargeCollectionDocService.java

private void prepareResponseDataForConnectionType(final WaterChargeDashBoardRequest collectionDetailsRequest,
        final List<WaterChargeConnectionTypeResponse> waterchargeConndemandList, final String aggregationField,
        final Map<String, BigDecimal> connectionResidentialTotalDemandMap,
        final Map<String, Long> connectionCommercialcountMap,
        final Map<String, BigDecimal> connectionCOmmercialTotalDemandMap, final Map.Entry<String, Long> entry,
        final Map<String, BigDecimal> connectionResidentialTotalCollectionMap,
        final Map<String, BigDecimal> connectionCOmmercialTotalCollectionMap) {
    String name;/*from  w  ww. j  a va2s. com*/
    final WaterChargeConnectionTypeResponse receiptData = new WaterChargeConnectionTypeResponse();
    name = entry.getKey();

    if (WaterTaxConstants.REGIONNAMEAGGREGATIONFIELD.equals(aggregationField))
        receiptData.setRegionName(name);
    else if (WaterTaxConstants.DISTRICTNAMEAGGREGATIONFIELD.equals(aggregationField)) {
        receiptData.setRegionName(collectionDetailsRequest.getRegionName());
        receiptData.setDistrictName(name);
    } else if (WaterTaxConstants.CITYNAMEAGGREGATIONFIELD.equals(aggregationField)) {
        receiptData.setUlbName(name);
        receiptData.setDistrictName(collectionDetailsRequest.getDistrictName());
        receiptData.setUlbGrade(collectionDetailsRequest.getUlbGrade());
    } else if (WaterTaxConstants.CITYGRADEAGGREGATIONFIELD.equals(aggregationField))
        receiptData.setUlbGrade(name);
    else if (WaterTaxConstants.REVENUEWARDAGGREGATIONFIELD.equals(aggregationField))
        receiptData.setWardName(name);
    final Date fromDate = new DateTime().withMonthOfYear(4).dayOfMonth().withMinimumValue().toDate();
    final Date toDate = org.apache.commons.lang3.time.DateUtils.addDays(new Date(), 1);

    final int noOfMonths = DateUtils.noOfMonthsBetween(fromDate, toDate) + 1;
    final BigDecimal totalResDemandValue = !connectionResidentialTotalDemandMap.isEmpty()
            && connectionResidentialTotalDemandMap.get(name) != null
                    ? connectionResidentialTotalDemandMap.get(name).setScale(0, BigDecimal.ROUND_HALF_UP)
                    : BigDecimal.ZERO;
    final BigDecimal totalResCollections = !connectionResidentialTotalCollectionMap.isEmpty()
            && connectionResidentialTotalCollectionMap.get(name) != null
                    ? connectionResidentialTotalCollectionMap.get(name).setScale(0, BigDecimal.ROUND_HALF_UP)
                    : BigDecimal.ZERO;
    final BigDecimal proportionalDemand = totalResDemandValue
            .divide(BigDecimal.valueOf(12), BigDecimal.ROUND_HALF_UP).multiply(BigDecimal.valueOf(noOfMonths));
    receiptData.setResidentialAchievement(totalResCollections.multiply(WaterTaxConstants.BIGDECIMAL_100)
            .divide(proportionalDemand, 1, BigDecimal.ROUND_HALF_UP));

    final BigDecimal totalCommDemandValue = !connectionCOmmercialTotalDemandMap.isEmpty()
            && connectionCOmmercialTotalDemandMap.get(name) != null
                    ? connectionCOmmercialTotalDemandMap.get(name).setScale(0, BigDecimal.ROUND_HALF_UP)
                    : BigDecimal.ZERO;
    final BigDecimal totalCommCollections = !connectionCOmmercialTotalCollectionMap.isEmpty()
            && connectionCOmmercialTotalCollectionMap.get(name) != null
                    ? connectionCOmmercialTotalCollectionMap.get(name).setScale(0, BigDecimal.ROUND_HALF_UP)
                    : BigDecimal.ZERO;
    final BigDecimal commproportionalDemand = totalCommDemandValue
            .divide(BigDecimal.valueOf(12), BigDecimal.ROUND_HALF_UP).multiply(BigDecimal.valueOf(noOfMonths));
    receiptData.setCommercialAchievement(commproportionalDemand.compareTo(BigDecimal.ZERO) > 0
            ? totalCommCollections.multiply(WaterTaxConstants.BIGDECIMAL_100).divide(commproportionalDemand, 1,
                    BigDecimal.ROUND_HALF_UP)
            : BigDecimal.ZERO);

    receiptData
            .setWaterChargeCommercialaverage(connectionCommercialcountMap.get(name) != null
                    ? totalCommDemandValue.divide(BigDecimal.valueOf(connectionCommercialcountMap.get(name)), 1,
                            BigDecimal.ROUND_HALF_UP)
                    : BigDecimal.ZERO);

    receiptData.setWaterChargeResidentialaverage(
            totalResDemandValue.divide(BigDecimal.valueOf(entry.getValue()), 1, BigDecimal.ROUND_HALF_UP));

    receiptData.setResidentialConnectionCount(entry.getValue());
    receiptData.setUlbName(name);
    receiptData.setResidentialtotalCollection(!connectionResidentialTotalCollectionMap.isEmpty()
            && connectionResidentialTotalCollectionMap.get(name) != null
                    ? connectionResidentialTotalCollectionMap.get(name)
                    : BigDecimal.ZERO);
    receiptData.setCommercialConnectionCount(connectionCommercialcountMap.get(name));
    receiptData.setComercialtotalCollection(!connectionCOmmercialTotalCollectionMap.isEmpty()
            && connectionCOmmercialTotalCollectionMap.get(name) != null
                    ? connectionCOmmercialTotalCollectionMap.get(name)
                    : BigDecimal.ZERO);

    waterchargeConndemandList.add(receiptData);
}

From source file:com.lp.server.fertigung.ejbfac.FertigungFacBean.java

public LossollmaterialDto createLossollmaterial(LossollmaterialDto lossollmaterialDto,
        TheClientDto theClientDto) throws EJBExceptionLP {
    // log//from  w w  w  . ja  va 2  s  .  co m
    myLogger.logData(lossollmaterialDto);
    // begin
    LosDto losDto = losFindByPrimaryKey(lossollmaterialDto.getLosIId());
    if (losDto.getStatusCNr().equals(FertigungFac.STATUS_ERLEDIGT)) {
        throw new EJBExceptionLP(EJBExceptionLP.FEHLER_FERTIGUNG_DAS_LOS_IST_BEREITS_ERLEDIGT, "");
    }
    if (losDto.getStatusCNr().equals(FertigungFac.STATUS_STORNIERT)) {
        throw new EJBExceptionLP(EJBExceptionLP.FEHLER_FERTIGUNG_DAS_LOS_IST_STORNIERT, "");
    }

    if (lossollmaterialDto.getIBeginnterminoffset() == null) {
        lossollmaterialDto.setIBeginnterminoffset(0);
    }

    lossollmaterialDto.setPersonalIIdAendern(theClientDto.getIDPersonal());
    // primary key
    Integer iId = getPKGeneratorObj().getNextPrimaryKey(PKConst.PK_LOSSOLLMATERIAL);
    lossollmaterialDto.setIId(iId);
    // nachtraeglich ?
    boolean bNachtraeglich = false;
    if (lossollmaterialDto.getBNachtraeglich() == null) {
        lossollmaterialDto.setBNachtraeglich(Helper.boolean2Short(true));
        bNachtraeglich = true;
    }
    if (getMandantFac().hatZusatzfunktionberechtigung(MandantFac.ZUSATZFUNKTION_GERAETESERIENNUMMERN,
            theClientDto)) {
        if (losDto.getStuecklisteIId() != null) {

            // PJ 16622

            Artikel artikel = em.find(Artikel.class, lossollmaterialDto.getArtikelIId());
            if (Helper.short2boolean(artikel.getBSeriennrtragend())) {

                BigDecimal ssg = lossollmaterialDto.getNMenge().divide(losDto.getNLosgroesse(), 4,
                        BigDecimal.ROUND_HALF_UP);

                if (ssg.doubleValue() != 1) {
                    throw new EJBExceptionLP(
                            EJBExceptionLP.FEHLER_POSITIONSMENGE_EINES_SNR_ARTIKELS_MUSS_1_SEIN_WENN_GERAETESNR,
                            new Exception(
                                    "FEHLER_POSITIONSMENGE_EINES_SNR_ARTIKELS_MUSS_1_SEIN_WENN_GERAETESNR"));

                }

            }

        }
    }

    try {
        // rounddto: vor dem Create
        lossollmaterialDto.round(new Integer(4),
                getMandantFac().getNachkommastellenPreisAllgemein(theClientDto.getMandant()));
        Lossollmaterial lossollmaterial = new Lossollmaterial(lossollmaterialDto.getIId(),
                lossollmaterialDto.getLosIId(), lossollmaterialDto.getArtikelIId(),
                lossollmaterialDto.getNMenge(), lossollmaterialDto.getEinheitCNr(),
                lossollmaterialDto.getMontageartIId(), lossollmaterialDto.getISort(),
                lossollmaterialDto.getBNachtraeglich(), lossollmaterialDto.getNSollpreis(),
                lossollmaterialDto.getPersonalIIdAendern(), lossollmaterialDto.getIBeginnterminoffset());

        em.persist(lossollmaterial);
        em.flush();
        lossollmaterialDto.setTAendern(lossollmaterial.getTAendern());
        setLossollmaterialFromLossollmaterialDto(lossollmaterial, lossollmaterialDto, theClientDto);
        // reservierung
        if (bNachtraeglich) {
            // Reservierung anlegen
            ArtikelDto artikelDto = getArtikelFac().artikelFindByPrimaryKey(lossollmaterialDto.getArtikelIId(),
                    theClientDto);
            // wenn los angelegt -> reservierung
            if (losDto.getStatusCNr().equals(FertigungFac.STATUS_ANGELEGT)) {
                java.sql.Date dTermin;
                if (lossollmaterialDto.getNMenge().compareTo(new BigDecimal(0)) > 0) {
                    // Positive Reservierung: produktionsstart
                    dTermin = losDto.getTProduktionsbeginn();
                } else {
                    // Negative Reservierung: produktionsende
                    dTermin = losDto.getTProduktionsende();
                }
                createReservierung(artikelDto, lossollmaterialDto.getIId(), lossollmaterialDto.getNMenge(),
                        new java.sql.Timestamp(dTermin.getTime()));
            }
            // wenn ausgegeben -> fehlmenge
            else {
                getFehlmengeFac().aktualisiereFehlmenge(LocaleFac.BELEGART_LOS, lossollmaterialDto.getIId(),
                        false, theClientDto);
            }
        }
        return lossollmaterialDto;
    } catch (EntityExistsException ex) {
        throw new EJBExceptionLP(EJBExceptionLP.FEHLER_BEIM_ANLEGEN, ex);
    } catch (RemoteException ex) {
        throwEJBExceptionLPRespectOld(ex);
        return null;
    }
}