Example usage for java.math BigDecimal multiply

List of usage examples for java.math BigDecimal multiply

Introduction

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

Prototype

public BigDecimal multiply(BigDecimal multiplicand) 

Source Link

Document

Returns a BigDecimal whose value is (this × multiplicand), and whose scale is (this.scale() + multiplicand.scale()) .

Usage

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

private void validateForRepaymentCapacity(BigDecimal totalInstallmentAmount, BigDecimal loanAmount,
        Double repaymentCapacity, Errors errors, BigDecimal totalBalance) {
    if (repaymentCapacity == null || repaymentCapacity == 0) {
        return;/*w w  w  .j  av a 2s.c o m*/
    }
    Double calculatedRepaymentCapacity = totalBalance.multiply(CashFlowConstants.HUNDRED)
            .divide(totalInstallmentAmount, 2, BigDecimal.ROUND_HALF_UP).doubleValue();
    if (calculatedRepaymentCapacity < repaymentCapacity) {
        errors.addError(AccountConstants.REPAYMENT_CAPACITY_LESS_THAN_ALLOWED,
                new String[] { calculatedRepaymentCapacity.toString(), repaymentCapacity.toString() });
    }
}

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

private String computeDiffBetweenCumulativeAndInstallmentPercent(DateTime dateOfCashFlow, BigDecimal cashflow,
        LoanScheduleDto loanScheduleDto) {
    BigDecimal totalInstallmentForMonth = cumulativeTotalForMonth(dateOfCashFlow, loanScheduleDto);
    String value;//from w w w .  j a  v  a  2 s.  c o m
    if (cashflow.doubleValue() != 0) {
        value = String.valueOf(totalInstallmentForMonth.multiply(BigDecimal.valueOf(100)).divide(cashflow,
                AccountingRules.getDigitsAfterDecimal(), RoundingMode.HALF_UP));
    } else {
        value = "Infinity";
    }
    return value;
}

From source file:com.wso2telco.dep.reportingservice.southbound.SbHostObjectUtils.java

/**
 * Apply charges with tax./* w w w . j  a v a 2s  .  co m*/
 *
 * @param apiYear the api year
 * @param apiMonth the api month
 * @param application the application
 * @param apiName the api name
 * @param apiVersion the api version
 * @param operatorSub the operator sub
 * @param CatEntry the cat entry
 * @param rate the rate
 * @throws Exception 
 */
private static void applyChargesWithTax(String apiYear, String apiMonth, Application application,
        String apiName, String apiVersion, BillingSubscription.OperatorSubscription operatorSub,
        Map.Entry<CategoryCharge, BilledCharge> CatEntry, ChargeRate rate) throws Exception {
    String month = apiMonth;
    String year = apiYear;
    boolean isSurcharge = false;

    if (application == null) {
        throw new APIManagementException("no key generated for this api");
    }
    APIKey prodKey = getAppKey(application, APIConstants.API_KEY_TYPE_PRODUCTION);

    Set<APIRequestDTO> requestTimes = new HashSet<APIRequestDTO>();
    if (prodKey != null) {
        String api_version = apiName + ":v" + apiVersion;

        TaxDAO taxDAO = new TaxDAO();
        requestTimes = taxDAO.getAPIRequestTimesForSubscription(Short.parseShort(year), Short.parseShort(month),
                apiName, api_version, prodKey.getConsumerKey(), operatorSub.getOperator(),
                operatorSub.getOperationId(), CatEntry.getKey().getCategory(),
                CatEntry.getKey().getSubcategory());

    }

    String billCategory = CatEntry.getKey().getCategory();
    String billSubCategory = CatEntry.getKey().getSubcategory();
    BigDecimal billRate = rate.getValue();
    BigDecimal OpscomPercnt = null;

    Object SubsRate = getRateSubcategory(rate, billCategory, billSubCategory);
    if (SubsRate != null) {
        billRate = new BigDecimal((String) SubsRate);
    }

    // Surcharge value
    if (rate.getSurchargeEntity() != null) {
        billRate = new BigDecimal(rate.getSurchargeEntity().getSurchargeElementValue());
        OpscomPercnt = new BigDecimal(rate.getSurchargeEntity().getSurchargeElementOpco())
                .divide(new BigDecimal(100));
        isSurcharge = true;
    }

    TaxDAO taxDAO = new TaxDAO();
    List<Tax> taxList = taxDAO.getTaxesForTaxList(rate.getTaxList());
    BigDecimal totalCharge = BigDecimal.ZERO;
    BigDecimal totalTax = BigDecimal.ZERO;
    BigDecimal totalOpcom = BigDecimal.ZERO;
    BigDecimal totalAdscom = BigDecimal.ZERO;

    int reqCount = 0;
    for (APIRequestDTO req : requestTimes) {

        if (reqCount >= CatEntry.getValue().getCount()) {
            break;
        }

        BigDecimal charge = billRate.multiply(new BigDecimal(req.getRequestCount()));
        if (isSurcharge) {
            BigDecimal opcoCommision = billRate.multiply(OpscomPercnt);
            totalOpcom = totalOpcom.add(opcoCommision);
            totalAdscom = totalAdscom.add(charge.subtract(opcoCommision));
        } else {
            totalCharge = totalCharge.add(charge);
        }

        Date date = req.getDate();
        for (Tax tax : taxList) {

            // check if the date of payment request falls between this tax
            // validity period
            if (!date.before(tax.getEffective_from()) && !date.after(tax.getEffective_to())) {
                totalTax = totalTax.add(tax.getValue().multiply(charge));
            }
        }
        reqCount++;
    }

    CatEntry.getValue().addPrice(totalCharge);
    CatEntry.getValue().addTax(totalTax);
    CatEntry.getValue().addOpcom(totalOpcom);
    CatEntry.getValue().addAdscom(totalAdscom);

}

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

/**
 *
 *//*  w ww . ja v  a 2s.c  o  m*/
