Example usage for java.math BigDecimal ONE

List of usage examples for java.math BigDecimal ONE

Introduction

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

Prototype

BigDecimal ONE

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

Click Source Link

Document

The value 1, with a scale of 0.

Usage

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

/**
 * @param yearId/*from   w  w w  .  jav a2s. com*/
 * @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:org.ofbiz.accounting.invoice.InvoiceServices.java

public static Map<String, Object> createInvoiceFromReturn(DispatchContext dctx, Map<String, Object> context) {
    Delegator delegator = dctx.getDelegator();
    LocalDispatcher dispatcher = dctx.getDispatcher();
    GenericValue userLogin = (GenericValue) context.get("userLogin");
    Locale locale = (Locale) context.get("locale");

    String returnId = (String) context.get("returnId");
    List<GenericValue> billItems = UtilGenerics.checkList(context.get("billItems"));
    String errorMsg = UtilProperties.getMessage(resource, "AccountingErrorCreatingInvoiceForReturn",
            UtilMisc.toMap("returnId", returnId), locale);
    // List invoicesCreated = new ArrayList();
    try {/*from w w w  . j a v a  2 s . c  o m*/
        String invoiceTypeId;
        String description;
        // get the return header
        GenericValue returnHeader = EntityQuery.use(delegator).from("ReturnHeader").where("returnId", returnId)
                .queryOne();
        if (returnHeader == null || returnHeader.get("returnHeaderTypeId") == null) {
            return ServiceUtil.returnError("Return type cannot be null");
        }

        if (returnHeader.getString("returnHeaderTypeId").startsWith("CUSTOMER_")) {
            invoiceTypeId = "CUST_RTN_INVOICE";
            description = "Return Invoice for Customer Return #" + returnId;
        } else {
            invoiceTypeId = "PURC_RTN_INVOICE";
            description = "Return Invoice for Vendor Return #" + returnId;
        }
        // set the invoice data
        Map<String, Object> input = UtilMisc.<String, Object>toMap("invoiceTypeId", invoiceTypeId, "statusId",
                "INVOICE_IN_PROCESS");
        input.put("partyId", returnHeader.get("toPartyId"));
        input.put("partyIdFrom", returnHeader.get("fromPartyId"));
        input.put("currencyUomId", returnHeader.get("currencyUomId"));
        input.put("invoiceDate", UtilDateTime.nowTimestamp());
        input.put("description", description);
        input.put("billingAccountId", returnHeader.get("billingAccountId"));
        input.put("userLogin", userLogin);

        // call the service to create the invoice
        Map<String, Object> serviceResults = dispatcher.runSync("createInvoice", input);
        if (ServiceUtil.isError(serviceResults)) {
            return ServiceUtil.returnError(errorMsg, null, null, serviceResults);
        }
        String invoiceId = (String) serviceResults.get("invoiceId");

        // keep track of the invoice total vs the promised return total (how much the customer promised to return)
        BigDecimal invoiceTotal = ZERO;
        BigDecimal promisedTotal = ZERO;

        // loop through shipment receipts to create invoice items and return item billings for each item and adjustment
        int invoiceItemSeqNum = 1;
        String invoiceItemSeqId = UtilFormatOut.formatPaddedNumber(invoiceItemSeqNum,
                INVOICE_ITEM_SEQUENCE_ID_DIGITS);

        for (GenericValue item : billItems) {
            boolean shipmentReceiptFound = false;
            boolean itemIssuanceFound = false;
            if ("ShipmentReceipt".equals(item.getEntityName())) {
                shipmentReceiptFound = true;
            } else if ("ItemIssuance".equals(item.getEntityName())) {
                itemIssuanceFound = true;
            } else {
                Debug.logError("Unexpected entity " + item + " of type " + item.getEntityName(), module);
            }
            // we need the related return item and product
            GenericValue returnItem = null;
            if (shipmentReceiptFound) {
                returnItem = item.getRelatedOne("ReturnItem", true);
            } else if (itemIssuanceFound) {
                GenericValue shipmentItem = item.getRelatedOne("ShipmentItem", true);
                GenericValue returnItemShipment = EntityUtil
                        .getFirst(shipmentItem.getRelated("ReturnItemShipment", null, null, false));
                returnItem = returnItemShipment.getRelatedOne("ReturnItem", true);
            }
            if (returnItem == null)
                continue; // Just to prevent NPE
            GenericValue product = returnItem.getRelatedOne("Product", true);

            // extract the return price as a big decimal for convenience
            BigDecimal returnPrice = returnItem.getBigDecimal("returnPrice");

            // determine invoice item type from the return item type
            String invoiceItemTypeId = getInvoiceItemType(delegator, returnItem.getString("returnItemTypeId"),
                    null, invoiceTypeId, null);
            if (invoiceItemTypeId == null) {
                return ServiceUtil.returnError(errorMsg + UtilProperties.getMessage(resource,
                        "AccountingNoKnownInvoiceItemTypeReturnItemType",
                        UtilMisc.toMap("returnItemTypeId", returnItem.getString("returnItemTypeId")), locale));
            }
            BigDecimal quantity = BigDecimal.ZERO;
            if (shipmentReceiptFound) {
                quantity = item.getBigDecimal("quantityAccepted");
            } else if (itemIssuanceFound) {
                quantity = item.getBigDecimal("quantity");
            }

            // create the invoice item for this shipment receipt
            input = UtilMisc.toMap("invoiceId", invoiceId, "invoiceItemTypeId", invoiceItemTypeId, "quantity",
                    quantity);
            input.put("invoiceItemSeqId", "" + invoiceItemSeqId); // turn the int into a string with ("" + int) hack
            input.put("amount", returnItem.get("returnPrice"));
            input.put("productId", returnItem.get("productId"));
            input.put("taxableFlag", product.get("taxable"));
            input.put("description", returnItem.get("description"));
            // TODO: what about the productFeatureId?
            input.put("userLogin", userLogin);
            serviceResults = dispatcher.runSync("createInvoiceItem", input);
            if (ServiceUtil.isError(serviceResults)) {
                return ServiceUtil.returnError(errorMsg, null, null, serviceResults);
            }

            // copy the return item information into ReturnItemBilling
            input = UtilMisc.toMap("returnId", returnId, "returnItemSeqId", returnItem.get("returnItemSeqId"),
                    "invoiceId", invoiceId);
            input.put("invoiceItemSeqId", "" + invoiceItemSeqId); // turn the int into a string with ("" + int) hack
            input.put("quantity", quantity);
            input.put("amount", returnItem.get("returnPrice"));
            input.put("userLogin", userLogin);
            if (shipmentReceiptFound) {
                input.put("shipmentReceiptId", item.get("receiptId"));
            }
            serviceResults = dispatcher.runSync("createReturnItemBilling", input);
            if (ServiceUtil.isError(serviceResults)) {
                return ServiceUtil.returnError(errorMsg, null, null, serviceResults);
            }
            if (Debug.verboseOn()) {
                Debug.logVerbose("Creating Invoice Item with amount " + returnPrice + " and quantity "
                        + quantity + " for shipment [" + item.getString("shipmentId") + ":"
                        + item.getString("shipmentItemSeqId") + "]", module);
            }

            String parentInvoiceItemSeqId = invoiceItemSeqId;
            // increment the seqId counter after creating the invoice item and return item billing
            invoiceItemSeqNum += 1;
            invoiceItemSeqId = UtilFormatOut.formatPaddedNumber(invoiceItemSeqNum,
                    INVOICE_ITEM_SEQUENCE_ID_DIGITS);

            // keep a running total (note: a returnItem may have many receipts. hence, the promised total quantity is the receipt quantityAccepted + quantityRejected)
            BigDecimal cancelQuantity = ZERO;
            if (shipmentReceiptFound) {
                cancelQuantity = item.getBigDecimal("quantityRejected");
            } else if (itemIssuanceFound) {
                cancelQuantity = item.getBigDecimal("cancelQuantity");
            }
            if (cancelQuantity == null)
                cancelQuantity = ZERO;
            BigDecimal actualAmount = returnPrice.multiply(quantity).setScale(DECIMALS, ROUNDING);
            BigDecimal promisedAmount = returnPrice.multiply(quantity.add(cancelQuantity)).setScale(DECIMALS,
                    ROUNDING);
            invoiceTotal = invoiceTotal.add(actualAmount).setScale(DECIMALS, ROUNDING);
            promisedTotal = promisedTotal.add(promisedAmount).setScale(DECIMALS, ROUNDING);

            // for each adjustment related to this ReturnItem, create a separate invoice item
            List<GenericValue> adjustments = returnItem.getRelated("ReturnAdjustment", null, null, true);
            for (GenericValue adjustment : adjustments) {

                if (adjustment.get("amount") == null) {
                    Debug.logWarning("Return adjustment [" + adjustment.get("returnAdjustmentId")
                            + "] has null amount and will be skipped", module);
                    continue;
                }

                // determine invoice item type from the return item type
                invoiceItemTypeId = getInvoiceItemType(delegator,
                        adjustment.getString("returnAdjustmentTypeId"), null, invoiceTypeId, null);
                if (invoiceItemTypeId == null) {
                    return ServiceUtil
                            .returnError(
                                    errorMsg + UtilProperties
                                            .getMessage(resource,
                                                    "AccountingNoKnownInvoiceItemTypeReturnAdjustmentType",
                                                    UtilMisc.toMap("returnAdjustmentTypeId",
                                                            adjustment.getString("returnAdjustmentTypeId")),
                                                    locale));
                }

                // prorate the adjustment amount by the returned amount; do not round ratio
                BigDecimal ratio = quantity.divide(returnItem.getBigDecimal("returnQuantity"), 100, ROUNDING);
                BigDecimal amount = adjustment.getBigDecimal("amount");
                amount = amount.multiply(ratio).setScale(DECIMALS, ROUNDING);
                if (Debug.verboseOn()) {
                    Debug.logVerbose("Creating Invoice Item with amount " + adjustment.getBigDecimal("amount")
                            + " prorated to " + amount + " for return adjustment ["
                            + adjustment.getString("returnAdjustmentId") + "]", module);
                }

                // prepare invoice item data for this adjustment
                input = UtilMisc.toMap("invoiceId", invoiceId, "invoiceItemTypeId", invoiceItemTypeId,
                        "quantity", BigDecimal.ONE);
                input.put("amount", amount);
                input.put("invoiceItemSeqId", "" + invoiceItemSeqId); // turn the int into a string with ("" + int) hack
                input.put("productId", returnItem.get("productId"));
                input.put("description", adjustment.get("description"));
                input.put("overrideGlAccountId", adjustment.get("overrideGlAccountId"));
                input.put("parentInvoiceId", invoiceId);
                input.put("parentInvoiceItemSeqId", parentInvoiceItemSeqId);
                input.put("taxAuthPartyId", adjustment.get("taxAuthPartyId"));
                input.put("taxAuthGeoId", adjustment.get("taxAuthGeoId"));
                input.put("userLogin", userLogin);

                // only set taxable flag when the adjustment is not a tax
                // TODO: Note that we use the value of Product.taxable here. This is not an ideal solution. Instead, use returnAdjustment.includeInTax
                if (adjustment.get("returnAdjustmentTypeId").equals("RET_SALES_TAX_ADJ")) {
                    input.put("taxableFlag", "N");
                }

                // create the invoice item
                serviceResults = dispatcher.runSync("createInvoiceItem", input);
                if (ServiceUtil.isError(serviceResults)) {
                    return ServiceUtil.returnError(errorMsg, null, null, serviceResults);
                }

                // increment the seqId counter
                invoiceItemSeqNum += 1;
                invoiceItemSeqId = UtilFormatOut.formatPaddedNumber(invoiceItemSeqNum,
                        INVOICE_ITEM_SEQUENCE_ID_DIGITS);

                // keep a running total (promised adjustment in this case is the same as the invoice adjustment)
                invoiceTotal = invoiceTotal.add(amount).setScale(DECIMALS, ROUNDING);
                promisedTotal = promisedTotal.add(amount).setScale(DECIMALS, ROUNDING);
            }
        }

        // ratio of the invoice total to the promised total so far or zero if the amounts were zero
        BigDecimal actualToPromisedRatio = ZERO;
        if (invoiceTotal.signum() != 0) {
            actualToPromisedRatio = invoiceTotal.divide(promisedTotal, 100, ROUNDING); // do not round ratio
        }

        // loop through return-wide adjustments and create invoice items for each
        List<GenericValue> adjustments = returnHeader.getRelated("ReturnAdjustment",
                UtilMisc.toMap("returnItemSeqId", "_NA_"), null, true);
        for (GenericValue adjustment : adjustments) {

            // determine invoice item type from the return item type
            String invoiceItemTypeId = getInvoiceItemType(delegator,
                    adjustment.getString("returnAdjustmentTypeId"), null, invoiceTypeId, null);
            if (invoiceItemTypeId == null) {
                return ServiceUtil
                        .returnError(
                                errorMsg + UtilProperties
                                        .getMessage(resource,
                                                "AccountingNoKnownInvoiceItemTypeReturnAdjustmentType",
                                                UtilMisc.toMap("returnAdjustmentTypeId",
                                                        adjustment.getString("returnAdjustmentTypeId")),
                                                locale));
            }

            // prorate the adjustment amount by the actual to promised ratio
            BigDecimal amount = adjustment.getBigDecimal("amount").multiply(actualToPromisedRatio)
                    .setScale(DECIMALS, ROUNDING);
            if (Debug.verboseOn()) {
                Debug.logVerbose("Creating Invoice Item with amount " + adjustment.getBigDecimal("amount")
                        + " prorated to " + amount + " for return adjustment ["
                        + adjustment.getString("returnAdjustmentId") + "]", module);
            }

            // prepare the invoice item for the return-wide adjustment
            input = UtilMisc.toMap("invoiceId", invoiceId, "invoiceItemTypeId", invoiceItemTypeId, "quantity",
                    BigDecimal.ONE);
            input.put("amount", amount);
            input.put("invoiceItemSeqId", "" + invoiceItemSeqId); // turn the int into a string with ("" + int) hack
            input.put("description", adjustment.get("description"));
            input.put("overrideGlAccountId", adjustment.get("overrideGlAccountId"));
            input.put("taxAuthPartyId", adjustment.get("taxAuthPartyId"));
            input.put("taxAuthGeoId", adjustment.get("taxAuthGeoId"));
            input.put("userLogin", userLogin);

            // XXX TODO Note: we need to implement ReturnAdjustment.includeInTax for this to work properly
            input.put("taxableFlag", adjustment.get("includeInTax"));

            // create the invoice item
            serviceResults = dispatcher.runSync("createInvoiceItem", input);
            if (ServiceUtil.isError(serviceResults)) {
                return ServiceUtil.returnError(errorMsg, null, null, serviceResults);
            }

            // increment the seqId counter
            invoiceItemSeqNum += 1;
            invoiceItemSeqId = UtilFormatOut.formatPaddedNumber(invoiceItemSeqNum,
                    INVOICE_ITEM_SEQUENCE_ID_DIGITS);
        }

        // Set the invoice to READY
        serviceResults = dispatcher.runSync("setInvoiceStatus", UtilMisc.<String, Object>toMap("invoiceId",
                invoiceId, "statusId", "INVOICE_READY", "userLogin", userLogin));
        if (ServiceUtil.isError(serviceResults)) {
            return ServiceUtil.returnError(errorMsg, null, null, serviceResults);
        }

        // return the invoiceId
        Map<String, Object> results = ServiceUtil.returnSuccess();
        results.put("invoiceId", invoiceId);
        return results;
    } catch (GenericServiceException e) {
        Debug.logError(e, errorMsg + e.getMessage(), module);
        return ServiceUtil.returnError(errorMsg + e.getMessage());
    } catch (GenericEntityException e) {
        Debug.logError(e, errorMsg + e.getMessage(), module);
        return ServiceUtil.returnError(errorMsg + e.getMessage());
    }
}

