Example usage for java.math BigDecimal setScale

List of usage examples for java.math BigDecimal setScale

Introduction

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

Prototype

@Deprecated(since = "9")
public BigDecimal setScale(int newScale, int roundingMode) 

Source Link

Document

Returns a BigDecimal whose scale is the specified value, and whose unscaled value is determined by multiplying or dividing this BigDecimal 's unscaled value by the appropriate power of ten to maintain its overall value.

Usage

From source file:org.kuali.kra.award.printing.xmlstream.AwardBaseStream.java

private BigDecimal getObligatedTotalDirect() {
    BigDecimal obligatedTotalDirect = null;
    if (awardAmountInfo.getObligatedTotalDirect() != null) {
        obligatedTotalDirect = new BigDecimal(awardAmountInfo.getObligatedTotalDirect().doubleValue());
        obligatedTotalDirect = obligatedTotalDirect.setScale(2, BigDecimal.ROUND_HALF_DOWN);
    }//from   w  w  w .  ja  v a  2s .  c  o  m
    return obligatedTotalDirect;
}

From source file:org.kuali.kra.award.printing.xmlstream.AwardBaseStream.java

private BigDecimal getObligatedDistributableAmt() {
    BigDecimal obligatedDistributableAmt = null;
    if (awardAmountInfo.getObliDistributableAmount() != null) {
        obligatedDistributableAmt = awardAmountInfo.getObliDistributableAmount().bigDecimalValue();
        obligatedDistributableAmt = obligatedDistributableAmt.setScale(2, BigDecimal.ROUND_HALF_DOWN);
    }//  w  ww  .  j  ava  2 s . c  o m
    return obligatedDistributableAmt;
}

From source file:org.kuali.kra.award.printing.xmlstream.AwardBaseStream.java

private BigDecimal getAnticipatedTotalDirect() {
    BigDecimal anticipatedTotalDirect = null;
    if (awardAmountInfo.getAnticipatedTotalDirect() != null) {
        anticipatedTotalDirect = new BigDecimal(awardAmountInfo.getAnticipatedTotalDirect().doubleValue());
        anticipatedTotalDirect = anticipatedTotalDirect.setScale(2, BigDecimal.ROUND_HALF_DOWN);
    }//  w w w  .  j a v a2s  .co  m
    return anticipatedTotalDirect;
}

From source file:org.kuali.kra.award.printing.xmlstream.AwardBaseStream.java

private BigDecimal getObligatedTotalIndirect() {
    BigDecimal obligatedTotalIndirect = null;
    if (awardAmountInfo.getObligatedTotalIndirect() != null) {
        obligatedTotalIndirect = new BigDecimal(awardAmountInfo.getObligatedTotalIndirect().doubleValue());
        obligatedTotalIndirect = obligatedTotalIndirect.setScale(2, BigDecimal.ROUND_HALF_DOWN);
    }//from   w  w w .  ja  v a  2s.co  m
    return obligatedTotalIndirect;
}

From source file:org.kuali.kra.award.printing.xmlstream.AwardBaseStream.java

private BigDecimal getAntDistributableAmount() {
    BigDecimal anticipatedDistributableAmt = null;
    if (awardAmountInfo.getAntDistributableAmount() != null) {
        anticipatedDistributableAmt = awardAmountInfo.getAntDistributableAmount().bigDecimalValue();
        anticipatedDistributableAmt = anticipatedDistributableAmt.setScale(2, BigDecimal.ROUND_HALF_DOWN);
    }/*from ww  w  . ja v  a2s.co m*/
    return anticipatedDistributableAmt;
}

From source file:org.kawanfw.sql.jdbc.ResultSetHttp.java

/**
 * Retrieves the value of the designated column in the current row of this
 * <code>ResultSet</code> object as a <code>java.sql.BigDecimal</code> in
 * the Java programming language./*ww  w .  j  a  v a2s  . c  o m*/
 * 
 * @param columnIndex
 *            the first column is 1, the second is 2, ...
 * @param scale
 *            the number of digits to the right of the decimal point
 * @return the column value; if the value is SQL <code>NULL</code>, the
 *         value returned is <code>null</code>
 * @exception SQLException
 *                if a database access error occurs
 * @deprecated
 */
@Override
public BigDecimal getBigDecimal(int columnIndex, int scale) throws SQLException {

    if (scale < 0) {
        throw new SQLException("invalid scale: " + scale + ". Scale must be >= 0");
    }

    BigDecimal bd = getBigDecimal(columnIndex);

    if (bd != null) {
        bd = bd.setScale(scale, BigDecimal.ROUND_DOWN);
    }

    return bd;
}

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