private void getRevenueCountProportion(List<EmpcntClientProjectData> empOpenCntClientProjectDataList,
        List<EmpcntClientProjectData> empCloseCntClientProjectDataList, EmployeeMaster employee, TabMonth month,
        TabYear year, CostCentre costCentre, CountClassification countType, BigDecimal remainProportion,
        Map<Integer, BigDecimal> unAssignedProjects, Integer countTypeId,
        Map<String, EmployeePcTagsTeamStruct> employeePcTagsTeamStructMap) {

    logger.debug("<====getRevenueCountProportion Start====>");
    logger.debug("unAssignedProjects:" + unAssignedProjects.size());
    // get the EmpCntPcApportionApproach for the employee
    Integer employeeId = employee.getEmployeeId();
    Integer yearId = year.getYearId();
    Integer monthId = month.getMonthId();
    String costCentreId = costCentre.getCostCentreId();
    BigDecimal deviderHour = new BigDecimal(Constants.TOTAL_WORKING_HOURS);
    Integer apportionApproach = 0;
    BigDecimal allignedTimeZero = BigDecimal.ZERO;
    BigDecimal asistededTimeZero = BigDecimal.ZERO;
    List<EmpCntPcApportionApproach> empCntPcApportionApproachList = empCntPcApportionApproachDao
            .findByYearIdMonthIdEmployeeId(yearId, monthId, employeeId);
    if (!empCntPcApportionApproachList.isEmpty()) {
        apportionApproach = empCntPcApportionApproachList.get(0).getApportionApproach();
    } else {
        return;
    }

    // logger.debug("1363 : apportionApproach===> "+apportionApproach);
    // get the EmployeePcTagsTeamStruct for the employee
    List<EmployeePcTagsTeamStruct> employeePcTagsTeamStructList = employeePcTagsTeamStructDao
            .findByYearIdMonthIdEmployeeId(yearId, monthId, employeeId);

    if (apportionApproach == 1) {
        for (EmployeePcTagsTeamStruct employeePcTagsTeamStruct : employeePcTagsTeamStructList) {
            BigDecimal count = BigDecimal.ZERO;
            Map<Integer, CollageProjectRevenue> revenueMap = new HashMap<Integer, CollageProjectRevenue>();
            Map<Integer, ProjectMaster> projectMap = new HashMap<Integer, ProjectMaster>();

            BigDecimal proportion = employeePcTagsTeamStruct.getProportion();
            String profitcentreId = employeePcTagsTeamStruct.getProfitCentre().getProfitCentreId();

            // Calculate for each profit centre
            BigDecimal pcProportion = proportion.multiply(remainProportion);

            // asissted projects on count
            List<CollageProjectRevenue> collageProjectRevenueList = collageProjectRevenueDao
                    .findByYearIdMonthIdProfitCentreIdCostCentreId(yearId, monthId, profitcentreId,
                            costCentreId);
            if (!collageProjectRevenueList.isEmpty()) {
                // Select valid project id
                for (CollageProjectRevenue proRevenue : collageProjectRevenueList) {
                    Integer projectId = proRevenue.getProjectMaster().getProjectId();
                    if (unAssignedProjects.isEmpty()) {
                        revenueMap.put(projectId, proRevenue);
                        List<ProjectMaster> projectList = projectMasterDao.findByProjectId(projectId);
                        projectMap.put(projectId, projectList.get(0));
                    } else {
                        if (unAssignedProjects.containsKey(projectId) == false) {
                            revenueMap.put(projectId, proRevenue);
                            List<ProjectMaster> projectList = projectMasterDao.findByProjectId(projectId);
                            projectMap.put(projectId, projectList.get(0));
                        }
                    }

                }

                Integer projectCount = revenueMap.size();
                count = new BigDecimal(projectCount);
                if (projectCount > 0) {
                    for (Integer key : revenueMap.keySet()) {
                        BigDecimal projectValue = BigDecimal.ONE.divide(count, 2, RoundingMode.HALF_EVEN);
                        projectValue = projectValue.multiply(pcProportion);
                        ProjectMaster projectMaster = projectMap.get(key);
                        CompanyMaster companyMaster = projectMaster.getCompanyMaster();
                        projectValue = projectValue.setScale(2, RoundingMode.CEILING);
                        // logger.debug("1406 projectValue:======>"+projectValue);
                        EmpcntClientProjectData empcntClientProjectData = new EmpcntClientProjectData(employee,
                                companyMaster, countType, month, projectMaster, year, costCentre,
                                allignedTimeZero, asistededTimeZero, projectValue, projectValue);
                        if (countTypeId == 1) {
                            empOpenCntClientProjectDataList.add(empcntClientProjectData);
                        }
                        if (countTypeId == 2) {
                            empCloseCntClientProjectDataList.add(empcntClientProjectData);
                        }
                        // copy proprotion
                        String mapId = yearId + "-" + monthId + "-" + employeeId + "-" + profitcentreId;
                        EmployeePcTagsTeamStruct employeePcTagsTeamStructCopy = employeePcTagsTeamStruct;
                        employeePcTagsTeamStructCopy.setApportionedCnt(projectValue);
                        employeePcTagsTeamStructMap.put(mapId, employeePcTagsTeamStructCopy);
                    }
                }
            }
        }
    } else if (apportionApproach == 2) {
        for (EmployeePcTagsTeamStruct employeePcTagsTeamStruct : employeePcTagsTeamStructList) {
            BigDecimal count = BigDecimal.ZERO;
            Map<Integer, BigDecimal> hoursMap = new HashMap<Integer, BigDecimal>();
            Map<Integer, Integer> companyMap = new HashMap<Integer, Integer>();

            BigDecimal proportion = employeePcTagsTeamStruct.getProportion();
            String profitcentreId = employeePcTagsTeamStruct.getProfitCentre().getProfitCentreId();
            // Calculate for each profit centre
            BigDecimal pcProportion = proportion.multiply(remainProportion);
            BigDecimal hoursSum = BigDecimal.ZERO;

            List<Object[]> objectList = executionDataDao.findByYearIdMonthIdCostCentreIdProfitCentreId(yearId,
                    monthId, costCentreId, profitcentreId);

            if (!objectList.isEmpty()) {

                for (Object[] result : objectList) {
                    Integer projectId = (Integer) result[0];
                    BigDecimal hour = (BigDecimal) result[1];
                    Integer companyId = (Integer) result[2];
                    if (unAssignedProjects.isEmpty()) {
                        hoursMap.put(projectId, hour);
                        companyMap.put(projectId, companyId);
                        hoursSum.add(hour);
                    } else {
                        if (unAssignedProjects.containsKey(projectId) == false) {
                            hoursMap.put(projectId, hour);
                            companyMap.put(projectId, companyId);
                            hoursSum.add(hour);
                        }
                    }
                }
                for (Integer projectId : hoursMap.keySet()) {
                    BigDecimal hour = hoursMap.get(projectId);
                    ProjectMaster projectMaster = new ProjectMaster();
                    projectMaster.setProjectId(projectId);
                    Integer companyId = companyMap.get(projectId);
                    CompanyMaster companyMaster = new CompanyMaster();
                    companyMaster.setCompanyId(companyId);
                    BigDecimal resultHour = hour.divide(hoursSum, 2, RoundingMode.HALF_EVEN);
                    resultHour = resultHour.multiply(pcProportion);
                    resultHour = resultHour.setScale(2, RoundingMode.CEILING);
                    // logger.debug("1462 :resultHour=====>"+resultHour);
                    EmpcntClientProjectData empcntClientProjectData = new EmpcntClientProjectData(employee,
                            companyMaster, countType, month, projectMaster, year, costCentre, asistededTimeZero,
                            allignedTimeZero, resultHour, resultHour);
                    if (countTypeId == 1) {
                        empOpenCntClientProjectDataList.add(empcntClientProjectData);
                    }
                    if (countTypeId == 2) {
                        empCloseCntClientProjectDataList.add(empcntClientProjectData);
                    }
                    // copy proprotion
                    String mapId = yearId + "-" + monthId + "-" + employeeId + "-" + profitcentreId;
                    EmployeePcTagsTeamStruct employeePcTagsTeamStructCopy = employeePcTagsTeamStruct;
                    employeePcTagsTeamStructCopy.setApportionedCnt(resultHour);
                    employeePcTagsTeamStructMap.put(mapId, employeePcTagsTeamStructCopy);
                }
            }

        }
    } else if (apportionApproach == 3) {
        for (EmployeePcTagsTeamStruct employeePcTagsTeamStruct : employeePcTagsTeamStructList) {
            Map<Integer, CollageProjectRevenue> revenueMap = new HashMap<Integer, CollageProjectRevenue>();
            Map<Integer, ProjectMaster> projectMap = new HashMap<Integer, ProjectMaster>();

            BigDecimal proportion = employeePcTagsTeamStruct.getProportion();
            BigDecimal devider = new BigDecimal(100);
            proportion = proportion.divide(devider);
            logger.debug("===========================================>" + proportion);
            String profitcentreId = employeePcTagsTeamStruct.getProfitCentre().getProfitCentreId();
            // Calculate for each profit centre
            BigDecimal pcProportion = proportion.multiply(remainProportion);
            BigDecimal revenueSum = BigDecimal.ZERO;
            List<CollageProjectRevenue> collageProjectRevenueList = collageProjectRevenueDao
                    .findByYearIdMonthIdProfitCentreIdCostCentreId(yearId, monthId, profitcentreId,
                            costCentreId);
            if (!collageProjectRevenueList.isEmpty()) {

                for (CollageProjectRevenue revenue : collageProjectRevenueList) {
                    if (unAssignedProjects.isEmpty()) {
                        Integer projectId = revenue.getProjectMaster().getProjectId();
                        logger.debug("1497 =projectId====>" + projectId);
                        revenueMap.put(projectId, revenue);
                        List<ProjectMaster> projectList = projectMasterDao.findByProjectId(projectId);
                        projectMap.put(projectId, projectList.get(0));
                        BigDecimal revenueVal = revenue.getRevenueValue();
                        // logger.debug("1503 =RevenueValue====>"+revenueVal);
                        revenueSum = revenueSum.add(revenueVal);
                    } else {
                        Integer projectId = revenue.getProjectMaster().getProjectId();
                        if (unAssignedProjects.containsKey(projectId) == false) {
                            // logger.debug("1507 =projectId====>"+projectId);
                            revenueMap.put(projectId, revenue);
                            List<ProjectMaster> projectList = projectMasterDao.findByProjectId(projectId);
                            projectMap.put(projectId, projectList.get(0));
                            BigDecimal revenueVal = revenue.getRevenueValue();
                            // logger.debug("1514 =RevenueValue====>"+revenue.getRevenueValue()
                            // +" : "+revenueVal);
                            revenueSum = revenueSum.add(revenueVal);

                        }
                    }
                }
                logger.debug("1543 =revenueSum====>" + revenueSum);
                for (Integer projectId : revenueMap.keySet()) {
                    CollageProjectRevenue collageProjectRevenue = revenueMap.get(projectId);
                    ProjectMaster projectMaster = projectMap.get(projectId);
                    CompanyMaster companyMaster = projectMaster.getCompanyMaster();
                    BigDecimal revenueValue = collageProjectRevenue.getRevenueValue();

                    logger.debug("1516 =revenueSum : revenueValue====>" + revenueSum + " : " + revenueValue);
                    revenueValue = revenueValue.divide(revenueSum, 2, RoundingMode.HALF_EVEN);
                    revenueValue = revenueValue.multiply(pcProportion);
                    revenueValue = revenueValue.setScale(2, RoundingMode.CEILING);
                    logger.debug("1515 :Aportioned Count======>" + revenueValue);

                    EmpcntClientProjectData empcntClientProjectData = new EmpcntClientProjectData(employee,
                            companyMaster, countType, month, projectMaster, year, costCentre, allignedTimeZero,
                            asistededTimeZero, revenueValue, revenueValue);
                    if (countTypeId == 1) {
                        empOpenCntClientProjectDataList.add(empcntClientProjectData);
                    }
                    if (countTypeId == 2) {
                        empCloseCntClientProjectDataList.add(empcntClientProjectData);
                    }
                    // copy proprotion
                    String mapId = yearId + "-" + monthId + "-" + employeeId + "-" + profitcentreId;
                    EmployeePcTagsTeamStruct employeePcTagsTeamStructCopy = employeePcTagsTeamStruct;
                    employeePcTagsTeamStructCopy.setApportionedCnt(revenueValue);
                    employeePcTagsTeamStructMap.put(mapId, employeePcTagsTeamStructCopy);
                }
            }

        }

    }
    // logger.debug("<====getRevenueCountProportion End====>");
}

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