From source file:org.apache.fineract.portfolio.loanaccount.service.LoanWritePlatformServiceJpaRepositoryImpl.java

private void addInstallmentIfPenaltyAppliedAfterLastDueDate(Loan loan, LocalDate lastChargeDate) {
    if (lastChargeDate != null) {
        List<LoanRepaymentScheduleInstallment> installments = loan.fetchRepaymentScheduleInstallments();
        LoanRepaymentScheduleInstallment lastInstallment = loan
                .fetchRepaymentScheduleInstallment(installments.size());
        if (lastChargeDate.isAfter(lastInstallment.getDueDate())) {
            if (lastInstallment.isRecalculatedInterestComponent()) {
                installments.remove(lastInstallment);
                lastInstallment = loan.fetchRepaymentScheduleInstallment(installments.size());
            }//w  w  w  .  j  a  v  a  2 s  .  co  m
            boolean recalculatedInterestComponent = true;
            BigDecimal principal = BigDecimal.ZERO;
            BigDecimal interest = BigDecimal.ZERO;
            BigDecimal feeCharges = BigDecimal.ZERO;
            BigDecimal penaltyCharges = BigDecimal.ONE;
            LoanRepaymentScheduleInstallment newEntry = new LoanRepaymentScheduleInstallment(loan,
                    installments.size() + 1, lastInstallment.getDueDate(), lastChargeDate, principal, interest,
                    feeCharges, penaltyCharges, recalculatedInterestComponent);
            installments.add(newEntry);
        }
    }
}

From source file:com.lp.server.lieferschein.ejbfac.LieferscheinFacBean.java