@Transactional(rollbackFor = Exception.class, value = "transactionManager")
@Override/*  w w  w . j  av a  2  s .c om*/
public RepayOrder gotoYJFRepay(long repayUserId, long demandId, long repayPlanId) throws Exception {

    List<UserBaseInfoDO> repayUsers = userBaseInfoManager.queryByType(null, String.valueOf(repayUserId));
    UserBaseInfoDO repayUser = null;
    if (ListUtil.isNotEmpty(repayUsers)) {
        repayUser = repayUsers.get(0);
        if (!"normal".equals(repayUser.getState())) {
            logger.error("?userId{}", repayUserId);
            throw new Exception("user state error");
        }
    } else {
        logger.error("?userId{}", repayUserId);
        throw new Exception("can not find repay user");
    }

    Trade trade = tradeDao.getByDemandId(demandId);
    LoanDemandDO loan = loanDemandManager.queryLoanDemandByDemandId(trade.getDemandId());

    RepayPlanInfo repayPlanInfo = null;

    if (DivisionWayEnum.SIT_WAY.code().equals(loan.getRepayDivisionWay())) {
        RepayPlanQueryOrder repayPlanQueryOrder = new RepayPlanQueryOrder();
        repayPlanQueryOrder.setRepayDivisionWay(DivisionWayEnum.SIT_WAY.code());
        repayPlanQueryOrder.setPageSize(999999);
        repayPlanQueryOrder.setPageNumber(1);
        repayPlanQueryOrder.setTradeId(trade.getId());
        repayPlanQueryOrder.setPeriodNo(1);
        QueryBaseBatchResult<RepayPlanInfo> result = repayPlanService.queryRepayPlanInfo(repayPlanQueryOrder);
        if (ListUtil.isNotEmpty(result.getPageList())) {
            repayPlanInfo = result.getPageList().get(0);
            repayPlanId = repayPlanInfo.getRepayPlanId(); // ?id
        }
    } else {
        if (repayPlanId == 0) {
            throw new RuntimeException(
                    "??repayPlanId=" + repayPlanId + "id?0");
        }
    }

    // ??
    Money availableBalance = null;

    YzzUserAccountQueryResponse accountResult = apiTool.queryUserAccount(repayUser.getAccountId());

    if (accountResult.success()) {
        availableBalance = new Money(accountResult.getAvailableBalance());
    } else {
        throw new Exception("??");
    }

    RepayPlanDO repayPlan = repayPlanDAO.findById(repayPlanId);

    if (StringUtil.equalsIgnoreCase("PS", repayPlan.getStatus())
            || StringUtil.equalsIgnoreCase("AS", repayPlan.getStatus())) {
        throw new Exception("?");
    }

    if (StringUtil.isBlank(repayPlan.getCreateRepayNo())) {
        // 
        RepayTradeOrder order = new RepayTradeOrder();
        order.setPayerUserId(repayUser.getAccountId());
        order.setTradeAmount(repayPlanInfo.getAmount());
        order.setTradeMemo(repayPlanInfo.getNote());
        order.setTradeName(repayPlanInfo.getTradeName() + "");
        RepayTradeResult result = repayService.createRepayTrade(order, this.getOpenApiContext());
        if (!result.isSuccess()) {
            return null;
        }

        repayPlan.setCreateRepayNo(result.getTradeNo());

        repayPlan.setStatus(RepayPlanStatusEnum.APPLY.getCode());
        try {
            repayPlanDAO.update(repayPlan);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    long repayAmount = 0;
    double repayCutAmount = 0;
    // ?
    double repayDivisionAmount = 0;
    // ??,??
    if (DivisionWayEnum.SIT_WAY.code().equals(loan.getRepayDivisionWay())) {
        // 
        long divisionTemplateLoanBaseId = loan.getDivisionTemplateId();
        DivisionTemplateLoanDO divisionTemplateLoan = divisionTemplateLoanService
                .getByBaseId(divisionTemplateLoanBaseId);
        List<DivsionRuleRole> repayRolelist = divisionService
                .getRuleRole(String.valueOf(divisionTemplateLoan.getRepayTemplateId()));
        double payInterest = 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());
                    payInterest += bg.setScale(10, BigDecimal.ROUND_HALF_UP).doubleValue();

                    if (druleRole.getRoleId() != SysUserRoleEnum.INVESTOR.getValue()) {
                        repayDivisionAmount += Math.round(trade.getLoanedAmount()
                                * bg.setScale(10, BigDecimal.ROUND_HALF_UP).doubleValue());
                    }
                }
            }
        }
        repayAmount = trade.getLoanedAmount() + (long) repayCutAmount;
        if (availableBalance.getCent() < repayAmount) {
            logger.info("??---id" + repayUser.getUserId());
            return null;
        }
    }

    String repayYjfUserId = tradeDetailDao.getYjfUserNameByUserId(repayUserId);

    logger.info("repayUserId :" + repayUserId + " " + repayYjfUserId + " " + repayUser.getAccountId());

    long tradeId = trade.getId();

    RepayOrder repayOrder = new RepayOrder();

    // ??,??
    if (DivisionWayEnum.SIT_WAY.code().equals(loan.getRepayDivisionWay())) {

        // ?
        List<TransferTrade> investTradeList = transferTradeDao.getPhaseTransferTrades(tradeId,
                DivisionPhaseEnum.ORIGINAL_PHASE.code(), TradeDetailStatusEnum.PS.code(), //???
                new String[] { SysUserRoleEnum.INVESTOR.getRoleCode() });

        // ?
        List<TransferTrade> investDevisionList = transferTradeDao.getPhaseTransferTrades(tradeId,
                DivisionPhaseEnum.REPAY_PHASE.getCode(), null, //???
                new String[] { SysUserRoleEnum.INVESTOR.getRoleCode() });

        // 
        List<TransferTrade> divisionList = divisionService.queryRepayDivision(tradeId);

        List<RepaySubOrder> subOrders = new ArrayList<RepaySubOrder>();
        for (int i = 0; i < investTradeList.size(); i++) {
            TransferTrade tt = investTradeList.get(i);
            RepaySubOrder subOrder = new RepaySubOrder();
            Money transferAmount = Money.cent(tt.getAmount());

            TransferTrade td = this.getRepayDetail(investDevisionList, investTradeList.get(i));
            if (null == td) {
                transferAmount.addTo(Money.cent(0l));
            } else {
                transferAmount.addTo(Money.cent(td.getAmount()));
            }

            subOrder.setTransferAmount(transferAmount.toString());
            subOrder.setMemo("");
            subOrder.setOrderNo(BusinessNumberUtil.gainOutBizNoNumber());
            subOrder.setPayeeUserId(tt.getYjfUserName());
            subOrder.setTradeName("");
            subOrders.add(subOrder);
        }

        repayOrder.setPayerUserId(repayUser.getAccountId());
        repayOrder.setOrderNo(BusinessNumberUtil.gainOutBizNoNumber());
        repayOrder.setRefTradeNo(trade.getCode());
        //
        if (repayDivisionAmount > 0) {
            RepaySubOrder shardOrder = new RepaySubOrder();
            shardOrder.setMemo("");
            shardOrder.setOrderNo(BusinessNumberUtil.gainOutBizNoNumber());
            shardOrder.setPayeeUserId(Constants.EXCHANGE_ACCOUNT);
            shardOrder.setTradeName("");
            shardOrder.setTransferAmount(Money.cent((long) repayDivisionAmount).toString());
            repayOrder.setShardOrder(shardOrder);
        }
        repayOrder.setSubOrders(subOrders);
        repayOrder.setTradeNo(repayPlan.getCreateRepayNo());
    }
    //?
    repayPlan.setRepayNo(repayOrder.getOrderNo());
    repayPlan.setStatus(RepayPlanStatusEnum.APPLY.getCode());
    repayPlanDAO.update(repayPlan);

    return repayOrder;
}

From source file:com.ugam.collage.plus.service.people_count.impl.PeopleAccountingServiceImpl.java

/**
 * @param empcntClientProjectDataList/*from   w w w  .j a  va2s . c o  m*/
 * @param empClientProjectTeamStructList
 * @param employee
 * @param month
 * @param year
 * @param costCentre
 * @param countType
 * @param allignedTimeZero
 * @param assistedTimeZero
 * @param apportionedTimeZero
 * @param allignedTimeOne
 * @param totalTimeOne
 */