/**
 * @param empcntClientProjectDataList//from   w  w  w.  j a va 2s . 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:com.ugam.collage.plus.service.people_count.impl.PeopleAccountingServiceImpl.java

/**
 * @param empcntClientProjectDataList//ww  w  .ja v a2  s.com
 * @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====>");
}

From source file:mx.edu.um.mateo.activos.dao.impl.ActivoDaoHibernate.java

private Activo deprecia(Activo activo, Date fecha) {
    // depreciacion anual
    BigDecimal porciento = activo.getPorciento();
    log.trace("Activo - MOI - Porciento: {} - {} - {}",
            new Object[] { activo.getId(), activo.getMoi(), porciento });
    BigDecimal depreciacionAnual = activo.getMoi().multiply(porciento);
    log.trace("DepreciacionAnual: {}", depreciacionAnual);

    // depreciacion mensual
    BigDecimal depreciacionMensual = BigDecimal.ZERO;
    Date fechaCompra = activo.getFechaCompra();
    if (fechaCompra.before(fecha) && days360(fechaCompra, fecha) / 30 < activo.getVidaUtil()) {
        depreciacionMensual = depreciacionAnual.divide(new BigDecimal("12"), 2, RoundingMode.HALF_UP);
    }//from w w w . ja v a  2  s.  c o m
    log.trace("DepreciacionMensual: {}", depreciacionMensual);

    // depreciacion acumulada
    BigDecimal depreciacionAcumulada;
    Long meses = 0L;
    if ((fechaCompra.before(fecha) && !activo.getInactivo())
            || (fechaCompra.before(fecha) && activo.getInactivo() && activo.getFechaInactivo().after(fecha))) {
        meses = days360(fechaCompra, fecha) / 30;
    } else if (fechaCompra.before(fecha) && activo.getInactivo() && activo.getFechaInactivo().before(fecha)) {
        meses = days360(fechaCompra, activo.getFechaInactivo()) / 30;
    }
    if (meses < activo.getVidaUtil()) {
        depreciacionAcumulada = depreciacionMensual.multiply(new BigDecimal(meses));
    } else {
        depreciacionAcumulada = activo.getMoi();
    }
    log.trace("DepreciacionAcumulada: {}", depreciacionAcumulada);

    // valor neto
    BigDecimal valorNeto = activo.getMoi().subtract(depreciacionAcumulada);
    log.trace("ValorNeto: {}", valorNeto);

    activo.setFechaDepreciacion(fecha);
    activo.setDepreciacionAnual(depreciacionAnual);
    activo.setDepreciacionMensual(depreciacionMensual);
    activo.setDepreciacionAcumulada(depreciacionAcumulada);
    activo.setValorNeto(valorNeto);

    return activo;
}

From source file:org.egov.works.web.actions.estimate.EstimatePDFGenerator.java

private PdfPTable createBudgetDetailsForEstimateTable(final AbstractEstimate estimate)
        throws DocumentException {
    try {//from  w ww . j ava2s  .  c  o  m

        final PdfPTable estBudgetDetailsTable = new PdfPTable(4);
        estBudgetDetailsTable.setWidthPercentage(75);
        estBudgetDetailsTable.setWidths(new float[] { 0.6f, 1f, 0.5f, 1f });

        BigDecimal totalGrant;
        BigDecimal budgetAvailable;
        BigDecimal balOnHand;
        BigDecimal amtAppropriated = BigDecimal.ZERO;
        BigDecimal totGrantafterMultiFactor = BigDecimal.ZERO;

        BigDecimal totalUtilizedAmt;
        BigDecimal amtAppropriatedsofar = BigDecimal.ZERO;
        worksService.getAccountdetailtypeByName("DEPOSITCODE");
        AbstractEstimateAppropriation latestAbstractEstimateAppropriation;

        if (abstractEstimateAppropriationList != null && !abstractEstimateAppropriationList.isEmpty()) {
            latestAbstractEstimateAppropriation = abstractEstimateAppropriationList
                    .get(abstractEstimateAppropriationList.size() - 1);

            if (latestAbstractEstimateAppropriation != null)
                if (estimate.getDepositCode() == null) {
                    if (latestAbstractEstimateAppropriation.getBudgetUsage().getConsumedAmount() != 0) {
                        final Department dept = getDeptFromBudgtAppropriationNo(
                                latestAbstractEstimateAppropriation.getBudgetUsage().getAppropriationnumber());
                        totalGrant = abstractEstimateService.getTotalGrantForYearAsOnDate(
                                estimate.getFinancialDetails().get(0),
                                latestAbstractEstimateAppropriation.getBudgetUsage().getFinancialYearId()
                                        .longValue(),
                                Integer.parseInt(dept.getId().toString()),
                                latestAbstractEstimateAppropriation.getBudgetUsage().getUpdatedTime());
                        final BigDecimal planningBudgetPerc = abstractEstimateService
                                .getPlanningBudgetPercentage(estimate.getFinancialDetails().get(0),
                                        latestAbstractEstimateAppropriation.getBudgetUsage()
                                                .getFinancialYearId().longValue(),
                                        Integer.parseInt(dept.getId().toString()));
                        if (planningBudgetPerc != null && planningBudgetPerc.compareTo(BigDecimal.ZERO) != 0) {
                            totGrantafterMultiFactor = totalGrant
                                    .multiply(planningBudgetPerc.divide(new BigDecimal(100)));
                            appValue = planningBudgetPerc.divide(new BigDecimal(100)).toString();
                        }

                        budgetAvailable = latestAbstractEstimateAppropriation.getBalanceAvailable();
                        balOnHand = budgetAvailable.add(new BigDecimal(
                                latestAbstractEstimateAppropriation.getBudgetUsage().getConsumedAmount()));
                        amtAppropriated = totGrantafterMultiFactor.subtract(balOnHand);
                    }
                } else if (latestAbstractEstimateAppropriation.getDepositWorksUsage().getConsumedAmount()
                        .doubleValue() != 0) {
                    totalUtilizedAmt = depositWorksUsageService.getTotalUtilizedAmountForDepositWorks(
                            latestAbstractEstimateAppropriation.getAbstractEstimate().getFinancialDetails()
                                    .get(0),
                            latestAbstractEstimateAppropriation.getDepositWorksUsage().getCreatedDate());
                    if (totalUtilizedAmt == null)
                        totalUtilizedAmt = BigDecimal.ZERO;
                    amtAppropriatedsofar = totalUtilizedAmt.subtract(
                            latestAbstractEstimateAppropriation.getDepositWorksUsage().getConsumedAmount());
                }
        }
        addRow(estBudgetDetailsTable, true, centerPara("Estimate Date"),
                centerPara(DateUtils.getFormattedDate(estimate.getEstimateDate(), "dd/MM/yyyy")),
                centerPara("Fund"), centerPara(estimate.getFinancialDetails().isEmpty() ? ""
                        : estimate.getFinancialDetails().get(0).getFund().getName()));
        if (estimate.getDepositCode() == null) {
            addRow(estBudgetDetailsTable, true, centerPara("Function "),
                    centerPara(estimate.getFinancialDetails().isEmpty() ? ""
                            : estimate.getFinancialDetails().get(0).getFunction().getName()),
                    centerPara("Budget Head"), centerPara(estimate.getFinancialDetails().isEmpty() ? ""
                            : estimate.getFinancialDetails().get(0).getBudgetGroup().getName()));
            addRow(estBudgetDetailsTable, true, centerPara("Amount Appropriated so far"),
                    centerPara(amtAppropriated == null ? "" : toCurrency(amtAppropriated.doubleValue())),
                    centerPara("Estimate Amount"),
                    centerPara(toCurrency(estimate.getTotalAmount().getValue())));
        } else {
            addRow(estBudgetDetailsTable, true, centerPara("Function "),
                    centerPara(estimate.getFinancialDetails().isEmpty() ? ""
                            : estimate.getFinancialDetails().get(0).getFunction().getName()),
                    centerPara("Deposit COA/Deposit Code"),
                    centerPara(estimate.getFinancialDetails().isEmpty() ? ""
                            : estimate.getFinancialDetails().get(0).getCoa().getGlcode().concat("-")
                                    .concat(estimate.getFinancialDetails().get(0).getCoa().getName())
                                    .concat(" / ").concat(estimate.getDepositCode().getCode())));
            addRow(estBudgetDetailsTable, true, centerPara("Amount Appropriated so far"),
                    centerPara(
                            amtAppropriatedsofar == null ? "" : toCurrency(amtAppropriatedsofar.doubleValue())),
                    centerPara("Estimate Amount"),
                    makePara(toCurrency(estimate.getTotalAmount().getValue()), Element.ALIGN_RIGHT));
        }

        return estBudgetDetailsTable;
    } catch (final Exception e) {
        throw new ApplicationRuntimeException("Exception occured while estimate details method 2 " + e);
    }
}

From source file:com.sisrni.managedbean.ProyectosMB.java

public void guardarProyecto() {
    try {//w  w  w. j  a va2 s . co m
        //validacion al guardar proyecto vacio
        if ((siBuscoPersona == false && actualizar == false)
                || (siBuscoPersonaExterna == false && actualizar == false)) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,
                    "Requerido", "Debe ingresar toda la informacin correspondiente"));
        } else {
            //guardar persona solicitante
            if ((reemplazarSol == false && siEditoPersona == true) || (reemplazarSol == false
                    && siEditoPersona == false && actualizar == false && activarBotonNuevaPersona == false)) {
                //                personaService.merge(persona);

            } else {
                String facultadArregloSol[] = facultadSelectedPojoSol.split(",");
                if (facultadArregloSol[1].equals("1")) {
                    EscuelaDepartamento escuelaselec = escuelaDepartamentoService
                            .findById(escuelaDeptoSelectedSol.getIdEscuelaDepto());
                    persona.setIdEscuelaDepto(escuelaselec);
                } else {
                    Unidad unidadSelectedSoli = unidadService.findById(Integer.parseInt(facultadArregloSol[0]));
                    persona.setIdUnidad(unidadSelectedSoli);
                }
                persona.setPasaporte("-");
                persona.setExtranjero(Boolean.FALSE);
                persona.setActivo(Boolean.TRUE);
                persona.setIdOrganismo(organismoService.findById(1));
                //guardar telefono fijo solicitante
                telefonoSolFijo.setIdPersona(persona);
                telefonoSolFijo.setIdTipoTelefono(tipoTelefonoFijo);
                persona.getTelefonoList().add(telefonoSolFijo);
                //guardar telefono celular solicitante
                telefonoSolCel.setIdPersona(persona);
                telefonoSolCel.setIdTipoTelefono(tipoTelefonoCel);
                persona.getTelefonoList().add(telefonoSolCel);
                if ((reemplazarSol == true && existeSol == 1) || actualizar == true) {
                    personaService.merge(persona);
                } else {
                    personaService.save(persona);
                }
            }
            //guardar persona Asistente
            if (tabAsis == true) {
                if ((reemplazarAsis == false && siEditoPersonaAsistente == true)
                        || (reemplazarAsis == false && siEditoPersonaAsistente == false && actualizar == false
                                && activarBotonNuevaPersonaAsistente == false)
                        || (reemplazarAsis == false && desvincularAsistente == false && actualizar == false
                                && activarBotonNuevaPersonaAsistente == false)) {
                    //                    personaService.merge(personaAsistente);
                } else {
                    String facultadArregloAsis[] = facultadSelectedPojoAsis.split(",");
                    if (facultadArregloAsis[1].equals("1")) {
                        EscuelaDepartamento escuelaselecAsis = escuelaDepartamentoService
                                .findById(escuelaDeptoSelectedAsis.getIdEscuelaDepto());
                        personaAsistente.setIdEscuelaDepto(escuelaselecAsis);
                    } else {
                        Unidad unidadSelectedAsist = unidadService
                                .findById(Integer.parseInt(facultadArregloAsis[0]));
                        personaAsistente.setIdUnidad(unidadSelectedAsist);
                    }
                    personaAsistente.setPasaporte("-");
                    personaAsistente.setExtranjero(Boolean.FALSE);
                    personaAsistente.setActivo(Boolean.TRUE);
                    //guardar telefono fijo asistente
                    telefonoAsisFijo.setIdPersona(personaAsistente);
                    telefonoAsisFijo.setIdTipoTelefono(tipoTelefonoFijo);
                    personaAsistente.getTelefonoList().add(telefonoAsisFijo);
                    //guardar telefono celular asistente
                    telefonoAsisCel.setIdPersona(personaAsistente);
                    telefonoAsisCel.setIdTipoTelefono(tipoTelefonoCel);
                    personaAsistente.getTelefonoList().add(telefonoAsisCel);
                    if ((existeAsis == 1 && reemplazarAsis == true)
                            || (actualizar == true && asistenteNull == false && existeAsis == 1)) {
                        personaService.merge(personaAsistente);
                    } else {
                        personaService.save(personaAsistente);
                    }
                }
            }
            //Guardar informacion de referente externo
            if ((reemplazarRefExt == false && siEditoPersonaExterna == true)
                    || (reemplazarRefExt == false && siEditoPersonaExterna == false && actualizar == false
                            && activarBotonNuevaPersonaExterna == false)) {
                //                personaService.merge(personaExterna);
            } else {
                Organismo organismoExt = organismoService.findById(organismoSelectedRefExt.getIdOrganismo());
                personaExterna.setIdOrganismo(organismoExt);
                personaExterna.setDuiPersona("-");
                personaExterna.setExtranjero(Boolean.TRUE);
                personaExterna.setActivo(Boolean.TRUE);
                //guardar telefono fijo persona externa
                telefonoRefextFijo.setIdPersona(personaExterna);
                telefonoRefextFijo.setIdTipoTelefono(tipoTelefonoFijo);
                personaExterna.getTelefonoList().add(telefonoRefextFijo);
                //guardar telefono fijo persona externa
                telefonoRefextCel.setIdPersona(personaExterna);
                telefonoRefextCel.setIdTipoTelefono(tipoTelefonoCel);
                personaExterna.getTelefonoList().add(telefonoRefextCel);
                if ((existeRefExt == 1 && reemplazarRefExt == true) || actualizar == true) {
                    personaService.merge(personaExterna);
                } else {
                    personaService.save(personaExterna);
                }
            }
            //Guardando datos del proyecto
            proyecto.setFechaInicio(fechaI);
            proyecto.setFechaFin(fechaF);
            SimpleDateFormat formateador = new SimpleDateFormat("dd-MM-yyyy");
            formateador.format(fechaActual);
            proyecto.setFechoIngreso(fechaActual);
            proyecto.setIdTipoProyecto(tipoProyectoService.findById(proyectoSelected.getIdTipoProyecto()));
            PropuestaConvenio propuesta;
            if (propuestaConvenioSelected.getIdPropuesta() == null) {
            } else {
                propuesta = propuestaConvenioService.findById(propuestaConvenioSelected.getIdPropuesta());
                proyecto.setIdPropuestaConvenio(propuesta);
            }
            Pais paiscooperante = paisService.findById(paisCooperanteSelected.getIdPais());
            proyecto.setIdPaisCooperante(paiscooperante);
            proyecto.setAnioGestion(Integer.parseInt(anio.trim()));
            //seteando monto
            if (tipoCambioSelected.getIdTipoCambio() == 2) {
            } else {
                TipoCambio aux = tipoCambioService.findById(tipoCambioSelected.getIdTipoCambio());
                BigDecimal d = proyecto.getMontoProyecto();
                d = d.multiply(aux.getDolaresPorUnidad());
                proyecto.setMontoProyecto(d);
            }
            //Intermedia de proyecto y area de conocimiento
            for (int i = 0; i < areaConocimientoSelected.length; i++) {
                AreaConocimiento area = areaConocimientoService
                        .findById(Integer.parseInt(areaConocimientoSelected[i]));
                if (area != null) {
                    areasConocimiento.add(area);
                }
            }
            proyecto.setAreaConocimientoList(areasConocimiento);
            // guardar organismo
            for (int i = 0; i < organismoProySelected.length; i++) {
                Organismo organismo = organismoService.findById(Integer.parseInt(organismoProySelected[i]));
                if (organismo != null) {
                    organismosProyecto.add(organismo);
                }
            }
            proyecto.setOrganismoList(organismosProyecto);
            //guardar facultades beneficiadas
            for (int i = 0; i < facultadBeneficiadaSelected.length; i++) {
                Facultad facultades = facultadService
                        .findById(Integer.parseInt(facultadBeneficiadaSelected[i]));
                if (facultades != null) {
                    facultadesBeneficiadaList.add(facultades);
                }
            }
            proyecto.setFacultadList(facultadesBeneficiadaList);
            //si selecciona facultad o unidad
            String facultadArreglo[] = facultadSelectedPojoP.split(",");
            if (facultadArreglo[1].equals("1")) {
                Facultad facSelected = facultadService.findById(Integer.parseInt(facultadArreglo[0]));
                proyecto.setIdFacultad(facSelected);
            } else {
                proyecto.setIdUnidad(Integer.parseInt(facultadArreglo[0]));
            }
            if (actualizar == true) {
                proyectoService.merge(proyecto);
                //
                if ((tabAsis == true && asistenteNull == true) || (tabAsis == true && reemplazarAsis == true)) {
                    String facultadArregloAsis[] = facultadSelectedPojoAsis.split(",");
                    if (facultadArregloAsis[1].equals("1")) {
                        EscuelaDepartamento escuelaselecAsis = escuelaDepartamentoService
                                .findById(escuelaDeptoSelectedAsis.getIdEscuelaDepto());
                        personaAsistente.setIdEscuelaDepto(escuelaselecAsis);
                    } else {
                        Unidad unidadSelectedAsist = unidadService
                                .findById(Integer.parseInt(facultadArregloAsis[0]));
                        personaAsistente.setIdUnidad(unidadSelectedAsist);
                    }
                    personaAsistente.setPasaporte("-");
                    personaAsistente.setExtranjero(Boolean.FALSE);
                    personaAsistente.setActivo(Boolean.TRUE);
                    //guardar telefono fijo asistente
                    telefonoAsisFijo.setIdPersona(personaAsistente);
                    telefonoAsisFijo.setIdTipoTelefono(tipoTelefonoFijo);
                    personaAsistente.getTelefonoList().add(telefonoAsisFijo);
                    //guardar telefono celular asistente
                    telefonoAsisCel.setIdPersona(personaAsistente);
                    telefonoAsisCel.setIdTipoTelefono(tipoTelefonoCel);
                    personaAsistente.getTelefonoList().add(telefonoAsisCel);

                    if ((existeAsis == 1 && asistenteNull == false)
                            || (actualizar == true && asistenteNull == false)) {
                        personaService.merge(personaAsistente);
                    } else {
                        personaService.save(personaAsistente);
                    }
                    //
                    //guardar en tabla intermedia persona_proyecto Asistente          
                    personaProyectoAsisPK.setIdPersona(personaAsistente.getIdPersona());
                    personaProyectoAsisPK.setIdProyecto(proyecto.getIdProyecto());
                    personaProyectoAsis.setProyecto(proyecto);
                    personaProyectoAsis.setPersona(personaAsistente);
                    personaProyectoAsis.setIdTipoPersona(tipoPersonaAsis);
                    personaProyectoAsis.setPersonaProyectoPK(personaProyectoAsisPK);
                    proyecto.getPersonaProyectoList().add(personaProyectoAsis);
                    if (asistenteNull == true) {
                        proyectoService.merge(proyecto);
                    }
                } else if ((tabAsis == true && asistenteNull == true)
                        || (buscoYEncontroAsistente == true && tabAsis == true)) {
                    //guardar en tabla intermedia persona_proyecto Asistente          
                    personaProyectoAsisPK.setIdPersona(personaAsistente.getIdPersona());
                    personaProyectoAsisPK.setIdProyecto(proyecto.getIdProyecto());
                    personaProyectoAsis.setProyecto(proyecto);
                    personaProyectoAsis.setPersona(personaAsistente);
                    personaProyectoAsis.setIdTipoPersona(tipoPersonaAsis);
                    personaProyectoAsis.setPersonaProyectoPK(personaProyectoAsisPK);
                    proyecto.getPersonaProyectoList().add(personaProyectoAsis);

                    proyectoService.merge(proyecto);
                }
                //si desvinculo el coordinador interno
                if (desvincularPersona == true) {
                    //guardar en tabla intermedia persona_proyecto de un solicitante 
                    personaProyectoPK.setIdPersona(persona.getIdPersona());
                    personaProyectoPK.setIdProyecto(proyecto.getIdProyecto());
                    personaProyecto.setProyecto(proyecto);
                    personaProyecto.setPersona(persona);
                    personaProyecto.setIdTipoPersona(tipoPersonaSol);
                    personaProyecto.setPersonaProyectoPK(personaProyectoPK);
                    proyecto.getPersonaProyectoList().add(personaProyecto);
                    proyectoService.merge(proyecto);
                    if ((existeSol == 1) || (reemplazarSol == true)) {
                        personaService.merge(persona);
                    } else {
                        personaService.save(persona);
                    }
                }
                //si desvinculo el coordinador asistente
                if (desvincularAsistente == true && tabAsis == true) {
                    //guardar en tabla intermedia persona_proyecto de un solicitante 
                    personaProyectoPK.setIdPersona(personaAsistente.getIdPersona());
                    personaProyectoPK.setIdProyecto(proyecto.getIdProyecto());
                    personaProyecto.setProyecto(proyecto);
                    personaProyecto.setPersona(personaAsistente);
                    personaProyecto.setIdTipoPersona(tipoPersonaAsis);
                    personaProyecto.setPersonaProyectoPK(personaProyectoPK);
                    proyecto.getPersonaProyectoList().add(personaProyecto);
                    proyectoService.merge(proyecto);
                    if ((existeAsis == 1) || (reemplazarAsis == true)) {
                        personaService.merge(personaAsistente);
                    } else {
                        personaService.save(persona);
                    }
                }
                if (desvincularExterna == true) {
                    //guardar en tabla intermedia persona_proyecto Referente externo
                    personaProyectoExtPK.setIdPersona(personaExterna.getIdPersona());
                    personaProyectoExtPK.setIdProyecto(proyecto.getIdProyecto());
                    personaProyectoExt.setProyecto(proyecto);
                    personaProyectoExt.setPersona(personaExterna);
                    personaProyectoExt.setIdTipoPersona(tipoPersonaRefext);
                    personaProyectoExt.setPersonaProyectoPK(personaProyectoExtPK);
                    proyecto.getPersonaProyectoList().add(personaProyectoExt);
                    proyectoService.merge(proyecto);
                    if ((existeRefExt == 1) || (reemplazarRefExt == true)) {
                        personaService.merge(personaExterna);
                    } else {
                        personaService.save(personaExterna);
                    }
                }
            } else {
                proyectoService.save(proyecto);

                //guardar en tabla intermedia persona_proyecto de un solicitante 
                personaProyectoPK.setIdPersona(persona.getIdPersona());
                personaProyectoPK.setIdProyecto(proyecto.getIdProyecto());
                personaProyecto.setProyecto(proyecto);
                personaProyecto.setPersona(persona);
                personaProyecto.setIdTipoPersona(tipoPersonaSol);
                personaProyecto.setPersonaProyectoPK(personaProyectoPK);
                proyecto.getPersonaProyectoList().add(personaProyecto);
                if (tabAsis == true) {
                    //guardar en tabla intermedia persona_proyecto Asistente          
                    personaProyectoAsisPK.setIdPersona(personaAsistente.getIdPersona());
                    personaProyectoAsisPK.setIdProyecto(proyecto.getIdProyecto());
                    personaProyectoAsis.setProyecto(proyecto);
                    personaProyectoAsis.setPersona(personaAsistente);
                    personaProyectoAsis.setIdTipoPersona(tipoPersonaAsis);
                    personaProyectoAsis.setPersonaProyectoPK(personaProyectoAsisPK);
                    proyecto.getPersonaProyectoList().add(personaProyectoAsis);
                }
                //guardar en tabla intermedia persona_proyecto Referente externo
                personaProyectoExtPK.setIdPersona(personaExterna.getIdPersona());
                personaProyectoExtPK.setIdProyecto(proyecto.getIdProyecto());
                personaProyectoExt.setProyecto(proyecto);
                personaProyectoExt.setPersona(personaExterna);
                personaProyectoExt.setIdTipoPersona(tipoPersonaRefext);
                personaProyectoExt.setPersonaProyectoPK(personaProyectoExtPK);
                proyecto.getPersonaProyectoList().add(personaProyectoExt);
                //Actualizar el proyecto
                proyectoService.merge(proyecto);
            }
            regresar();
        }
    } catch (Exception e) {
        if (actualizar) {
            FacesContext.getCurrentInstance().addMessage(null,
                    new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error!", "Error al modificar el registro."));
        } else {
            FacesContext.getCurrentInstance().addMessage(null,
                    new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error!", "Error al guardar el registro"));
        }
    }

}

From source file:org.ofbiz.accounting.invoice.InvoiceServices.java

private static BigDecimal calcHeaderAdj(Delegator delegator, GenericValue adj, String invoiceTypeId,
        String invoiceId, String invoiceItemSeqId, BigDecimal divisor, BigDecimal multiplier,
        BigDecimal baseAmount, int decimals, int rounding, GenericValue userLogin, LocalDispatcher dispatcher,
        Locale locale) {//from ww w. j a  v  a  2  s  .  com
    BigDecimal adjAmount = ZERO;
    if (adj.get("amount") != null) {

        // pro-rate the amount
        BigDecimal amount = ZERO;
        // make sure the divisor is not 0 to avoid NaN problems; just leave the amount as 0 and skip it in essense
        if (divisor.signum() != 0) {
            // multiply first then divide to avoid rounding errors
            amount = baseAmount.multiply(multiplier).divide(divisor, decimals, rounding);
        }
        if (amount.signum() != 0) {
            Map<String, Object> createInvoiceItemContext = FastMap.newInstance();
            createInvoiceItemContext.put("invoiceId", invoiceId);
            createInvoiceItemContext.put("invoiceItemSeqId", invoiceItemSeqId);
            createInvoiceItemContext.put("invoiceItemTypeId", getInvoiceItemType(delegator,
                    adj.getString("orderAdjustmentTypeId"), null, invoiceTypeId, "INVOICE_ADJ"));
            createInvoiceItemContext.put("description", adj.get("description"));
            createInvoiceItemContext.put("quantity", BigDecimal.ONE);
            createInvoiceItemContext.put("amount", amount);
            createInvoiceItemContext.put("overrideGlAccountId", adj.get("overrideGlAccountId"));
            //createInvoiceItemContext.put("productId", orderItem.get("productId"));
            //createInvoiceItemContext.put("productFeatureId", orderItem.get("productFeatureId"));
            //createInvoiceItemContext.put("uomId", "");
            //createInvoiceItemContext.put("taxableFlag", product.get("taxable"));
            createInvoiceItemContext.put("taxAuthPartyId", adj.get("taxAuthPartyId"));
            createInvoiceItemContext.put("taxAuthGeoId", adj.get("taxAuthGeoId"));
            createInvoiceItemContext.put("taxAuthorityRateSeqId", adj.get("taxAuthorityRateSeqId"));
            createInvoiceItemContext.put("userLogin", userLogin);

            Map<String, Object> createInvoiceItemResult = null;
            try {
                createInvoiceItemResult = dispatcher.runSync("createInvoiceItem", createInvoiceItemContext);
            } catch (GenericServiceException e) {
                Debug.logError(e, "Service/other problem creating InvoiceItem from order header adjustment",
                        module);
                return adjAmount;
            }
            if (ServiceUtil.isError(createInvoiceItemResult)) {
                return adjAmount;
            }

            // Create the OrderAdjustmentBilling record
            Map<String, Object> createOrderAdjustmentBillingContext = FastMap.newInstance();
            createOrderAdjustmentBillingContext.put("orderAdjustmentId", adj.getString("orderAdjustmentId"));
            createOrderAdjustmentBillingContext.put("invoiceId", invoiceId);
            createOrderAdjustmentBillingContext.put("invoiceItemSeqId", invoiceItemSeqId);
            createOrderAdjustmentBillingContext.put("amount", amount);
            createOrderAdjustmentBillingContext.put("userLogin", userLogin);

            try {
                dispatcher.runSync("createOrderAdjustmentBilling", createOrderAdjustmentBillingContext);
            } catch (GenericServiceException e) {
                return adjAmount;
            }

        }
        amount = amount.setScale(decimals, rounding);
        adjAmount = amount;
    } else if (adj.get("sourcePercentage") != null) {
        // pro-rate the amount
        BigDecimal percent = adj.getBigDecimal("sourcePercentage");
        percent = percent.divide(new BigDecimal(100), 100, rounding);
        BigDecimal amount = ZERO;
        // make sure the divisor is not 0 to avoid NaN problems; just leave the amount as 0 and skip it in essense
        if (divisor.signum() != 0) {
            // multiply first then divide to avoid rounding errors
            amount = percent.multiply(divisor);
        }
        if (amount.signum() != 0) {
            Map<String, Object> createInvoiceItemContext = FastMap.newInstance();
            createInvoiceItemContext.put("invoiceId", invoiceId);
            createInvoiceItemContext.put("invoiceItemSeqId", invoiceItemSeqId);
            createInvoiceItemContext.put("invoiceItemTypeId", getInvoiceItemType(delegator,
                    adj.getString("orderAdjustmentTypeId"), null, invoiceTypeId, "INVOICE_ADJ"));
            createInvoiceItemContext.put("description", adj.get("description"));
            createInvoiceItemContext.put("quantity", BigDecimal.ONE);
            createInvoiceItemContext.put("amount", amount);
            createInvoiceItemContext.put("overrideGlAccountId", adj.get("overrideGlAccountId"));
            //createInvoiceItemContext.put("productId", orderItem.get("productId"));
            //createInvoiceItemContext.put("productFeatureId", orderItem.get("productFeatureId"));
            //createInvoiceItemContext.put("uomId", "");
            //createInvoiceItemContext.put("taxableFlag", product.get("taxable"));
            createInvoiceItemContext.put("taxAuthPartyId", adj.get("taxAuthPartyId"));
            createInvoiceItemContext.put("taxAuthGeoId", adj.get("taxAuthGeoId"));
            createInvoiceItemContext.put("taxAuthorityRateSeqId", adj.get("taxAuthorityRateSeqId"));
            createInvoiceItemContext.put("userLogin", userLogin);

            Map<String, Object> createInvoiceItemResult = null;
            try {
                createInvoiceItemResult = dispatcher.runSync("createInvoiceItem", createInvoiceItemContext);
            } catch (GenericServiceException e) {
                Debug.logError(e, "Service/other problem creating InvoiceItem from order header adjustment",
                        module);
                return adjAmount;
            }
            if (ServiceUtil.isError(createInvoiceItemResult)) {
                return adjAmount;
            }

            // Create the OrderAdjustmentBilling record
            Map<String, Object> createOrderAdjustmentBillingContext = FastMap.newInstance();
            createOrderAdjustmentBillingContext.put("orderAdjustmentId", adj.getString("orderAdjustmentId"));
            createOrderAdjustmentBillingContext.put("invoiceId", invoiceId);
            createOrderAdjustmentBillingContext.put("invoiceItemSeqId", invoiceItemSeqId);
            createOrderAdjustmentBillingContext.put("amount", amount);
            createOrderAdjustmentBillingContext.put("userLogin", userLogin);

            try {
                dispatcher.runSync("createOrderAdjustmentBilling", createOrderAdjustmentBillingContext);
            } catch (GenericServiceException e) {
                return adjAmount;
            }

        }
        amount = amount.setScale(decimals, rounding);
        adjAmount = amount;
    }

    Debug.logInfo("adjAmount: " + adjAmount + ", divisor: " + divisor + ", multiplier: " + multiplier
            + ", invoiceTypeId: " + invoiceTypeId + ", invoiceId: " + invoiceId + ", itemSeqId: "
            + invoiceItemSeqId + ", decimals: " + decimals + ", rounding: " + rounding + ", adj: " + adj,
            module);
    return adjAmount;
}