protected void uebernimmAuftragsposition(boolean bEsGibtNochPositiveOffene, LieferscheinDto lieferscheinDto,
        AuftragpositionDto auftragpositionDto, List<Artikelset> artikelsets, TheClientDto theClientDto)
        throws RemoteException {

    if (AuftragServiceFac.AUFTRAGPOSITIONSTATUS_ERLEDIGT
            .equals(auftragpositionDto.getAuftragpositionstatusCNr()))
        return;/*from w w w  . ja  va  2s.c o  m*/

    if (auftragpositionDto.getNMenge() == null) {
        LieferscheinpositionDto lieferscheinpositionDto = auftragpositionDto.cloneAsLieferscheinpositionDto();
        lieferscheinpositionDto.setLieferscheinIId(lieferscheinDto.getIId());
        lieferscheinpositionDto.setISort(null);
        getLieferscheinpositionFac().createLieferscheinposition(lieferscheinpositionDto, false, theClientDto);
        return;
    }

    // IMS 2129
    // wenn es noch positive offene gibt, dann duerfen die
    // negativen noch nicht geliefert werden
    if (auftragpositionDto.getNMenge().signum() < 0 && bEsGibtNochPositiveOffene) {
        return;
    }

    // dieses Flag legt fest, ob eine Lieferscheinposition
    // fuer die aktuelle
    // Auftragposition angleget oder aktualisiert werden
    // soll
    boolean bLieferscheinpositionErzeugen = false;

    // die Menge, mit der eine neue Lieferscheinposition
    // angelegt oder eine
    // bestehende Lieferscheinposition aktualisiert werden
    // soll
    BigDecimal nMengeFuerLieferscheinposition = null;

    // die Serien- oder Chargennummer, die bei der Abbuchung
    // verwendet werden soll
    String cSerienchargennummer = null;

    if (auftragpositionDto.getPositionsartCNr().equals(AuftragServiceFac.AUFTRAGPOSITIONART_HANDEINGABE)) {

        // PJ17906
        if (auftragpositionDto.getNMenge() != null && auftragpositionDto.getNMenge().doubleValue() == 0) {
            auftragpositionDto.setAuftragpositionstatusCNr(AuftragServiceFac.AUFTRAGPOSITIONSTATUS_ERLEDIGT);
            getAuftragpositionFac().updateOffeneMengeAuftragposition(auftragpositionDto.getIId(), theClientDto);
            return;
        }

        bLieferscheinpositionErzeugen = true;
        nMengeFuerLieferscheinposition = auftragpositionDto.getNOffeneMenge();
    } else if (auftragpositionDto.getPositionsartCNr().equals(AuftragServiceFac.AUFTRAGPOSITIONART_IDENT)) {

        // PJ17906
        if (auftragpositionDto.getNMenge() != null && auftragpositionDto.getNMenge().doubleValue() == 0) {
            auftragpositionDto.setAuftragpositionstatusCNr(AuftragServiceFac.AUFTRAGPOSITIONSTATUS_ERLEDIGT);
            getAuftragpositionFac().updateOffeneMengeAuftragposition(auftragpositionDto.getIId(), theClientDto);
            return;
        }

        ArtikelDto artikelDto = getArtikelFac().artikelFindByPrimaryKey(auftragpositionDto.getArtikelIId(),
                theClientDto);

        // nicht lagerbewirtschaftete Artikel werden mit der
        // vollen offenen Menge uebernommen sofern es nicht ein
        // Artikelset-Kopfartikel ist
        if (!artikelDto.isLagerbewirtschaftet()) {
            bLieferscheinpositionErzeugen = true;

            if (isArtikelSetHead(artikelDto.getIId(), theClientDto)) {
                BigDecimal verfuegbareMenge = getAvailableAmountArtikelset(auftragpositionDto.getIId(),
                        artikelsets);
                nMengeFuerLieferscheinposition = auftragpositionDto.getNOffeneMenge().min(verfuegbareMenge);
            } else {
                nMengeFuerLieferscheinposition = auftragpositionDto.getNOffeneMenge();
            }
        } else {
            if (artikelDto.isSeriennrtragend()) {
                // seriennummerbehaftete Artikel werden nur
                // uebernommen wenn sie in einem Artikelset vorhanden sind
                if (auftragpositionDto.getPositioniIdArtikelset() != null) {
                    Artikelset artikelset = getAppropriateArtikelset(
                            auftragpositionDto.getPositioniIdArtikelset(), artikelsets);
                    if (null != artikelset) {
                        BigDecimal sollsatzgroesse = auftragpositionDto.getNMenge()
                                .divide(artikelset.getHead().getNMenge());
                        nMengeFuerLieferscheinposition = sollsatzgroesse
                                .multiply(artikelset.getAvailableAmount());
                        bLieferscheinpositionErzeugen = true;
                    }
                    // BigDecimal verfuegbareMenge =
                    // getAvailableAmountArtikelset(auftragpositionDto.
                    // getPositioniIdArtikelset(),
                    // artikelsets) ;
                    // bLieferscheinpositionErzeugen = true ;
                    // if(verfuegbareMenge != null) {
                    // nMengeFuerLieferscheinposition =
                    // auftragpositionDto.getNOffeneMenge() ;
                    // }
                }
            } else if (artikelDto.isChargennrtragend()) {
                // chargennummernbehaftete Artikel koennen
                // nur uebernommen werden, wenn
                // es nur eine Charge gibt und mit der
                // Menge, die in dieser Charge
                // vorhanden ist
                SeriennrChargennrAufLagerDto[] alleChargennummern = getLagerFac().getAllSerienChargennrAufLager(
                        artikelDto.getIId(), lieferscheinDto.getLagerIId(), theClientDto, true, false);
                if (alleChargennummern != null && alleChargennummern.length == 1) {
                    BigDecimal nLagerstd = alleChargennummern[0].getNMenge();
                    cSerienchargennummer = alleChargennummern[0].getCSeriennrChargennr();

                    if (nLagerstd.signum() > 0) {
                        bLieferscheinpositionErzeugen = true;
                        nMengeFuerLieferscheinposition = auftragpositionDto.getNOffeneMenge().min(nLagerstd);
                    }
                }
            } else {
                // bei lagerbewirtschafteten Artikeln muss
                // die Menge auf Lager
                // beruecksichtigt werden
                BigDecimal nMengeAufLager = getLagerFac().getMengeAufLager(artikelDto.getIId(),
                        lieferscheinDto.getLagerIId(), null, theClientDto);

                if (nMengeAufLager.signum() > 0) {
                    bLieferscheinpositionErzeugen = true;
                    if (auftragpositionDto.getPositioniIdArtikelset() != null) {

                        Artikelset artikelset = getAppropriateArtikelset(
                                auftragpositionDto.getPositioniIdArtikelset(), artikelsets);
                        if (null != artikelset) {
                            BigDecimal sollsatzGroesse = auftragpositionDto.getNMenge()
                                    .divide(artikelset.getHead().getNMenge());
                            nMengeFuerLieferscheinposition = auftragpositionDto.getNOffeneMenge()
                                    .min(artikelset.getAvailableAmount()).multiply(sollsatzGroesse)
                                    .min(nMengeAufLager);
                        } else {
                            nMengeFuerLieferscheinposition = BigDecimal.ONE;
                        }
                    } else {
                        nMengeFuerLieferscheinposition = auftragpositionDto.getNOffeneMenge()
                                .min(nMengeAufLager);
                    }
                }
            }
        }
        // TODO: Vorerst mal eine Zwischensummenposition auf "OFFEN"
        // belassen. ghp, 07.09.2012
        // } else
        // if(auftragpositionDto.getAuftragpositionartCNr().equals(AuftragServiceFac.AUFTRAGPOSITIONART_INTELLIGENTE_ZWISCHENSUMME))
        // {
        // auftragpositionDto.setAuftragpositionstatusCNr(AuftragServiceFac.AUFTRAGPOSITIONSTATUS_ERLEDIGT)
        // ;
        // getAuftragpositionFac().updateAuftragpositionOhneWeitereAktion(auftragpositionDto,
        // theClientDto) ;
    }

    if (bLieferscheinpositionErzeugen && nMengeFuerLieferscheinposition != null) {
        LieferscheinpositionDto lieferscheinpositionBisherDto = getLieferscheinpositionByLieferscheinAuftragposition(
                lieferscheinDto.getIId(), auftragpositionDto.getIId());

        if (lieferscheinpositionBisherDto == null) {
            LieferscheinpositionDto lieferscheinpositionDto = auftragpositionDto
                    .cloneAsLieferscheinpositionDto();

            if (auftragpositionDto.getPositioniIdArtikelset() != null) {
                LieferscheinpositionDto[] lPositionDtos = null;
                Query query = em.createNamedQuery("LieferscheinpositionfindByAuftragposition");
                query.setParameter(1, auftragpositionDto.getPositioniIdArtikelset());
                Collection<?> cl = query.getResultList();
                lPositionDtos = assembleLieferscheinpositionDtos(cl);

                for (int j = 0; j < lPositionDtos.length; j++) {
                    if (lPositionDtos[j].getLieferscheinIId().equals(lieferscheinDto.getIId())) {
                        lieferscheinpositionDto.setPositioniIdArtikelset(lPositionDtos[j].getIId());
                        break;
                    }
                }

                getBelegVerkaufFac().setupPositionWithIdentities(lieferscheinpositionDto,
                        getAvailableSnrsArtikelset(auftragpositionDto.getPositioniIdArtikelset(), artikelsets),
                        theClientDto);

                cSerienchargennummer = null;
            }

            lieferscheinpositionDto.setLieferscheinIId(lieferscheinDto.getIId());

            // TODO: Problematisch bei seriennummern-artikeln (artikelset?)
            lieferscheinpositionDto.setNMenge(nMengeFuerLieferscheinposition);

            if (null != cSerienchargennummer) {
                lieferscheinpositionDto.setSeriennrChargennrMitMenge(
                        SeriennrChargennrMitMengeDto.erstelleDtoAusEinerChargennummer(cSerienchargennummer,
                                nMengeFuerLieferscheinposition));
            }
            lieferscheinpositionDto.setISort(null);
            getLieferscheinpositionFac().createLieferscheinposition(lieferscheinpositionDto, false,
                    theClientDto);
        } else {
            lieferscheinpositionBisherDto.setNMenge(nMengeFuerLieferscheinposition);

            if (auftragpositionDto.getPositionsartCNr().equals(AuftragServiceFac.AUFTRAGPOSITIONART_IDENT)) {
                ArtikelDto artikelDto = getArtikelFac()
                        .artikelFindByPrimaryKey(auftragpositionDto.getArtikelIId(), theClientDto);

                if (artikelDto.isChargennrtragend() || artikelDto.isSeriennrtragend()) {
                    lieferscheinpositionBisherDto.setSeriennrChargennrMitMenge(
                            SeriennrChargennrMitMengeDto.erstelleDtoAusEinerChargennummer(cSerienchargennummer,
                                    nMengeFuerLieferscheinposition));
                } else {
                    lieferscheinpositionBisherDto.setSeriennrChargennrMitMenge(null);
                }

            }

            getLieferscheinpositionFac().updateLieferscheinpositionSichtAuftrag(lieferscheinpositionBisherDto,
                    theClientDto);
        }
    }
}