private void getSingleProjectDetail(List<EmpcntClientProjectData> empOpenCntClientProjectDataList,
        List<EmpcntClientProjectData> empCloseCntClientProjectDataList,
        List<EmpClientProjectTeamStruct> empClientProjectTeamStructList, EmployeeMaster employee,
        TabMonth month, TabYear year, CostCentre costCentre, CountClassification countType,
        BigDecimal allignedTimeZero, BigDecimal assistedTimeZero, BigDecimal apportionedTimeZero,
        BigDecimal allignedTimeOne, BigDecimal totalTimeOne, Integer countTypeId,
        Map<String, EmployeePcTagsTeamStruct> employeePcTagsTeamStructMap) {

    /*
     * Also assign to assisted if project detail present in both assigned
     * and unassigned list
     * 
     * Note : Only in unassigned project . do the remaining count as per
     * revenue to apportion
     * 
     * If not present in revenue table then go to zero project details
     */
    logger.debug("<====getSingleProjectDetail START====>");
    Integer employeeId = employee.getEmployeeId();
    Integer yearId = year.getYearId();
    Integer monthId = month.getMonthId();
    String costCentreId = costCentre.getCostCentreId();
    BigDecimal deviderHour = new BigDecimal(Constants.TOTAL_WORKING_HOURS);
    logger.debug("getSingleProjectDetail parameter===>" + employeeId + "::" + yearId + "::" + monthId + "::"
            + costCentreId + "::" + deviderHour);

    // Get project details
    Map<Integer, EmpClientProjectTeamStruct> employeeProjectIds = new HashMap<Integer, EmpClientProjectTeamStruct>();

    Map<Integer, EmpClientProjectTeamStruct> validEmployeeProjectIds = new HashMap<Integer, EmpClientProjectTeamStruct>();

    for (EmpClientProjectTeamStruct empClientProjectTeamStructThree : empClientProjectTeamStructList) {
        employeeProjectIds.put(empClientProjectTeamStructThree.getProjectMaster().getProjectId(),
                empClientProjectTeamStructThree);
    }

    validEmployeeProjectIds.putAll(employeeProjectIds);
    // logger.debug("validEmployeeProjectIds 1:size===>" +
    // validEmployeeProjectIds.size());

    // check in revenue table
    for (Integer key : employeeProjectIds.keySet()) {
        EmpClientProjectTeamStruct mapValues = employeeProjectIds.get(key);
        List<CollageProjectRevenue> listValues = collageProjectRevenueDao
                .findByYearIdMonthIdProjectIdCostCentreId(mapValues.getTabYear().getYearId(),
                        mapValues.getTabMonth().getMonthId(), mapValues.getProjectMaster().getProjectId(),
                        costCentre.getCostCentreId());
        if (listValues.isEmpty()) {
            validEmployeeProjectIds.remove(key);
        }
    }
    // logger.debug("validEmployeeProjectIds 2:size===>" +
    // validEmployeeProjectIds.size());
    if (validEmployeeProjectIds.isEmpty()) {
        getZeroProjectsDetail(yearId, monthId, costCentreId, empOpenCntClientProjectDataList,
                empCloseCntClientProjectDataList, employee, month, year, costCentre, countType,
                allignedTimeZero, assistedTimeZero, totalTimeOne, totalTimeOne, countTypeId,
                employeePcTagsTeamStructMap);
    }
    // Get list of project from execution data for that employee
    List<Integer> projectIdList = executionDataDao.findByPersonYearMonthCostCentre(employeeId, yearId, monthId,
            costCentreId);
    // logger.debug("execution data projects===>" + projectIdList.size());

    if (projectIdList.isEmpty()) {
        // logger.debug("Contain InValid projects :(Assign count one)===>");

        for (Integer projectId : validEmployeeProjectIds.keySet()) {
            EmpClientProjectTeamStruct mapValues = validEmployeeProjectIds.get(projectId);
            // logger.debug("978: Contain InValid projects :(Assign count one)===>"+1);
            EmpcntClientProjectData empcntClientProjectData = new EmpcntClientProjectData(employee,
                    mapValues.getCompanyMaster(), countType, month, mapValues.getProjectMaster(), year,
                    costCentre, allignedTimeOne, assistedTimeZero, apportionedTimeZero, allignedTimeOne);
            if (countTypeId == 1) {
                empOpenCntClientProjectDataList.add(empcntClientProjectData);
            } else if (countTypeId == 2) {
                empCloseCntClientProjectDataList.add(empcntClientProjectData);
            }
        }
    } else {
        // logger.debug("Else Contain Valid projects===>");
        Integer validEmployeeProjectCount = validEmployeeProjectIds.size();
        // Get valid projects list=>project is both revenue data and
        // execution data
        Set<Integer> validAllProjects = new HashSet<Integer>();
        for (Integer projectId : projectIdList) {
            List<CollageProjectRevenue> listValues = collageProjectRevenueDao
                    .findByYearIdMonthIdProjectIdCostCentreId(yearId, monthId, projectId, costCentreId);
            if (!listValues.isEmpty()) {
                validAllProjects.add(projectId);
            }

        }
        Integer validAllProjectCount = validAllProjects.size();
        // logger.debug("validAllProjects :size===>" +
        // validAllProjects.size());
        // Total hour worked by an Employee
        List<BigDecimal> toatalHours = executionDataDao.findByPersonIdYearIdMonthIdCostCentreId(employeeId,
                yearId, monthId, costCentreId);
        BigDecimal toatlTime = toatalHours.get(0);
        // logger.debug("ToatalHours===>" + toatlTime);

        // Separate assigned projects from execution data projects
        Map<Integer, BigDecimal> assignedProjects = new HashMap<Integer, BigDecimal>();
        Map<Integer, BigDecimal> unAssignedProjects = new HashMap<Integer, BigDecimal>();
        List<Object[]> allProjectTimeList = executionDataDao
                .findByEmployeeIdYearIdMonthIdCostCentreId(employeeId, yearId, monthId, costCentreId);
        for (Object[] result : allProjectTimeList) {
            Integer projectId = (Integer) result[0];
            BigDecimal hour = (BigDecimal) result[1];
            Integer companyId = (Integer) result[2];
            if (validEmployeeProjectIds.containsKey(projectId) && validAllProjects.contains(projectId)) {
                // logger.debug("UnAssignedProjects===>" +
                // projectId+"::"+hour+"::"+companyId);
                assignedProjects.put(projectId, hour);
            }
            if (!validEmployeeProjectIds.containsKey(projectId) && validAllProjects.contains(projectId)) {
                // logger.debug("assignedProjects===>" +
                // projectId+"::"+hour+"::"+companyId);
                unAssignedProjects.put(projectId, hour);
            }
        }
        if (validEmployeeProjectCount == 1 && validAllProjectCount == 1
                && validAllProjects.containsAll(validEmployeeProjectIds.keySet())
                && unAssignedProjects.isEmpty()) {

            // logger.debug("validEmployeeProjectCount==validAllProjectCount :(Only in assigned projects)");
            for (Integer key : assignedProjects.keySet()) {
                // Get time spent on each project by employee id
                Integer projectId = key;
                EmpClientProjectTeamStruct mapValues = validEmployeeProjectIds.get(projectId);
                // logger.debug("1034 :validEmployeeProjectCount==validAllProjectCount :(Only in assigned projects)===>1");
                EmpcntClientProjectData empcntClientProjectData = new EmpcntClientProjectData(employee,
                        mapValues.getCompanyMaster(), countType, month, mapValues.getProjectMaster(), year,
                        costCentre, allignedTimeOne, assistedTimeZero, apportionedTimeZero, allignedTimeOne);
                if (countTypeId == 1) {
                    empOpenCntClientProjectDataList.add(empcntClientProjectData);
                }
                if (countTypeId == 2) {
                    empCloseCntClientProjectDataList.add(empcntClientProjectData);
                }
            }

        } else if (!assignedProjects.isEmpty() && !unAssignedProjects.isEmpty()) {
            // logger.debug("1047 : Both in assigned and unassigned projects===>");
            if (toatlTime.compareTo(new BigDecimal(Constants.TOTAL_WORKING_HOURS)) >= 0) {
                // logger.debug("Worked hours===> >=168");
                for (Integer key : assignedProjects.keySet()) {
                    // Get time spent on each project by employee id
                    Integer projectId = key;
                    BigDecimal timeByProject = assignedProjects.get(key);
                    EmpClientProjectTeamStruct mapValues = validEmployeeProjectIds.get(projectId);
                    BigDecimal workedHours = timeByProject.divide(toatlTime, 2, RoundingMode.HALF_EVEN);
                    workedHours = workedHours.setScale(2, RoundingMode.CEILING);
                    // logger.debug("1056 :assigned:(Both in assigned and unassigned projects===>"+workedHours);
                    EmpcntClientProjectData empcntClientProjectData = new EmpcntClientProjectData(employee,
                            mapValues.getCompanyMaster(), countType, month, mapValues.getProjectMaster(), year,
                            costCentre, workedHours, assistedTimeZero, apportionedTimeZero, workedHours);
                    if (countTypeId == 1) {
                        empOpenCntClientProjectDataList.add(empcntClientProjectData);
                    }
                    if (countTypeId == 2) {
                        empCloseCntClientProjectDataList.add(empcntClientProjectData);
                    }
                }
                for (Integer key : unAssignedProjects.keySet()) {
                    // Get time spent on each project by employee id
                    Integer projectId = key;
                    BigDecimal timeByProject = unAssignedProjects.get(key);
                    EmpClientProjectTeamStruct mapValues = validEmployeeProjectIds.get(projectId);
                    BigDecimal workedHours = timeByProject.divide(toatlTime, 2, RoundingMode.HALF_EVEN);
                    workedHours = workedHours.setScale(2, RoundingMode.CEILING);
                    // logger.debug("1073 :unassigned :(Both in assigned and unassigned projects===>"+workedHours);
                    EmpcntClientProjectData empcntClientProjectData = new EmpcntClientProjectData(employee,
                            mapValues.getCompanyMaster(), countType, month, mapValues.getProjectMaster(), year,
                            costCentre, apportionedTimeZero, workedHours, apportionedTimeZero, workedHours);
                    if (countTypeId == 1) {
                        empOpenCntClientProjectDataList.add(empcntClientProjectData);
                    }
                    if (countTypeId == 2) {
                        empCloseCntClientProjectDataList.add(empcntClientProjectData);
                    }
                }
            } else {
                // logger.debug("Worked hours===> <168");
                BigDecimal totalUnAssingnedHours = BigDecimal.ZERO;
                BigDecimal assingnedHours = BigDecimal.ZERO;
                for (Integer key : unAssignedProjects.keySet()) {
                    // Get time spent on each project by employee id
                    BigDecimal timeByProject = unAssignedProjects.get(key);
                    BigDecimal workedHours = timeByProject.divide(deviderHour, 2, RoundingMode.HALF_EVEN);
                    totalUnAssingnedHours = totalUnAssingnedHours.add(workedHours);
                    workedHours = workedHours.setScale(2, RoundingMode.CEILING);
                    // Assign to assisted count for unAssignedProjects
                    Integer projectId = key;
                    List<ProjectMaster> projectList = projectMasterDao.findByProjectId(projectId);
                    ProjectMaster projectMaster = projectList.get(0);
                    CompanyMaster companyMaster = projectMaster.getCompanyMaster();
                    // logger.debug("769: Assisted hours (Both in assigned and unassigned projects) 2===>"+workedHours);
                    EmpcntClientProjectData empcntClientProjectData = new EmpcntClientProjectData(employee,
                            companyMaster, countType, month, projectMaster, year, costCentre,
                            apportionedTimeZero, workedHours, apportionedTimeZero, workedHours);
                    if (countTypeId == 1) {
                        empOpenCntClientProjectDataList.add(empcntClientProjectData);
                    }
                    if (countTypeId == 2) {
                        empCloseCntClientProjectDataList.add(empcntClientProjectData);
                    }
                }
                totalUnAssingnedHours = BigDecimal.ONE.subtract(totalUnAssingnedHours);
                // logger.debug("totalUnAssingnedHours===> "+totalUnAssingnedHours);
                for (Map.Entry<Integer, BigDecimal> entry : assignedProjects.entrySet()) {
                    assingnedHours = assingnedHours.add(entry.getValue());
                }

                // logger.debug("assingnedHours===> "+assingnedHours);
                for (Integer key : assignedProjects.keySet()) {
                    Integer projectId = key;
                    BigDecimal timeByProject = assignedProjects.get(key);
                    // logger.debug("1119 :projectId : timeByProject===> "+projectId+" : "+timeByProject);
                    EmpClientProjectTeamStruct mapValues = validEmployeeProjectIds.get(projectId);
                    BigDecimal averageWorkedHours = timeByProject.divide(assingnedHours, 2,
                            RoundingMode.HALF_EVEN);
                    // logger.debug("1121 :assingnedHours : totalUnAssingnedHours===> "+assingnedHours+" : "+totalUnAssingnedHours);
                    BigDecimal actualWorkedHours = averageWorkedHours.multiply(totalUnAssingnedHours);
                    actualWorkedHours = actualWorkedHours.setScale(2, RoundingMode.CEILING);
                    // logger.debug("1124 :averageWorkedHours : actualWorkedHours===> "+averageWorkedHours+" : "+actualWorkedHours);
                    EmpcntClientProjectData empcntClientProjectData = new EmpcntClientProjectData(employee,
                            mapValues.getCompanyMaster(), countType, month, mapValues.getProjectMaster(), year,
                            costCentre, actualWorkedHours, assistedTimeZero, apportionedTimeZero,
                            actualWorkedHours);
                    if (countTypeId == 1) {
                        empOpenCntClientProjectDataList.add(empcntClientProjectData);
                    }
                    if (countTypeId == 2) {
                        empCloseCntClientProjectDataList.add(empcntClientProjectData);
                    }
                }
            }
        }

        else if (assignedProjects.isEmpty() && !unAssignedProjects.isEmpty()) {
            // logger.debug("In  unassigned projects only===>");
            if (toatlTime.compareTo(new BigDecimal(Constants.TOTAL_WORKING_HOURS)) >= 0) {
                // logger.debug("Worked hours===> >=168");
                for (Integer key : unAssignedProjects.keySet()) {
                    // Get time spent on each project by employee id
                    Integer projectId = key;
                    BigDecimal timeByProject = unAssignedProjects.get(key);
                    EmpClientProjectTeamStruct mapValues = validEmployeeProjectIds.get(projectId);
                    BigDecimal workedHours = timeByProject.divide(toatlTime, 2, RoundingMode.HALF_EVEN);
                    workedHours = workedHours.setScale(2, RoundingMode.CEILING);
                    // logger.debug("1148 :In unassigned projects only===>"+workedHours);
                    EmpcntClientProjectData empcntClientProjectData = new EmpcntClientProjectData(employee,
                            mapValues.getCompanyMaster(), countType, month, mapValues.getProjectMaster(), year,
                            costCentre, apportionedTimeZero, workedHours, apportionedTimeZero, workedHours);
                    if (countTypeId == 1) {
                        empOpenCntClientProjectDataList.add(empcntClientProjectData);
                    }
                    if (countTypeId == 2) {
                        empCloseCntClientProjectDataList.add(empcntClientProjectData);
                    }
                }
            } else {
                // logger.debug("Worked hours===> <168");
                BigDecimal totalUnAssingnedHours = BigDecimal.ZERO;
                BigDecimal assingnedHours = BigDecimal.ZERO;
                for (Integer key : unAssignedProjects.keySet()) {
                    // Get time spent on each project by employee id
                    BigDecimal timeByProject = unAssignedProjects.get(key);
                    BigDecimal workedHours = timeByProject.divide(deviderHour, 2, RoundingMode.HALF_EVEN);
                    workedHours = workedHours.setScale(2, RoundingMode.CEILING);
                    totalUnAssingnedHours = totalUnAssingnedHours.add(workedHours);

                    // Assign to assisted count for unAssignedProjects
                    Integer projectId = key;
                    List<ProjectMaster> projectList = projectMasterDao.findByProjectId(projectId);
                    ProjectMaster projectMaster = projectList.get(0);
                    CompanyMaster companyMaster = projectMaster.getCompanyMaster();
                    // logger.debug("1173: Assisted hours (In unassigned projects) 2===>"+workedHours);
                    EmpcntClientProjectData empcntClientProjectData = new EmpcntClientProjectData(employee,
                            companyMaster, countType, month, projectMaster, year, costCentre,
                            apportionedTimeZero, workedHours, apportionedTimeZero, workedHours);
                    if (countTypeId == 1) {
                        empOpenCntClientProjectDataList.add(empcntClientProjectData);
                    }
                    if (countTypeId == 2) {
                        empCloseCntClientProjectDataList.add(empcntClientProjectData);
                    }
                }
                logger.debug("1209 totalUnAssingnedHours===> " + totalUnAssingnedHours);

                BigDecimal remainProportion = BigDecimal.ONE.subtract(totalUnAssingnedHours);
                logger.debug("remainProportion===> " + remainProportion);
                getRevenueCountProportion(empOpenCntClientProjectDataList, empCloseCntClientProjectDataList,
                        employee, month, year, costCentre, countType, remainProportion, unAssignedProjects,
                        countTypeId, employeePcTagsTeamStructMap);

            }
        }

    }
    // logger.debug("<====getSingleProjectDetail END====>");
}

