List of usage examples for java.math BigDecimal multiply
public BigDecimal multiply(BigDecimal multiplicand)
(this × multiplicand)
, and whose scale is (this.scale() + multiplicand.scale()) . From source file:com.ugam.collage.plus.service.people_count.impl.PeopleAccountingServiceImpl.java
/** * @param yearId/*from w w w.j ava 2s .c o m*/ * @param monthId * @param costCentreId * @param empcntClientProjectDataVoList * @param empcntClientProjectDataList * @param employeeIdList * @param employeeMonthlyAssignmentCount */ private void ruleFive(Integer yearId, Integer monthId, String costCentreId, List<EmpcntClientProjectData> empOpenCntClientProjectDataList, List<EmpcntClientProjectData> empCloseCntClientProjectDataList, List<EmpcntClientProjectData> empAverageCntClientProjectDataList, List<Integer> employeeIdList, EmployeeMonthlyAssignment employeeMonthlyAssignmentCount, Integer countTypeId, Map<String, EmployeePcTagsTeamStruct> employeePcTagsTeamStructMap) { BigDecimal assistedTimeZero = BigDecimal.ZERO; BigDecimal allignedTimeZero = BigDecimal.ZERO; EmployeeMaster employeeMaster = employeeMonthlyAssignmentCount.getEmployeeMaster(); TabMonth tabMonth = employeeMonthlyAssignmentCount.getTabMonth(); TabYear tabYear = employeeMonthlyAssignmentCount.getTabYear(); CostCentre costCentre = employeeMonthlyAssignmentCount.getCostCentre(); CountClassification countClassification = new CountClassification(); countClassification.setId(countTypeId); // get the employee aligned project for opening count List<EmpClientProjectTeamStruct> empClientProjectTeamStructList = empClientProjectTeamStructDao .findByYearMonthTypeEmps(yearId, monthId, countTypeId, employeeIdList); for (EmpClientProjectTeamStruct empClientProjectTeamStruct : empClientProjectTeamStructList) { // get the EmpCntPcApportionApproach for the employee and type List<EmpCntPcApportionApproach> empCntPcApportionApproachList = empCntPcApportionApproachDao .findByYearIdMonthIdEmployeeIdTypeId(yearId, monthId, empClientProjectTeamStruct.getEmployeeMaster().getEmployeeId(), countTypeId); // get the EmployeePcTagsTeamStruct for the employee and type List<EmployeePcTagsTeamStruct> employeePcTagsTeamStructList = employeePcTagsTeamStructDao .findByyearIdMonthIdEmployeeIdTypeId(yearId, monthId, empClientProjectTeamStruct.getEmployeeMaster().getEmployeeId(), countTypeId); if (empCntPcApportionApproachList.get(0).getApportionApproach() == 1) { for (EmployeePcTagsTeamStruct employeePcTagsTeamStruct : employeePcTagsTeamStructList) { String profitCentreId = employeePcTagsTeamStruct.getProfitCentre().getProfitCentreId(); List<CollageProjectRevenue> collageProjectRevenueList = collageProjectRevenueDao .findByYearIdMonthIdProfitCentreId(yearId, monthId, profitCentreId); BigDecimal projectCount = new BigDecimal(collageProjectRevenueList.size()); for (CollageProjectRevenue collageProjectRevenue : collageProjectRevenueList) { BigDecimal projectValue = BigDecimal.ONE.divide(projectCount, 2, RoundingMode.HALF_EVEN); projectValue = projectValue.multiply(BigDecimal.ONE); projectValue = projectValue.multiply(employeePcTagsTeamStruct.getProportion()); EmpcntClientProjectData empcntClientProjectData = new EmpcntClientProjectData( employeeMaster, collageProjectRevenue.getProjectMaster().getCompanyMaster(), countClassification, tabMonth, collageProjectRevenue.getProjectMaster(), tabYear, costCentre, allignedTimeZero, assistedTimeZero, projectValue, projectValue); if (countTypeId == 1) { empOpenCntClientProjectDataList.add(empcntClientProjectData); } if (countTypeId == 2) { empCloseCntClientProjectDataList.add(empcntClientProjectData); } // copy proprotion String mapId = yearId + "-" + monthId + "-" + employeeMaster.getEmployeeId() + "-" + profitCentreId; EmployeePcTagsTeamStruct employeePcTagsTeamStructCopy = employeePcTagsTeamStruct; employeePcTagsTeamStructCopy.setApportionedCnt(projectValue); employeePcTagsTeamStructMap.put(mapId, employeePcTagsTeamStructCopy); } } } else if (empCntPcApportionApproachList.get(0).getApportionApproach() == 2) { for (EmployeePcTagsTeamStruct employeePcTagsTeamStruct : employeePcTagsTeamStructList) { String profitCentreId = employeePcTagsTeamStruct.getProfitCentre().getProfitCentreId(); List<Object[]> objectList = executionDataDao.findByYearIdMonthIdCostCentreIdProfitCentreId( yearId, monthId, costCentreId, profitCentreId); BigDecimal hoursSum = BigDecimal.ZERO; for (Object[] hours : objectList) { BigDecimal hour = (BigDecimal) hours[1]; hoursSum.add(hour); } for (Object[] result : objectList) { Integer projectId = (Integer) result[0]; BigDecimal hour = (BigDecimal) result[1]; Integer companyId = (Integer) result[2]; ProjectMaster projectMaster = new ProjectMaster(); projectMaster.setProjectId(projectId); CompanyMaster companyMaster = new CompanyMaster(); companyMaster.setCompanyId(companyId); BigDecimal resultHour = hour.divide(hoursSum, 2, RoundingMode.HALF_EVEN); resultHour = resultHour.multiply(BigDecimal.ONE); resultHour = resultHour.multiply(employeePcTagsTeamStruct.getProportion()); EmpcntClientProjectData empcntClientProjectData = new EmpcntClientProjectData( employeeMaster, companyMaster, countClassification, tabMonth, projectMaster, tabYear, costCentre, allignedTimeZero, assistedTimeZero, resultHour, resultHour); if (countTypeId == 1) { empOpenCntClientProjectDataList.add(empcntClientProjectData); } if (countTypeId == 2) { empCloseCntClientProjectDataList.add(empcntClientProjectData); } // copy proprotion String mapId = yearId + "-" + monthId + "-" + employeeMaster.getEmployeeId() + "-" + profitCentreId; EmployeePcTagsTeamStruct employeePcTagsTeamStructCopy = employeePcTagsTeamStruct; employeePcTagsTeamStructCopy.setApportionedCnt(resultHour); employeePcTagsTeamStructMap.put(mapId, employeePcTagsTeamStructCopy); } } } else if (empCntPcApportionApproachList.get(0).getApportionApproach() == 3) { for (EmployeePcTagsTeamStruct employeePcTagsTeamStruct : employeePcTagsTeamStructList) { String profitCentreId = employeePcTagsTeamStruct.getProfitCentre().getProfitCentreId(); List<CollageProjectRevenue> collageProjectRevenueList = collageProjectRevenueDao .findByYearIdMonthIdProfitCentreId(yearId, monthId, profitCentreId); BigDecimal revenueSum = BigDecimal.ZERO; for (CollageProjectRevenue val : collageProjectRevenueList) { revenueSum.add(val.getRevenueValue()); } for (CollageProjectRevenue collageProjectRevenue : collageProjectRevenueList) { BigDecimal revenueValue = collageProjectRevenue.getRevenueValue().divide(revenueSum, 2, RoundingMode.HALF_EVEN); revenueValue = revenueValue.multiply(BigDecimal.ONE); revenueValue = revenueValue.multiply(employeePcTagsTeamStruct.getProportion()); EmpcntClientProjectData empcntClientProjectData = new EmpcntClientProjectData( employeeMaster, collageProjectRevenue.getProjectMaster().getCompanyMaster(), countClassification, tabMonth, collageProjectRevenue.getProjectMaster(), tabYear, costCentre, allignedTimeZero, assistedTimeZero, revenueValue, revenueValue); if (countTypeId == 1) { empOpenCntClientProjectDataList.add(empcntClientProjectData); } if (countTypeId == 2) { empCloseCntClientProjectDataList.add(empcntClientProjectData); } // copy proprotion String mapId = yearId + "-" + monthId + "-" + employeeMaster.getEmployeeId() + "-" + profitCentreId; EmployeePcTagsTeamStruct employeePcTagsTeamStructCopy = employeePcTagsTeamStruct; employeePcTagsTeamStructCopy.setApportionedCnt(revenueValue); employeePcTagsTeamStructMap.put(mapId, employeePcTagsTeamStructCopy); } } } } }
From source file:com.cloud.storage.StorageManagerImpl.java
@Override public void createCapacityEntry(StoragePoolVO storagePool, short capacityType, long allocated) { SearchCriteria<CapacityVO> capacitySC = _capacityDao.createSearchCriteria(); capacitySC.addAnd("hostOrPoolId", SearchCriteria.Op.EQ, storagePool.getId()); capacitySC.addAnd("dataCenterId", SearchCriteria.Op.EQ, storagePool.getDataCenterId()); capacitySC.addAnd("capacityType", SearchCriteria.Op.EQ, capacityType); List<CapacityVO> capacities = _capacityDao.search(capacitySC, null); long totalOverProvCapacity; if (storagePool.getPoolType().supportsOverProvisioning()) { // All this is for the inaccuracy of floats for big number multiplication. BigDecimal overProvFactor = getStorageOverProvisioningFactor(storagePool.getId()); totalOverProvCapacity = overProvFactor.multiply(new BigDecimal(storagePool.getCapacityBytes())) .longValue();/*from w ww. ja v a 2 s . c om*/ s_logger.debug("Found storage pool " + storagePool.getName() + " of type " + storagePool.getPoolType().toString() + " with overprovisioning factor " + overProvFactor.toString()); s_logger.debug("Total over provisioned capacity calculated is " + overProvFactor + " * " + storagePool.getCapacityBytes()); } else { s_logger.debug("Found storage pool " + storagePool.getName() + " of type " + storagePool.getPoolType().toString()); totalOverProvCapacity = storagePool.getCapacityBytes(); } s_logger.debug("Total over provisioned capacity of the pool " + storagePool.getName() + " id: " + storagePool.getId() + " is " + totalOverProvCapacity); CapacityState capacityState = CapacityState.Enabled; if (storagePool.getScope() == ScopeType.ZONE) { DataCenterVO dc = ApiDBUtils.findZoneById(storagePool.getDataCenterId()); AllocationState allocationState = dc.getAllocationState(); capacityState = (allocationState == AllocationState.Disabled) ? CapacityState.Disabled : CapacityState.Enabled; } else { if (storagePool.getClusterId() != null) { ClusterVO cluster = ApiDBUtils.findClusterById(storagePool.getClusterId()); if (cluster != null) { AllocationState allocationState = _configMgr.findClusterAllocationState(cluster); capacityState = (allocationState == AllocationState.Disabled) ? CapacityState.Disabled : CapacityState.Enabled; } } } if (storagePool.getScope() == ScopeType.HOST) { List<StoragePoolHostVO> stoargePoolHostVO = _storagePoolHostDao.listByPoolId(storagePool.getId()); if (stoargePoolHostVO != null && !stoargePoolHostVO.isEmpty()) { HostVO host = _hostDao.findById(stoargePoolHostVO.get(0).getHostId()); if (host != null) { capacityState = (host.getResourceState() == ResourceState.Disabled) ? CapacityState.Disabled : CapacityState.Enabled; } } } if (capacities.size() == 0) { CapacityVO capacity = new CapacityVO(storagePool.getId(), storagePool.getDataCenterId(), storagePool.getPodId(), storagePool.getClusterId(), allocated, totalOverProvCapacity, capacityType); capacity.setCapacityState(capacityState); _capacityDao.persist(capacity); } else { CapacityVO capacity = capacities.get(0); if (capacity.getTotalCapacity() != totalOverProvCapacity || allocated != capacity.getUsedCapacity() || capacity.getCapacityState() != capacityState) { capacity.setTotalCapacity(totalOverProvCapacity); capacity.setUsedCapacity(allocated); capacity.setCapacityState(capacityState); _capacityDao.update(capacity.getId(), capacity); } } s_logger.debug("Successfully set Capacity - " + totalOverProvCapacity + " for capacity type - " + capacityType + " , DataCenterId - " + storagePool.getDataCenterId() + ", HostOrPoolId - " + storagePool.getId() + ", PodId " + storagePool.getPodId()); }
From source file:org.mifos.accounts.servicefacade.WebTierAccountServiceFacade.java
@Override public void applyGroupCharge(Map<Integer, String> idsAndValues, Short chargeId, boolean isPenaltyType) { MifosUser user = (MifosUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); UserContext userContext = toUserContext(user); TreeMap<Integer, String> idsAndValueAsTreeMap = new TreeMap<Integer, String>(idsAndValues); try {//from w ww. j a v a 2 s .c o m AccountBO parentAccount = ((LoanBO) legacyAccountDao.getAccount( new AccountBusinessService().getAccount(idsAndValueAsTreeMap.firstKey()).getAccountId())) .getParentAccount(); BigDecimal parentAmount = ((LoanBO) parentAccount).getLoanAmount().getAmount(); BigDecimal membersAmount = BigDecimal.ZERO; for (Map.Entry<Integer, String> entry : idsAndValues.entrySet()) { LoanBO individual = loanDao.findById(entry.getKey()); Double chargeAmount = Double.valueOf(entry.getValue()); if (chargeAmount.equals(0.0)) { continue; } membersAmount = membersAmount.add(individual.getLoanAmount().getAmount()); individual.updateDetails(userContext); if (isPenaltyType && !chargeId.equals(Short.valueOf(AccountConstants.MISC_PENALTY))) { PenaltyBO penalty = this.penaltyDao.findPenaltyById(chargeId.intValue()); individual.addAccountPenalty(new AccountPenaltiesEntity(individual, penalty, chargeAmount)); } else { individual.applyCharge(chargeId, chargeAmount); } } boolean isRateCharge = false; if (!chargeId.equals(Short.valueOf(AccountConstants.MISC_FEES)) && !chargeId.equals(Short.valueOf(AccountConstants.MISC_PENALTY))) { if (isPenaltyType) { PenaltyBO penalty = this.penaltyDao.findPenaltyById(chargeId.intValue()); if (penalty instanceof RatePenaltyBO) { isRateCharge = true; } } else { FeeBO fee = feeDao.findById(chargeId); if (fee.getFeeType().equals(RateAmountFlag.RATE)) { isRateCharge = true; } } } Double chargeAmount = null; if (!isRateCharge) { chargeAmount = sumCharge(idsAndValues); } else { chargeAmount = Double.valueOf(idsAndValueAsTreeMap.firstEntry().getValue()); BigDecimal chargeAmountBig = new BigDecimal(chargeAmount); membersAmount = membersAmount.multiply(chargeAmountBig); int scale = Money.getInternalPrecision(); chargeAmountBig = membersAmount.divide(parentAmount, scale, RoundingMode.HALF_EVEN); chargeAmount = chargeAmountBig.doubleValue(); } parentAccount.updateDetails(userContext); CustomerLevel customerLevel = null; if (parentAccount.isCustomerAccount()) { customerLevel = parentAccount.getCustomer().getLevel(); } if (parentAccount.getPersonnel() != null) { checkPermissionForApplyCharges(parentAccount.getType(), customerLevel, userContext, parentAccount.getOffice().getOfficeId(), parentAccount.getPersonnel().getPersonnelId()); } else { checkPermissionForApplyCharges(parentAccount.getType(), customerLevel, userContext, parentAccount.getOffice().getOfficeId(), userContext.getId()); } this.transactionHelper.startTransaction(); if (isPenaltyType && parentAccount instanceof LoanBO) { PenaltyBO penalty = this.penaltyDao.findPenaltyById(chargeId.intValue()); ((LoanBO) parentAccount) .addAccountPenalty(new AccountPenaltiesEntity(parentAccount, penalty, chargeAmount)); } else { parentAccount.applyCharge(chargeId, chargeAmount); } this.transactionHelper.commitTransaction(); } catch (ServiceException e) { this.transactionHelper.rollbackTransaction(); throw new MifosRuntimeException(e); } catch (ApplicationException e) { this.transactionHelper.rollbackTransaction(); throw new BusinessRuleException(e.getKey(), e); } }
From source file:org.kuali.kpme.tklm.leave.accrual.service.AccrualServiceImpl.java
@SuppressWarnings("unchecked") @Override//from w w w . ja v a 2 s . co m public void runAccrual(String principalId, DateTime startDate, DateTime endDate, boolean recordRanData, String runAsPrincipalId) { List<LeaveBlock> accrualLeaveBlocks = new ArrayList<LeaveBlock>(); Map<String, BigDecimal> accumulatedAccrualCatToAccrualAmounts = new HashMap<String, BigDecimal>(); Map<String, BigDecimal> accumulatedAccrualCatToNegativeAccrualAmounts = new HashMap<String, BigDecimal>(); if (startDate != null && endDate != null) { LOG.info("AccrualServiceImpl.runAccrual() STARTED with Principal: " + principalId + " Start: " + startDate.toString() + " End: " + endDate.toString()); } if (startDate.isAfter(endDate)) { LOG.error("Start Date " + startDate.toString() + " should not be later than End Date " + endDate.toString()); return; // throw new RuntimeException("Start Date " + startDate.toString() + " should not be later than End Date " + endDate.toString()); } //Inactivate all previous accrual-generated entries for this span of time deactivateOldAccruals(principalId, startDate, endDate, runAsPrincipalId); //Build a rate range aggregate with appropriate information for this period of time detailing Rate Ranges for job //entries for this range of time RateRangeAggregate rrAggregate = this.buildRateRangeAggregate(principalId, startDate, endDate); PrincipalHRAttributes phra = null; PrincipalHRAttributes endPhra = null; LeavePlanContract lp = null; List<? extends AccrualCategoryContract> accrCatList = null; //Iterate over every day in span DateTime currentDate = startDate; while (!currentDate.isAfter(endDate)) { RateRange currentRange = rrAggregate.getRateOnDate(currentDate); if (currentRange == null) { currentDate = currentDate.plusDays(1); continue; } phra = currentRange.getPrincipalHRAttributes(); if (phra == null || currentDate.toLocalDate().isBefore(phra.getServiceLocalDate())) { currentDate = currentDate.plusDays(1); continue; } // use the effectiveDate of this principalHRAttribute to search for inactive entries for this principalId // If there's an inactive entry, it means the job is going to end on the effectiveDate of the inactive entry // used for minimumPercentage and proration endPhra = currentRange.getEndPrincipalHRAttributes(); if (endPhra != null && currentDate.toLocalDate().isAfter(endPhra.getEffectiveLocalDate())) { currentDate = currentDate.plusDays(1); continue; } // if the date range is before the service date of this employee, do not calculate accrual if (endDate.toLocalDate().isBefore(phra.getServiceLocalDate())) { return; } lp = currentRange.getLeavePlan(); accrCatList = currentRange.getAcList(); // if the employee status is changed, create an empty leave block on the currentDate if (currentRange.isStatusChanged()) { this.createEmptyLeaveBlockForStatusChange(principalId, accrualLeaveBlocks, currentDate.toLocalDate()); } // if no job found for the employee on the currentDate, do nothing if (CollectionUtils.isEmpty(currentRange.getJobs())) { currentDate = currentDate.plusDays(1); continue; } BigDecimal ftePercentage = currentRange.getAccrualRatePercentageModifier(); BigDecimal totalOfStandardHours = currentRange.getStandardHours(); boolean fullFteGranted = false; for (AccrualCategoryContract anAC : accrCatList) { if (anAC == null) continue; fullFteGranted = false; if (!currentDate.toLocalDate().isBefore(phra.getEffectiveLocalDate()) && !anAC.getAccrualEarnInterval().equals("N")) { // "N" means no accrual boolean prorationFlag = this.isProrationFlag(anAC.getProration()); // get the accrual rule AccrualCategoryRuleContract currentAcRule = this .getRuleForAccrualCategory(currentRange.getAcRuleList(), anAC); // check if accrual category rule changed if (currentAcRule != null) { DateTime ruleStartDate = getRuleStartDate(currentAcRule.getServiceUnitOfTime(), phra.getServiceLocalDate(), currentAcRule.getStart()); DateTime previousIntervalDay = this.getPrevIntervalDate(ruleStartDate, anAC.getAccrualEarnInterval(), phra.getPayCalendar(), rrAggregate.getCalEntryMap()); DateTime nextIntervalDay = this.getNextIntervalDate(ruleStartDate, anAC.getAccrualEarnInterval(), phra.getPayCalendar(), rrAggregate.getCalEntryMap()); RateRangeContract previousRange = rrAggregate.getRateOnDate(previousIntervalDay); AccrualCategoryRuleContract previousAcRule = null; if (previousRange != null) { previousAcRule = this.getRuleForAccrualCategory(previousRange.getAcRuleList(), anAC); } // rule changed if (previousAcRule != null && !previousAcRule.getLmAccrualCategoryRuleId() .equals(currentAcRule.getLmAccrualCategoryRuleId())) { if (currentDate.toLocalDate().compareTo(previousIntervalDay.toLocalDate()) >= 0 && currentDate.toLocalDate().compareTo(nextIntervalDay.toLocalDate()) <= 0) { int workDaysInBetween = TKUtils.getWorkDays(ruleStartDate, nextIntervalDay); boolean minReachedFlag = minimumPercentageReachedForPayPeriod( anAC.getMinPercentWorked(), anAC.getAccrualEarnInterval(), workDaysInBetween, nextIntervalDay, phra.getPayCalendar(), rrAggregate.getCalEntryMap()); if (prorationFlag) { if (minReachedFlag) { // min reached, proration=true, rule changed, then use actual work days of currentRule for calculation // so nothing special needs to be done here } else { //minimum percentage NOT reached, proration = true, rule changed, then use previousRule for the whole pay period currentAcRule = previousAcRule; } } else { if (minReachedFlag) { // min reached, proration = false, rule changed, then accrual the whole fte of the new rule for this pay interval accumulatedAccrualCatToAccrualAmounts.put(anAC.getLmAccrualCategoryId(), currentAcRule.getAccrualRate()); fullFteGranted = true; } else { //min NOT reached, proration = false, rule changed, then accrual the whole fte of the previous rule for this pay interval accumulatedAccrualCatToAccrualAmounts.put(anAC.getLmAccrualCategoryId(), previousAcRule.getAccrualRate()); fullFteGranted = true; } } } } } // check for first pay period of principal attributes considering minimum percentage and proration DateTime firstIntervalDate = this.getNextIntervalDate( phra.getEffectiveLocalDate().toDateTimeAtStartOfDay(), anAC.getAccrualEarnInterval(), phra.getPayCalendar(), rrAggregate.getCalEntryMap()); if (!currentDate.toLocalDate().isBefore(phra.getEffectiveLocalDate()) && !currentDate.toLocalDate().isAfter(firstIntervalDate.toLocalDate())) { int workDaysInBetween = TKUtils.getWorkDays( phra.getEffectiveLocalDate().toDateTimeAtStartOfDay(), firstIntervalDate); boolean minReachedFlag = minimumPercentageReachedForPayPeriod(anAC.getMinPercentWorked(), anAC.getAccrualEarnInterval(), workDaysInBetween, firstIntervalDate, phra.getPayCalendar(), rrAggregate.getCalEntryMap()); if (prorationFlag) { if (minReachedFlag) { // minimum reached, proration = true, first pay period, then use actual work days of currentRule for calculation // so nothing special needs to be done here } else { // min NOT reached, proration = true, first pay period, then no accrual for this pay period accumulatedAccrualCatToAccrualAmounts.remove(anAC.getLmAccrualCategoryId()); accumulatedAccrualCatToNegativeAccrualAmounts.remove(anAC.getLmAccrualCategoryId()); continue; } } else { if (minReachedFlag && currentAcRule != null) { // minimum reached, proration = false, first pay period, then accrual the whole fte of current AC rule for this pay interval accumulatedAccrualCatToAccrualAmounts.put(anAC.getLmAccrualCategoryId(), currentAcRule.getAccrualRate()); fullFteGranted = true; } else { // min NOT reached, proration = false, first pay period, then no accrual for this pay period accumulatedAccrualCatToAccrualAmounts.remove(anAC.getLmAccrualCategoryId()); accumulatedAccrualCatToNegativeAccrualAmounts.remove(anAC.getLmAccrualCategoryId()); continue; } } } // last accrual interval if (endPhra != null) { // the employment is going to end on the effectiveDate of enPhra DateTime previousIntervalDate = this.getPrevIntervalDate( endPhra.getEffectiveLocalDate().toDateTimeAtStartOfDay(), anAC.getAccrualEarnInterval(), phra.getPayCalendar(), rrAggregate.getCalEntryMap()); // currentDate is between the end date and the last interval date, so we are in the last interval if (!currentDate.toLocalDate().isAfter(endPhra.getEffectiveLocalDate()) && currentDate.toLocalDate().isAfter(previousIntervalDate.toLocalDate())) { DateTime lastIntervalDate = this.getNextIntervalDate( endPhra.getEffectiveLocalDate().toDateTimeAtStartOfDay(), anAC.getAccrualEarnInterval(), phra.getPayCalendar(), rrAggregate.getCalEntryMap()); int workDaysInBetween = TKUtils.getWorkDays(previousIntervalDate, endPhra.getEffectiveLocalDate().toDateTimeAtStartOfDay()); boolean minReachedFlag = minimumPercentageReachedForPayPeriod( anAC.getMinPercentWorked(), anAC.getAccrualEarnInterval(), workDaysInBetween, lastIntervalDate, phra.getPayCalendar(), rrAggregate.getCalEntryMap()); if (prorationFlag) { if (minReachedFlag) { // minimum reached, proration = true, first pay period, then use actual work days of currentRule for calculation // so nothing special needs to be done here } else { // min NOT reached, proration = true, first pay period, then no accrual for this pay period accumulatedAccrualCatToAccrualAmounts.remove(anAC.getLmAccrualCategoryId()); accumulatedAccrualCatToNegativeAccrualAmounts .remove(anAC.getLmAccrualCategoryId()); continue; } } else { if (minReachedFlag) { // minimum reached, proration = false, first pay period, then accrual the whole fte of current AC rule for this pay interval accumulatedAccrualCatToAccrualAmounts.put(anAC.getLmAccrualCategoryId(), currentAcRule.getAccrualRate()); fullFteGranted = true; } else { // min NOT reached, proration = false, first pay period, then no accrual for this pay period accumulatedAccrualCatToAccrualAmounts.remove(anAC.getLmAccrualCategoryId()); accumulatedAccrualCatToNegativeAccrualAmounts .remove(anAC.getLmAccrualCategoryId()); continue; } } } } if (currentAcRule == null) { accumulatedAccrualCatToAccrualAmounts.remove(anAC.getLmAccrualCategoryId()); accumulatedAccrualCatToNegativeAccrualAmounts.remove(anAC.getLmAccrualCategoryId()); continue; } //Fetch the accrual rate based on rate range for today(Rate range is the accumulated list of jobs and accrual rate for today) BigDecimal accrualRate = currentAcRule.getAccrualRate(); int numberOfWorkDays = this.getWorkDaysInInterval(currentDate, anAC.getAccrualEarnInterval(), phra.getPayCalendar(), rrAggregate.getCalEntryMap()); BigDecimal dayRate = numberOfWorkDays > 0 ? accrualRate.divide(new BigDecimal(numberOfWorkDays), 6, BigDecimal.ROUND_HALF_UP) : new BigDecimal(0); //get not eligible for accrual hours based on leave block on this day BigDecimal noAccrualHours = getNotEligibleForAccrualHours(principalId, currentDate.toLocalDate()); if (noAccrualHours != null && noAccrualHours.compareTo(BigDecimal.ZERO) != 0 && totalOfStandardHours.compareTo(BigDecimal.ZERO) != 0) { BigDecimal dayHours = totalOfStandardHours.divide(new BigDecimal(5), 6, BigDecimal.ROUND_HALF_UP); // if leave hours on the day is more than the standard hours, use the standard hour to calculate the adjustment if (noAccrualHours.abs().compareTo(dayHours.abs()) == 1) { noAccrualHours = dayHours.abs().negate(); } BigDecimal noAccrualRate = dayRate.multiply(noAccrualHours.divide(dayHours)); this.calculateHours(anAC.getLmAccrualCategoryId(), ftePercentage, noAccrualRate, accumulatedAccrualCatToNegativeAccrualAmounts); } // only accrual on work days if (!TKUtils.isWeekend(currentDate) && !fullFteGranted) { //Add to total accumulatedAccrualCatToAccrualAmounts //use rule and ftePercentage to calculate the hours this.calculateHours(anAC.getLmAccrualCategoryId(), ftePercentage, dayRate, accumulatedAccrualCatToAccrualAmounts); } //Determine if we are at the accrual earn interval in the span, if so add leave block for accumulated accrual amount to list //and reset accumulatedAccrualCatToAccrualAmounts and accumulatedAccrualCatToNegativeAccrualAmounts for this accrual category if (this.isDateAnIntervalDate(currentDate.toLocalDate(), anAC.getAccrualEarnInterval(), phra.getPayCalendar(), rrAggregate.getCalEntryMap())) { BigDecimal acHours = accumulatedAccrualCatToAccrualAmounts .get(anAC.getLmAccrualCategoryId()); if (acHours != null) { createLeaveBlock(principalId, accrualLeaveBlocks, currentDate.toLocalDate(), acHours, anAC, null, true, currentRange.getLeaveCalendarDocumentId(), null); accumulatedAccrualCatToAccrualAmounts.remove(anAC.getLmAccrualCategoryId()); // reset accumulatedAccrualCatToAccrualAmounts fullFteGranted = false; } BigDecimal adjustmentHours = accumulatedAccrualCatToNegativeAccrualAmounts .get(anAC.getLmAccrualCategoryId()); if (adjustmentHours != null && adjustmentHours.compareTo(BigDecimal.ZERO) != 0) { // do not create leave block if the ajustment amount is 0 createLeaveBlock(principalId, accrualLeaveBlocks, currentDate.toLocalDate(), adjustmentHours, anAC, null, false, currentRange.getLeaveCalendarDocumentId(), null); accumulatedAccrualCatToNegativeAccrualAmounts.remove(anAC.getLmAccrualCategoryId()); // reset accumulatedAccrualCatToNegativeAccrualAmounts } } } } //Determine if today is a system scheduled time off and accrue holiday if so. SystemScheduledTimeOffContract ssto = currentRange.getSysScheTimeOff(); if (ssto != null) { AccrualCategory anAC = HrServiceLocator.getAccrualCategoryService() .getAccrualCategory(ssto.getAccrualCategory(), ssto.getEffectiveLocalDate()); if (anAC == null) { LOG.error("Cannot find Accrual Category for system scheduled time off " + ssto.getLmSystemScheduledTimeOffId()); return; // throw new RuntimeException("Cannot find Accrual Category for system scheduled time off " + ssto.getLmSystemScheduledTimeOffId()); } BigDecimal hrs = ssto.getAmountofTime().multiply(ftePercentage); // system scheduled time off leave block createLeaveBlock(principalId, accrualLeaveBlocks, currentDate.toLocalDate(), hrs, anAC, ssto.getLmSystemScheduledTimeOffId(), true, currentRange.getLeaveCalendarDocumentId(), null); // we only need to create usage leave block for ssto if there is a scheduled time off date if (ssto.getScheduledTimeOffDate() != null) { // usage leave block with negative amount. Assign primary leave assignment information to ssto usage leave block createLeaveBlock(principalId, accrualLeaveBlocks, ssto.getScheduledTimeOffLocalDate(), hrs.negate(), anAC, ssto.getLmSystemScheduledTimeOffId(), true, currentRange.getLeaveCalendarDocumentId(), currentRange.getPrimaryLeaveAssignmentId()); } } // if today is the last day of the employment, create leave blocks if there's any hours available if (endPhra != null && currentDate.toLocalDate().equals(endPhra.getEffectiveLocalDate())) { // accumulated accrual amount if (!accumulatedAccrualCatToAccrualAmounts.isEmpty()) { for (Map.Entry<String, BigDecimal> entry : accumulatedAccrualCatToAccrualAmounts.entrySet()) { if (entry.getValue() != null && entry.getValue().compareTo(BigDecimal.ZERO) != 0) { AccrualCategory anAC = HrServiceLocator.getAccrualCategoryService() .getAccrualCategory(entry.getKey()); createLeaveBlock(principalId, accrualLeaveBlocks, currentDate.toLocalDate(), entry.getValue(), anAC, null, true, currentRange.getLeaveCalendarDocumentId(), null); } } accumulatedAccrualCatToAccrualAmounts = new HashMap<String, BigDecimal>(); // reset accumulatedAccrualCatToAccrualAmounts } // negative/adjustment accrual amount if (!accumulatedAccrualCatToNegativeAccrualAmounts.isEmpty()) { for (Map.Entry<String, BigDecimal> entry : accumulatedAccrualCatToNegativeAccrualAmounts .entrySet()) { if (entry.getValue() != null && entry.getValue().compareTo(BigDecimal.ZERO) != 0) { AccrualCategory anAC = HrServiceLocator.getAccrualCategoryService() .getAccrualCategory(entry.getKey()); createLeaveBlock(principalId, accrualLeaveBlocks, currentDate.toLocalDate(), entry.getValue(), anAC, null, true, currentRange.getLeaveCalendarDocumentId(), null); } } accumulatedAccrualCatToNegativeAccrualAmounts = new HashMap<String, BigDecimal>(); // reset accumulatedAccrualCatToNegativeAccrualAmounts } phra = null; // reset principal attribute so new value will be retrieved endPhra = null; // reset end principal attribute so new value will be retrieved } currentDate = currentDate.plusDays(1); } //Save accrual leave blocks at the very end LmServiceLocator.getLeaveBlockService().saveLeaveBlocks(accrualLeaveBlocks); // record timestamp of this accrual run in database if (recordRanData) { LmServiceLocator.getPrincipalAccrualRanService().updatePrincipalAccrualRanInfo(principalId); } }
From source file:org.kuali.ole.select.document.service.impl.OlePaymentRequestServiceImpl.java
/** * @see org.kuali.ole.select.document.service.OlePaymentRequestService#calculateProrateItemSurcharge(org.kuali.ole.select.document.OlePaymentRequestDocument) *//*w w w. jav a2 s . c o m*/ @Override public void calculateProrateItemSurcharge(OlePaymentRequestDocument paymentRequestDocument) { LOG.debug("Inside Calculation for ProrateItemSurcharge"); // KualiDecimal addChargeItem = paymentRequestDocument.getGrandPreTaxTotalExcludingDiscount().subtract(paymentRequestDocument.getLineItemPreTaxTotal()); BigDecimal addChargeItem = BigDecimal.ZERO; List<OlePaymentRequestItem> item = paymentRequestDocument.getItems(); for (OlePaymentRequestItem items : item) { if (!items.getItemType().isQuantityBasedGeneralLedgerIndicator() && !items.getItemTypeCode() .equalsIgnoreCase(PurapConstants.ItemTypeCodes.ITEM_TYPE_PMT_TERMS_DISCOUNT_CODE) && items.getItemUnitPrice() != null) { addChargeItem = addChargeItem.add(items.getItemUnitPrice()); } } List<BigDecimal> newUnitPriceList = new ArrayList<BigDecimal>(); BigDecimal totalExtPrice = new BigDecimal(0); BigDecimal newUnitPrice = new BigDecimal(0); BigDecimal extPrice = new BigDecimal(0); BigDecimal unitPricePercent = new BigDecimal(0); BigDecimal hundred = new BigDecimal(100); BigDecimal one = new BigDecimal(1); BigDecimal totalSurCharge = new BigDecimal(0); BigDecimal totalItemQuantity = new BigDecimal(0); BigDecimal itemSurchargeCons = new BigDecimal(0); for (int i = 0; item.size() > i; i++) { OlePaymentRequestItem items = (OlePaymentRequestItem) paymentRequestDocument.getItem(i); if ((items.getItemType().isQuantityBasedGeneralLedgerIndicator()) && !ObjectUtils.isNull(items.getItemQuantity())) { if (paymentRequestDocument.getProrateBy().equals(OLEConstants.PRORATE_BY_QTY)) { totalItemQuantity = totalItemQuantity.add(items.getItemQuantity().bigDecimalValue()); } if (paymentRequestDocument.getProrateBy().equals(OLEConstants.PRORATE_BY_DOLLAR) || paymentRequestDocument.getProrateBy().equals(OLEConstants.MANUAL_PRORATE) || paymentRequestDocument.getProrateBy().equals(OLEConstants.PRORATE_BY_QTY)) { if (items.getItemDiscount() == null) { items.setItemDiscount(KualiDecimal.ZERO); } if (items.getItemDiscountType() != null && items.getItemDiscountType() .equalsIgnoreCase(OleSelectConstant.DISCOUNT_TYPE_PERCENTAGE)) { newUnitPrice = (hundred.subtract(items.getItemDiscount().bigDecimalValue())).divide(hundred) .multiply(items.getItemListPrice().bigDecimalValue()); } else { newUnitPrice = items.getItemListPrice().bigDecimalValue() .subtract(items.getItemDiscount().bigDecimalValue()); } newUnitPriceList.add(newUnitPrice); extPrice = newUnitPrice.multiply(items.getItemQuantity().bigDecimalValue()); totalExtPrice = totalExtPrice.add(extPrice); } if (paymentRequestDocument.getProrateBy().equals(OLEConstants.MANUAL_PRORATE)) { if (items.getItemSurcharge() == null) { items.setItemSurcharge(BigDecimal.ZERO); } totalSurCharge = totalSurCharge .add(items.getItemQuantity().bigDecimalValue().multiply(items.getItemSurcharge())); } } } if (paymentRequestDocument.getProrateBy().equals(OLEConstants.PRORATE_BY_QTY)) { if (totalItemQuantity.compareTo(BigDecimal.ZERO) != 0) { itemSurchargeCons = one.divide(totalItemQuantity, 8, RoundingMode.HALF_UP); } } for (int i = 0, j = 0; item.size() > i; i++) { OlePaymentRequestItem items = (OlePaymentRequestItem) paymentRequestDocument.getItem(i); if (items.getItemType().isQuantityBasedGeneralLedgerIndicator() && newUnitPriceList.size() > j && !ObjectUtils.isNull(items.getItemQuantity())) { if (paymentRequestDocument.getProrateBy().equals(OLEConstants.PRORATE_BY_DOLLAR)) { if (totalExtPrice.compareTo(BigDecimal.ZERO) != 0) { unitPricePercent = newUnitPriceList.get(j).divide(totalExtPrice, 8, RoundingMode.HALF_UP); } items.setItemSurcharge( unitPricePercent.multiply(addChargeItem).setScale(4, RoundingMode.HALF_UP)); items.setItemUnitPrice(newUnitPriceList.get(j).add(items.getItemSurcharge())); } if (paymentRequestDocument.getProrateBy().equals(OLEConstants.PRORATE_BY_QTY)) { items.setItemSurcharge( itemSurchargeCons.multiply(addChargeItem).setScale(4, RoundingMode.HALF_UP)); items.setItemUnitPrice(newUnitPriceList.get(j).add(items.getItemSurcharge())); } if (paymentRequestDocument.getProrateBy().equals(OLEConstants.MANUAL_PRORATE) && items.getItemSurcharge() != null) { items.setItemUnitPrice(newUnitPriceList.get(j).add(items.getItemSurcharge())); } j++; } } if (paymentRequestDocument.getProrateBy().equals(OLEConstants.MANUAL_PRORATE)) { if (totalSurCharge.compareTo(addChargeItem) != 0) { GlobalVariables.getMessageMap().putError(PurapConstants.ITEM_TAB_ERROR_PROPERTY, OLEKeyConstants.ERROR_PAYMENT_REQUEST_TOTAL_MISMATCH); } } LOG.debug("Leaving Calculation for ProrateItemSurcharge"); }
From source file:org.egov.dao.budget.BudgetDetailsHibernateDAO.java
/** * @description - returns the Sanctioned Planning Budget amount based on * various parameters. For an year if there is an approved RE, * then the RE sanctioned planning amount will be returned else * the sanctioned BE amount will be returned. This will take * care of the re-appropriations also. * @param parameter// ww w . j av a 2s . c om * Map contains deptid,functionid, functionaryid,schemeid, * subschemeid,boundaryid,budgetheadid,financialyearid,fundid * it'll get the budgeted amount based on the parameters. * @return Sanctioned Planning Budget amount @ */ @Override public BigDecimal getSanctionedPlanningBudget(final Map<String, Object> paramMap) { final BigDecimal multiplicationFactor = new BigDecimal( Double.parseDouble(getAppConfigFor("EGF", "planning_budget_multiplication_factor"))); final BigDecimal budgetedAmtForYear = zeroOrValue(getBudgetedAmtForYear(paramMap)); return budgetedAmtForYear.multiply(multiplicationFactor); }
From source file:com.ugam.collage.plus.service.people_count.impl.PeopleAccountingServiceImpl.java
/** * @param yearId/*from w w w .j av a 2s . c o m*/ * @param monthId * @param costCentreId * @param empcntClientProjectDataVoList * @param empcntClientProjectDataList * @param employeeIdList * @param employeeMonthlyAssignmentCount */ private void ruleSix(Integer yearId, Integer monthId, String costCentreId, List<EmpcntClientProjectData> empOpenCntClientProjectDataList, List<EmpcntClientProjectData> empCloseCntClientProjectDataList, List<EmpcntClientProjectData> empAverageCntClientProjectDataList, List<Integer> employeeIdList, EmployeeMonthlyAssignment employeeMonthlyAssignmentCount, Integer countTypeId, Map<String, EmployeePcTagsTeamStruct> employeePcTagsTeamStructMap) { BigDecimal constantHours = new BigDecimal(Constants.TOTAL_WORKING_HOURS); BigDecimal allignedTimeZero = BigDecimal.ZERO; BigDecimal assistedTimeZero = BigDecimal.ZERO; BigDecimal apportionedTimeZero = BigDecimal.ZERO; EmployeeMaster employeeMaster = employeeMonthlyAssignmentCount.getEmployeeMaster(); TabMonth tabMonth = employeeMonthlyAssignmentCount.getTabMonth(); TabYear tabYear = employeeMonthlyAssignmentCount.getTabYear(); CostCentre costCentre = employeeMonthlyAssignmentCount.getCostCentre(); CountClassification countClassification = new CountClassification(); countClassification.setId(countTypeId); // Get the employee aligned project for opening count List<EmpClientProjectTeamStruct> empClientProjectTeamStructList = empClientProjectTeamStructDao .findByYearMonthTypeEmps(yearId, monthId, countTypeId, employeeIdList); // Get Total hours of existing project then do for profit centre // projects; Map<Integer, Set<Integer>> employeeIdProjectIdsMap = new HashMap<Integer, Set<Integer>>(); Map<Integer, Integer> projectIdCompanyIdsMap = new HashMap<Integer, Integer>(); for (EmpClientProjectTeamStruct empClientProjectTeamStruct : empClientProjectTeamStructList) { int employeeId = empClientProjectTeamStruct.getEmployeeMaster().getEmployeeId(); Integer projectId = empClientProjectTeamStruct.getProjectMaster().getProjectId(); Integer companyId = empClientProjectTeamStruct.getCompanyMaster().getCompanyId(); if (employeeIdProjectIdsMap.containsKey(employeeId) && employeeIdProjectIdsMap.get(employeeId) != null) { employeeIdProjectIdsMap.get(employeeId).add(projectId); } else { Set<Integer> projectIds = new HashSet<Integer>(); projectIds.add(projectId); employeeIdProjectIdsMap.put(employeeId, projectIds); } projectIdCompanyIdsMap.put(projectId, companyId); } for (Integer employeeId : employeeIdProjectIdsMap.keySet()) { Set<Integer> projectIds = new HashSet<Integer>(); BigDecimal proportionOfCount = BigDecimal.ZERO; projectIds.addAll(employeeIdProjectIdsMap.get(employeeId)); for (Integer projectId : projectIds) { List<BigDecimal> totalHour = executionDataDao.findByProjectId(projectId); BigDecimal propotionOfProject = totalHour.get(0).divide(constantHours, 2, RoundingMode.HALF_EVEN); proportionOfCount = proportionOfCount.add(propotionOfProject); ProjectMaster pMaster = new ProjectMaster(); pMaster.setProjectId(projectId); CompanyMaster cMaster = new CompanyMaster(); cMaster.setCompanyId(projectIdCompanyIdsMap.get(projectId)); EmpcntClientProjectData empcntClientProjectData = new EmpcntClientProjectData(employeeMaster, cMaster, countClassification, tabMonth, pMaster, tabYear, costCentre, allignedTimeZero, propotionOfProject, apportionedTimeZero, propotionOfProject); if (countTypeId == 1) { empOpenCntClientProjectDataList.add(empcntClientProjectData); } if (countTypeId == 2) { empCloseCntClientProjectDataList.add(empcntClientProjectData); } } List<Integer> projectIdList = new ArrayList<Integer>(projectIds); // get the EmpCntPcApportionApproach for the employee and type List<EmpCntPcApportionApproach> empCntPcApportionApproachList = empCntPcApportionApproachDao .findByYearIdMonthIdEmployeeIdTypeId(yearId, monthId, employeeId, countTypeId); // get the EmployeePcTagsTeamStruct for the employee and type List<EmployeePcTagsTeamStruct> employeePcTagsTeamStructList = employeePcTagsTeamStructDao .findByyearIdMonthIdEmployeeIdTypeId(yearId, monthId, employeeId, countTypeId); BigDecimal remainingCount = BigDecimal.ONE.subtract(proportionOfCount); if (empCntPcApportionApproachList.get(0).getApportionApproach() == 1) { for (EmployeePcTagsTeamStruct employeePcTagsTeamStruct : employeePcTagsTeamStructList) { String profitCentreId = employeePcTagsTeamStruct.getProfitCentre().getProfitCentreId(); List<CollageProjectRevenue> collageProjectRevenueList = collageProjectRevenueDao .findByYearIdMonthIdProfitCentreIdProjectIds(yearId, monthId, profitCentreId, projectIdList); BigDecimal projectCount = new BigDecimal(collageProjectRevenueList.size()); for (CollageProjectRevenue collageProjectRevenue : collageProjectRevenueList) { BigDecimal projectValue = BigDecimal.ONE.divide(projectCount, 2, RoundingMode.HALF_EVEN); projectValue = projectValue.multiply(remainingCount); projectValue = projectValue.multiply(employeePcTagsTeamStruct.getProportion()); EmpcntClientProjectData empcntClientProjectData = new EmpcntClientProjectData( employeeMaster, collageProjectRevenue.getProjectMaster().getCompanyMaster(), countClassification, tabMonth, collageProjectRevenue.getProjectMaster(), tabYear, costCentre, allignedTimeZero, assistedTimeZero, projectValue, projectValue); if (countTypeId == 1) { empOpenCntClientProjectDataList.add(empcntClientProjectData); } if (countTypeId == 2) { empCloseCntClientProjectDataList.add(empcntClientProjectData); } // copy proprotion String mapId = yearId + "-" + monthId + "-" + employeeMaster.getEmployeeId() + "-" + profitCentreId; EmployeePcTagsTeamStruct employeePcTagsTeamStructCopy = employeePcTagsTeamStruct; employeePcTagsTeamStructCopy.setApportionedCnt(projectValue); employeePcTagsTeamStructMap.put(mapId, employeePcTagsTeamStructCopy); } } } else if (empCntPcApportionApproachList.get(0).getApportionApproach() == 2) { for (EmployeePcTagsTeamStruct employeePcTagsTeamStruct : employeePcTagsTeamStructList) { String profitCentreId = employeePcTagsTeamStruct.getProfitCentre().getProfitCentreId(); List<Object[]> objectList = executionDataDao .findByYearIdMonthIdCostCentreIdProfitCentreIdProjectIds(yearId, monthId, costCentreId, profitCentreId, projectIdList); BigDecimal hoursSum = BigDecimal.ZERO; for (Object[] hours : objectList) { BigDecimal hour = (BigDecimal) hours[1]; hoursSum.add(hour); } for (Object[] result : objectList) { Integer projectId = (Integer) result[0]; BigDecimal hour = (BigDecimal) result[1]; Integer companyId = (Integer) result[2]; ProjectMaster projectMaster = new ProjectMaster(); projectMaster.setProjectId(projectId); CompanyMaster companyMaster = new CompanyMaster(); companyMaster.setCompanyId(companyId); BigDecimal resultHour = hour.divide(hoursSum, 2, RoundingMode.HALF_EVEN); resultHour = resultHour.multiply(remainingCount); resultHour = resultHour.multiply(employeePcTagsTeamStruct.getProportion()); EmpcntClientProjectData empcntClientProjectData = new EmpcntClientProjectData( employeeMaster, companyMaster, countClassification, tabMonth, projectMaster, tabYear, costCentre, allignedTimeZero, assistedTimeZero, resultHour, resultHour); if (countTypeId == 1) { empOpenCntClientProjectDataList.add(empcntClientProjectData); } if (countTypeId == 2) { empCloseCntClientProjectDataList.add(empcntClientProjectData); } // copy proprotion String mapId = yearId + "-" + monthId + "-" + employeeMaster.getEmployeeId() + "-" + profitCentreId; EmployeePcTagsTeamStruct employeePcTagsTeamStructCopy = employeePcTagsTeamStruct; employeePcTagsTeamStructCopy.setApportionedCnt(resultHour); employeePcTagsTeamStructMap.put(mapId, employeePcTagsTeamStructCopy); } } } else if (empCntPcApportionApproachList.get(0).getApportionApproach() == 3) { for (EmployeePcTagsTeamStruct employeePcTagsTeamStruct : employeePcTagsTeamStructList) { String profitCentreId = employeePcTagsTeamStruct.getProfitCentre().getProfitCentreId(); List<CollageProjectRevenue> collageProjectRevenueList = collageProjectRevenueDao .findByYearIdMonthIdProfitCentreIdProjectIds(yearId, monthId, profitCentreId, projectIdList); BigDecimal revenueSum = BigDecimal.ZERO; for (CollageProjectRevenue val : collageProjectRevenueList) { revenueSum.add(val.getRevenueValue()); } for (CollageProjectRevenue collageProjectRevenue : collageProjectRevenueList) { BigDecimal revenueValue = collageProjectRevenue.getRevenueValue().divide(revenueSum); revenueValue = revenueValue.multiply(remainingCount); revenueValue = revenueValue.multiply(employeePcTagsTeamStruct.getProportion()); EmpcntClientProjectData empcntClientProjectData = new EmpcntClientProjectData( employeeMaster, collageProjectRevenue.getProjectMaster().getCompanyMaster(), countClassification, tabMonth, collageProjectRevenue.getProjectMaster(), tabYear, costCentre, allignedTimeZero, assistedTimeZero, revenueValue, revenueValue); if (countTypeId == 1) { empOpenCntClientProjectDataList.add(empcntClientProjectData); } if (countTypeId == 2) { empCloseCntClientProjectDataList.add(empcntClientProjectData); } // copy proprotion String mapId = yearId + "-" + monthId + "-" + employeeMaster.getEmployeeId() + "-" + profitCentreId; EmployeePcTagsTeamStruct employeePcTagsTeamStructCopy = employeePcTagsTeamStruct; employeePcTagsTeamStructCopy.setApportionedCnt(revenueValue); employeePcTagsTeamStructMap.put(mapId, employeePcTagsTeamStructCopy); } } } } }
From source file:com.turborep.turbotracker.sales.service.Salesserviceimpl.java
public void RollBackSalesOrderLineItems(Cuso cuso, Integer newstatus, Integer userID, String userName) { Session aSession = null;// ww w. j av a2s.co m boolean returnvalue = false; try { aSession = itsSessionFactory.openSession(); String prwarehouseQuery = "FROM Cusodetail WHERE cuSOID =" + cuso.getCuSoid(); Query aQuery = aSession.createQuery(prwarehouseQuery); if (cuso.getTransactionStatus() == 1 && (newstatus == -2 || newstatus == -1 || newstatus == 0 || newstatus == 2)) { String transstatus = ""; if (newstatus == -2) { transstatus = "Quote"; } else if (newstatus == -1) { transstatus = "Void"; } else if (newstatus == 0) { transstatus = "onHold"; } else if (newstatus == 2) { transstatus = "Closed"; } ArrayList<Cusodetail> cusodtllist = (ArrayList<Cusodetail>) aQuery.list(); for (Cusodetail aCusodetail : cusodtllist) { aCusodetail.setUserID(userID); aCusodetail.setUserName(userName); itsjobService.RollBackPrMasterPrWareHouseInventory(aCusodetail.getCuSoid(), aCusodetail.getCuSodetailId()); if (aCusodetail.getCuSodetailId() > 0) { Cuso aCuso = (Cuso) aSession.get(Cuso.class, aCusodetail.getCuSoid()); TpInventoryLog aTpInventoryLog = new TpInventoryLog(); Prmaster aPrmaster = productService .getProducts(" WHERE prMasterID=" + aCusodetail.getPrMasterId()); aTpInventoryLog.setPrMasterID(aCusodetail.getPrMasterId()); aTpInventoryLog.setProductCode(aPrmaster.getItemCode()); aTpInventoryLog.setWareHouseID(aCuso.getPrFromWarehouseId()); aTpInventoryLog.setTransType("SO"); aTpInventoryLog.setTransDecription("SO Status Open to " + transstatus); aTpInventoryLog.setTransID(aCusodetail.getCuSoid()); aTpInventoryLog.setTransDetailID(aCusodetail.getCuSodetailId()); aTpInventoryLog.setProductOut( aCusodetail.getQuantityOrdered().compareTo(new BigDecimal("0.0000")) == -1 ? aCusodetail.getQuantityOrdered() : new BigDecimal("0.0000")); aTpInventoryLog.setProductIn( aCusodetail.getQuantityOrdered().compareTo(new BigDecimal("0.0000")) == 1 ? aCusodetail.getQuantityOrdered() : new BigDecimal("0.0000")); aTpInventoryLog.setUserID(aCuso.getCreatedById()); aTpInventoryLog.setCreatedOn(new Date()); itsInventoryService.saveInventoryTransactions(aTpInventoryLog); /* * TpInventoryLogMaster Created on 04-12-2015 Code * Starts RollBack */ BigDecimal oqo = aCusodetail.getQuantityOrdered().subtract(aCusodetail.getQuantityBilled()); Prwarehouse otheprwarehouse = (Prwarehouse) aSession.get(Prwarehouse.class, aCuso.getPrFromWarehouseId()); Prwarehouseinventory otheprwarehsinventory = itsInventoryService .getPrwarehouseInventory(aCuso.getPrFromWarehouseId(), aPrmaster.getPrMasterId()); TpInventoryLogMaster oprmatpInventoryLogMstr = new TpInventoryLogMaster( aPrmaster.getPrMasterId(), aPrmaster.getItemCode(), aCuso.getPrFromWarehouseId(), otheprwarehouse.getSearchName(), aPrmaster.getInventoryOnHand(), otheprwarehsinventory.getInventoryOnHand(), oqo.multiply(new BigDecimal(-1)), BigDecimal.ZERO, "SO", aCuso.getCuSoid(), aCusodetail.getCuSodetailId(), aCuso.getSonumber(), null, /* Product out */(oqo.compareTo(BigDecimal.ZERO) < 0) ? oqo.multiply(new BigDecimal(-1)) : BigDecimal.ZERO, /* Product in */(oqo.compareTo(BigDecimal.ZERO) > 0) ? oqo : BigDecimal.ZERO, "SO Status Open to " + transstatus, aCusodetail.getUserID(), aCusodetail.getUserName(), new Date()); itsInventoryService.addTpInventoryLogMaster(oprmatpInventoryLogMstr); /* Code Ends */ } } } else if ((cuso.getTransactionStatus() == -2 || cuso.getTransactionStatus() == -1 || cuso.getTransactionStatus() == 0 || cuso.getTransactionStatus() == 2) && newstatus == 1) { String transstatus = ""; if (cuso.getTransactionStatus() == -2) { transstatus = "Quote"; } else if (cuso.getTransactionStatus() == -1) { transstatus = "Void"; } else if (cuso.getTransactionStatus() == 0) { transstatus = "onHold"; } else if (newstatus == 2) { transstatus = "Closed"; } ArrayList<Cusodetail> cusodtllist = (ArrayList<Cusodetail>) aQuery.list(); for (Cusodetail aCusodetail : cusodtllist) { aCusodetail.setUserID(userID); aCusodetail.setUserName(userName); itsjobService.insertPrMasterPrWareHouseInventory(aCusodetail.getCuSoid(), aCusodetail.getCuSodetailId()); if (aCusodetail.getCuSodetailId() > 0) { Cuso aCuso = (Cuso) aSession.get(Cuso.class, aCusodetail.getCuSoid()); TpInventoryLog aTpInventoryLog = new TpInventoryLog(); aTpInventoryLog.setPrMasterID(aCusodetail.getPrMasterId()); Prmaster aPrmaster = productService .getProducts(" WHERE prMasterID=" + aCusodetail.getPrMasterId()); aTpInventoryLog.setProductCode(aPrmaster.getItemCode()); aTpInventoryLog.setWareHouseID(aCuso.getPrFromWarehouseId()); aTpInventoryLog.setTransType("SO"); aTpInventoryLog.setTransDecription("SO Status " + transstatus + " to OPen"); aTpInventoryLog.setTransID(aCusodetail.getCuSoid()); aTpInventoryLog.setTransDetailID(aCusodetail.getCuSodetailId()); aTpInventoryLog.setProductOut( aCusodetail.getQuantityOrdered().compareTo(new BigDecimal("0.0000")) == 1 ? aCusodetail.getQuantityOrdered() : new BigDecimal("0.0000")); aTpInventoryLog.setProductIn( aCusodetail.getQuantityOrdered().compareTo(new BigDecimal("0.0000")) == -1 ? aCusodetail.getQuantityOrdered() : new BigDecimal("0.0000")); aTpInventoryLog.setUserID(aCuso.getCreatedById()); aTpInventoryLog.setCreatedOn(new Date()); itsInventoryService.saveInventoryTransactions(aTpInventoryLog); /* * TpInventoryLogMaster Created on 04-12-2015 Code * Starts */ BigDecimal qo = aCusodetail.getQuantityOrdered().subtract(aCusodetail.getQuantityBilled()); Prwarehouse theprwarehouse = (Prwarehouse) aSession.get(Prwarehouse.class, aCuso.getPrFromWarehouseId()); Prwarehouseinventory theprwarehsinventory = itsInventoryService .getPrwarehouseInventory(aCuso.getPrFromWarehouseId(), aPrmaster.getPrMasterId()); TpInventoryLogMaster prmatpInventoryLogMstr = new TpInventoryLogMaster( aPrmaster.getPrMasterId(), aPrmaster.getItemCode(), aCuso.getPrFromWarehouseId(), theprwarehouse.getSearchName(), aPrmaster.getInventoryOnHand(), theprwarehsinventory.getInventoryOnHand(), aCusodetail.getQuantityOrdered(), BigDecimal.ZERO, "SO", aCuso.getCuSoid(), aCusodetail.getCuSodetailId(), aCuso.getSonumber(), null, /* Product out */(qo.compareTo(BigDecimal.ZERO) > 0) ? qo : BigDecimal.ZERO, /* Product in */(qo.compareTo(BigDecimal.ZERO) < 0) ? qo.multiply(new BigDecimal(-1)) : BigDecimal.ZERO, "SO Status " + transstatus + " to OPen", aCusodetail.getUserID(), aCusodetail.getUserName(), new Date()); itsInventoryService.addTpInventoryLogMaster(prmatpInventoryLogMstr); /* Code Ends */ } } } } catch (Exception e) { itsLogger.error(e.getMessage(), e); } finally { aSession.flush(); aSession.close(); } }
From source file:com.wso2telco.dep.reportingservice.northbound.NbHostObjectUtils.java
/** * Apply charges with tax./*from w ww .j ava 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); TaxDAO taxDAO = new TaxDAO(); Set<APIRequestDTO> requestTimes = new HashSet<APIRequestDTO>(); if (prodKey != null) { String api_version = apiName + ":v" + apiVersion; requestTimes = taxDAO.getNbAPIRequestTimesForSubscription(Short.parseShort(year), Short.parseShort(month), apiName, api_version, prodKey.getConsumerKey(), operatorSub.getOperationId(), CatEntry.getKey().getCategory(), CatEntry.getKey().getSubcategory()); } // ChargeRate rate = operatorSub.getRate(); 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; } 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 += taxFraction x charge 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.mg.merp.planning.support.MPSProcessorServiceBean.java
private long mpsMaterialBreakdown(Bom bom, MpsLine mpsLine, long numberOfJobs, BigDecimal lotQty, long requiredDate) { long reqDate = requiredDate; List<BomRoute> routeList = ormTemplate .findByCriteria(OrmTemplate.createCriteria(BomRoute.class).add(Restrictions.eq("Bom", bom)) .add(Restrictions.le("EffOnDate", MfUtils.tickToDate(requiredDate))) .add(Restrictions.ge("EffOffDate", MfUtils.tickToDate(requiredDate))) .addOrder(Order.desc("OperNum"))); // for (BomRoute bomRoute : routeList) { //?? ? ? long timeOper = numberOfJobs * bomRoute.getSetupTicks() + lotQty.longValue() * numberOfJobs * bomRoute.getRunTicks(); //? ? ? TimeRange timeRange = MfUtils.getTimes(mps.getWeekCal().getId(), reqDate, timeOper, ScheduleDirection.BACKWARD); long operStartDate = timeRange.getStartDateTime(); List<BomMaterial> materialList = ormTemplate.findByCriteria( OrmTemplate.createCriteria(BomMaterial.class).add(Restrictions.eq("BomRoute", bomRoute)) .add(Restrictions.le("EffOnDate", MfUtils.tickToDate(operStartDate))) .add(Restrictions.ge("EffOffDate", MfUtils.tickToDate(operStartDate)))); for (BomMaterial bomMaterial : materialList) { GenericItem planningItem = findPlanningItem(bomMaterial.getCatalog()); if (planningItem == null) continue; BigDecimal MaterialQty = lotQty.multiply(new BigDecimal(numberOfJobs)) .multiply(MfUtils.calculateBOMMaterialQuan(bomMaterial, MfUtils.tickToDate(requiredDate), bom.getPlanningLotQty())); short bucketOffset = MfUtils.determineBucketOffset(mps.getPlanningLevel().getId(), MfUtils.tickToDate(operStartDate)); if (bucketOffset == -1) throw new BusinessException( "? ? ? ? dd/mm/yyyy"); BucketRange bucketRange = MfUtils.determineBucketRange(mps.getPlanningLevel().getId(), bucketOffset);// w w w.j ava 2 s . c om MpsLine mpsl = prepareMPSLine(mps, planningItem, bucketOffset, mpsLine.getMpsSequence()); mpsl.setBucketOffset(bucketOffset); mpsl.setBucketOffsetDate(bucketRange.getBucketStart()); mpsl.setLevelCode(planningItem.getLowLevelCode()); if (bomMaterial.getMeasure().getId() != planningItem.getMeasure().getId()) MaterialQty = getMeasureConversionService().conversion(bomMaterial.getMeasure(), planningItem.getMeasure(), planningItem.getCatalog(), bucketRange.getBucketStart(), MaterialQty); mpsl.setProductionDemandQty(mpsl.getProductionDemandQty().add(MaterialQty)); mpsl.setMeasure(planningItem.getMeasure()); } timeRange = MfUtils.getTimes(mps.getWeekCal().getId(), operStartDate, bomRoute.getMoveTicks() * numberOfJobs, ScheduleDirection.BACKWARD); reqDate = timeRange.getStartDateTime();// ? ? } return reqDate; }