From source file:com.gst.portfolio.loanaccount.service.LoanWritePlatformServiceJpaRepositoryImpl.java

private void addInstallmentIfPenaltyAppliedAfterLastDueDate(Loan loan, LocalDate lastChargeDate) {
    if (lastChargeDate != null) {
        List<LoanRepaymentScheduleInstallment> installments = loan.getRepaymentScheduleInstallments();
        LoanRepaymentScheduleInstallment lastInstallment = loan
                .fetchRepaymentScheduleInstallment(installments.size());
        if (lastChargeDate.isAfter(lastInstallment.getDueDate())) {
            if (lastInstallment.isRecalculatedInterestComponent()) {
                installments.remove(lastInstallment);
                lastInstallment = loan.fetchRepaymentScheduleInstallment(installments.size());
            }/* ww w.  java 2s  .  c o  m*/
            boolean recalculatedInterestComponent = true;
            BigDecimal principal = BigDecimal.ZERO;
            BigDecimal interest = BigDecimal.ZERO;
            BigDecimal feeCharges = BigDecimal.ZERO;
            BigDecimal penaltyCharges = BigDecimal.ONE;
            final Set<LoanInterestRecalcualtionAdditionalDetails> compoundingDetails = null;
            LoanRepaymentScheduleInstallment newEntry = new LoanRepaymentScheduleInstallment(loan,
                    installments.size() + 1, lastInstallment.getDueDate(), lastChargeDate, principal, interest,
                    feeCharges, penaltyCharges, recalculatedInterestComponent, compoundingDetails);
            installments.add(newEntry);
            loan.addLoanRepaymentScheduleInstallment(newEntry);
        }
    }
}

From source file:pe.gob.mef.gescon.web.ui.PendienteMB.java

public String sendUsuMod() {
    String pagina = null;// w  w w. ja v  a  2s .co  m
    try {
        if (StringUtils.isBlank(this.getSelectedPregunta().getVmsjusuario1())) {
            FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, Constante.SEVERETY_ALERTA,
                    "Campo requerido. Ingrese el mensaje a enviar");
            FacesContext.getCurrentInstance().addMessage(null, message);
            pagina = null;
        } else {
            /* Validando si la cantidad de pregutnas destacados lleg al lmite (10 max.).*/
            if (this.getChkDestacado()) {
                ConsultaService consultaService = (ConsultaService) ServiceFinder.findBean("ConsultaService");
                HashMap filter = new HashMap();
                filter.put("ntipoconocimientoid", Constante.PREGUNTAS);
                BigDecimal cant = consultaService.countDestacadosByTipoConocimiento(filter);
                if (cant.intValue() >= 10) {
                    this.setListaDestacados(consultaService.getDestacadosByTipoConocimiento(filter));
                    RequestContext.getCurrentInstance().execute("PF('destDialog').show();");
                    return "";
                }
            }
            PreguntaService service = (PreguntaService) ServiceFinder.findBean("PreguntaService");
            this.getSelectedPregunta().setNdestacado(this.getChkDestacado() ? BigDecimal.ONE : BigDecimal.ZERO);
            this.getSelectedPregunta()
                    .setVmsjusuario1(this.getSelectedPregunta().getVmsjusuario1().toUpperCase());
            service.saveOrUpdate(this.getSelectedPregunta());

            AsignacionService serviceasig = (AsignacionService) ServiceFinder.findBean("AsignacionService");
            this.getSelectedAsignacion().setNestadoid(BigDecimal.valueOf(Long.parseLong("2")));
            this.getSelectedAsignacion().setDfechaatencion(new Date());
            this.getSelectedAsignacion().setNaccionid(BigDecimal.valueOf(Long.parseLong("11")));
            serviceasig.saveOrUpdate(this.getSelectedAsignacion());

            Asignacion asignacion = new Asignacion();
            asignacion.setNasignacionid(serviceasig.getNextPK());
            asignacion.setNtipoconocimientoid(Constante.PREGUNTAS);
            asignacion.setNconocimientoid(this.getSelectedPregunta().getNpreguntaid());
            asignacion.setNestadoid(BigDecimal.valueOf(Long.parseLong("1")));
            CategoriaService categoriaService = (CategoriaService) ServiceFinder.findBean("CategoriaService");
            asignacion.setNusuarioid(categoriaService
                    .getCategoriaById(this.getSelectedPregunta().getNcategoriaid()).getNmoderador());
            asignacion.setDfechacreacion(new Date());
            asignacion.setDfechaasignacion(new Date());
            serviceasig.saveOrUpdate(asignacion);

            LoginMB loginMB = (LoginMB) JSFUtils.getSessionAttribute("loginMB");
            loginMB.refreshNotifications();

            this.fMsjUsu1 = "true";
            pagina = "/index.xhtml";
        }

    } catch (Exception e) {
        log.error(e.getMessage());
        e.printStackTrace();
    }
    return pagina;
}

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