From source file:org.apache.ofbiz.shipment.thirdparty.usps.UspsServices.java

public static Map<String, Object> uspsDeliveryConfirmation(DispatchContext dctx,
        Map<String, ? extends Object> context) {
    Delegator delegator = dctx.getDelegator();
    String shipmentId = (String) context.get("shipmentId");
    String shipmentRouteSegmentId = (String) context.get("shipmentRouteSegmentId");
    Locale locale = (Locale) context.get("locale");

    Map<String, Object> shipmentGatewayConfig = ShipmentServices.getShipmentGatewayConfigFromShipment(delegator,
            shipmentId, locale);/*from w  w  w. j ava 2  s . co m*/
    String shipmentGatewayConfigId = (String) shipmentGatewayConfig.get("shipmentGatewayConfigId");
    String resource = (String) shipmentGatewayConfig.get("configProps");
    if (UtilValidate.isEmpty(shipmentGatewayConfigId) && UtilValidate.isEmpty(resource)) {
        return ServiceUtil.returnError(
                UtilProperties.getMessage(resourceError, "FacilityShipmentUspsGatewayNotAvailable", locale));
    }

    try {
        GenericValue shipment = EntityQuery.use(delegator).from("Shipment").where("shipmentId", shipmentId)
                .queryOne();
        if (shipment == null) {
            return ServiceUtil.returnError(
                    UtilProperties.getMessage(resourceError, "ProductShipmentNotFoundId", locale) + shipmentId);
        }

        GenericValue shipmentRouteSegment = EntityQuery.use(delegator).from("ShipmentRouteSegment")
                .where("shipmentId", shipmentId, "shipmentRouteSegmentId", shipmentRouteSegmentId).queryOne();
        if (shipmentRouteSegment == null) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                    "ProductShipmentRouteSegmentNotFound",
                    UtilMisc.toMap("shipmentId", shipmentId, "shipmentRouteSegmentId", shipmentRouteSegmentId),
                    locale));
        }

        // ensure the carrier is USPS
        if (!"USPS".equals(shipmentRouteSegment.getString("carrierPartyId"))) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                    "FacilityShipmentUspsNotRouteSegmentCarrier",
                    UtilMisc.toMap("shipmentRouteSegmentId", shipmentRouteSegmentId, "shipmentId", shipmentId),
                    locale));
        }

        // get the origin address
        GenericValue originAddress = shipmentRouteSegment.getRelatedOne("OriginPostalAddress", false);
        if (originAddress == null) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                    "FacilityShipmentRouteSegmentOriginPostalAddressNotFound",
                    UtilMisc.toMap("shipmentId", shipmentId, "shipmentRouteSegmentId", shipmentRouteSegmentId),
                    locale));
        }
        if (!"USA".equals(originAddress.getString("countryGeoId"))) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                    "FacilityShipmentUspsRouteSegmentOriginCountryGeoNotInUsa",
                    UtilMisc.toMap("shipmentId", shipmentId, "shipmentRouteSegmentId", shipmentRouteSegmentId),
                    locale));
        }

        // get the destination address
        GenericValue destinationAddress = shipmentRouteSegment.getRelatedOne("DestPostalAddress", false);
        if (destinationAddress == null) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                    "FacilityShipmentRouteSegmentDestPostalAddressNotFound",
                    UtilMisc.toMap("shipmentId", shipmentId, "shipmentRouteSegmentId", shipmentRouteSegmentId),
                    locale));
        }
        if (!"USA".equals(destinationAddress.getString("countryGeoId"))) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                    "FacilityShipmentUspsRouteSegmentOriginCountryGeoNotInUsa",
                    UtilMisc.toMap("shipmentId", shipmentId, "shipmentRouteSegmentId", shipmentRouteSegmentId),
                    locale));
        }

        // get the service type from the CarrierShipmentMethod
        String shipmentMethodTypeId = shipmentRouteSegment.getString("shipmentMethodTypeId");
        String partyId = shipmentRouteSegment.getString("carrierPartyId");

        GenericValue carrierShipmentMethod = EntityQuery.use(delegator).from("CarrierShipmentMethod")
                .where("partyId", partyId, "roleTypeId", "CARRIER", "shipmentMethodTypeId",
                        shipmentMethodTypeId)
                .queryOne();
        if (carrierShipmentMethod == null) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                    "FacilityShipmentUspsNoCarrierShipmentMethod",
                    UtilMisc.toMap("carrierPartyId", partyId, "shipmentMethodTypeId", shipmentMethodTypeId),
                    locale));
        }
        String serviceType = carrierShipmentMethod.getString("carrierServiceCode");
        if (UtilValidate.isEmpty(serviceType)) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                    "FacilityShipmentUspsUnableDetermineServiceCode", locale));
        }

        // get the packages for this shipment route segment
        List<GenericValue> shipmentPackageRouteSegList = shipmentRouteSegment
                .getRelated("ShipmentPackageRouteSeg", null, UtilMisc.toList("+shipmentPackageSeqId"), false);
        if (UtilValidate.isEmpty(shipmentPackageRouteSegList)) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                    "FacilityShipmentPackageRouteSegsNotFound",
                    UtilMisc.toMap("shipmentId", shipmentId, "shipmentRouteSegmentId", shipmentRouteSegmentId),
                    locale));
        }

        for (GenericValue shipmentPackageRouteSeg : shipmentPackageRouteSegList) {
            Document requestDocument = createUspsRequestDocument("DeliveryConfirmationV2.0Request", true,
                    delegator, shipmentGatewayConfigId, resource);
            Element requestElement = requestDocument.getDocumentElement();

            UtilXml.addChildElementValue(requestElement, "Option", "3", requestDocument);
            UtilXml.addChildElement(requestElement, "ImageParameters", requestDocument);

            // From address
            if (UtilValidate.isNotEmpty(originAddress.getString("attnName"))) {
                UtilXml.addChildElementValue(requestElement, "FromName", originAddress.getString("attnName"),
                        requestDocument);
                UtilXml.addChildElementValue(requestElement, "FromFirm", originAddress.getString("toName"),
                        requestDocument);
            } else {
                UtilXml.addChildElementValue(requestElement, "FromName", originAddress.getString("toName"),
                        requestDocument);
            }
            // The following 2 assignments are not typos - USPS address1 = OFBiz address2, USPS address2 = OFBiz address1
            UtilXml.addChildElementValue(requestElement, "FromAddress1", originAddress.getString("address2"),
                    requestDocument);
            UtilXml.addChildElementValue(requestElement, "FromAddress2", originAddress.getString("address1"),
                    requestDocument);
            UtilXml.addChildElementValue(requestElement, "FromCity", originAddress.getString("city"),
                    requestDocument);
            UtilXml.addChildElementValue(requestElement, "FromState",
                    originAddress.getString("stateProvinceGeoId"), requestDocument);
            UtilXml.addChildElementValue(requestElement, "FromZip5", originAddress.getString("postalCode"),
                    requestDocument);
            UtilXml.addChildElement(requestElement, "FromZip4", requestDocument);

            // To address
            if (UtilValidate.isNotEmpty(destinationAddress.getString("attnName"))) {
                UtilXml.addChildElementValue(requestElement, "ToName", destinationAddress.getString("attnName"),
                        requestDocument);
                UtilXml.addChildElementValue(requestElement, "ToFirm", destinationAddress.getString("toName"),
                        requestDocument);
            } else {
                UtilXml.addChildElementValue(requestElement, "ToName", destinationAddress.getString("toName"),
                        requestDocument);
            }
            // The following 2 assignments are not typos - USPS address1 = OFBiz address2, USPS address2 = OFBiz address1
            UtilXml.addChildElementValue(requestElement, "ToAddress1", destinationAddress.getString("address2"),
                    requestDocument);
            UtilXml.addChildElementValue(requestElement, "ToAddress2", destinationAddress.getString("address1"),
                    requestDocument);
            UtilXml.addChildElementValue(requestElement, "ToCity", destinationAddress.getString("city"),
                    requestDocument);
            UtilXml.addChildElementValue(requestElement, "ToState",
                    destinationAddress.getString("stateProvinceGeoId"), requestDocument);
            UtilXml.addChildElementValue(requestElement, "ToZip5", destinationAddress.getString("postalCode"),
                    requestDocument);
            UtilXml.addChildElement(requestElement, "ToZip4", requestDocument);

            GenericValue shipmentPackage = shipmentPackageRouteSeg.getRelatedOne("ShipmentPackage", false);

            // WeightInOunces
            String weightStr = shipmentPackage.getString("weight");
            if (UtilValidate.isEmpty(weightStr)) {
                return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                        "FacilityShipmentUspsWeightNotFound",
                        UtilMisc.toMap("shipmentId", shipmentPackage.getString("shipmentId"),
                                "shipmentPackageSeqId", shipmentPackage.getString("shipmentPackageSeqId")),
                        locale));
            }

            BigDecimal weight = BigDecimal.ZERO;
            try {
                weight = new BigDecimal(weightStr);
            } catch (NumberFormatException nfe) {
                nfe.printStackTrace(); // TODO: handle exception
            }

            String weightUomId = shipmentPackage.getString("weightUomId");
            if (UtilValidate.isEmpty(weightUomId)) {
                // assume weight is in pounds for consistency (this assumption is made in uspsDomesticRate also)
                weightUomId = "WT_lb";
            }
            if (!"WT_oz".equals(weightUomId)) {
                // attempt a conversion to pounds
                GenericValue uomConversion = EntityQuery.use(delegator).from("UomConversion")
                        .where("uomId", weightUomId, "uomIdTo", "WT_oz").queryOne();
                if (uomConversion == null
                        || UtilValidate.isEmpty(uomConversion.getString("conversionFactor"))) {
                    return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                            "FacilityShipmentUspsWeightUnsupported",
                            UtilMisc.toMap("weightUomId", weightUomId, "shipmentId",
                                    shipmentPackage.getString("shipmentId"), "shipmentPackageSeqId",
                                    shipmentPackage.getString("shipmentPackageSeqId"), "weightUom", "WT_oz"),
                            locale));
                }
                weight = weight.multiply(uomConversion.getBigDecimal("conversionFactor"));
            }

            DecimalFormat df = new DecimalFormat("#");
            UtilXml.addChildElementValue(requestElement, "WeightInOunces",
                    df.format(weight.setScale(0, BigDecimal.ROUND_CEILING)), requestDocument);

            UtilXml.addChildElementValue(requestElement, "ServiceType", serviceType, requestDocument);
            UtilXml.addChildElementValue(requestElement, "ImageType", "TIF", requestDocument);
            UtilXml.addChildElementValue(requestElement, "AddressServiceRequested", "True", requestDocument);

            Document responseDocument = null;
            try {
                responseDocument = sendUspsRequest("DeliveryConfirmationV2", requestDocument, delegator,
                        shipmentGatewayConfigId, resource, locale);
            } catch (UspsRequestException e) {
                Debug.logInfo(e, module);
                return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                        "FacilityShipmentUspsDeliveryConfirmationSendingError",
                        UtilMisc.toMap("errorString", e.getMessage()), locale));
            }
            Element responseElement = responseDocument.getDocumentElement();

            Element respErrorElement = UtilXml.firstChildElement(responseElement, "Error");
            if (respErrorElement != null) {
                return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                        "FacilityShipmentUspsDeliveryConfirmationResponseError",
                        UtilMisc.toMap("shipmentId", shipmentPackage.getString("shipmentId"),
                                "shipmentPackageSeqId", shipmentPackage.getString("shipmentPackageSeqId"),
                                "errorString", UtilXml.childElementValue(respErrorElement, "Description")),
                        locale));
            }

            String labelImageString = UtilXml.childElementValue(responseElement, "DeliveryConfirmationLabel");
            if (UtilValidate.isEmpty(labelImageString)) {
                return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                        "FacilityShipmentUspsDeliveryConfirmationResponseIncompleteElementDeliveryConfirmationLabel",
                        locale));
            }
            shipmentPackageRouteSeg.setBytes("labelImage", Base64.base64Decode(labelImageString.getBytes()));
            String trackingCode = UtilXml.childElementValue(responseElement, "DeliveryConfirmationNumber");
            if (UtilValidate.isEmpty(trackingCode)) {
                return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                        "FacilityShipmentUspsDeliveryConfirmationResponsenIncompleteElementDeliveryConfirmationNumber",
                        locale));
            }
            shipmentPackageRouteSeg.set("trackingCode", trackingCode);
            shipmentPackageRouteSeg.store();
        }

    } catch (GenericEntityException gee) {
        Debug.logInfo(gee, module);
        return ServiceUtil.returnError(
                UtilProperties.getMessage(resourceError, "FacilityShipmentUspsDeliveryConfirmationReadingError",
                        UtilMisc.toMap("errorString", gee.getMessage()), locale));
    }

    return ServiceUtil.returnSuccess();
}

From source file:com.ugam.collage.plus.service.people_count.impl.PeopleAccountingServiceImpl.java

/**
 * @param empcntClientProjectDataList/*from www  .j a va2 s . c o m*/
 * @param empClientProjectTeamStructList
 * @param employee
 * @param month
 * @param year
 * @param costCentre
 * @param countType
 * @param allignedTimeZero
 * @param assistedTimeZero
 * @param apportionedTimeZero
 * @param allignedTimeOne
 * @param totalTimeOne
 * @return
 */

private void getMultipleProjectDetail(List<EmpcntClientProjectData> empOpenCntClientProjectDataList,
        List<EmpcntClientProjectData> empCloseCntClientProjectDataList,
        List<EmpClientProjectTeamStruct> empClientProjectTeamStructList, EmployeeMaster employee,
        TabMonth month, TabYear year, CostCentre costCentre, CountClassification countType,
        BigDecimal allignedTimeZero, BigDecimal assistedTimeZero, BigDecimal apportionedTimeZero,
        BigDecimal allignedTimeOne, BigDecimal totalTimeOne, Integer countTypeId,
        Map<String, EmployeePcTagsTeamStruct> employeePcTagsTeamStructMap) {

    logger.debug("<====getMultipleProjectDetail START====>");
    Integer employeeId = employee.getEmployeeId();
    Integer yearId = year.getYearId();
    Integer monthId = month.getMonthId();
    String costCentreId = costCentre.getCostCentreId();
    BigDecimal deviderHour = new BigDecimal(Constants.TOTAL_WORKING_HOURS);
    logger.debug("getMultipleProjectDetail parameter===>" + employeeId + "::" + yearId + "::" + monthId + "::"
            + costCentreId + "::" + deviderHour);

    // Get project details
    Map<Integer, EmpClientProjectTeamStruct> employeeProjectIds = new HashMap<Integer, EmpClientProjectTeamStruct>();

    Map<Integer, EmpClientProjectTeamStruct> validEmployeeProjectIds = new HashMap<Integer, EmpClientProjectTeamStruct>();

    for (EmpClientProjectTeamStruct empClientProjectTeamStructThree : empClientProjectTeamStructList) {
        employeeProjectIds.put(empClientProjectTeamStructThree.getProjectMaster().getProjectId(),
                empClientProjectTeamStructThree);
    }

    validEmployeeProjectIds.putAll(employeeProjectIds);
    // logger.debug("validEmployeeProjectIds 1:size===>" +
    // validEmployeeProjectIds.size());

    // check in revenue table
    for (Integer key : employeeProjectIds.keySet()) {
        EmpClientProjectTeamStruct mapValues = employeeProjectIds.get(key);
        List<CollageProjectRevenue> listValues = collageProjectRevenueDao
                .findByYearIdMonthIdProjectIdCostCentreId(mapValues.getTabYear().getYearId(),
                        mapValues.getTabMonth().getMonthId(), mapValues.getProjectMaster().getProjectId(),
                        costCentre.getCostCentreId());
        if (listValues.isEmpty()) {
            validEmployeeProjectIds.remove(key);
        }
    }
    // logger.debug("validEmployeeProjectIds 2:size===>" +
    // validEmployeeProjectIds.size());
    // For all invalid projects calculate count zero
    if (validEmployeeProjectIds.isEmpty()) {
        getZeroProjectsDetail(yearId, monthId, costCentreId, empOpenCntClientProjectDataList,
                empCloseCntClientProjectDataList, employee, month, year, costCentre, countType,
                allignedTimeZero, assistedTimeZero, totalTimeOne, totalTimeOne, countTypeId,
                employeePcTagsTeamStructMap);
    }
    // Get list of project from execution data for that employee
    List<Integer> projectIdList = executionDataDao.findByPersonYearMonthCostCentre(employeeId, yearId, monthId,
            costCentreId);
    // logger.debug("execution data projects===>" + projectIdList.size());

    // If List is empty
    if (projectIdList.isEmpty()) {
        // logger.debug("Contain InValid projects (: Find by Revenue)===>");

        Map<Integer, BigDecimal> projectRevenueMap = new HashMap<Integer, BigDecimal>();
        BigDecimal sumOfRevenue = BigDecimal.ZERO;

        List<Object[]> collageProjectRevenueList = collageProjectRevenueDao.findByCostCentreIdYearIdMonthId(
                costCentre.getCostCentreId(), year.getYearId(), month.getMonthId());

        for (Object[] collageProjectRevenue : collageProjectRevenueList) {
            Integer projectId = (Integer) collageProjectRevenue[0];
            BigDecimal revenue = (BigDecimal) collageProjectRevenue[1];
            projectRevenueMap.put(projectId, revenue);
        }
        // logger.debug("projectRevenueMap size===>" +
        // projectRevenueMap.size());

        for (Integer key : projectRevenueMap.keySet()) {
            sumOfRevenue = sumOfRevenue.add(projectRevenueMap.get(key));
        }
        logger.debug("sumOfRevenue===>" + sumOfRevenue);

        for (Integer projectId : validEmployeeProjectIds.keySet()) {
            EmpClientProjectTeamStruct mapValues = validEmployeeProjectIds.get(projectId);
            BigDecimal revenue = projectRevenueMap.get(projectId);
            logger.debug("revenue===>" + revenue);
            BigDecimal projectRevenueCount = revenue.divide(sumOfRevenue, 2, RoundingMode.HALF_EVEN);
            projectRevenueCount = projectRevenueCount.setScale(2, RoundingMode.CEILING);
            // logger.debug("685 empOpenCntClientProjectData ProjectId:Revenue===>"+projectId+" : "
            // + projectRevenueCount);
            EmpcntClientProjectData empcntClientProjectData = new EmpcntClientProjectData(employee,
                    mapValues.getCompanyMaster(), countType, month, mapValues.getProjectMaster(), year,
                    costCentre, projectRevenueCount, BigDecimal.ZERO, BigDecimal.ZERO, projectRevenueCount);
            if (countTypeId == 1) {
                empOpenCntClientProjectDataList.add(empcntClientProjectData);
            }
            if (countTypeId == 2) {
                empCloseCntClientProjectDataList.add(empcntClientProjectData);
            }
        }
    } else {
        // logger.debug("Else Contain Valid projects===>");
        Integer validEmployeeProjectCount = validEmployeeProjectIds.size();
        // Get valid projects list=>project is both revenue data and
        // execution data
        Set<Integer> validAllProjects = new HashSet<Integer>();
        for (Integer projectId : projectIdList) {
            List<CollageProjectRevenue> listValues = collageProjectRevenueDao
                    .findByYearIdMonthIdProjectIdCostCentreId(yearId, monthId, projectId, costCentreId);
            if (!listValues.isEmpty()) {
                validAllProjects.add(projectId);
            }

        }
        Integer validAllProjectCount = validAllProjects.size();
        // logger.debug("validAllProjects :size===>" +
        // validAllProjects.size());
        // Total hour worked by an Employee
        List<BigDecimal> toatalHours = executionDataDao.findByPersonIdYearIdMonthIdCostCentreId(employeeId,
                yearId, monthId, costCentreId);
        BigDecimal toatlTime = toatalHours.get(0);
        // logger.debug("ToatalHours===>" + toatlTime);

        // Separate assigned projects from execution data projects
        Map<Integer, BigDecimal> assignedProjects = new HashMap<Integer, BigDecimal>();
        Map<Integer, BigDecimal> unAssignedProjects = new HashMap<Integer, BigDecimal>();
        List<Object[]> allProjectTimeList = executionDataDao
                .findByEmployeeIdYearIdMonthIdCostCentreId(employeeId, yearId, monthId, costCentreId);
        for (Object[] result : allProjectTimeList) {
            Integer projectId = (Integer) result[0];
            BigDecimal hour = (BigDecimal) result[1];
            Integer companyId = (Integer) result[2];
            if (validEmployeeProjectIds.containsKey(projectId) && validAllProjects.contains(projectId)) {
                // logger.debug("UnAssignedProjects===>" +
                // projectId+"::"+hour+"::"+companyId);
                assignedProjects.put(projectId, hour);
            }
            if (!validEmployeeProjectIds.containsKey(projectId) && validAllProjects.contains(projectId)) {
                // logger.debug("assignedProjects===>" +
                // projectId+"::"+hour+"::"+companyId);
                unAssignedProjects.put(projectId, hour);
            }
        }

        if (validEmployeeProjectCount == validAllProjectCount
                && validAllProjects.containsAll(validEmployeeProjectIds.keySet())
                && unAssignedProjects.isEmpty()) {

            // logger.debug("validEmployeeProjectCount==validAllProjectCount :(Only in assigned projects)");
            for (Integer key : assignedProjects.keySet()) {
                // Get time spent on each project by employee id
                Integer projectId = key;
                BigDecimal timeByProject = assignedProjects.get(key);
                EmpClientProjectTeamStruct mapValues = validEmployeeProjectIds.get(projectId);
                // logger.debug("744 : Worked hours (Only in assigned projects) 1===>"+timeByProject+
                // " : "+toatlTime);
                BigDecimal workedHours = timeByProject.divide(toatlTime, 2, RoundingMode.HALF_EVEN);
                workedHours = workedHours.setScale(2, RoundingMode.CEILING);
                // logger.debug("745: Worked hours (Only in assigned projects) 2===>"+workedHours);
                EmpcntClientProjectData empcntClientProjectData = new EmpcntClientProjectData(employee,
                        mapValues.getCompanyMaster(), countType, month, mapValues.getProjectMaster(), year,
                        costCentre, workedHours, assistedTimeZero, apportionedTimeZero, workedHours);
                if (countTypeId == 1) {
                    empOpenCntClientProjectDataList.add(empcntClientProjectData);
                }
                if (countTypeId == 2) {
                    empCloseCntClientProjectDataList.add(empcntClientProjectData);
                }
            }

        } else if (!assignedProjects.isEmpty() && !unAssignedProjects.isEmpty()) {
            // logger.debug("validEmployeeProjectCount!=validAllProjectCount :(Both in assigned and unassigned projects)");
            if (toatlTime.compareTo(new BigDecimal(Constants.TOTAL_WORKING_HOURS)) >= 0) {
                // logger.debug("Worked hours===> >=168");
                for (Integer key : assignedProjects.keySet()) {
                    // Get time spent on each project by employee id
                    Integer projectId = key;
                    BigDecimal timeByProject = assignedProjects.get(key);
                    EmpClientProjectTeamStruct mapValues = validEmployeeProjectIds.get(projectId);
                    BigDecimal workedHours = timeByProject.divide(toatlTime, 2, RoundingMode.HALF_EVEN);
                    workedHours = workedHours.setScale(2, RoundingMode.CEILING);
                    // logger.debug("768: Aligned hours (Both in assigned and unassigned projects) 1===>"+workedHours);
                    EmpcntClientProjectData empcntClientProjectData = new EmpcntClientProjectData(employee,
                            mapValues.getCompanyMaster(), countType, month, mapValues.getProjectMaster(), year,
                            costCentre, workedHours, assistedTimeZero, apportionedTimeZero, workedHours);
                    if (countTypeId == 1) {
                        empOpenCntClientProjectDataList.add(empcntClientProjectData);
                    }
                    if (countTypeId == 2) {
                        empCloseCntClientProjectDataList.add(empcntClientProjectData);
                    }
                }
                for (Integer key : unAssignedProjects.keySet()) {
                    // Get time spent on each project by employee id
                    Integer projectId = key;
                    BigDecimal timeByProject = unAssignedProjects.get(key);
                    List<ProjectMaster> projectList = projectMasterDao.findByProjectId(projectId);
                    ProjectMaster projectMaster = projectList.get(0);
                    CompanyMaster companyMaster = projectMaster.getCompanyMaster();
                    BigDecimal workedHours = timeByProject.divide(toatlTime, 2, RoundingMode.HALF_EVEN);
                    workedHours = workedHours.setScale(2, RoundingMode.CEILING);
                    // logger.debug("787: Assisted hours (Both in assigned and unassigned projects) 2===>"+workedHours);
                    EmpcntClientProjectData empcntClientProjectData = new EmpcntClientProjectData(employee,
                            companyMaster, countType, month, projectMaster, year, costCentre,
                            apportionedTimeZero, workedHours, apportionedTimeZero, workedHours);
                    if (countTypeId == 1) {
                        empOpenCntClientProjectDataList.add(empcntClientProjectData);
                    }
                    if (countTypeId == 2) {
                        empCloseCntClientProjectDataList.add(empcntClientProjectData);
                    }
                }
            } else {
                // logger.debug("Worked hours===> <168");
                BigDecimal totalUnAssingnedHours = BigDecimal.ZERO;
                BigDecimal assingnedHours = BigDecimal.ZERO;
                for (Integer key : unAssignedProjects.keySet()) {
                    // Get time spent on each project by employee id
                    Integer projectId = key;
                    // logger.debug("Project Id===>"+key);
                    BigDecimal timeByProject = unAssignedProjects.get(key);
                    BigDecimal workedHours = timeByProject.divide(deviderHour, 2, RoundingMode.HALF_EVEN);
                    workedHours = workedHours.setScale(2, RoundingMode.CEILING);
                    totalUnAssingnedHours = totalUnAssingnedHours.add(workedHours);
                    // Assign to assisted count for unAssignedProjects
                    List<ProjectMaster> projectList = projectMasterDao.findByProjectId(projectId);
                    ProjectMaster projectMaster = projectList.get(0);
                    CompanyMaster companyMaster = projectMaster.getCompanyMaster();
                    // logger.debug("811: Assisted hours (Both in assigned and unassigned projects) 2===>"+workedHours);
                    EmpcntClientProjectData empcntClientProjectData = new EmpcntClientProjectData(employee,
                            companyMaster, countType, month, projectMaster, year, costCentre,
                            apportionedTimeZero, workedHours, apportionedTimeZero, workedHours);
                    if (countTypeId == 1) {
                        empOpenCntClientProjectDataList.add(empcntClientProjectData);
                    }
                    if (countTypeId == 2) {
                        empCloseCntClientProjectDataList.add(empcntClientProjectData);
                    }
                }
                totalUnAssingnedHours = BigDecimal.ONE.subtract(totalUnAssingnedHours);
                // logger.debug("totalUnAssingnedHours===> "+totalUnAssingnedHours);
                for (Map.Entry<Integer, BigDecimal> entry : assignedProjects.entrySet()) {
                    assingnedHours = assingnedHours.add(entry.getValue());
                }
                // logger.debug("Aligned Hours===> "+assingnedHours);
                for (Integer key : assignedProjects.keySet()) {
                    Integer projectId = key;
                    BigDecimal timeByProject = assignedProjects.get(key);
                    // logger.debug("831 :projectId : timeByProject===> "+projectId+" : "+timeByProject);
                    EmpClientProjectTeamStruct mapValues = validEmployeeProjectIds.get(projectId);
                    BigDecimal averageWorkedHours = timeByProject.divide(assingnedHours, 2,
                            RoundingMode.HALF_EVEN);
                    // logger.debug("834 :averageWorkedHours : assingnedHours===> "+averageWorkedHours+" : "+assingnedHours);
                    BigDecimal actualWorkedHours = averageWorkedHours.multiply(totalUnAssingnedHours);
                    actualWorkedHours = actualWorkedHours.setScale(2, RoundingMode.CEILING);
                    // logger.debug("836: actualWorkedHours : totalUnAssingnedHours 2===>"+actualWorkedHours+" : "+totalUnAssingnedHours);
                    EmpcntClientProjectData empcntClientProjectData = new EmpcntClientProjectData(employee,
                            mapValues.getCompanyMaster(), countType, month, mapValues.getProjectMaster(), year,
                            costCentre, actualWorkedHours, assistedTimeZero, apportionedTimeZero,
                            actualWorkedHours);
                    if (countTypeId == 1) {
                        empOpenCntClientProjectDataList.add(empcntClientProjectData);
                    }
                    if (countTypeId == 2) {
                        empCloseCntClientProjectDataList.add(empcntClientProjectData);
                    }
                }
            }
        } else if (assignedProjects.isEmpty() && !unAssignedProjects.isEmpty()) {
            // logger.debug("Only in unassigned projects===>");
            if (toatlTime.compareTo(new BigDecimal(Constants.TOTAL_WORKING_HOURS)) >= 0) {
                // logger.debug(" unassigned projects Worked hours===> >=168");
                for (Integer key : unAssignedProjects.keySet()) {
                    // Get time spent on each project by employee id
                    Integer projectId = key;
                    BigDecimal timeByProject = unAssignedProjects.get(key);
                    List<ProjectMaster> projectList = projectMasterDao.findByProjectId(projectId);
                    ProjectMaster projectMaster = projectList.get(0);
                    CompanyMaster companyMaster = projectMaster.getCompanyMaster();
                    BigDecimal workedHours = timeByProject.divide(toatlTime, 2, RoundingMode.HALF_EVEN);
                    workedHours = workedHours.setScale(2, RoundingMode.CEILING);
                    // logger.debug("860: Assisted hours (Both in assigned and unassigned projects) 2===>"+workedHours);
                    EmpcntClientProjectData empcntClientProjectData = new EmpcntClientProjectData(employee,
                            companyMaster, countType, month, projectMaster, year, costCentre,
                            apportionedTimeZero, workedHours, apportionedTimeZero, workedHours);
                    if (countTypeId == 1) {
                        empOpenCntClientProjectDataList.add(empcntClientProjectData);
                    }
                    if (countTypeId == 2) {
                        empCloseCntClientProjectDataList.add(empcntClientProjectData);
                    }
                }
            } else {
                // logger.debug("unassigned projects Worked hours===> <168");
                BigDecimal totalUnAssingnedHours = BigDecimal.ZERO;
                BigDecimal assingnedHours = BigDecimal.ZERO;
                for (Integer key : unAssignedProjects.keySet()) {
                    // Get time spent on each project by employee id
                    Integer projectId = key;
                    BigDecimal timeByProject = unAssignedProjects.get(key);
                    BigDecimal workedHours = timeByProject.divide(deviderHour, 2, RoundingMode.HALF_EVEN);
                    workedHours = workedHours.setScale(2, RoundingMode.CEILING);
                    totalUnAssingnedHours = totalUnAssingnedHours.add(workedHours);
                    // Assign to assisted count for unAssignedProjects
                    List<ProjectMaster> projectList = projectMasterDao.findByProjectId(projectId);
                    ProjectMaster projectMaster = projectList.get(0);
                    CompanyMaster companyMaster = projectMaster.getCompanyMaster();
                    // logger.debug("884: Assisted hours in unassigned projects) 2===>"+workedHours);
                    EmpcntClientProjectData empcntClientProjectData = new EmpcntClientProjectData(employee,
                            companyMaster, countType, month, projectMaster, year, costCentre,
                            apportionedTimeZero, workedHours, apportionedTimeZero, workedHours);
                    if (countTypeId == 1) {
                        empOpenCntClientProjectDataList.add(empcntClientProjectData);
                    }
                    if (countTypeId == 2) {
                        empCloseCntClientProjectDataList.add(empcntClientProjectData);
                    }
                }
                // logger.debug("totalUnAssingnedHours===> "+totalUnAssingnedHours);
                if (totalUnAssingnedHours.compareTo(BigDecimal.ONE) == -1) {
                    BigDecimal remainProportion = BigDecimal.ONE.subtract(totalUnAssingnedHours);
                    getRevenueCountProportion(empOpenCntClientProjectDataList, empCloseCntClientProjectDataList,
                            employee, month, year, costCentre, countType, remainProportion, unAssignedProjects,
                            countTypeId, employeePcTagsTeamStructMap);
                }
            }
        }

    }
    // logger.debug("<====getMultipleProjectDetail END====>");
}