/**
 * @param yearId// w ww . j  a v  a2  s  .  c om
 * @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:org.apache.ofbiz.accounting.invoice.InvoiceServices.java

public static Map<String, Object> createInvoiceFromReturn(DispatchContext dctx, Map<String, Object> context) {
    Delegator delegator = dctx.getDelegator();
    LocalDispatcher dispatcher = dctx.getDispatcher();
    GenericValue userLogin = (GenericValue) context.get("userLogin");
    Locale locale = (Locale) context.get("locale");

    String returnId = (String) context.get("returnId");
    List<GenericValue> billItems = UtilGenerics.checkList(context.get("billItems"));
    String errorMsg = UtilProperties.getMessage(resource, "AccountingErrorCreatingInvoiceForReturn",
            UtilMisc.toMap("returnId", returnId), locale);
    // List invoicesCreated = new ArrayList();
    try {//from ww w .  j  a  va  2 s  . c o m
        String invoiceTypeId;
        String description;
        // get the return header
        GenericValue returnHeader = EntityQuery.use(delegator).from("ReturnHeader").where("returnId", returnId)
                .queryOne();
        if (returnHeader == null || returnHeader.get("returnHeaderTypeId") == null) {
            return ServiceUtil.returnError(
                    UtilProperties.getMessage(resource, "AccountingReturnTypeCannotBeNull", locale));
        }

        if (returnHeader.getString("returnHeaderTypeId").startsWith("CUSTOMER_")) {
            invoiceTypeId = "CUST_RTN_INVOICE";
            description = "Return Invoice for Customer Return #" + returnId;
        } else {
            invoiceTypeId = "PURC_RTN_INVOICE";
            description = "Return Invoice for Vendor Return #" + returnId;
        }

        List<GenericValue> returnItems = returnHeader.getRelated("ReturnItem", null, null, false);
        if (!returnItems.isEmpty()) {
            for (GenericValue returnItem : returnItems) {
                if ("RETURN_COMPLETED".equals(returnItem.getString("statusId"))) {
                    GenericValue product = returnItem.getRelatedOne("Product", false);
                    if (!ProductWorker.isPhysical(product)) {
                        boolean isNonPhysicalItemToReturn = false;
                        List<GenericValue> returnItemBillings = returnItem.getRelated("ReturnItemBilling", null,
                                null, false);

                        if (!returnItemBillings.isEmpty()) {
                            GenericValue invoice = EntityUtil.getFirst(returnItemBillings)
                                    .getRelatedOne("Invoice", false);
                            if ("INVOICE_CANCELLED".equals(invoice.getString("statusId"))) {
                                isNonPhysicalItemToReturn = true;
                            }
                        } else {
                            isNonPhysicalItemToReturn = true;
                        }

                        if (isNonPhysicalItemToReturn) {
                            if (UtilValidate.isEmpty(billItems)) {
                                billItems = new ArrayList<GenericValue>();
                            }

                            billItems.add(returnItem);
                        }
                    }
                }
            }
        }

        Map<String, Object> results = ServiceUtil.returnSuccess();
        if (UtilValidate.isNotEmpty(billItems)) {
            // set the invoice data
            Map<String, Object> input = UtilMisc.<String, Object>toMap("invoiceTypeId", invoiceTypeId,
                    "statusId", "INVOICE_IN_PROCESS");
            input.put("partyId", returnHeader.get("toPartyId"));
            input.put("partyIdFrom", returnHeader.get("fromPartyId"));
            input.put("currencyUomId", returnHeader.get("currencyUomId"));
            input.put("invoiceDate", UtilDateTime.nowTimestamp());
            input.put("description", description);
            input.put("billingAccountId", returnHeader.get("billingAccountId"));
            input.put("userLogin", userLogin);

            // call the service to create the invoice
            Map<String, Object> serviceResults = dispatcher.runSync("createInvoice", input);
            if (ServiceUtil.isError(serviceResults)) {
                return ServiceUtil.returnError(errorMsg, null, null, serviceResults);
            }
            String invoiceId = (String) serviceResults.get("invoiceId");

            // keep track of the invoice total vs the promised return total (how much the customer promised to return)
            BigDecimal invoiceTotal = ZERO;
            BigDecimal promisedTotal = ZERO;

            // loop through shipment receipts to create invoice items and return item billings for each item and adjustment
            int invoiceItemSeqNum = 1;
            String invoiceItemSeqId = UtilFormatOut.formatPaddedNumber(invoiceItemSeqNum,
                    INVOICE_ITEM_SEQUENCE_ID_DIGITS);

            for (GenericValue item : billItems) {
                boolean shipmentReceiptFound = false;
                boolean itemIssuanceFound = false;
                GenericValue returnItem = null;
                BigDecimal quantity = BigDecimal.ZERO;

                if ("ShipmentReceipt".equals(item.getEntityName())) {
                    shipmentReceiptFound = true;
                } else if ("ItemIssuance".equals(item.getEntityName())) {
                    itemIssuanceFound = true;
                } else if ("ReturnItem".equals(item.getEntityName())) {
                    quantity = item.getBigDecimal("returnQuantity");
                    returnItem = item;
                } else {
                    Debug.logError("Unexpected entity " + item + " of type " + item.getEntityName(), module);
                }
                // we need the related return item and product
                if (shipmentReceiptFound) {
                    returnItem = item.getRelatedOne("ReturnItem", true);
                } else if (itemIssuanceFound) {
                    GenericValue shipmentItem = item.getRelatedOne("ShipmentItem", true);
                    GenericValue returnItemShipment = EntityUtil
                            .getFirst(shipmentItem.getRelated("ReturnItemShipment", null, null, false));
                    returnItem = returnItemShipment.getRelatedOne("ReturnItem", true);
                }
                if (returnItem == null)
                    continue; // Just to prevent NPE
                GenericValue product = returnItem.getRelatedOne("Product", true);

                // extract the return price as a big decimal for convenience
                BigDecimal returnPrice = returnItem.getBigDecimal("returnPrice");

                // determine invoice item type from the return item type
                String invoiceItemTypeId = getInvoiceItemType(delegator,
                        returnItem.getString("returnItemTypeId"), null, invoiceTypeId, null);
                if (invoiceItemTypeId == null) {
                    return ServiceUtil.returnError(errorMsg + UtilProperties.getMessage(resource,
                            "AccountingNoKnownInvoiceItemTypeReturnItemType",
                            UtilMisc.toMap("returnItemTypeId", returnItem.getString("returnItemTypeId")),
                            locale));
                }
                if (shipmentReceiptFound) {
                    quantity = item.getBigDecimal("quantityAccepted");
                } else if (itemIssuanceFound) {
                    quantity = item.getBigDecimal("quantity");
                }

                // create the invoice item for this shipment receipt
                input = UtilMisc.toMap("invoiceId", invoiceId, "invoiceItemTypeId", invoiceItemTypeId,
                        "quantity", quantity);
                input.put("invoiceItemSeqId", "" + invoiceItemSeqId); // turn the int into a string with ("" + int) hack
                input.put("amount", returnItem.get("returnPrice"));
                input.put("productId", returnItem.get("productId"));
                input.put("taxableFlag", product.get("taxable"));
                input.put("description", returnItem.get("description"));
                // TODO: what about the productFeatureId?
                input.put("userLogin", userLogin);
                serviceResults = dispatcher.runSync("createInvoiceItem", input);
                if (ServiceUtil.isError(serviceResults)) {
                    return ServiceUtil.returnError(errorMsg, null, null, serviceResults);
                }

                // copy the return item information into ReturnItemBilling
                input = UtilMisc.toMap("returnId", returnId, "returnItemSeqId",
                        returnItem.get("returnItemSeqId"), "invoiceId", invoiceId);
                input.put("invoiceItemSeqId", "" + invoiceItemSeqId); // turn the int into a string with ("" + int) hack
                input.put("quantity", quantity);
                input.put("amount", returnItem.get("returnPrice"));
                input.put("userLogin", userLogin);
                if (shipmentReceiptFound) {
                    input.put("shipmentReceiptId", item.get("receiptId"));
                }
                serviceResults = dispatcher.runSync("createReturnItemBilling", input);
                if (ServiceUtil.isError(serviceResults)) {
                    return ServiceUtil.returnError(errorMsg, null, null, serviceResults);
                }
                if (Debug.verboseOn()) {
                    Debug.logVerbose("Creating Invoice Item with amount " + returnPrice + " and quantity "
                            + quantity + " for shipment [" + item.getString("shipmentId") + ":"
                            + item.getString("shipmentItemSeqId") + "]", module);
                }

                String parentInvoiceItemSeqId = invoiceItemSeqId;
                // increment the seqId counter after creating the invoice item and return item billing
                invoiceItemSeqNum += 1;
                invoiceItemSeqId = UtilFormatOut.formatPaddedNumber(invoiceItemSeqNum,
                        INVOICE_ITEM_SEQUENCE_ID_DIGITS);

                // keep a running total (note: a returnItem may have many receipts. hence, the promised total quantity is the receipt quantityAccepted + quantityRejected)
                BigDecimal cancelQuantity = ZERO;
                if (shipmentReceiptFound) {
                    cancelQuantity = item.getBigDecimal("quantityRejected");
                } else if (itemIssuanceFound) {
                    cancelQuantity = item.getBigDecimal("cancelQuantity");
                }
                if (cancelQuantity == null)
                    cancelQuantity = ZERO;
                BigDecimal actualAmount = returnPrice.multiply(quantity).setScale(DECIMALS, ROUNDING);
                BigDecimal promisedAmount = returnPrice.multiply(quantity.add(cancelQuantity))
                        .setScale(DECIMALS, ROUNDING);
                invoiceTotal = invoiceTotal.add(actualAmount).setScale(DECIMALS, ROUNDING);
                promisedTotal = promisedTotal.add(promisedAmount).setScale(DECIMALS, ROUNDING);

                // for each adjustment related to this ReturnItem, create a separate invoice item
                List<GenericValue> adjustments = returnItem.getRelated("ReturnAdjustment", null, null, true);
                for (GenericValue adjustment : adjustments) {

                    if (adjustment.get("amount") == null) {
                        Debug.logWarning("Return adjustment [" + adjustment.get("returnAdjustmentId")
                                + "] has null amount and will be skipped", module);
                        continue;
                    }

                    // determine invoice item type from the return item type
                    invoiceItemTypeId = getInvoiceItemType(delegator,
                            adjustment.getString("returnAdjustmentTypeId"), null, invoiceTypeId, null);
                    if (invoiceItemTypeId == null) {
                        return ServiceUtil
                                .returnError(
                                        errorMsg + UtilProperties.getMessage(resource,
                                                "AccountingNoKnownInvoiceItemTypeReturnAdjustmentType",
                                                UtilMisc.toMap("returnAdjustmentTypeId",
                                                        adjustment.getString("returnAdjustmentTypeId")),
                                                locale));
                    }

                    // prorate the adjustment amount by the returned amount; do not round ratio
                    BigDecimal ratio = quantity.divide(returnItem.getBigDecimal("returnQuantity"), 100,
                            ROUNDING);
                    BigDecimal amount = adjustment.getBigDecimal("amount");
                    amount = amount.multiply(ratio).setScale(DECIMALS, ROUNDING);
                    if (Debug.verboseOn()) {
                        Debug.logVerbose("Creating Invoice Item with amount "
                                + adjustment.getBigDecimal("amount") + " prorated to " + amount
                                + " for return adjustment [" + adjustment.getString("returnAdjustmentId") + "]",
                                module);
                    }

                    // prepare invoice item data for this adjustment
                    input = UtilMisc.toMap("invoiceId", invoiceId, "invoiceItemTypeId", invoiceItemTypeId,
                            "quantity", BigDecimal.ONE);
                    input.put("amount", amount);
                    input.put("invoiceItemSeqId", "" + invoiceItemSeqId); // turn the int into a string with ("" + int) hack
                    input.put("productId", returnItem.get("productId"));
                    input.put("description", adjustment.get("description"));
                    input.put("overrideGlAccountId", adjustment.get("overrideGlAccountId"));
                    input.put("parentInvoiceId", invoiceId);
                    input.put("parentInvoiceItemSeqId", parentInvoiceItemSeqId);
                    input.put("taxAuthPartyId", adjustment.get("taxAuthPartyId"));
                    input.put("taxAuthGeoId", adjustment.get("taxAuthGeoId"));
                    input.put("userLogin", userLogin);

                    // only set taxable flag when the adjustment is not a tax
                    // TODO: Note that we use the value of Product.taxable here. This is not an ideal solution. Instead, use returnAdjustment.includeInTax
                    if (adjustment.get("returnAdjustmentTypeId").equals("RET_SALES_TAX_ADJ")) {
                        input.put("taxableFlag", "N");
                    }

                    // create the invoice item
                    serviceResults = dispatcher.runSync("createInvoiceItem", input);
                    if (ServiceUtil.isError(serviceResults)) {
                        return ServiceUtil.returnError(errorMsg, null, null, serviceResults);
                    }

                    // increment the seqId counter
                    invoiceItemSeqNum += 1;
                    invoiceItemSeqId = UtilFormatOut.formatPaddedNumber(invoiceItemSeqNum,
                            INVOICE_ITEM_SEQUENCE_ID_DIGITS);

                    // keep a running total (promised adjustment in this case is the same as the invoice adjustment)
                    invoiceTotal = invoiceTotal.add(amount).setScale(DECIMALS, ROUNDING);
                    promisedTotal = promisedTotal.add(amount).setScale(DECIMALS, ROUNDING);
                }
            }

            // ratio of the invoice total to the promised total so far or zero if the amounts were zero
            BigDecimal actualToPromisedRatio = ZERO;
            if (invoiceTotal.signum() != 0) {
                actualToPromisedRatio = invoiceTotal.divide(promisedTotal, 100, ROUNDING); // do not round ratio
            }

            // loop through return-wide adjustments and create invoice items for each
            List<GenericValue> adjustments = returnHeader.getRelated("ReturnAdjustment",
                    UtilMisc.toMap("returnItemSeqId", "_NA_"), null, true);
            for (GenericValue adjustment : adjustments) {

                // determine invoice item type from the return item type
                String invoiceItemTypeId = getInvoiceItemType(delegator,
                        adjustment.getString("returnAdjustmentTypeId"), null, invoiceTypeId, null);
                if (invoiceItemTypeId == null) {
                    return ServiceUtil
                            .returnError(
                                    errorMsg + UtilProperties
                                            .getMessage(resource,
                                                    "AccountingNoKnownInvoiceItemTypeReturnAdjustmentType",
                                                    UtilMisc.toMap("returnAdjustmentTypeId",
                                                            adjustment.getString("returnAdjustmentTypeId")),
                                                    locale));
                }

                // prorate the adjustment amount by the actual to promised ratio
                BigDecimal amount = adjustment.getBigDecimal("amount").multiply(actualToPromisedRatio)
                        .setScale(DECIMALS, ROUNDING);
                if (Debug.verboseOn()) {
                    Debug.logVerbose("Creating Invoice Item with amount " + adjustment.getBigDecimal("amount")
                            + " prorated to " + amount + " for return adjustment ["
                            + adjustment.getString("returnAdjustmentId") + "]", module);
                }

                // prepare the invoice item for the return-wide adjustment
                input = UtilMisc.toMap("invoiceId", invoiceId, "invoiceItemTypeId", invoiceItemTypeId,
                        "quantity", BigDecimal.ONE);
                input.put("amount", amount);
                input.put("invoiceItemSeqId", "" + invoiceItemSeqId); // turn the int into a string with ("" + int) hack
                input.put("description", adjustment.get("description"));
                input.put("overrideGlAccountId", adjustment.get("overrideGlAccountId"));
                input.put("taxAuthPartyId", adjustment.get("taxAuthPartyId"));
                input.put("taxAuthGeoId", adjustment.get("taxAuthGeoId"));
                input.put("userLogin", userLogin);

                // XXX TODO Note: we need to implement ReturnAdjustment.includeInTax for this to work properly
                input.put("taxableFlag", adjustment.get("includeInTax"));

                // create the invoice item
                serviceResults = dispatcher.runSync("createInvoiceItem", input);
                if (ServiceUtil.isError(serviceResults)) {
                    return ServiceUtil.returnError(errorMsg, null, null, serviceResults);
                }

                // increment the seqId counter
                invoiceItemSeqNum += 1;
                invoiceItemSeqId = UtilFormatOut.formatPaddedNumber(invoiceItemSeqNum,
                        INVOICE_ITEM_SEQUENCE_ID_DIGITS);
            }

            // Set the invoice to READY
            serviceResults = dispatcher.runSync("setInvoiceStatus", UtilMisc.<String, Object>toMap("invoiceId",
                    invoiceId, "statusId", "INVOICE_READY", "userLogin", userLogin));
            if (ServiceUtil.isError(serviceResults)) {
                return ServiceUtil.returnError(errorMsg, null, null, serviceResults);
            }

            // return the invoiceId
            results.put("invoiceId", invoiceId);
        }
        return results;
    } catch (GenericServiceException e) {
        Debug.logError(e, errorMsg + e.getMessage(), module);
        return ServiceUtil.returnError(errorMsg + e.getMessage());
    } catch (GenericEntityException e) {
        Debug.logError(e, errorMsg + e.getMessage(), module);
        return ServiceUtil.returnError(errorMsg + e.getMessage());
    }
}

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   w ww  .  jav a 2s .  c  om
    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;
}

From source file:pe.gob.mef.gescon.web.ui.PendienteMB.java

public String edit() {
    String pagina = null;/* w  w  w.  j ava  2  s.  c om*/
    try {
        LoginMB loginMB = (LoginMB) JSFUtils.getSessionAttribute("loginMB");
        User usuario = loginMB.getUser();
        if (this.getChkDestacado()) {
            ConsultaService consultaService = (ConsultaService) ServiceFinder.findBean("ConsultaService");
            HashMap filter = new HashMap();
            filter.put("ntipoconocimientoid", Constante.BASELEGAL);
            BigDecimal cant = consultaService.countDestacadosByTipoConocimiento(filter);
            if (cant.intValue() >= 10) {
                this.setListaDestacados(consultaService.getDestacadosByTipoConocimiento(filter));
                RequestContext.getCurrentInstance().execute("PF('destDialog').show();");
                return "";
            }
        }
        if (!CollectionUtils.isEmpty(this.getListaTarget())) {
            for (BaseLegal v : this.getListaTarget()) {
                if (v.getNestadoid().equals(BigDecimal.ZERO)) {
                    FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR.",
                            "Debe seleccionar el estado de todos los vnculos agregados.");
                    FacesContext.getCurrentInstance().addMessage(null, message);
                    return "";
                }
            }
        }
        if (this.getSelectedCategoria() != null) {
            this.getSelectedBaseLegal().setNcategoriaid(this.getSelectedBaseLegal().getNcategoriaid());
            cat_nueva = this.getSelectedBaseLegal().getNcategoriaid();
        } else {
            this.getSelectedBaseLegal().setNcategoriaid(this.getSelectedBaseLegal().getNcategoriaid());
            cat_nueva = this.getSelectedBaseLegal().getNcategoriaid();
        }
        BaseLegalService service = (BaseLegalService) ServiceFinder.findBean("BaseLegalService");
        this.getSelectedBaseLegal()
                .setVnombre(StringUtils.capitalize(this.getSelectedBaseLegal().getVnombre()));
        this.getSelectedBaseLegal().setVnumero(
                this.getTipoNorma().concat(" - ").concat(StringUtils.upperCase(this.getNumeroNorma())));
        this.getSelectedBaseLegal().setNrangoid(this.getSelectedBaseLegal().getNrangoid());
        this.getSelectedBaseLegal()
                .setNgobnacional(this.getChkGobNacional() ? BigDecimal.ONE : BigDecimal.ZERO);
        this.getSelectedBaseLegal()
                .setNgobregional(this.getChkGobRegional() ? BigDecimal.ONE : BigDecimal.ZERO);
        this.getSelectedBaseLegal().setNgoblocal(this.getChkGobLocal() ? BigDecimal.ONE : BigDecimal.ZERO);
        this.getSelectedBaseLegal()
                .setNmancomunidades(this.getChkMancomunidades() ? BigDecimal.ONE : BigDecimal.ZERO);
        this.getSelectedBaseLegal().setNdestacado(this.getChkDestacado() ? BigDecimal.ONE : BigDecimal.ZERO);
        this.getSelectedBaseLegal().setVsumilla(this.getSelectedBaseLegal().getVsumilla().trim());
        this.getSelectedBaseLegal().setDfechapublicacion(this.getSelectedBaseLegal().getDfechapublicacion());
        this.getSelectedBaseLegal().setVtema(this.getSelectedBaseLegal().getVtema());
        this.getSelectedBaseLegal().setVusuariomodificacion(usuario.getVlogin());
        this.getSelectedBaseLegal().setDfechamodificacion(new Date());
        service.saveOrUpdate(this.getSelectedBaseLegal());

        BaseLegalHistorialService serviceHistorial = (BaseLegalHistorialService) ServiceFinder
                .findBean("BaseLegalHistorialService");
        BaselegalHist hist = serviceHistorial
                .getLastHistorialByBaselegal(this.getSelectedBaseLegal().getNbaselegalid());

        BaselegalHist baseHist = new BaselegalHist();
        baseHist.setNhistorialid(serviceHistorial.getNextPK());
        baseHist.setNbaselegalid(this.getSelectedBaseLegal().getNbaselegalid());
        baseHist.setNcategoriaid(this.getSelectedBaseLegal().getNcategoriaid());
        baseHist.setVnombre(this.getSelectedBaseLegal().getVnombre());
        baseHist.setVnumero(this.getSelectedBaseLegal().getVnumero());
        baseHist.setNrangoid(this.getSelectedBaseLegal().getNrangoid());
        baseHist.setNgobnacional(this.getSelectedBaseLegal().getNgobnacional());
        baseHist.setNgobregional(this.getSelectedBaseLegal().getNgobregional());
        baseHist.setNgoblocal(this.getSelectedBaseLegal().getNgoblocal());
        baseHist.setNmancomunidades(this.getSelectedBaseLegal().getNmancomunidades());
        baseHist.setNdestacado(this.getSelectedBaseLegal().getNdestacado());
        baseHist.setVsumilla(this.getSelectedBaseLegal().getVsumilla());
        baseHist.setDfechapublicacion(this.getSelectedBaseLegal().getDfechapublicacion());
        baseHist.setVtema(this.getSelectedBaseLegal().getVtema());
        baseHist.setNactivo(this.getSelectedBaseLegal().getNactivo());
        baseHist.setNestadoid(this.getSelectedBaseLegal().getNestadoid());
        baseHist.setNversion(BigDecimal.valueOf(hist.getNversion().intValue() + 1));
        baseHist.setVusuariocreacion(usuario.getVlogin());
        baseHist.setDfechacreacion(new Date());
        baseHist.setVusuariomodificacion(this.getSelectedBaseLegal().getVusuariomodificacion());
        baseHist.setDfechamodificacion(this.getSelectedBaseLegal().getDfechamodificacion());
        serviceHistorial.saveOrUpdate(baseHist);

        Tbaselegal tbaselegal = new Tbaselegal();
        BeanUtils.copyProperties(tbaselegal, this.getSelectedBaseLegal());

        String ruta0 = path + this.getSelectedBaseLegal().getNbaselegalid().toString() + "/"
                + BigDecimal.ZERO.toString() + "/";
        String ruta1 = path + this.getSelectedBaseLegal().getNbaselegalid().toString() + "/"
                + baseHist.getNversion().toString() + "/";

        ArchivoService aservice = (ArchivoService) ServiceFinder.findBean("ArchivoService");
        Archivo archivo = aservice.getArchivoByBaseLegal(this.getSelectedBaseLegal());
        if (this.getUploadFile() != null) {
            archivo.setVnombre(this.getUploadFile().getFileName());
            archivo.setVruta(ruta0 + archivo.getVnombre());
            archivo.setVusuariomodificacion(usuario.getVlogin());
            archivo.setDfechamodificacion(new Date());
            aservice.saveOrUpdate(archivo);
            saveFile(ruta0);
        }

        ArchivoHistorialService aserviceHist = (ArchivoHistorialService) ServiceFinder
                .findBean("ArchivoHistorialService");
        ArchivoHist aHist = aserviceHist.getLastArchivoHistByBaseLegalHist(baseHist);

        ArchivoHist archivoHist = new ArchivoHist();
        archivoHist.setNarchivohistid(aserviceHist.getNextPK());
        archivoHist.setNhistorialid(baseHist.getNhistorialid());
        archivoHist.setNbaselegalid(baseHist.getNbaselegalid());
        archivoHist.setVnombre(archivo.getVnombre());
        archivoHist.setVruta(ruta1 + archivo.getVnombre());
        archivoHist.setVusuariocreacion(usuario.getVlogin());
        archivoHist.setDfechacreacion(new Date());
        aserviceHist.saveOrUpdate(archivoHist);
        saveFile(ruta1);

        VinculoBaseLegalService vservice = (VinculoBaseLegalService) ServiceFinder
                .findBean("VinculoBaseLegalService");
        vservice.deleteByBaseLegal(this.getSelectedBaseLegal());
        for (BaseLegal v : this.getListaTarget()) {
            TvinculoBaselegalId id = new TvinculoBaselegalId();
            id.setNbaselegalid(tbaselegal.getNbaselegalid());
            id.setNvinculoid(vservice.getNextPK());
            VinculoBaselegal vinculo = new VinculoBaselegal();
            vinculo.setId(id);
            vinculo.setTbaselegal(tbaselegal);
            vinculo.setNbaselegalvinculadaid(v.getNbaselegalid());
            vinculo.setNtipovinculo(v.getNestadoid());
            vinculo.setDfechacreacion(new Date());
            vinculo.setVusuariocreacion(usuario.getVlogin());
            vservice.saveOrUpdate(vinculo);

            BaseLegal blvinculada = service.getBaselegalById(v.getNbaselegalid());
            blvinculada.setNestadoid(v.getNestadoid());
            blvinculada.setDfechamodificacion(new Date());
            blvinculada.setVusuariomodificacion(usuario.getVlogin());
            service.saveOrUpdate(blvinculada);

            if (v.getNbaselegalid().toString().equals(Constante.ESTADO_BASELEGAL_MODIFICADA)
                    || v.getNbaselegalid().toString().equals(Constante.ESTADO_BASELEGAL_CONCORDADO)) {

                ConocimientoService cservice = (ConocimientoService) ServiceFinder
                        .findBean("ConocimientoService");
                List<Consulta> listaConocimientos = cservice
                        .getConcimientosByVinculoBaseLegalId(blvinculada.getNbaselegalid());
                for (Consulta c : listaConocimientos) {
                    Conocimiento conocimiento = cservice.getConocimientoById(c.getId());
                    conocimiento.setDfechamodificacion(new Date());
                    conocimiento.setVusuariomodificacion(usuario.getVlogin());
                    String descHtml = GcmFileUtils.readStringFromFileServer(conocimiento.getVruta(),
                            "html.txt");
                    String descPlain = GcmFileUtils.readStringFromFileServer(conocimiento.getVruta(),
                            "plain.txt");
                    cservice.saveOrUpdate(conocimiento);

                    HistorialService historialService = (HistorialService) ServiceFinder
                            .findBean("HistorialService");
                    Historial lastHistorial = historialService
                            .getLastHistorialByConocimiento(conocimiento.getNconocimientoid());
                    int lastversion;
                    if (lastHistorial != null) {
                        lastversion = lastHistorial.getNnumversion().intValue();
                    } else {
                        lastversion = 0;
                    }
                    String newpath = "";
                    if (conocimiento.getNtipoconocimientoid().equals(Constante.BASELEGAL)) {
                        newpath = "bl/";
                    } else if (conocimiento.getNtipoconocimientoid().equals(Constante.BUENAPRACTICA)) {
                        newpath = "bp/";
                    } else if (conocimiento.getNtipoconocimientoid().equals(Constante.CONTENIDO)) {
                        newpath = "ct/";
                    } else if (conocimiento.getNtipoconocimientoid().equals(Constante.OPORTUNIDADMEJORA)) {
                        newpath = "om/";
                    } else if (conocimiento.getNtipoconocimientoid().equals(Constante.PREGUNTAS)) {
                        newpath = "pr/";
                    } else if (conocimiento.getNtipoconocimientoid().equals(Constante.WIKI)) {
                        newpath = "wk/";
                    }

                    String url = newpath.concat(conocimiento.getNconocimientoid().toString()).concat("/")
                            .concat(Integer.toString(lastversion + 1)).concat("/");

                    ThistorialId thistorialId = new ThistorialId();
                    thistorialId.setNconocimientoid(conocimiento.getNconocimientoid());
                    thistorialId.setNhistorialid(historialService.getNextPK());
                    Historial historial = new Historial();
                    historial.setId(thistorialId);
                    historial.setNtipoconocimientoid(conocimiento.getNtipoconocimientoid());
                    historial.setNcategoriaid(conocimiento.getNcategoriaid());
                    historial.setVtitulo(conocimiento.getVtitulo());
                    historial.setNactivo(BigDecimal.ONE);
                    historial.setNsituacionid(conocimiento.getNsituacionid());
                    historial.setVruta(url);
                    historial.setNnumversion(BigDecimal.valueOf(lastversion + 1));
                    historial.setDfechacreacion(new Date());
                    historial.setVusuariocreacion(usuario.getVlogin());
                    historialService.saveOrUpdate(historial);

                    GcmFileUtils.writeStringToFileServer(url, "html.txt", descHtml);
                    GcmFileUtils.writeStringToFileServer(url, "plain.txt", descPlain);

                    SeccionService seccionService = (SeccionService) ServiceFinder.findBean("SeccionService");
                    SeccionHistService seccionHistService = (SeccionHistService) ServiceFinder
                            .findBean("SeccionHistService");
                    List<Seccion> listaSecc = seccionService
                            .getSeccionesByConocimiento(conocimiento.getNconocimientoid());
                    if (!CollectionUtils.isEmpty(listaSecc)) {
                        String url0 = conocimiento.getVruta().concat("s");
                        String url1 = url.concat("s");
                        for (Seccion seccion : listaSecc) {
                            seccion.setDetalleHtml(
                                    GcmFileUtils.readStringFromFileServer(seccion.getVruta(), "html.txt"));
                            ruta0 = url0.concat(seccion.getNorden().toString()).concat("/");
                            seccion.setVruta(ruta0);
                            seccion.setDfechamodificacion(new Date());
                            seccion.setVusuariomodificacion(usuario.getVlogin());
                            seccionService.saveOrUpdate(seccion);

                            seccion.setDetallePlain(Jsoup.parse(seccion.getDetalleHtml()).text());

                            ruta1 = url1.concat(seccion.getNorden().toString()).concat("/");
                            TseccionHistId tseccionHistId = new TseccionHistId();
                            tseccionHistId.setNconocimientoid(thistorialId.getNconocimientoid());
                            tseccionHistId.setNhistorialid(thistorialId.getNhistorialid());
                            tseccionHistId.setNseccionhid(seccionHistService.getNextPK());
                            SeccionHist seccionHist = new SeccionHist();
                            seccionHist.setId(tseccionHistId);
                            seccionHist.setNorden(seccion.getNorden());
                            seccionHist.setVruta(ruta1);
                            seccionHist.setVtitulo(seccion.getVtitulo());
                            seccionHist.setVusuariocreacion(usuario.getVlogin());
                            seccionHist.setDfechacreacion(new Date());
                            seccionHistService.saveOrUpdate(seccionHist);

                            GcmFileUtils.writeStringToFileServer(ruta1, "html.txt", seccion.getDetalleHtml());
                            GcmFileUtils.writeStringToFileServer(ruta1, "plain.txt", seccion.getDetallePlain());
                        }
                    }

                    VinculoService vinculoService = (VinculoService) ServiceFinder.findBean("VinculoService");
                    Vinculo vinculoC = new Vinculo();
                    vinculoC.setNvinculoid(vinculoService.getNextPK());
                    vinculoC.setNconocimientoid(conocimiento.getNconocimientoid());
                    vinculoC.setNconocimientovinc(tbaselegal.getNbaselegalid());
                    vinculoC.setNtipoconocimientovinc(Constante.BASELEGAL);
                    vinculoC.setDfechacreacion(new Date());
                    vinculoC.setVusuariocreacion(usuario.getVlogin());
                    vinculoService.saveOrUpdate(vinculoC);

                    List<Vinculo> vinculos = vinculoService
                            .getVinculosByConocimiento(conocimiento.getNtipoconocimientoid());
                    VinculoHistService vinculoHistService = (VinculoHistService) ServiceFinder
                            .findBean("VinculoHistService");
                    for (Vinculo vinc : vinculos) {
                        TvinculoHistId vinculoHistId = new TvinculoHistId();
                        vinculoHistId.setNvinculohid(vinculoHistService.getNextPK());
                        vinculoHistId.setNconocimientoid(thistorialId.getNconocimientoid());
                        vinculoHistId.setNhistorialid(thistorialId.getNhistorialid());
                        VinculoHist vinculoHist = new VinculoHist();
                        vinculoHist.setId(vinculoHistId);
                        vinculoHist.setNconocimientovinc(vinc.getNconocimientovinc());
                        vinculoHist.setDfechacreacion(new Date());
                        vinculoHist.setVusuariocreacion(usuario.getVlogin());
                        vinculoHistService.saveOrUpdate(vinculoHist);
                    }
                }
            } else if (v.getNbaselegalid().toString().equals(Constante.ESTADO_BASELEGAL_DEROGADA)) {
                ConocimientoService cservice = (ConocimientoService) ServiceFinder
                        .findBean("ConocimientoService");
                List<Consulta> listaConocimientos = cservice
                        .getConcimientosByVinculoBaseLegalId(blvinculada.getNbaselegalid());
                for (Consulta c : listaConocimientos) {
                    Conocimiento conocimiento = cservice.getConocimientoById(c.getId());
                    conocimiento.setNflgvinculo(BigDecimal.ONE);
                    conocimiento.setDfechamodificacion(new Date());
                    conocimiento.setVusuariomodificacion(usuario.getVlogin());
                }
            }

            VinculoBaselegalHistorialService vserviceHist = (VinculoBaselegalHistorialService) ServiceFinder
                    .findBean("VinculoBaselegalHistorialService");
            VinculoBaselegalHist vinculoHist = new VinculoBaselegalHist();
            vinculoHist.setNvinculohistid(vserviceHist.getNextPK());
            vinculoHist.setNhistorialid(baseHist.getNhistorialid());
            vinculoHist.setNbaselegalid(baseHist.getNbaselegalid());
            vinculoHist.setNbaselegalvinculadaid(v.getNbaselegalid());
            vinculoHist.setNtipovinculo(v.getNestadoid());
            vinculoHist.setDfechacreacion(new Date());
            vinculoHist.setVusuariocreacion(usuario.getVlogin());
            vserviceHist.saveOrUpdate(vinculoHist);
        }

        if (cat_antigua != cat_nueva) {
            AsignacionService serviceasig = (AsignacionService) ServiceFinder.findBean("AsignacionService");
            this.getSelectedAsignacion().setNestadoid(BigDecimal.valueOf(Long.parseLong("2")));
            this.getSelectedAsignacion().setDfechaatencion(new Date());
            this.getSelectedAsignacion().setNaccionid(BigDecimal.valueOf(Long.parseLong("12")));
            serviceasig.saveOrUpdate(this.getSelectedAsignacion());

            Asignacion asignacion = new Asignacion();
            asignacion.setNasignacionid(serviceasig.getNextPK());
            asignacion.setNtipoconocimientoid(Constante.BASELEGAL);
            asignacion.setNconocimientoid(this.getSelectedBaseLegal().getNbaselegalid());
            asignacion.setNestadoid(BigDecimal.valueOf(Long.parseLong("1")));
            CategoriaService categoriaService = (CategoriaService) ServiceFinder.findBean("CategoriaService");
            asignacion.setNusuarioid(categoriaService
                    .getCategoriaById(this.getSelectedBaseLegal().getNcategoriaid()).getNmoderador());
            asignacion.setDfechaasignacion(new Date());
            asignacion.setDfechacreacion(new Date());
            serviceasig.saveOrUpdate(asignacion);

            pagina = "/index.xhtml";
        } else {
            pagina = "";
        }
        loginMB.refreshNotifications();
    } catch (Exception e) {
        e.getMessage();
        e.printStackTrace();
    }
    return pagina;
}