List of usage examples for java.math BigDecimal divide
public BigDecimal divide(BigDecimal divisor, int scale, RoundingMode roundingMode)
From source file:org.ofbiz.accounting.invoice.InvoiceServices.java
public static Map<String, Object> createCommissionInvoices(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"); List<String> salesInvoiceIds = UtilGenerics.checkList(context.get("invoiceIds")); List<Map<String, String>> invoicesCreated = FastList.newInstance(); Map<String, List<Map<String, Object>>> commissionParties = FastMap.newInstance(); for (String salesInvoiceId : salesInvoiceIds) { List<String> salesRepPartyIds = UtilGenerics.checkList(context.get("partyIds")); BigDecimal amountTotal = InvoiceWorker.getInvoiceTotal(delegator, salesInvoiceId); if (amountTotal.signum() == 0) { Debug.logWarning("Invoice [" + salesInvoiceId + "] has an amount total of [" + amountTotal + "], so no commission invoice will be created", module); return ServiceUtil.returnError(UtilProperties.getMessage(resource, "AccountingInvoiceCommissionZeroInvoiceAmount", locale)); }// w w w . j a va 2 s . c om BigDecimal appliedFraction = amountTotal.divide(amountTotal, 12, ROUNDING); GenericValue invoice = null; boolean isReturn = false; List<String> billFromVendorInvoiceRoles = new ArrayList<String>(); List<GenericValue> invoiceItems = new ArrayList<GenericValue>(); try { List<EntityExpr> invoiceRoleConds = UtilMisc.toList( EntityCondition.makeCondition("invoiceId", EntityOperator.EQUALS, salesInvoiceId), EntityCondition.makeCondition("roleTypeId", EntityOperator.EQUALS, "BILL_FROM_VENDOR")); EntityQuery roleQuery = EntityQuery.use(delegator).select("partyId").from("InvoiceRole") .where(invoiceRoleConds); billFromVendorInvoiceRoles = EntityUtil.getFieldListFromEntityList(roleQuery.queryList(), "partyId", true); invoiceRoleConds = UtilMisc.toList( EntityCondition.makeCondition("invoiceId", EntityOperator.EQUALS, salesInvoiceId), EntityCondition.makeCondition("roleTypeId", EntityOperator.EQUALS, "SALES_REP")); // if the receiving parties is empty then we will create commission invoices for all sales agent associated to sales invoice. if (UtilValidate.isEmpty(salesRepPartyIds)) { salesRepPartyIds = EntityUtil.getFieldListFromEntityList( roleQuery.where(invoiceRoleConds).queryList(), "partyId", true); if (UtilValidate.isEmpty(salesRepPartyIds)) { return ServiceUtil.returnError(UtilProperties.getMessage(resource, "No party found with role sales representative for sales invoice " + salesInvoiceId, locale)); } } else { List<String> salesInvoiceRolePartyIds = EntityUtil.getFieldListFromEntityList( roleQuery.where(invoiceRoleConds).queryList(), "partyId", true); if (UtilValidate.isNotEmpty(salesInvoiceRolePartyIds)) { salesRepPartyIds = UtilGenerics.checkList( CollectionUtils.intersection(salesRepPartyIds, salesInvoiceRolePartyIds)); } } invoice = EntityQuery.use(delegator).from("Invoice").where("invoiceId", salesInvoiceId).queryOne(); String invoiceTypeId = invoice.getString("invoiceTypeId"); if ("CUST_RTN_INVOICE".equals(invoiceTypeId)) { isReturn = true; } else if (!"SALES_INVOICE".equals(invoiceTypeId)) { Debug.logWarning("This type of invoice has no commission; returning success", module); return ServiceUtil.returnError( UtilProperties.getMessage(resource, "AccountingInvoiceCommissionInvalid", locale)); } invoiceItems = EntityQuery.use(delegator).from("InvoiceItem").where("invoiceId", salesInvoiceId) .queryList(); } catch (GenericEntityException e) { return ServiceUtil.returnError(e.getMessage()); } // Map of commission Lists (of Maps) for each party. // Determine commissions for various parties. for (GenericValue invoiceItem : invoiceItems) { BigDecimal amount = ZERO; BigDecimal quantity = ZERO; quantity = invoiceItem.getBigDecimal("quantity"); amount = invoiceItem.getBigDecimal("amount"); amount = isReturn ? amount.negate() : amount; String productId = invoiceItem.getString("productId"); String invoiceItemSeqId = invoiceItem.getString("invoiceItemSeqId"); String invoiceId = invoiceItem.getString("invoiceId"); // Determine commission parties for this invoiceItem if (UtilValidate.isNotEmpty(productId)) { Map<String, Object> resultMap = null; try { resultMap = dispatcher.runSync("getCommissionForProduct", UtilMisc.<String, Object>toMap("productId", productId, "invoiceId", invoiceId, "invoiceItemSeqId", invoiceItemSeqId, "invoiceItemTypeId", invoiceItem.getString("invoiceItemTypeId"), "amount", amount, "quantity", quantity, "userLogin", userLogin)); } catch (GenericServiceException e) { return ServiceUtil.returnError(e.getMessage()); } // build a Map of partyIds (both to and from) in a commission and the amounts // Note that getCommissionForProduct returns a List of Maps with a lot values. See services.xml definition for reference. List<Map<String, Object>> itemCommissions = UtilGenerics .checkList(resultMap.get("commissions")); if (UtilValidate.isNotEmpty(itemCommissions)) { for (Map<String, Object> commissionMap : itemCommissions) { commissionMap.put("invoice", invoice); commissionMap.put("appliedFraction", appliedFraction); if (!billFromVendorInvoiceRoles.contains(commissionMap.get("partyIdFrom")) || !salesRepPartyIds.contains(commissionMap.get("partyIdTo"))) { continue; } String partyIdFromTo = (String) commissionMap.get("partyIdFrom") + (String) commissionMap.get("partyIdTo"); if (!commissionParties.containsKey(partyIdFromTo)) { commissionParties.put(partyIdFromTo, UtilMisc.toList(commissionMap)); } else { (commissionParties.get(partyIdFromTo)).add(commissionMap); } } } } } } Timestamp now = UtilDateTime.nowTimestamp(); // Create invoice for each commission receiving party for (Map.Entry<String, List<Map<String, Object>>> commissionParty : commissionParties.entrySet()) { List<GenericValue> toStore = FastList.newInstance(); List<Map<String, Object>> commList = commissionParty.getValue(); // get the billing parties if (UtilValidate.isEmpty(commList)) { continue; } // From and To are reversed between commission and invoice String partyIdBillTo = (String) (commList.get(0)).get("partyIdFrom"); String partyIdBillFrom = (String) (commList.get(0)).get("partyIdTo"); GenericValue invoice = (GenericValue) (commList.get(0)).get("invoice"); BigDecimal appliedFraction = (BigDecimal) (commList.get(0)).get("appliedFraction"); Long days = (Long) (commList.get(0)).get("days"); // create the invoice record // To and From are in commission's sense, opposite for invoice Map<String, Object> createInvoiceMap = FastMap.newInstance(); createInvoiceMap.put("partyId", partyIdBillTo); createInvoiceMap.put("partyIdFrom", partyIdBillFrom); createInvoiceMap.put("invoiceDate", now); // if there were days associated with the commission agreement, then set a dueDate for the invoice. if (days != null) { createInvoiceMap.put("dueDate", UtilDateTime.getDayEnd(now, days)); } createInvoiceMap.put("invoiceTypeId", "COMMISSION_INVOICE"); // start with INVOICE_IN_PROCESS, in the INVOICE_READY we can't change the invoice (or shouldn't be able to...) createInvoiceMap.put("statusId", "INVOICE_IN_PROCESS"); createInvoiceMap.put("currencyUomId", invoice.getString("currencyUomId")); createInvoiceMap.put("userLogin", userLogin); // store the invoice first Map<String, Object> createInvoiceResult = null; try { createInvoiceResult = dispatcher.runSync("createInvoice", createInvoiceMap); } catch (GenericServiceException e) { return ServiceUtil.returnError( UtilProperties.getMessage(resource, "AccountingInvoiceCommissionError", locale), null, null, createInvoiceResult); } String invoiceId = (String) createInvoiceResult.get("invoiceId"); // create the bill-from (or pay-to) contact mech as the primary PAYMENT_LOCATION of the party from the store GenericValue partyContactMechPurpose = null; try { partyContactMechPurpose = EntityQuery.use(delegator).from("PartyContactMechPurpose") .where("partyId", partyIdBillTo, "contactMechPurposeTypeId", "BILLING_LOCATION") .queryFirst(); } catch (GenericEntityException e) { return ServiceUtil.returnError(e.getMessage()); } if (partyContactMechPurpose != null) { GenericValue invoiceContactMech = delegator.makeValue("InvoiceContactMech", UtilMisc.toMap("invoiceId", invoiceId, "contactMechId", partyContactMechPurpose.getString("contactMechId"), "contactMechPurposeTypeId", "BILLING_LOCATION")); toStore.add(invoiceContactMech); } try { partyContactMechPurpose = EntityQuery.use(delegator).from("PartyContactMechPurpose") .where("partyId", partyIdBillTo, "contactMechPurposeTypeId", "PAYMENT_LOCATION") .queryFirst(); } catch (GenericEntityException e) { return ServiceUtil.returnError(e.getMessage()); } if (partyContactMechPurpose != null) { GenericValue invoiceContactMech = delegator.makeValue("InvoiceContactMech", UtilMisc.toMap("invoiceId", invoiceId, "contactMechId", partyContactMechPurpose.getString("contactMechId"), "contactMechPurposeTypeId", "PAYMENT_LOCATION")); toStore.add(invoiceContactMech); } // create the item records for (Map<String, Object> commissionMap : commList) { BigDecimal elemAmount = ((BigDecimal) commissionMap.get("commission")).multiply(appliedFraction); BigDecimal quantity = (BigDecimal) commissionMap.get("quantity"); String invoiceIdFrom = (String) commissionMap.get("invoiceId"); String invoiceItemSeqIdFrom = (String) commissionMap.get("invoiceItemSeqId"); elemAmount = elemAmount.setScale(DECIMALS, ROUNDING); Map<String, Object> resMap = null; try { resMap = dispatcher.runSync("createInvoiceItem", UtilMisc.toMap("invoiceId", invoiceId, "productId", commissionMap.get("productId"), "invoiceItemTypeId", "COMM_INV_ITEM", "quantity", quantity, "amount", elemAmount, "userLogin", userLogin)); dispatcher.runSync("createInvoiceItemAssoc", UtilMisc.toMap("invoiceIdFrom", invoiceIdFrom, "invoiceItemSeqIdFrom", invoiceItemSeqIdFrom, "invoiceIdTo", invoiceId, "invoiceItemSeqIdTo", resMap.get("invoiceItemSeqId"), "invoiceItemAssocTypeId", "COMMISSION_INVOICE", "partyIdFrom", partyIdBillFrom, "partyIdTo", partyIdBillTo, "quantity", quantity, "amount", elemAmount, "userLogin", userLogin)); } catch (GenericServiceException e) { return ServiceUtil.returnError(e.getMessage()); } if (ServiceUtil.isError(resMap)) { return ServiceUtil.returnError( UtilProperties.getMessage(resource, "AccountingInvoiceCommissionErrorItem", locale), null, null, resMap); } } // store value objects try { delegator.storeAll(toStore); } catch (GenericEntityException e) { Debug.logError(e, "Entity/data problem creating commission invoice: " + e.toString(), module); return ServiceUtil.returnError( UtilProperties.getMessage(resource, "AccountingInvoiceCommissionEntityDataProblem", UtilMisc.toMap("reason", e.toString()), locale)); } invoicesCreated.add(UtilMisc.<String, String>toMap("commissionInvoiceId", invoiceId, "salesRepresentative ", partyIdBillFrom)); } String invCreated = new Integer(invoicesCreated.size()).toString(); Map<String, Object> result = ServiceUtil.returnSuccess(UtilProperties.getMessage(resource, "AccountingCommissionInvoicesCreated", UtilMisc.toMap("invoicesCreated", invCreated), locale)); Debug.logInfo("Created Commission invoices for each commission receiving parties " + invCreated, module); result.put("invoicesCreated", invoicesCreated); return result; }
From source file:org.ofbiz.accounting.invoice.InvoiceServices.java
public static Map<String, Object> createInvoiceForOrder(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"); if (DECIMALS == -1 || ROUNDING == -1) { return ServiceUtil.returnError( UtilProperties.getMessage(resource, "AccountingAritmeticPropertiesNotConfigured", locale)); }/* w ww. ja v a 2 s .c o m*/ String orderId = (String) context.get("orderId"); List<GenericValue> billItems = UtilGenerics.checkList(context.get("billItems")); String invoiceId = (String) context.get("invoiceId"); if (UtilValidate.isEmpty(billItems)) { Debug.logVerbose("No order items to invoice; not creating invoice; returning success", module); return ServiceUtil .returnSuccess(UtilProperties.getMessage(resource, "AccountingNoOrderItemsToInvoice", locale)); } try { GenericValue orderHeader = EntityQuery.use(delegator).from("OrderHeader").where("orderId", orderId) .queryOne(); if (orderHeader == null) { return ServiceUtil .returnError(UtilProperties.getMessage(resource, "AccountingNoOrderHeader", locale)); } // figure out the invoice type String invoiceType = null; String orderType = orderHeader.getString("orderTypeId"); if (orderType.equals("SALES_ORDER")) { invoiceType = "SALES_INVOICE"; } else if (orderType.equals("PURCHASE_ORDER")) { invoiceType = "PURCHASE_INVOICE"; } // Set the precision depending on the type of invoice int invoiceTypeDecimals = UtilNumber.getBigDecimalScale("invoice." + invoiceType + ".decimals"); if (invoiceTypeDecimals == -1) invoiceTypeDecimals = DECIMALS; // Make an order read helper from the order OrderReadHelper orh = new OrderReadHelper(orderHeader); // get the product store GenericValue productStore = orh.getProductStore(); // get the shipping adjustment mode (Y = Pro-Rate; N = First-Invoice) String prorateShipping = productStore != null ? productStore.getString("prorateShipping") : "Y"; if (prorateShipping == null) { prorateShipping = "Y"; } // get the billing parties String billToCustomerPartyId = orh.getBillToParty().getString("partyId"); String billFromVendorPartyId = orh.getBillFromParty().getString("partyId"); // get some price totals BigDecimal shippableAmount = orh.getShippableTotal(null); BigDecimal orderSubTotal = orh.getOrderItemsSubTotal(); // these variables are for pro-rating order amounts across invoices, so they should not be rounded off for maximum accuracy BigDecimal invoiceShipProRateAmount = ZERO; BigDecimal invoiceSubTotal = ZERO; BigDecimal invoiceQuantity = ZERO; GenericValue billingAccount = orderHeader.getRelatedOne("BillingAccount", false); String billingAccountId = billingAccount != null ? billingAccount.getString("billingAccountId") : null; Timestamp invoiceDate = (Timestamp) context.get("eventDate"); if (UtilValidate.isEmpty(invoiceDate)) { // TODO: ideally this should be the same time as when a shipment is sent and be passed in as a parameter invoiceDate = UtilDateTime.nowTimestamp(); } // TODO: perhaps consider billing account net days term as well? Long orderTermNetDays = orh.getOrderTermNetDays(); Timestamp dueDate = null; if (orderTermNetDays != null) { dueDate = UtilDateTime.getDayEnd(invoiceDate, orderTermNetDays); } // create the invoice record if (UtilValidate.isEmpty(invoiceId)) { Map<String, Object> createInvoiceContext = FastMap.newInstance(); createInvoiceContext.put("partyId", billToCustomerPartyId); createInvoiceContext.put("partyIdFrom", billFromVendorPartyId); createInvoiceContext.put("billingAccountId", billingAccountId); createInvoiceContext.put("invoiceDate", invoiceDate); createInvoiceContext.put("dueDate", dueDate); createInvoiceContext.put("invoiceTypeId", invoiceType); // start with INVOICE_IN_PROCESS, in the INVOICE_READY we can't change the invoice (or shouldn't be able to...) createInvoiceContext.put("statusId", "INVOICE_IN_PROCESS"); createInvoiceContext.put("currencyUomId", orderHeader.getString("currencyUom")); createInvoiceContext.put("userLogin", userLogin); // store the invoice first Map<String, Object> createInvoiceResult = dispatcher.runSync("createInvoice", createInvoiceContext); if (ServiceUtil.isError(createInvoiceResult)) { return ServiceUtil.returnError( UtilProperties.getMessage(resource, "AccountingErrorCreatingInvoiceFromOrder", locale), null, null, createInvoiceResult); } // call service, not direct entity op: delegator.create(invoice); invoiceId = (String) createInvoiceResult.get("invoiceId"); } // order roles to invoice roles List<GenericValue> orderRoles = orderHeader.getRelated("OrderRole", null, null, false); Map<String, Object> createInvoiceRoleContext = FastMap.newInstance(); createInvoiceRoleContext.put("invoiceId", invoiceId); createInvoiceRoleContext.put("userLogin", userLogin); for (GenericValue orderRole : orderRoles) { createInvoiceRoleContext.put("partyId", orderRole.getString("partyId")); createInvoiceRoleContext.put("roleTypeId", orderRole.getString("roleTypeId")); Map<String, Object> createInvoiceRoleResult = dispatcher.runSync("createInvoiceRole", createInvoiceRoleContext); if (ServiceUtil.isError(createInvoiceRoleResult)) { return ServiceUtil.returnError( UtilProperties.getMessage(resource, "AccountingErrorCreatingInvoiceFromOrder", locale), null, null, createInvoiceRoleResult); } } // order terms to invoice terms. // TODO: it might be nice to filter OrderTerms to only copy over financial terms. List<GenericValue> orderTerms = orh.getOrderTerms(); createInvoiceTerms(delegator, dispatcher, invoiceId, orderTerms, userLogin, locale); // billing accounts // List billingAccountTerms = null; // for billing accounts we will use related information if (billingAccount != null) { /* * jacopoc: billing account terms were already copied as order terms * when the order was created. // get the billing account terms billingAccountTerms = billingAccount.getRelated("BillingAccountTerm", null, null, false); // set the invoice terms as defined for the billing account createInvoiceTerms(delegator, dispatcher, invoiceId, billingAccountTerms, userLogin, locale); */ // set the invoice bill_to_customer from the billing account List<GenericValue> billToRoles = billingAccount.getRelated("BillingAccountRole", UtilMisc.toMap("roleTypeId", "BILL_TO_CUSTOMER"), null, false); for (GenericValue billToRole : billToRoles) { if (!(billToRole.getString("partyId").equals(billToCustomerPartyId))) { createInvoiceRoleContext = UtilMisc.toMap("invoiceId", invoiceId, "partyId", billToRole.get("partyId"), "roleTypeId", "BILL_TO_CUSTOMER", "userLogin", userLogin); Map<String, Object> createInvoiceRoleResult = dispatcher.runSync("createInvoiceRole", createInvoiceRoleContext); if (ServiceUtil.isError(createInvoiceRoleResult)) { return ServiceUtil.returnError( UtilProperties.getMessage(resource, "AccountingErrorCreatingInvoiceRoleFromOrder", locale), null, null, createInvoiceRoleResult); } } } // set the bill-to contact mech as the contact mech of the billing account if (UtilValidate.isNotEmpty(billingAccount.getString("contactMechId"))) { Map<String, Object> createBillToContactMechContext = UtilMisc.toMap("invoiceId", invoiceId, "contactMechId", billingAccount.getString("contactMechId"), "contactMechPurposeTypeId", "BILLING_LOCATION", "userLogin", userLogin); Map<String, Object> createBillToContactMechResult = dispatcher .runSync("createInvoiceContactMech", createBillToContactMechContext); if (ServiceUtil.isError(createBillToContactMechResult)) { return ServiceUtil.returnError( UtilProperties.getMessage(resource, "AccountingErrorCreatingInvoiceContactMechFromOrder", locale), null, null, createBillToContactMechResult); } } } else { List<GenericValue> billingLocations = orh.getBillingLocations(); if (UtilValidate.isNotEmpty(billingLocations)) { for (GenericValue ocm : billingLocations) { Map<String, Object> createBillToContactMechContext = UtilMisc.toMap("invoiceId", invoiceId, "contactMechId", ocm.getString("contactMechId"), "contactMechPurposeTypeId", "BILLING_LOCATION", "userLogin", userLogin); Map<String, Object> createBillToContactMechResult = dispatcher .runSync("createInvoiceContactMech", createBillToContactMechContext); if (ServiceUtil.isError(createBillToContactMechResult)) { return ServiceUtil.returnError( UtilProperties.getMessage(resource, "AccountingErrorCreatingInvoiceContactMechFromOrder", locale), null, null, createBillToContactMechResult); } } } else { Debug.logWarning("No billing locations found for order [" + orderId + "] and none were created for Invoice [" + invoiceId + "]", module); } } // get a list of the payment method types //DEJ20050705 doesn't appear to be used: List paymentPreferences = orderHeader.getRelated("OrderPaymentPreference", null, null, false); // create the bill-from (or pay-to) contact mech as the primary PAYMENT_LOCATION of the party from the store GenericValue payToAddress = null; if (invoiceType.equals("PURCHASE_INVOICE")) { // for purchase orders, the pay to address is the BILLING_LOCATION of the vendor GenericValue billFromVendor = orh.getPartyFromRole("BILL_FROM_VENDOR"); if (billFromVendor != null) { List<GenericValue> billingContactMechs = billFromVendor.getRelatedOne("Party", false) .getRelated("PartyContactMechPurpose", UtilMisc.toMap("contactMechPurposeTypeId", "BILLING_LOCATION"), null, false); if (UtilValidate.isNotEmpty(billingContactMechs)) { payToAddress = EntityUtil.getFirst(billingContactMechs); } } } else { // for sales orders, it is the payment address on file for the store payToAddress = PaymentWorker.getPaymentAddress(delegator, productStore.getString("payToPartyId")); } if (payToAddress != null) { Map<String, Object> createPayToContactMechContext = UtilMisc.toMap("invoiceId", invoiceId, "contactMechId", payToAddress.getString("contactMechId"), "contactMechPurposeTypeId", "PAYMENT_LOCATION", "userLogin", userLogin); Map<String, Object> createPayToContactMechResult = dispatcher.runSync("createInvoiceContactMech", createPayToContactMechContext); if (ServiceUtil.isError(createPayToContactMechResult)) { return ServiceUtil.returnError( UtilProperties.getMessage(resource, "AccountingErrorCreatingInvoiceContactMechFromOrder", locale), null, null, createPayToContactMechResult); } } // sequence for items - all OrderItems or InventoryReservations + all Adjustments int invoiceItemSeqNum = 1; String invoiceItemSeqId = UtilFormatOut.formatPaddedNumber(invoiceItemSeqNum, INVOICE_ITEM_SEQUENCE_ID_DIGITS); // create the item records for (GenericValue currentValue : billItems) { GenericValue itemIssuance = null; GenericValue orderItem = null; GenericValue shipmentReceipt = null; if ("ItemIssuance".equals(currentValue.getEntityName())) { itemIssuance = currentValue; } else if ("OrderItem".equals(currentValue.getEntityName())) { orderItem = currentValue; } else if ("ShipmentReceipt".equals(currentValue.getEntityName())) { shipmentReceipt = currentValue; } else { Debug.logError("Unexpected entity " + currentValue + " of type " + currentValue.getEntityName(), module); } if (orderItem == null && itemIssuance != null) { orderItem = itemIssuance.getRelatedOne("OrderItem", false); } else if ((orderItem == null) && (shipmentReceipt != null)) { orderItem = shipmentReceipt.getRelatedOne("OrderItem", false); } else if ((orderItem == null) && (itemIssuance == null) && (shipmentReceipt == null)) { Debug.logError( "Cannot create invoice when orderItem, itemIssuance, and shipmentReceipt are all null", module); return ServiceUtil.returnError(UtilProperties.getMessage(resource, "AccountingIllegalValuesPassedToCreateInvoiceService", locale)); } GenericValue product = null; if (orderItem.get("productId") != null) { product = orderItem.getRelatedOne("Product", false); } // get some quantities BigDecimal billingQuantity = null; if (itemIssuance != null) { billingQuantity = itemIssuance.getBigDecimal("quantity"); BigDecimal cancelQty = itemIssuance.getBigDecimal("cancelQuantity"); if (cancelQty == null) { cancelQty = ZERO; } billingQuantity = billingQuantity.subtract(cancelQty).setScale(DECIMALS, ROUNDING); } else if (shipmentReceipt != null) { billingQuantity = shipmentReceipt.getBigDecimal("quantityAccepted"); } else { BigDecimal orderedQuantity = OrderReadHelper.getOrderItemQuantity(orderItem); BigDecimal invoicedQuantity = OrderReadHelper.getOrderItemInvoicedQuantity(orderItem); billingQuantity = orderedQuantity.subtract(invoicedQuantity); if (billingQuantity.compareTo(ZERO) < 0) { billingQuantity = ZERO; } } if (billingQuantity == null) billingQuantity = ZERO; // check if shipping applies to this item. Shipping is calculated for sales invoices, not purchase invoices. boolean shippingApplies = false; if ((product != null) && (ProductWorker.shippingApplies(product)) && (invoiceType.equals("SALES_INVOICE"))) { shippingApplies = true; } BigDecimal billingAmount = orderItem.getBigDecimal("unitPrice").setScale(invoiceTypeDecimals, ROUNDING); Map<String, Object> createInvoiceItemContext = FastMap.newInstance(); createInvoiceItemContext.put("invoiceId", invoiceId); createInvoiceItemContext.put("invoiceItemSeqId", invoiceItemSeqId); createInvoiceItemContext.put("invoiceItemTypeId", getInvoiceItemType(delegator, (orderItem.getString("orderItemTypeId")), (product == null ? null : product.getString("productTypeId")), invoiceType, "INV_FPROD_ITEM")); createInvoiceItemContext.put("description", orderItem.get("itemDescription")); createInvoiceItemContext.put("quantity", billingQuantity); createInvoiceItemContext.put("amount", billingAmount); createInvoiceItemContext.put("productId", orderItem.get("productId")); createInvoiceItemContext.put("productFeatureId", orderItem.get("productFeatureId")); createInvoiceItemContext.put("overrideGlAccountId", orderItem.get("overrideGlAccountId")); //createInvoiceItemContext.put("uomId", ""); createInvoiceItemContext.put("userLogin", userLogin); String itemIssuanceId = null; if (itemIssuance != null && itemIssuance.get("inventoryItemId") != null) { itemIssuanceId = itemIssuance.getString("itemIssuanceId"); createInvoiceItemContext.put("inventoryItemId", itemIssuance.get("inventoryItemId")); } // similarly, tax only for purchase invoices if ((product != null) && (invoiceType.equals("SALES_INVOICE"))) { createInvoiceItemContext.put("taxableFlag", product.get("taxable")); } Map<String, Object> createInvoiceItemResult = dispatcher.runSync("createInvoiceItem", createInvoiceItemContext); if (ServiceUtil.isError(createInvoiceItemResult)) { return ServiceUtil .returnError( UtilProperties.getMessage(resource, "AccountingErrorCreatingInvoiceItemFromOrder", locale), null, null, createInvoiceItemResult); } // this item total BigDecimal thisAmount = billingAmount.multiply(billingQuantity).setScale(invoiceTypeDecimals, ROUNDING); // add to the ship amount only if it applies to this item if (shippingApplies) { invoiceShipProRateAmount = invoiceShipProRateAmount.add(thisAmount) .setScale(invoiceTypeDecimals, ROUNDING); } // increment the invoice subtotal invoiceSubTotal = invoiceSubTotal.add(thisAmount).setScale(100, ROUNDING); // increment the invoice quantity invoiceQuantity = invoiceQuantity.add(billingQuantity).setScale(invoiceTypeDecimals, ROUNDING); // create the OrderItemBilling record Map<String, Object> createOrderItemBillingContext = FastMap.newInstance(); createOrderItemBillingContext.put("invoiceId", invoiceId); createOrderItemBillingContext.put("invoiceItemSeqId", invoiceItemSeqId); createOrderItemBillingContext.put("orderId", orderItem.get("orderId")); createOrderItemBillingContext.put("orderItemSeqId", orderItem.get("orderItemSeqId")); createOrderItemBillingContext.put("itemIssuanceId", itemIssuanceId); createOrderItemBillingContext.put("quantity", billingQuantity); createOrderItemBillingContext.put("amount", billingAmount); createOrderItemBillingContext.put("userLogin", userLogin); if ((shipmentReceipt != null) && (shipmentReceipt.getString("receiptId") != null)) { createOrderItemBillingContext.put("shipmentReceiptId", shipmentReceipt.getString("receiptId")); } Map<String, Object> createOrderItemBillingResult = dispatcher.runSync("createOrderItemBilling", createOrderItemBillingContext); if (ServiceUtil.isError(createOrderItemBillingResult)) { return ServiceUtil .returnError( UtilProperties.getMessage(resource, "AccountingErrorCreatingOrderItemBillingFromOrder", locale), null, null, createOrderItemBillingResult); } if ("ItemIssuance".equals(currentValue.getEntityName())) { List<GenericValue> shipmentItemBillings = EntityQuery.use(delegator).from("ShipmentItemBilling") .where("shipmentId", currentValue.get("shipmentId"), "shipmentItemSeqId", currentValue.get("shipmentItemSeqId")) .queryList(); if (UtilValidate.isEmpty(shipmentItemBillings)) { // create the ShipmentItemBilling record GenericValue shipmentItemBilling = delegator.makeValue("ShipmentItemBilling", UtilMisc.toMap("invoiceId", invoiceId, "invoiceItemSeqId", invoiceItemSeqId)); shipmentItemBilling.put("shipmentId", currentValue.get("shipmentId")); shipmentItemBilling.put("shipmentItemSeqId", currentValue.get("shipmentItemSeqId")); shipmentItemBilling.create(); } } String parentInvoiceItemSeqId = invoiceItemSeqId; // increment the counter invoiceItemSeqNum++; invoiceItemSeqId = UtilFormatOut.formatPaddedNumber(invoiceItemSeqNum, INVOICE_ITEM_SEQUENCE_ID_DIGITS); // Get the original order item from the DB, in case the quantity has been overridden GenericValue originalOrderItem = EntityQuery.use(delegator).from("OrderItem") .where("orderId", orderId, "orderItemSeqId", orderItem.get("orderItemSeqId")).queryOne(); // create the item adjustment as line items List<GenericValue> itemAdjustments = OrderReadHelper.getOrderItemAdjustmentList(orderItem, orh.getAdjustments()); for (GenericValue adj : itemAdjustments) { // Check against OrderAdjustmentBilling to see how much of this adjustment has already been invoiced BigDecimal adjAlreadyInvoicedAmount = null; try { Map<String, Object> checkResult = dispatcher.runSync("calculateInvoicedAdjustmentTotal", UtilMisc.toMap("orderAdjustment", adj)); adjAlreadyInvoicedAmount = (BigDecimal) checkResult.get("invoicedTotal"); } catch (GenericServiceException e) { Debug.logError(e, "Accounting trouble calling calculateInvoicedAdjustmentTotal service", module); return ServiceUtil.returnError(UtilProperties.getMessage(resource, "AccountingTroubleCallingCalculateInvoicedAdjustmentTotalService", locale)); } // If the absolute invoiced amount >= the abs of the adjustment amount, the full amount has already been invoiced, // so skip this adjustment if (adj.get("amount") == null) { // JLR 17/4/7 : fix a bug coming from POS in case of use of a discount (on item(s) or sale, item(s) here) and a cash amount higher than total (hence issuing change) continue; } if (adjAlreadyInvoicedAmount.abs().compareTo( adj.getBigDecimal("amount").setScale(invoiceTypeDecimals, ROUNDING).abs()) > 0) { continue; } BigDecimal originalOrderItemQuantity = OrderReadHelper.getOrderItemQuantity(originalOrderItem); BigDecimal amount = ZERO; if (originalOrderItemQuantity.signum() != 0) { if (adj.get("amount") != null) { // pro-rate the amount // set decimals = 100 means we don't round this intermediate value, which is very important amount = adj.getBigDecimal("amount").divide(originalOrderItemQuantity, 100, ROUNDING); amount = amount.multiply(billingQuantity); // Tax needs to be rounded differently from other order adjustments if (adj.getString("orderAdjustmentTypeId").equals("SALES_TAX")) { amount = amount.setScale(TAX_DECIMALS, TAX_ROUNDING); } else { amount = amount.setScale(invoiceTypeDecimals, ROUNDING); } } else if (adj.get("sourcePercentage") != null) { // pro-rate the amount // set decimals = 100 means we don't round this intermediate value, which is very important BigDecimal percent = adj.getBigDecimal("sourcePercentage"); percent = percent.divide(new BigDecimal(100), 100, ROUNDING); amount = billingAmount.multiply(percent); amount = amount.divide(originalOrderItemQuantity, 100, ROUNDING); amount = amount.multiply(billingQuantity); amount = amount.setScale(invoiceTypeDecimals, ROUNDING); } } if (amount.signum() != 0) { Map<String, Object> createInvoiceItemAdjContext = FastMap.newInstance(); createInvoiceItemAdjContext.put("invoiceId", invoiceId); createInvoiceItemAdjContext.put("invoiceItemSeqId", invoiceItemSeqId); createInvoiceItemAdjContext.put("invoiceItemTypeId", getInvoiceItemType(delegator, adj.getString("orderAdjustmentTypeId"), null, invoiceType, "INVOICE_ITM_ADJ")); createInvoiceItemAdjContext.put("quantity", BigDecimal.ONE); createInvoiceItemAdjContext.put("amount", amount); createInvoiceItemAdjContext.put("productId", orderItem.get("productId")); createInvoiceItemAdjContext.put("productFeatureId", orderItem.get("productFeatureId")); createInvoiceItemAdjContext.put("overrideGlAccountId", adj.get("overrideGlAccountId")); createInvoiceItemAdjContext.put("parentInvoiceId", invoiceId); createInvoiceItemAdjContext.put("parentInvoiceItemSeqId", parentInvoiceItemSeqId); //createInvoiceItemAdjContext.put("uomId", ""); createInvoiceItemAdjContext.put("userLogin", userLogin); createInvoiceItemAdjContext.put("taxAuthPartyId", adj.get("taxAuthPartyId")); createInvoiceItemAdjContext.put("taxAuthGeoId", adj.get("taxAuthGeoId")); createInvoiceItemAdjContext.put("taxAuthorityRateSeqId", adj.get("taxAuthorityRateSeqId")); // some adjustments fill out the comments field instead String description = (UtilValidate.isEmpty(adj.getString("description")) ? adj.getString("comments") : adj.getString("description")); createInvoiceItemAdjContext.put("description", description); // invoice items for sales tax are not taxable themselves // TODO: This is not an ideal solution. Instead, we need to use OrderAdjustment.includeInTax when it is implemented if (!(adj.getString("orderAdjustmentTypeId").equals("SALES_TAX"))) { createInvoiceItemAdjContext.put("taxableFlag", product.get("taxable")); } // If the OrderAdjustment is associated to a ProductPromo, // and the field ProductPromo.overrideOrgPartyId is set, // copy the value to InvoiceItem.overrideOrgPartyId: this // represent an organization override for the payToPartyId if (UtilValidate.isNotEmpty(adj.getString("productPromoId"))) { try { GenericValue productPromo = adj.getRelatedOne("ProductPromo", false); if (UtilValidate.isNotEmpty(productPromo.getString("overrideOrgPartyId"))) { createInvoiceItemAdjContext.put("overrideOrgPartyId", productPromo.getString("overrideOrgPartyId")); } } catch (GenericEntityException e) { Debug.logError(e, "Error looking up ProductPromo with id [" + adj.getString("productPromoId") + "]", module); } } Map<String, Object> createInvoiceItemAdjResult = dispatcher.runSync("createInvoiceItem", createInvoiceItemAdjContext); if (ServiceUtil.isError(createInvoiceItemAdjResult)) { return ServiceUtil.returnError( UtilProperties.getMessage(resource, "AccountingErrorCreatingInvoiceItemFromOrder", locale), null, null, createInvoiceItemAdjResult); } // 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); Map<String, Object> createOrderAdjustmentBillingResult = dispatcher .runSync("createOrderAdjustmentBilling", createOrderAdjustmentBillingContext); if (ServiceUtil.isError(createOrderAdjustmentBillingResult)) { return ServiceUtil.returnError( UtilProperties.getMessage(resource, "AccountingErrorCreatingOrderAdjustmentBillingFromOrder", locale), null, null, createOrderAdjustmentBillingContext); } // this adjustment amount BigDecimal thisAdjAmount = amount; // adjustments only apply to totals when they are not tax or shipping adjustments if (!"SALES_TAX".equals(adj.getString("orderAdjustmentTypeId")) && !"SHIPPING_ADJUSTMENT".equals(adj.getString("orderAdjustmentTypeId"))) { // increment the invoice subtotal invoiceSubTotal = invoiceSubTotal.add(thisAdjAmount).setScale(100, ROUNDING); // add to the ship amount only if it applies to this item if (shippingApplies) { invoiceShipProRateAmount = invoiceShipProRateAmount.add(thisAdjAmount) .setScale(invoiceTypeDecimals, ROUNDING); } } // increment the counter invoiceItemSeqNum++; invoiceItemSeqId = UtilFormatOut.formatPaddedNumber(invoiceItemSeqNum, INVOICE_ITEM_SEQUENCE_ID_DIGITS); } } } // create header adjustments as line items -- always to tax/shipping last Map<GenericValue, BigDecimal> shipAdjustments = FastMap.newInstance(); Map<GenericValue, BigDecimal> taxAdjustments = FastMap.newInstance(); List<GenericValue> headerAdjustments = orh.getOrderHeaderAdjustments(); for (GenericValue adj : headerAdjustments) { // Check against OrderAdjustmentBilling to see how much of this adjustment has already been invoiced BigDecimal adjAlreadyInvoicedAmount = null; try { Map<String, Object> checkResult = dispatcher.runSync("calculateInvoicedAdjustmentTotal", UtilMisc.toMap("orderAdjustment", adj)); adjAlreadyInvoicedAmount = ((BigDecimal) checkResult.get("invoicedTotal")) .setScale(invoiceTypeDecimals, ROUNDING); } catch (GenericServiceException e) { Debug.logError(e, "Accounting trouble calling calculateInvoicedAdjustmentTotal service", module); return ServiceUtil.returnError(UtilProperties.getMessage(resource, "AccountingTroubleCallingCalculateInvoicedAdjustmentTotalService", locale)); } // If the absolute invoiced amount >= the abs of the adjustment amount, the full amount has already been invoiced, // so skip this adjustment if (null == adj.get("amount")) { // JLR 17/4/7 : fix a bug coming from POS in case of use of a discount (on item(s) or sale, sale here) and a cash amount higher than total (hence issuing change) continue; } if (adjAlreadyInvoicedAmount.abs() .compareTo(adj.getBigDecimal("amount").setScale(invoiceTypeDecimals, ROUNDING).abs()) > 0) { continue; } if ("SHIPPING_CHARGES".equals(adj.getString("orderAdjustmentTypeId"))) { shipAdjustments.put(adj, adjAlreadyInvoicedAmount); } else if ("SALES_TAX".equals(adj.getString("orderAdjustmentTypeId"))) { taxAdjustments.put(adj, adjAlreadyInvoicedAmount); } else { // these will effect the shipping pro-rate (unless commented) // other adjustment type calcHeaderAdj(delegator, adj, invoiceType, invoiceId, invoiceItemSeqId, orderSubTotal, invoiceSubTotal, adj.getBigDecimal("amount").setScale(invoiceTypeDecimals, ROUNDING), invoiceTypeDecimals, ROUNDING, userLogin, dispatcher, locale); // invoiceShipProRateAmount += adjAmount; // do adjustments compound or are they based off subtotal? Here we will (unless commented) // invoiceSubTotal += adjAmount; // increment the counter invoiceItemSeqNum++; invoiceItemSeqId = UtilFormatOut.formatPaddedNumber(invoiceItemSeqNum, INVOICE_ITEM_SEQUENCE_ID_DIGITS); } } // next do the shipping adjustments. Note that we do not want to add these to the invoiceSubTotal or orderSubTotal for pro-rating tax later, as that would cause // numerator/denominator problems when the shipping is not pro-rated but rather charged all on the first invoice for (GenericValue adj : shipAdjustments.keySet()) { BigDecimal adjAlreadyInvoicedAmount = shipAdjustments.get(adj); if ("N".equalsIgnoreCase(prorateShipping)) { // Set the divisor and multiplier to 1 to avoid prorating BigDecimal divisor = BigDecimal.ONE; BigDecimal multiplier = BigDecimal.ONE; // The base amount in this case is the adjustment amount minus the total already invoiced for that adjustment, since // it won't be prorated BigDecimal baseAmount = adj.getBigDecimal("amount").setScale(invoiceTypeDecimals, ROUNDING) .subtract(adjAlreadyInvoicedAmount); calcHeaderAdj(delegator, adj, invoiceType, invoiceId, invoiceItemSeqId, divisor, multiplier, baseAmount, invoiceTypeDecimals, ROUNDING, userLogin, dispatcher, locale); } else { // Pro-rate the shipping amount based on shippable information BigDecimal divisor = shippableAmount; BigDecimal multiplier = invoiceShipProRateAmount; // The base amount in this case is the adjustment amount, since we want to prorate based on the full amount BigDecimal baseAmount = adj.getBigDecimal("amount").setScale(invoiceTypeDecimals, ROUNDING); calcHeaderAdj(delegator, adj, invoiceType, invoiceId, invoiceItemSeqId, divisor, multiplier, baseAmount, invoiceTypeDecimals, ROUNDING, userLogin, dispatcher, locale); } // Increment the counter invoiceItemSeqNum++; invoiceItemSeqId = UtilFormatOut.formatPaddedNumber(invoiceItemSeqNum, INVOICE_ITEM_SEQUENCE_ID_DIGITS); } // last do the tax adjustments String prorateTaxes = productStore != null ? productStore.getString("prorateTaxes") : "Y"; if (prorateTaxes == null) { prorateTaxes = "Y"; } for (Map.Entry<GenericValue, BigDecimal> entry : taxAdjustments.entrySet()) { GenericValue adj = entry.getKey(); BigDecimal adjAlreadyInvoicedAmount = entry.getValue(); BigDecimal adjAmount = null; if ("N".equalsIgnoreCase(prorateTaxes)) { // Set the divisor and multiplier to 1 to avoid prorating BigDecimal divisor = BigDecimal.ONE; BigDecimal multiplier = BigDecimal.ONE; // The base amount in this case is the adjustment amount minus the total already invoiced for that adjustment, since // it won't be prorated BigDecimal baseAmount = adj.getBigDecimal("amount").setScale(TAX_DECIMALS, TAX_ROUNDING) .subtract(adjAlreadyInvoicedAmount); adjAmount = calcHeaderAdj(delegator, adj, invoiceType, invoiceId, invoiceItemSeqId, divisor, multiplier, baseAmount, TAX_DECIMALS, TAX_ROUNDING, userLogin, dispatcher, locale); } else { // Pro-rate the tax amount based on shippable information BigDecimal divisor = orderSubTotal; BigDecimal multiplier = invoiceSubTotal; // The base amount in this case is the adjustment amount, since we want to prorate based on the full amount BigDecimal baseAmount = adj.getBigDecimal("amount"); adjAmount = calcHeaderAdj(delegator, adj, invoiceType, invoiceId, invoiceItemSeqId, divisor, multiplier, baseAmount, TAX_DECIMALS, TAX_ROUNDING, userLogin, dispatcher, locale); } invoiceSubTotal = invoiceSubTotal.add(adjAmount).setScale(invoiceTypeDecimals, ROUNDING); // Increment the counter invoiceItemSeqNum++; invoiceItemSeqId = UtilFormatOut.formatPaddedNumber(invoiceItemSeqNum, INVOICE_ITEM_SEQUENCE_ID_DIGITS); } // check for previous order payments List<GenericValue> orderPaymentPrefs = EntityQuery.use(delegator).from("OrderPaymentPreference").where( EntityCondition.makeCondition("orderId", EntityOperator.EQUALS, orderId), EntityCondition.makeCondition("statusId", EntityOperator.NOT_EQUAL, "PAYMENT_CANCELLED")) .queryList(); List<GenericValue> currentPayments = FastList.newInstance(); for (GenericValue paymentPref : orderPaymentPrefs) { List<GenericValue> payments = paymentPref.getRelated("Payment", null, null, false); currentPayments.addAll(payments); } // apply these payments to the invoice if they have any remaining amount to apply for (GenericValue payment : currentPayments) { if ("PMNT_VOID".equals(payment.getString("statusId")) || "PMNT_CANCELLED".equals(payment.getString("statusId"))) { continue; } BigDecimal notApplied = PaymentWorker.getPaymentNotApplied(payment); if (notApplied.signum() > 0) { Map<String, Object> appl = FastMap.newInstance(); appl.put("paymentId", payment.get("paymentId")); appl.put("invoiceId", invoiceId); appl.put("billingAccountId", billingAccountId); appl.put("amountApplied", notApplied); appl.put("userLogin", userLogin); Map<String, Object> createPayApplResult = dispatcher.runSync("createPaymentApplication", appl); if (ServiceUtil.isError(createPayApplResult)) { return ServiceUtil .returnError( UtilProperties.getMessage(resource, "AccountingErrorCreatingInvoiceFromOrder", locale), null, null, createPayApplResult); } } } // Should all be in place now. Depending on the ProductStore.autoApproveInvoice setting, set status to INVOICE_READY (unless it's a purchase invoice, which we set to INVOICE_IN_PROCESS) String autoApproveInvoice = productStore != null ? productStore.getString("autoApproveInvoice") : "Y"; if (!"N".equals(autoApproveInvoice)) { String nextStatusId = "PURCHASE_INVOICE".equals(invoiceType) ? "INVOICE_IN_PROCESS" : "INVOICE_READY"; Map<String, Object> setInvoiceStatusResult = dispatcher.runSync("setInvoiceStatus", UtilMisc.<String, Object>toMap("invoiceId", invoiceId, "statusId", nextStatusId, "userLogin", userLogin)); if (ServiceUtil.isError(setInvoiceStatusResult)) { return ServiceUtil.returnError( UtilProperties.getMessage(resource, "AccountingErrorCreatingInvoiceFromOrder", locale), null, null, setInvoiceStatusResult); } } Map<String, Object> resp = ServiceUtil.returnSuccess(); resp.put("invoiceId", invoiceId); resp.put("invoiceTypeId", invoiceType); return resp; } catch (GenericEntityException e) { Debug.logError(e, "Entity/data problem creating invoice from order items: " + e.toString(), module); return ServiceUtil.returnError( UtilProperties.getMessage(resource, "AccountingEntityDataProblemCreatingInvoiceFromOrderItems", UtilMisc.toMap("reason", e.toString()), locale)); } catch (GenericServiceException e) { Debug.logError(e, "Service/other problem creating invoice from order items: " + e.toString(), module); return ServiceUtil.returnError(UtilProperties.getMessage(resource, "AccountingServiceOtherProblemCreatingInvoiceFromOrderItems", UtilMisc.toMap("reason", e.toString()), locale)); } }
From source file:com.ugam.collage.plus.service.people_count.impl.PeopleAccountingServiceImpl.java
/** * @param empcntClientProjectDataList/*from w w w. j a va 2s . c o m*/ * @param empClientProjectTeamStructList * @param employee * @param month * @param year * @param costCentre * @param countType * @param allignedTimeZero * @param assistedTimeZero * @param apportionedTimeZero * @param allignedTimeOne * @param totalTimeOne * @return */ private void getMultipleProjectDetail(List<EmpcntClientProjectData> empOpenCntClientProjectDataList, List<EmpcntClientProjectData> empCloseCntClientProjectDataList, List<EmpClientProjectTeamStruct> empClientProjectTeamStructList, EmployeeMaster employee, TabMonth month, TabYear year, CostCentre costCentre, CountClassification countType, BigDecimal allignedTimeZero, BigDecimal assistedTimeZero, BigDecimal apportionedTimeZero, BigDecimal allignedTimeOne, BigDecimal totalTimeOne, Integer countTypeId, Map<String, EmployeePcTagsTeamStruct> employeePcTagsTeamStructMap) { logger.debug("<====getMultipleProjectDetail START====>"); Integer employeeId = employee.getEmployeeId(); Integer yearId = year.getYearId(); Integer monthId = month.getMonthId(); String costCentreId = costCentre.getCostCentreId(); BigDecimal deviderHour = new BigDecimal(Constants.TOTAL_WORKING_HOURS); logger.debug("getMultipleProjectDetail parameter===>" + employeeId + "::" + yearId + "::" + monthId + "::" + costCentreId + "::" + deviderHour); // Get project details Map<Integer, EmpClientProjectTeamStruct> employeeProjectIds = new HashMap<Integer, EmpClientProjectTeamStruct>(); Map<Integer, EmpClientProjectTeamStruct> validEmployeeProjectIds = new HashMap<Integer, EmpClientProjectTeamStruct>(); for (EmpClientProjectTeamStruct empClientProjectTeamStructThree : empClientProjectTeamStructList) { employeeProjectIds.put(empClientProjectTeamStructThree.getProjectMaster().getProjectId(), empClientProjectTeamStructThree); } validEmployeeProjectIds.putAll(employeeProjectIds); // logger.debug("validEmployeeProjectIds 1:size===>" + // validEmployeeProjectIds.size()); // check in revenue table for (Integer key : employeeProjectIds.keySet()) { EmpClientProjectTeamStruct mapValues = employeeProjectIds.get(key); List<CollageProjectRevenue> listValues = collageProjectRevenueDao .findByYearIdMonthIdProjectIdCostCentreId(mapValues.getTabYear().getYearId(), mapValues.getTabMonth().getMonthId(), mapValues.getProjectMaster().getProjectId(), costCentre.getCostCentreId()); if (listValues.isEmpty()) { validEmployeeProjectIds.remove(key); } } // logger.debug("validEmployeeProjectIds 2:size===>" + // validEmployeeProjectIds.size()); // For all invalid projects calculate count zero if (validEmployeeProjectIds.isEmpty()) { getZeroProjectsDetail(yearId, monthId, costCentreId, empOpenCntClientProjectDataList, empCloseCntClientProjectDataList, employee, month, year, costCentre, countType, allignedTimeZero, assistedTimeZero, totalTimeOne, totalTimeOne, countTypeId, employeePcTagsTeamStructMap); } // Get list of project from execution data for that employee List<Integer> projectIdList = executionDataDao.findByPersonYearMonthCostCentre(employeeId, yearId, monthId, costCentreId); // logger.debug("execution data projects===>" + projectIdList.size()); // If List is empty if (projectIdList.isEmpty()) { // logger.debug("Contain InValid projects (: Find by Revenue)===>"); Map<Integer, BigDecimal> projectRevenueMap = new HashMap<Integer, BigDecimal>(); BigDecimal sumOfRevenue = BigDecimal.ZERO; List<Object[]> collageProjectRevenueList = collageProjectRevenueDao.findByCostCentreIdYearIdMonthId( costCentre.getCostCentreId(), year.getYearId(), month.getMonthId()); for (Object[] collageProjectRevenue : collageProjectRevenueList) { Integer projectId = (Integer) collageProjectRevenue[0]; BigDecimal revenue = (BigDecimal) collageProjectRevenue[1]; projectRevenueMap.put(projectId, revenue); } // logger.debug("projectRevenueMap size===>" + // projectRevenueMap.size()); for (Integer key : projectRevenueMap.keySet()) { sumOfRevenue = sumOfRevenue.add(projectRevenueMap.get(key)); } logger.debug("sumOfRevenue===>" + sumOfRevenue); for (Integer projectId : validEmployeeProjectIds.keySet()) { EmpClientProjectTeamStruct mapValues = validEmployeeProjectIds.get(projectId); BigDecimal revenue = projectRevenueMap.get(projectId); logger.debug("revenue===>" + revenue); BigDecimal projectRevenueCount = revenue.divide(sumOfRevenue, 2, RoundingMode.HALF_EVEN); projectRevenueCount = projectRevenueCount.setScale(2, RoundingMode.CEILING); // logger.debug("685 empOpenCntClientProjectData ProjectId:Revenue===>"+projectId+" : " // + projectRevenueCount); EmpcntClientProjectData empcntClientProjectData = new EmpcntClientProjectData(employee, mapValues.getCompanyMaster(), countType, month, mapValues.getProjectMaster(), year, costCentre, projectRevenueCount, BigDecimal.ZERO, BigDecimal.ZERO, projectRevenueCount); if (countTypeId == 1) { empOpenCntClientProjectDataList.add(empcntClientProjectData); } if (countTypeId == 2) { empCloseCntClientProjectDataList.add(empcntClientProjectData); } } } else { // logger.debug("Else Contain Valid projects===>"); Integer validEmployeeProjectCount = validEmployeeProjectIds.size(); // Get valid projects list=>project is both revenue data and // execution data Set<Integer> validAllProjects = new HashSet<Integer>(); for (Integer projectId : projectIdList) { List<CollageProjectRevenue> listValues = collageProjectRevenueDao .findByYearIdMonthIdProjectIdCostCentreId(yearId, monthId, projectId, costCentreId); if (!listValues.isEmpty()) { validAllProjects.add(projectId); } } Integer validAllProjectCount = validAllProjects.size(); // logger.debug("validAllProjects :size===>" + // validAllProjects.size()); // Total hour worked by an Employee List<BigDecimal> toatalHours = executionDataDao.findByPersonIdYearIdMonthIdCostCentreId(employeeId, yearId, monthId, costCentreId); BigDecimal toatlTime = toatalHours.get(0); // logger.debug("ToatalHours===>" + toatlTime); // Separate assigned projects from execution data projects Map<Integer, BigDecimal> assignedProjects = new HashMap<Integer, BigDecimal>(); Map<Integer, BigDecimal> unAssignedProjects = new HashMap<Integer, BigDecimal>(); List<Object[]> allProjectTimeList = executionDataDao .findByEmployeeIdYearIdMonthIdCostCentreId(employeeId, yearId, monthId, costCentreId); for (Object[] result : allProjectTimeList) { Integer projectId = (Integer) result[0]; BigDecimal hour = (BigDecimal) result[1]; Integer companyId = (Integer) result[2]; if (validEmployeeProjectIds.containsKey(projectId) && validAllProjects.contains(projectId)) { // logger.debug("UnAssignedProjects===>" + // projectId+"::"+hour+"::"+companyId); assignedProjects.put(projectId, hour); } if (!validEmployeeProjectIds.containsKey(projectId) && validAllProjects.contains(projectId)) { // logger.debug("assignedProjects===>" + // projectId+"::"+hour+"::"+companyId); unAssignedProjects.put(projectId, hour); } } if (validEmployeeProjectCount == validAllProjectCount && validAllProjects.containsAll(validEmployeeProjectIds.keySet()) && unAssignedProjects.isEmpty()) { // logger.debug("validEmployeeProjectCount==validAllProjectCount :(Only in assigned projects)"); for (Integer key : assignedProjects.keySet()) { // Get time spent on each project by employee id Integer projectId = key; BigDecimal timeByProject = assignedProjects.get(key); EmpClientProjectTeamStruct mapValues = validEmployeeProjectIds.get(projectId); // logger.debug("744 : Worked hours (Only in assigned projects) 1===>"+timeByProject+ // " : "+toatlTime); BigDecimal workedHours = timeByProject.divide(toatlTime, 2, RoundingMode.HALF_EVEN); workedHours = workedHours.setScale(2, RoundingMode.CEILING); // logger.debug("745: Worked hours (Only in assigned projects) 2===>"+workedHours); EmpcntClientProjectData empcntClientProjectData = new EmpcntClientProjectData(employee, mapValues.getCompanyMaster(), countType, month, mapValues.getProjectMaster(), year, costCentre, workedHours, assistedTimeZero, apportionedTimeZero, workedHours); if (countTypeId == 1) { empOpenCntClientProjectDataList.add(empcntClientProjectData); } if (countTypeId == 2) { empCloseCntClientProjectDataList.add(empcntClientProjectData); } } } else if (!assignedProjects.isEmpty() && !unAssignedProjects.isEmpty()) { // logger.debug("validEmployeeProjectCount!=validAllProjectCount :(Both in assigned and unassigned projects)"); if (toatlTime.compareTo(new BigDecimal(Constants.TOTAL_WORKING_HOURS)) >= 0) { // logger.debug("Worked hours===> >=168"); for (Integer key : assignedProjects.keySet()) { // Get time spent on each project by employee id Integer projectId = key; BigDecimal timeByProject = assignedProjects.get(key); EmpClientProjectTeamStruct mapValues = validEmployeeProjectIds.get(projectId); BigDecimal workedHours = timeByProject.divide(toatlTime, 2, RoundingMode.HALF_EVEN); workedHours = workedHours.setScale(2, RoundingMode.CEILING); // logger.debug("768: Aligned hours (Both in assigned and unassigned projects) 1===>"+workedHours); EmpcntClientProjectData empcntClientProjectData = new EmpcntClientProjectData(employee, mapValues.getCompanyMaster(), countType, month, mapValues.getProjectMaster(), year, costCentre, workedHours, assistedTimeZero, apportionedTimeZero, workedHours); if (countTypeId == 1) { empOpenCntClientProjectDataList.add(empcntClientProjectData); } if (countTypeId == 2) { empCloseCntClientProjectDataList.add(empcntClientProjectData); } } for (Integer key : unAssignedProjects.keySet()) { // Get time spent on each project by employee id Integer projectId = key; BigDecimal timeByProject = unAssignedProjects.get(key); List<ProjectMaster> projectList = projectMasterDao.findByProjectId(projectId); ProjectMaster projectMaster = projectList.get(0); CompanyMaster companyMaster = projectMaster.getCompanyMaster(); BigDecimal workedHours = timeByProject.divide(toatlTime, 2, RoundingMode.HALF_EVEN); workedHours = workedHours.setScale(2, RoundingMode.CEILING); // logger.debug("787: Assisted hours (Both in assigned and unassigned projects) 2===>"+workedHours); EmpcntClientProjectData empcntClientProjectData = new EmpcntClientProjectData(employee, companyMaster, countType, month, projectMaster, year, costCentre, apportionedTimeZero, workedHours, apportionedTimeZero, workedHours); if (countTypeId == 1) { empOpenCntClientProjectDataList.add(empcntClientProjectData); } if (countTypeId == 2) { empCloseCntClientProjectDataList.add(empcntClientProjectData); } } } else { // logger.debug("Worked hours===> <168"); BigDecimal totalUnAssingnedHours = BigDecimal.ZERO; BigDecimal assingnedHours = BigDecimal.ZERO; for (Integer key : unAssignedProjects.keySet()) { // Get time spent on each project by employee id Integer projectId = key; // logger.debug("Project Id===>"+key); BigDecimal timeByProject = unAssignedProjects.get(key); BigDecimal workedHours = timeByProject.divide(deviderHour, 2, RoundingMode.HALF_EVEN); workedHours = workedHours.setScale(2, RoundingMode.CEILING); totalUnAssingnedHours = totalUnAssingnedHours.add(workedHours); // Assign to assisted count for unAssignedProjects List<ProjectMaster> projectList = projectMasterDao.findByProjectId(projectId); ProjectMaster projectMaster = projectList.get(0); CompanyMaster companyMaster = projectMaster.getCompanyMaster(); // logger.debug("811: Assisted hours (Both in assigned and unassigned projects) 2===>"+workedHours); EmpcntClientProjectData empcntClientProjectData = new EmpcntClientProjectData(employee, companyMaster, countType, month, projectMaster, year, costCentre, apportionedTimeZero, workedHours, apportionedTimeZero, workedHours); if (countTypeId == 1) { empOpenCntClientProjectDataList.add(empcntClientProjectData); } if (countTypeId == 2) { empCloseCntClientProjectDataList.add(empcntClientProjectData); } } totalUnAssingnedHours = BigDecimal.ONE.subtract(totalUnAssingnedHours); // logger.debug("totalUnAssingnedHours===> "+totalUnAssingnedHours); for (Map.Entry<Integer, BigDecimal> entry : assignedProjects.entrySet()) { assingnedHours = assingnedHours.add(entry.getValue()); } // logger.debug("Aligned Hours===> "+assingnedHours); for (Integer key : assignedProjects.keySet()) { Integer projectId = key; BigDecimal timeByProject = assignedProjects.get(key); // logger.debug("831 :projectId : timeByProject===> "+projectId+" : "+timeByProject); EmpClientProjectTeamStruct mapValues = validEmployeeProjectIds.get(projectId); BigDecimal averageWorkedHours = timeByProject.divide(assingnedHours, 2, RoundingMode.HALF_EVEN); // logger.debug("834 :averageWorkedHours : assingnedHours===> "+averageWorkedHours+" : "+assingnedHours); BigDecimal actualWorkedHours = averageWorkedHours.multiply(totalUnAssingnedHours); actualWorkedHours = actualWorkedHours.setScale(2, RoundingMode.CEILING); // logger.debug("836: actualWorkedHours : totalUnAssingnedHours 2===>"+actualWorkedHours+" : "+totalUnAssingnedHours); EmpcntClientProjectData empcntClientProjectData = new EmpcntClientProjectData(employee, mapValues.getCompanyMaster(), countType, month, mapValues.getProjectMaster(), year, costCentre, actualWorkedHours, assistedTimeZero, apportionedTimeZero, actualWorkedHours); if (countTypeId == 1) { empOpenCntClientProjectDataList.add(empcntClientProjectData); } if (countTypeId == 2) { empCloseCntClientProjectDataList.add(empcntClientProjectData); } } } } else if (assignedProjects.isEmpty() && !unAssignedProjects.isEmpty()) { // logger.debug("Only in unassigned projects===>"); if (toatlTime.compareTo(new BigDecimal(Constants.TOTAL_WORKING_HOURS)) >= 0) { // logger.debug(" unassigned projects Worked hours===> >=168"); for (Integer key : unAssignedProjects.keySet()) { // Get time spent on each project by employee id Integer projectId = key; BigDecimal timeByProject = unAssignedProjects.get(key); List<ProjectMaster> projectList = projectMasterDao.findByProjectId(projectId); ProjectMaster projectMaster = projectList.get(0); CompanyMaster companyMaster = projectMaster.getCompanyMaster(); BigDecimal workedHours = timeByProject.divide(toatlTime, 2, RoundingMode.HALF_EVEN); workedHours = workedHours.setScale(2, RoundingMode.CEILING); // logger.debug("860: Assisted hours (Both in assigned and unassigned projects) 2===>"+workedHours); EmpcntClientProjectData empcntClientProjectData = new EmpcntClientProjectData(employee, companyMaster, countType, month, projectMaster, year, costCentre, apportionedTimeZero, workedHours, apportionedTimeZero, workedHours); if (countTypeId == 1) { empOpenCntClientProjectDataList.add(empcntClientProjectData); } if (countTypeId == 2) { empCloseCntClientProjectDataList.add(empcntClientProjectData); } } } else { // logger.debug("unassigned projects Worked hours===> <168"); BigDecimal totalUnAssingnedHours = BigDecimal.ZERO; BigDecimal assingnedHours = BigDecimal.ZERO; for (Integer key : unAssignedProjects.keySet()) { // Get time spent on each project by employee id Integer projectId = key; BigDecimal timeByProject = unAssignedProjects.get(key); BigDecimal workedHours = timeByProject.divide(deviderHour, 2, RoundingMode.HALF_EVEN); workedHours = workedHours.setScale(2, RoundingMode.CEILING); totalUnAssingnedHours = totalUnAssingnedHours.add(workedHours); // Assign to assisted count for unAssignedProjects List<ProjectMaster> projectList = projectMasterDao.findByProjectId(projectId); ProjectMaster projectMaster = projectList.get(0); CompanyMaster companyMaster = projectMaster.getCompanyMaster(); // logger.debug("884: Assisted hours in unassigned projects) 2===>"+workedHours); EmpcntClientProjectData empcntClientProjectData = new EmpcntClientProjectData(employee, companyMaster, countType, month, projectMaster, year, costCentre, apportionedTimeZero, workedHours, apportionedTimeZero, workedHours); if (countTypeId == 1) { empOpenCntClientProjectDataList.add(empcntClientProjectData); } if (countTypeId == 2) { empCloseCntClientProjectDataList.add(empcntClientProjectData); } } // logger.debug("totalUnAssingnedHours===> "+totalUnAssingnedHours); if (totalUnAssingnedHours.compareTo(BigDecimal.ONE) == -1) { BigDecimal remainProportion = BigDecimal.ONE.subtract(totalUnAssingnedHours); getRevenueCountProportion(empOpenCntClientProjectDataList, empCloseCntClientProjectDataList, employee, month, year, costCentre, countType, remainProportion, unAssignedProjects, countTypeId, employeePcTagsTeamStructMap); } } } } // logger.debug("<====getMultipleProjectDetail END====>"); }
From source file:org.apache.ofbiz.accounting.invoice.InvoiceServices.java
public static Map<String, Object> createCommissionInvoices(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"); List<String> salesInvoiceIds = UtilGenerics.checkList(context.get("invoiceIds")); List<Map<String, String>> invoicesCreated = new LinkedList<Map<String, String>>(); Map<String, List<Map<String, Object>>> commissionParties = new HashMap<String, List<Map<String, Object>>>(); for (String salesInvoiceId : salesInvoiceIds) { List<String> salesRepPartyIds = UtilGenerics.checkList(context.get("partyIds")); BigDecimal amountTotal = InvoiceWorker.getInvoiceTotal(delegator, salesInvoiceId); if (amountTotal.signum() == 0) { Debug.logWarning("Invoice [" + salesInvoiceId + "] has an amount total of [" + amountTotal + "], so no commission invoice will be created", module); return ServiceUtil.returnError(UtilProperties.getMessage(resource, "AccountingInvoiceCommissionZeroInvoiceAmount", locale)); }/*from w ww. j a va2 s . c o m*/ BigDecimal appliedFraction = amountTotal.divide(amountTotal, 12, ROUNDING); GenericValue invoice = null; boolean isReturn = false; List<String> billFromVendorInvoiceRoles = new ArrayList<String>(); List<GenericValue> invoiceItems = new ArrayList<GenericValue>(); try { List<EntityExpr> invoiceRoleConds = UtilMisc.toList( EntityCondition.makeCondition("invoiceId", EntityOperator.EQUALS, salesInvoiceId), EntityCondition.makeCondition("roleTypeId", EntityOperator.EQUALS, "BILL_FROM_VENDOR")); EntityQuery roleQuery = EntityQuery.use(delegator).select("partyId").from("InvoiceRole") .where(invoiceRoleConds); billFromVendorInvoiceRoles = EntityUtil.getFieldListFromEntityList(roleQuery.queryList(), "partyId", true); invoiceRoleConds = UtilMisc.toList( EntityCondition.makeCondition("invoiceId", EntityOperator.EQUALS, salesInvoiceId), EntityCondition.makeCondition("roleTypeId", EntityOperator.EQUALS, "SALES_REP")); // if the receiving parties is empty then we will create commission invoices for all sales agent associated to sales invoice. if (UtilValidate.isEmpty(salesRepPartyIds)) { salesRepPartyIds = EntityUtil.getFieldListFromEntityList( roleQuery.where(invoiceRoleConds).queryList(), "partyId", true); if (UtilValidate.isEmpty(salesRepPartyIds)) { return ServiceUtil.returnError(UtilProperties.getMessage(resource, "No party found with role sales representative for sales invoice " + salesInvoiceId, locale)); } } else { List<String> salesInvoiceRolePartyIds = EntityUtil.getFieldListFromEntityList( roleQuery.where(invoiceRoleConds).queryList(), "partyId", true); if (UtilValidate.isNotEmpty(salesInvoiceRolePartyIds)) { salesRepPartyIds = UtilGenerics.checkList( CollectionUtils.intersection(salesRepPartyIds, salesInvoiceRolePartyIds)); } } invoice = EntityQuery.use(delegator).from("Invoice").where("invoiceId", salesInvoiceId).queryOne(); String invoiceTypeId = invoice.getString("invoiceTypeId"); if ("CUST_RTN_INVOICE".equals(invoiceTypeId)) { isReturn = true; } else if (!"SALES_INVOICE".equals(invoiceTypeId)) { Debug.logWarning("This type of invoice has no commission; returning success", module); return ServiceUtil.returnError( UtilProperties.getMessage(resource, "AccountingInvoiceCommissionInvalid", locale)); } invoiceItems = EntityQuery.use(delegator).from("InvoiceItem").where("invoiceId", salesInvoiceId) .queryList(); } catch (GenericEntityException e) { return ServiceUtil.returnError(e.getMessage()); } // Map of commission Lists (of Maps) for each party. // Determine commissions for various parties. for (GenericValue invoiceItem : invoiceItems) { BigDecimal amount = ZERO; BigDecimal quantity = ZERO; quantity = invoiceItem.getBigDecimal("quantity"); amount = invoiceItem.getBigDecimal("amount"); amount = isReturn ? amount.negate() : amount; String productId = invoiceItem.getString("productId"); String invoiceItemSeqId = invoiceItem.getString("invoiceItemSeqId"); String invoiceId = invoiceItem.getString("invoiceId"); // Determine commission parties for this invoiceItem if (UtilValidate.isNotEmpty(productId)) { Map<String, Object> resultMap = null; try { resultMap = dispatcher.runSync("getCommissionForProduct", UtilMisc.<String, Object>toMap("productId", productId, "invoiceId", invoiceId, "invoiceItemSeqId", invoiceItemSeqId, "invoiceItemTypeId", invoiceItem.getString("invoiceItemTypeId"), "amount", amount, "quantity", quantity, "userLogin", userLogin)); } catch (GenericServiceException e) { return ServiceUtil.returnError(e.getMessage()); } // build a Map of partyIds (both to and from) in a commission and the amounts // Note that getCommissionForProduct returns a List of Maps with a lot values. See services.xml definition for reference. List<Map<String, Object>> itemCommissions = UtilGenerics .checkList(resultMap.get("commissions")); if (UtilValidate.isNotEmpty(itemCommissions)) { for (Map<String, Object> commissionMap : itemCommissions) { commissionMap.put("invoice", invoice); commissionMap.put("appliedFraction", appliedFraction); if (!billFromVendorInvoiceRoles.contains(commissionMap.get("partyIdFrom")) || !salesRepPartyIds.contains(commissionMap.get("partyIdTo"))) { continue; } String partyIdFromTo = (String) commissionMap.get("partyIdFrom") + (String) commissionMap.get("partyIdTo"); if (!commissionParties.containsKey(partyIdFromTo)) { commissionParties.put(partyIdFromTo, UtilMisc.toList(commissionMap)); } else { (commissionParties.get(partyIdFromTo)).add(commissionMap); } } } } } } Timestamp now = UtilDateTime.nowTimestamp(); // Create invoice for each commission receiving party for (Map.Entry<String, List<Map<String, Object>>> commissionParty : commissionParties.entrySet()) { List<GenericValue> toStore = new LinkedList<GenericValue>(); List<Map<String, Object>> commList = commissionParty.getValue(); // get the billing parties if (UtilValidate.isEmpty(commList)) { continue; } // From and To are reversed between commission and invoice String partyIdBillTo = (String) (commList.get(0)).get("partyIdFrom"); String partyIdBillFrom = (String) (commList.get(0)).get("partyIdTo"); GenericValue invoice = (GenericValue) (commList.get(0)).get("invoice"); BigDecimal appliedFraction = (BigDecimal) (commList.get(0)).get("appliedFraction"); Long days = (Long) (commList.get(0)).get("days"); // create the invoice record // To and From are in commission's sense, opposite for invoice Map<String, Object> createInvoiceMap = new HashMap<String, Object>(); createInvoiceMap.put("partyId", partyIdBillTo); createInvoiceMap.put("partyIdFrom", partyIdBillFrom); createInvoiceMap.put("invoiceDate", now); // if there were days associated with the commission agreement, then set a dueDate for the invoice. if (days != null) { createInvoiceMap.put("dueDate", UtilDateTime.getDayEnd(now, days)); } createInvoiceMap.put("invoiceTypeId", "COMMISSION_INVOICE"); // start with INVOICE_IN_PROCESS, in the INVOICE_READY we can't change the invoice (or shouldn't be able to...) createInvoiceMap.put("statusId", "INVOICE_IN_PROCESS"); createInvoiceMap.put("currencyUomId", invoice.getString("currencyUomId")); createInvoiceMap.put("userLogin", userLogin); // store the invoice first Map<String, Object> createInvoiceResult = null; try { createInvoiceResult = dispatcher.runSync("createInvoice", createInvoiceMap); } catch (GenericServiceException e) { return ServiceUtil.returnError( UtilProperties.getMessage(resource, "AccountingInvoiceCommissionError", locale), null, null, createInvoiceResult); } String invoiceId = (String) createInvoiceResult.get("invoiceId"); // create the bill-from (or pay-to) contact mech as the primary PAYMENT_LOCATION of the party from the store GenericValue partyContactMechPurpose = null; try { partyContactMechPurpose = EntityQuery.use(delegator).from("PartyContactMechPurpose") .where("partyId", partyIdBillTo, "contactMechPurposeTypeId", "BILLING_LOCATION") .queryFirst(); } catch (GenericEntityException e) { return ServiceUtil.returnError(e.getMessage()); } if (partyContactMechPurpose != null) { GenericValue invoiceContactMech = delegator.makeValue("InvoiceContactMech", UtilMisc.toMap("invoiceId", invoiceId, "contactMechId", partyContactMechPurpose.getString("contactMechId"), "contactMechPurposeTypeId", "BILLING_LOCATION")); toStore.add(invoiceContactMech); } try { partyContactMechPurpose = EntityQuery.use(delegator).from("PartyContactMechPurpose") .where("partyId", partyIdBillTo, "contactMechPurposeTypeId", "PAYMENT_LOCATION") .queryFirst(); } catch (GenericEntityException e) { return ServiceUtil.returnError(e.getMessage()); } if (partyContactMechPurpose != null) { GenericValue invoiceContactMech = delegator.makeValue("InvoiceContactMech", UtilMisc.toMap("invoiceId", invoiceId, "contactMechId", partyContactMechPurpose.getString("contactMechId"), "contactMechPurposeTypeId", "PAYMENT_LOCATION")); toStore.add(invoiceContactMech); } // create the item records for (Map<String, Object> commissionMap : commList) { BigDecimal elemAmount = ((BigDecimal) commissionMap.get("commission")).multiply(appliedFraction); BigDecimal quantity = (BigDecimal) commissionMap.get("quantity"); String invoiceIdFrom = (String) commissionMap.get("invoiceId"); String invoiceItemSeqIdFrom = (String) commissionMap.get("invoiceItemSeqId"); elemAmount = elemAmount.setScale(DECIMALS, ROUNDING); Map<String, Object> resMap = null; try { resMap = dispatcher.runSync("createInvoiceItem", UtilMisc.toMap("invoiceId", invoiceId, "productId", commissionMap.get("productId"), "invoiceItemTypeId", "COMM_INV_ITEM", "quantity", quantity, "amount", elemAmount, "userLogin", userLogin)); dispatcher.runSync("createInvoiceItemAssoc", UtilMisc.toMap("invoiceIdFrom", invoiceIdFrom, "invoiceItemSeqIdFrom", invoiceItemSeqIdFrom, "invoiceIdTo", invoiceId, "invoiceItemSeqIdTo", resMap.get("invoiceItemSeqId"), "invoiceItemAssocTypeId", "COMMISSION_INVOICE", "partyIdFrom", partyIdBillFrom, "partyIdTo", partyIdBillTo, "quantity", quantity, "amount", elemAmount, "userLogin", userLogin)); } catch (GenericServiceException e) { return ServiceUtil.returnError(e.getMessage()); } if (ServiceUtil.isError(resMap)) { return ServiceUtil.returnError( UtilProperties.getMessage(resource, "AccountingInvoiceCommissionErrorItem", locale), null, null, resMap); } } // store value objects try { delegator.storeAll(toStore); } catch (GenericEntityException e) { Debug.logError(e, "Entity/data problem creating commission invoice: " + e.toString(), module); return ServiceUtil.returnError( UtilProperties.getMessage(resource, "AccountingInvoiceCommissionEntityDataProblem", UtilMisc.toMap("reason", e.toString()), locale)); } invoicesCreated.add(UtilMisc.<String, String>toMap("commissionInvoiceId", invoiceId, "salesRepresentative ", partyIdBillFrom)); } String invCreated = Integer.toString(invoicesCreated.size()); Map<String, Object> result = ServiceUtil.returnSuccess(UtilProperties.getMessage(resource, "AccountingCommissionInvoicesCreated", UtilMisc.toMap("invoicesCreated", invCreated), locale)); Debug.logInfo("Created Commission invoices for each commission receiving parties " + invCreated, module); result.put("invoicesCreated", invoicesCreated); return result; }
From source file:org.apache.ofbiz.accounting.invoice.InvoiceServices.java
public static Map<String, Object> createInvoiceForOrder(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"); if (DECIMALS == -1 || ROUNDING == -1) { return ServiceUtil.returnError( UtilProperties.getMessage(resource, "AccountingAritmeticPropertiesNotConfigured", locale)); }//w w w .j av a 2 s . com String orderId = (String) context.get("orderId"); List<GenericValue> billItems = UtilGenerics.checkList(context.get("billItems")); String invoiceId = (String) context.get("invoiceId"); if (UtilValidate.isEmpty(billItems)) { Debug.logVerbose("No order items to invoice; not creating invoice; returning success", module); return ServiceUtil .returnSuccess(UtilProperties.getMessage(resource, "AccountingNoOrderItemsToInvoice", locale)); } try { GenericValue orderHeader = EntityQuery.use(delegator).from("OrderHeader").where("orderId", orderId) .queryOne(); if (orderHeader == null) { return ServiceUtil .returnError(UtilProperties.getMessage(resource, "AccountingNoOrderHeader", locale)); } // figure out the invoice type String invoiceType = null; String orderType = orderHeader.getString("orderTypeId"); if (orderType.equals("SALES_ORDER")) { invoiceType = "SALES_INVOICE"; } else if (orderType.equals("PURCHASE_ORDER")) { invoiceType = "PURCHASE_INVOICE"; } // Set the precision depending on the type of invoice int invoiceTypeDecimals = UtilNumber.getBigDecimalScale("invoice." + invoiceType + ".decimals"); if (invoiceTypeDecimals == -1) invoiceTypeDecimals = DECIMALS; // Make an order read helper from the order OrderReadHelper orh = new OrderReadHelper(orderHeader); // get the product store GenericValue productStore = orh.getProductStore(); // get the shipping adjustment mode (Y = Pro-Rate; N = First-Invoice) String prorateShipping = productStore != null ? productStore.getString("prorateShipping") : "Y"; if (prorateShipping == null) { prorateShipping = "Y"; } // get the billing parties String billToCustomerPartyId = orh.getBillToParty().getString("partyId"); String billFromVendorPartyId = orh.getBillFromParty().getString("partyId"); // get some price totals BigDecimal shippableAmount = orh.getShippableTotal(null); BigDecimal shippableQuantity = orh.getShippableQuantity(null); BigDecimal orderSubTotal = orh.getOrderItemsSubTotal(); BigDecimal orderQuantity = orh.getTotalOrderItemsQuantity(); // these variables are for pro-rating order amounts across invoices, so they should not be rounded off for maximum accuracy BigDecimal invoiceShipProRateAmount = ZERO; BigDecimal invoiceShippableQuantity = ZERO; BigDecimal invoiceSubTotal = ZERO; BigDecimal invoiceQuantity = ZERO; GenericValue billingAccount = orderHeader.getRelatedOne("BillingAccount", false); String billingAccountId = billingAccount != null ? billingAccount.getString("billingAccountId") : null; Timestamp invoiceDate = (Timestamp) context.get("eventDate"); if (UtilValidate.isEmpty(invoiceDate)) { // TODO: ideally this should be the same time as when a shipment is sent and be passed in as a parameter invoiceDate = UtilDateTime.nowTimestamp(); } // TODO: perhaps consider billing account net days term as well? Long orderTermNetDays = orh.getOrderTermNetDays(); Timestamp dueDate = null; if (orderTermNetDays != null) { dueDate = UtilDateTime.getDayEnd(invoiceDate, orderTermNetDays); } // create the invoice record if (UtilValidate.isEmpty(invoiceId)) { Map<String, Object> createInvoiceContext = new HashMap<String, Object>(); createInvoiceContext.put("partyId", billToCustomerPartyId); createInvoiceContext.put("partyIdFrom", billFromVendorPartyId); createInvoiceContext.put("billingAccountId", billingAccountId); createInvoiceContext.put("invoiceDate", invoiceDate); createInvoiceContext.put("dueDate", dueDate); createInvoiceContext.put("invoiceTypeId", invoiceType); // start with INVOICE_IN_PROCESS, in the INVOICE_READY we can't change the invoice (or shouldn't be able to...) createInvoiceContext.put("statusId", "INVOICE_IN_PROCESS"); createInvoiceContext.put("currencyUomId", orderHeader.getString("currencyUom")); createInvoiceContext.put("userLogin", userLogin); // store the invoice first Map<String, Object> createInvoiceResult = dispatcher.runSync("createInvoice", createInvoiceContext); if (ServiceUtil.isError(createInvoiceResult)) { return ServiceUtil.returnError( UtilProperties.getMessage(resource, "AccountingErrorCreatingInvoiceFromOrder", locale), null, null, createInvoiceResult); } // call service, not direct entity op: delegator.create(invoice); invoiceId = (String) createInvoiceResult.get("invoiceId"); } // order roles to invoice roles List<GenericValue> orderRoles = orderHeader.getRelated("OrderRole", null, null, false); Map<String, Object> createInvoiceRoleContext = new HashMap<String, Object>(); createInvoiceRoleContext.put("invoiceId", invoiceId); createInvoiceRoleContext.put("userLogin", userLogin); for (GenericValue orderRole : orderRoles) { createInvoiceRoleContext.put("partyId", orderRole.getString("partyId")); createInvoiceRoleContext.put("roleTypeId", orderRole.getString("roleTypeId")); Map<String, Object> createInvoiceRoleResult = dispatcher.runSync("createInvoiceRole", createInvoiceRoleContext); if (ServiceUtil.isError(createInvoiceRoleResult)) { return ServiceUtil.returnError( UtilProperties.getMessage(resource, "AccountingErrorCreatingInvoiceFromOrder", locale), null, null, createInvoiceRoleResult); } } // order terms to invoice terms. // TODO: it might be nice to filter OrderTerms to only copy over financial terms. List<GenericValue> orderTerms = orh.getOrderTerms(); createInvoiceTerms(delegator, dispatcher, invoiceId, orderTerms, userLogin, locale); // billing accounts // List billingAccountTerms = null; // for billing accounts we will use related information if (billingAccount != null) { /* * jacopoc: billing account terms were already copied as order terms * when the order was created. // get the billing account terms billingAccountTerms = billingAccount.getRelated("BillingAccountTerm", null, null, false); // set the invoice terms as defined for the billing account createInvoiceTerms(delegator, dispatcher, invoiceId, billingAccountTerms, userLogin, locale); */ // set the invoice bill_to_customer from the billing account List<GenericValue> billToRoles = billingAccount.getRelated("BillingAccountRole", UtilMisc.toMap("roleTypeId", "BILL_TO_CUSTOMER"), null, false); for (GenericValue billToRole : billToRoles) { if (!(billToRole.getString("partyId").equals(billToCustomerPartyId))) { createInvoiceRoleContext = UtilMisc.toMap("invoiceId", invoiceId, "partyId", billToRole.get("partyId"), "roleTypeId", "BILL_TO_CUSTOMER", "userLogin", userLogin); Map<String, Object> createInvoiceRoleResult = dispatcher.runSync("createInvoiceRole", createInvoiceRoleContext); if (ServiceUtil.isError(createInvoiceRoleResult)) { return ServiceUtil.returnError( UtilProperties.getMessage(resource, "AccountingErrorCreatingInvoiceRoleFromOrder", locale), null, null, createInvoiceRoleResult); } } } // set the bill-to contact mech as the contact mech of the billing account if (UtilValidate.isNotEmpty(billingAccount.getString("contactMechId"))) { Map<String, Object> createBillToContactMechContext = UtilMisc.toMap("invoiceId", invoiceId, "contactMechId", billingAccount.getString("contactMechId"), "contactMechPurposeTypeId", "BILLING_LOCATION", "userLogin", userLogin); Map<String, Object> createBillToContactMechResult = dispatcher .runSync("createInvoiceContactMech", createBillToContactMechContext); if (ServiceUtil.isError(createBillToContactMechResult)) { return ServiceUtil.returnError( UtilProperties.getMessage(resource, "AccountingErrorCreatingInvoiceContactMechFromOrder", locale), null, null, createBillToContactMechResult); } } } else { List<GenericValue> billingLocations = orh.getBillingLocations(); if (UtilValidate.isNotEmpty(billingLocations)) { for (GenericValue ocm : billingLocations) { Map<String, Object> createBillToContactMechContext = UtilMisc.toMap("invoiceId", invoiceId, "contactMechId", ocm.getString("contactMechId"), "contactMechPurposeTypeId", "BILLING_LOCATION", "userLogin", userLogin); Map<String, Object> createBillToContactMechResult = dispatcher .runSync("createInvoiceContactMech", createBillToContactMechContext); if (ServiceUtil.isError(createBillToContactMechResult)) { return ServiceUtil.returnError( UtilProperties.getMessage(resource, "AccountingErrorCreatingInvoiceContactMechFromOrder", locale), null, null, createBillToContactMechResult); } } } else { Debug.logWarning("No billing locations found for order [" + orderId + "] and none were created for Invoice [" + invoiceId + "]", module); } } // get a list of the payment method types //DEJ20050705 doesn't appear to be used: List paymentPreferences = orderHeader.getRelated("OrderPaymentPreference", null, null, false); // create the bill-from (or pay-to) contact mech as the primary PAYMENT_LOCATION of the party from the store GenericValue payToAddress = null; if (invoiceType.equals("PURCHASE_INVOICE")) { // for purchase orders, the pay to address is the BILLING_LOCATION of the vendor GenericValue billFromVendor = orh.getPartyFromRole("BILL_FROM_VENDOR"); if (billFromVendor != null) { List<GenericValue> billingContactMechs = billFromVendor.getRelatedOne("Party", false) .getRelated("PartyContactMechPurpose", UtilMisc.toMap("contactMechPurposeTypeId", "BILLING_LOCATION"), null, false); if (UtilValidate.isNotEmpty(billingContactMechs)) { payToAddress = EntityUtil.getFirst(billingContactMechs); } } } else { // for sales orders, it is the payment address on file for the store payToAddress = PaymentWorker.getPaymentAddress(delegator, productStore.getString("payToPartyId")); } if (payToAddress != null) { Map<String, Object> createPayToContactMechContext = UtilMisc.toMap("invoiceId", invoiceId, "contactMechId", payToAddress.getString("contactMechId"), "contactMechPurposeTypeId", "PAYMENT_LOCATION", "userLogin", userLogin); Map<String, Object> createPayToContactMechResult = dispatcher.runSync("createInvoiceContactMech", createPayToContactMechContext); if (ServiceUtil.isError(createPayToContactMechResult)) { return ServiceUtil.returnError( UtilProperties.getMessage(resource, "AccountingErrorCreatingInvoiceContactMechFromOrder", locale), null, null, createPayToContactMechResult); } } // sequence for items - all OrderItems or InventoryReservations + all Adjustments int invoiceItemSeqNum = 1; String invoiceItemSeqId = UtilFormatOut.formatPaddedNumber(invoiceItemSeqNum, INVOICE_ITEM_SEQUENCE_ID_DIGITS); // create the item records for (GenericValue currentValue : billItems) { GenericValue itemIssuance = null; GenericValue orderItem = null; GenericValue shipmentReceipt = null; if ("ItemIssuance".equals(currentValue.getEntityName())) { itemIssuance = currentValue; } else if ("OrderItem".equals(currentValue.getEntityName())) { orderItem = currentValue; } else if ("ShipmentReceipt".equals(currentValue.getEntityName())) { shipmentReceipt = currentValue; } else { Debug.logError("Unexpected entity " + currentValue + " of type " + currentValue.getEntityName(), module); } if (orderItem == null && itemIssuance != null) { orderItem = itemIssuance.getRelatedOne("OrderItem", false); } else if ((orderItem == null) && (shipmentReceipt != null)) { orderItem = shipmentReceipt.getRelatedOne("OrderItem", false); } else if ((orderItem == null) && (itemIssuance == null) && (shipmentReceipt == null)) { Debug.logError( "Cannot create invoice when orderItem, itemIssuance, and shipmentReceipt are all null", module); return ServiceUtil.returnError(UtilProperties.getMessage(resource, "AccountingIllegalValuesPassedToCreateInvoiceService", locale)); } GenericValue product = null; if (orderItem.get("productId") != null) { product = orderItem.getRelatedOne("Product", false); } // get some quantities BigDecimal billingQuantity = null; if (itemIssuance != null) { billingQuantity = itemIssuance.getBigDecimal("quantity"); BigDecimal cancelQty = itemIssuance.getBigDecimal("cancelQuantity"); if (cancelQty == null) { cancelQty = ZERO; } billingQuantity = billingQuantity.subtract(cancelQty).setScale(DECIMALS, ROUNDING); } else if (shipmentReceipt != null) { billingQuantity = shipmentReceipt.getBigDecimal("quantityAccepted"); } else { BigDecimal orderedQuantity = OrderReadHelper.getOrderItemQuantity(orderItem); BigDecimal invoicedQuantity = OrderReadHelper.getOrderItemInvoicedQuantity(orderItem); billingQuantity = orderedQuantity.subtract(invoicedQuantity); if (billingQuantity.compareTo(ZERO) < 0) { billingQuantity = ZERO; } } if (billingQuantity == null) billingQuantity = ZERO; // check if shipping applies to this item. Shipping is calculated for sales invoices, not purchase invoices. boolean shippingApplies = false; if ((product != null) && (ProductWorker.shippingApplies(product)) && (invoiceType.equals("SALES_INVOICE"))) { shippingApplies = true; } BigDecimal billingAmount = BigDecimal.ZERO; GenericValue OrderAdjustment = EntityUtil.getFirst(orderItem.getRelated("OrderAdjustment", UtilMisc.toMap("orderAdjustmentTypeId", "VAT_TAX"), null, false)); /* Apply formula to get actual product price to set amount in invoice item Formula is: productPrice = (productPriceWithTax.multiply(100)) / (orderAdj sourcePercentage + 100)) product price = (43*100) / (20+100) = 35.83 (Here product price is 43 with VAT) */ if (UtilValidate.isNotEmpty(OrderAdjustment) && (OrderAdjustment.getBigDecimal("amount").signum() == 0) && UtilValidate.isNotEmpty(OrderAdjustment.getBigDecimal("amountAlreadyIncluded")) && OrderAdjustment.getBigDecimal("amountAlreadyIncluded").signum() != 0) { BigDecimal sourcePercentageTotal = OrderAdjustment.getBigDecimal("sourcePercentage") .add(new BigDecimal(100)); billingAmount = orderItem.getBigDecimal("unitPrice") .divide(sourcePercentageTotal, 100, ROUNDING).multiply(new BigDecimal(100)) .setScale(invoiceTypeDecimals, ROUNDING); } else { billingAmount = orderItem.getBigDecimal("unitPrice").setScale(invoiceTypeDecimals, ROUNDING); } Map<String, Object> createInvoiceItemContext = new HashMap<String, Object>(); createInvoiceItemContext.put("invoiceId", invoiceId); createInvoiceItemContext.put("invoiceItemSeqId", invoiceItemSeqId); createInvoiceItemContext.put("invoiceItemTypeId", getInvoiceItemType(delegator, (orderItem.getString("orderItemTypeId")), (product == null ? null : product.getString("productTypeId")), invoiceType, "INV_FPROD_ITEM")); createInvoiceItemContext.put("description", orderItem.get("itemDescription")); createInvoiceItemContext.put("quantity", billingQuantity); createInvoiceItemContext.put("amount", billingAmount); createInvoiceItemContext.put("productId", orderItem.get("productId")); createInvoiceItemContext.put("productFeatureId", orderItem.get("productFeatureId")); createInvoiceItemContext.put("overrideGlAccountId", orderItem.get("overrideGlAccountId")); createInvoiceItemContext.put("userLogin", userLogin); String itemIssuanceId = null; if (itemIssuance != null && itemIssuance.get("inventoryItemId") != null) { itemIssuanceId = itemIssuance.getString("itemIssuanceId"); createInvoiceItemContext.put("inventoryItemId", itemIssuance.get("inventoryItemId")); } // similarly, tax only for purchase invoices if ((product != null) && (invoiceType.equals("SALES_INVOICE"))) { createInvoiceItemContext.put("taxableFlag", product.get("taxable")); } Map<String, Object> createInvoiceItemResult = dispatcher.runSync("createInvoiceItem", createInvoiceItemContext); if (ServiceUtil.isError(createInvoiceItemResult)) { return ServiceUtil .returnError( UtilProperties.getMessage(resource, "AccountingErrorCreatingInvoiceItemFromOrder", locale), null, null, createInvoiceItemResult); } // this item total BigDecimal thisAmount = billingAmount.multiply(billingQuantity).setScale(invoiceTypeDecimals, ROUNDING); // add to the ship amount only if it applies to this item if (shippingApplies) { invoiceShipProRateAmount = invoiceShipProRateAmount.add(thisAmount) .setScale(invoiceTypeDecimals, ROUNDING); invoiceShippableQuantity = invoiceQuantity.add(billingQuantity).setScale(invoiceTypeDecimals, ROUNDING); } // increment the invoice subtotal invoiceSubTotal = invoiceSubTotal.add(thisAmount).setScale(100, ROUNDING); // increment the invoice quantity invoiceQuantity = invoiceQuantity.add(billingQuantity).setScale(invoiceTypeDecimals, ROUNDING); // create the OrderItemBilling record Map<String, Object> createOrderItemBillingContext = new HashMap<String, Object>(); createOrderItemBillingContext.put("invoiceId", invoiceId); createOrderItemBillingContext.put("invoiceItemSeqId", invoiceItemSeqId); createOrderItemBillingContext.put("orderId", orderItem.get("orderId")); createOrderItemBillingContext.put("orderItemSeqId", orderItem.get("orderItemSeqId")); createOrderItemBillingContext.put("itemIssuanceId", itemIssuanceId); createOrderItemBillingContext.put("quantity", billingQuantity); createOrderItemBillingContext.put("amount", billingAmount); createOrderItemBillingContext.put("userLogin", userLogin); if ((shipmentReceipt != null) && (shipmentReceipt.getString("receiptId") != null)) { createOrderItemBillingContext.put("shipmentReceiptId", shipmentReceipt.getString("receiptId")); } Map<String, Object> createOrderItemBillingResult = dispatcher.runSync("createOrderItemBilling", createOrderItemBillingContext); if (ServiceUtil.isError(createOrderItemBillingResult)) { return ServiceUtil .returnError( UtilProperties.getMessage(resource, "AccountingErrorCreatingOrderItemBillingFromOrder", locale), null, null, createOrderItemBillingResult); } if ("ItemIssuance".equals(currentValue.getEntityName())) { /* Find ShipmentItemBilling based on shipmentId, shipmentItemSeqId, invoiceId, invoiceItemSeqId as because if any order item has multiple quantity and reserved by multiple inventories then there will be multiple invoice items. In that case ShipmentItemBilling was creating only for one invoice item. Fixed under OFBIZ-6806. */ List<GenericValue> shipmentItemBillings = EntityQuery.use(delegator).from("ShipmentItemBilling") .where("shipmentId", currentValue.get("shipmentId"), "shipmentItemSeqId", currentValue.get("shipmentItemSeqId"), "invoiceId", invoiceId, "invoiceItemSeqId", invoiceItemSeqId) .queryList(); if (UtilValidate.isEmpty(shipmentItemBillings)) { // create the ShipmentItemBilling record GenericValue shipmentItemBilling = delegator.makeValue("ShipmentItemBilling", UtilMisc.toMap("invoiceId", invoiceId, "invoiceItemSeqId", invoiceItemSeqId)); shipmentItemBilling.put("shipmentId", currentValue.get("shipmentId")); shipmentItemBilling.put("shipmentItemSeqId", currentValue.get("shipmentItemSeqId")); shipmentItemBilling.create(); } } String parentInvoiceItemSeqId = invoiceItemSeqId; // increment the counter invoiceItemSeqNum++; invoiceItemSeqId = UtilFormatOut.formatPaddedNumber(invoiceItemSeqNum, INVOICE_ITEM_SEQUENCE_ID_DIGITS); // Get the original order item from the DB, in case the quantity has been overridden GenericValue originalOrderItem = EntityQuery.use(delegator).from("OrderItem") .where("orderId", orderId, "orderItemSeqId", orderItem.get("orderItemSeqId")).queryOne(); // create the item adjustment as line items List<GenericValue> itemAdjustments = OrderReadHelper.getOrderItemAdjustmentList(orderItem, orh.getAdjustments()); for (GenericValue adj : itemAdjustments) { // Check against OrderAdjustmentBilling to see how much of this adjustment has already been invoiced BigDecimal adjAlreadyInvoicedAmount = null; try { Map<String, Object> checkResult = dispatcher.runSync("calculateInvoicedAdjustmentTotal", UtilMisc.toMap("orderAdjustment", adj)); adjAlreadyInvoicedAmount = (BigDecimal) checkResult.get("invoicedTotal"); } catch (GenericServiceException e) { Debug.logError(e, "Accounting trouble calling calculateInvoicedAdjustmentTotal service", module); return ServiceUtil.returnError(UtilProperties.getMessage(resource, "AccountingTroubleCallingCalculateInvoicedAdjustmentTotalService", locale)); } // if (adj.get("amount") == null) { TODO check usage with webPos. Was: fix a bug coming from POS in case of use of a discount (on item(s) or sale, item(s) here) and a cash amount higher than total (hence issuing change) // continue; // } // Set adjustment amount as amountAlreadyIncluded to continue invoice item creation process Boolean isTaxIncludedInPrice = adj.getString("orderAdjustmentTypeId").equals("VAT_TAX") && UtilValidate.isNotEmpty(adj.getBigDecimal("amountAlreadyIncluded")) && adj.getBigDecimal("amountAlreadyIncluded").signum() != 0; if ((adj.getBigDecimal("amount").signum() == 0) && isTaxIncludedInPrice) { adj.set("amount", adj.getBigDecimal("amountAlreadyIncluded")); } // If the absolute invoiced amount >= the abs of the adjustment amount, the full amount has already been invoiced, so skip this adjustment if (adjAlreadyInvoicedAmount.abs().compareTo( adj.getBigDecimal("amount").setScale(invoiceTypeDecimals, ROUNDING).abs()) > 0) { continue; } BigDecimal originalOrderItemQuantity = OrderReadHelper.getOrderItemQuantity(originalOrderItem); BigDecimal amount = ZERO; if (originalOrderItemQuantity.signum() != 0) { if (adj.get("amount") != null) { if ("PROMOTION_ADJUSTMENT".equals(adj.getString("orderAdjustmentTypeId")) && adj.get("productPromoId") != null) { /* Find negative amountAlreadyIncluded in OrderAdjustment to subtract it from discounted amount. As we stored negative sales tax amount in order adjustment for discounted item. */ List<EntityExpr> exprs = UtilMisc.toList( EntityCondition.makeCondition("orderId", EntityOperator.EQUALS, orderItem.getString("orderId")), EntityCondition.makeCondition("orderItemSeqId", EntityOperator.EQUALS, orderItem.getString("orderItemSeqId")), EntityCondition.makeCondition("orderAdjustmentTypeId", EntityOperator.EQUALS, "VAT_TAX"), EntityCondition.makeCondition("amountAlreadyIncluded", EntityOperator.LESS_THAN, BigDecimal.ZERO)); EntityCondition andCondition = EntityCondition.makeCondition(exprs, EntityOperator.AND); GenericValue orderAdjustment = EntityUtil.getFirst(delegator .findList("OrderAdjustment", andCondition, null, null, null, false)); if (UtilValidate.isNotEmpty(orderAdjustment)) { amount = adj.getBigDecimal("amount") .subtract(orderAdjustment.getBigDecimal("amountAlreadyIncluded")) .setScale(100, ROUNDING); } else { amount = adj.getBigDecimal("amount"); } } else { // pro-rate the amount // set decimals = 100 means we don't round this intermediate value, which is very important if (isTaxIncludedInPrice) { BigDecimal priceWithTax = originalOrderItem.getBigDecimal("unitPrice"); // Get tax included in item price amount = priceWithTax.subtract(billingAmount); amount = amount.multiply(billingQuantity); // get adjustment amount /* Get tax amount of other invoice and calculate remaining amount need to store in invoice item(Handle case of of partial shipment and promotional item) to adjust tax amount in invoice item. */ BigDecimal otherInvoiceTaxAmount = BigDecimal.ZERO; GenericValue orderAdjBilling = EntityUtil.getFirst(delegator.findByAnd( "OrderAdjustmentBilling", UtilMisc.toMap("orderAdjustmentId", adj.getString("orderAdjustmentId")), null, false)); if (UtilValidate.isNotEmpty(orderAdjBilling)) { List<GenericValue> invoiceItems = delegator.findByAnd("InvoiceItem", UtilMisc.toMap("invoiceId", orderAdjBilling.getString("invoiceId"), "invoiceItemTypeId", "ITM_SALES_TAX", "productId", originalOrderItem.getString("productId")), null, isTaxIncludedInPrice); for (GenericValue invoiceItem : invoiceItems) { otherInvoiceTaxAmount = otherInvoiceTaxAmount .add(invoiceItem.getBigDecimal("amount")); } if (otherInvoiceTaxAmount.compareTo(BigDecimal.ZERO) > 0) { BigDecimal remainingAmount = adj.getBigDecimal("amountAlreadyIncluded") .subtract(otherInvoiceTaxAmount); amount = amount.min(remainingAmount); } } amount = amount.min(adj.getBigDecimal("amountAlreadyIncluded")).setScale(100, ROUNDING); } else { amount = adj.getBigDecimal("amount").divide(originalOrderItemQuantity, 100, ROUNDING); amount = amount.multiply(billingQuantity); } } // Tax needs to be rounded differently from other order adjustments if (adj.getString("orderAdjustmentTypeId").equals("SALES_TAX")) { amount = amount.setScale(TAX_DECIMALS, TAX_ROUNDING); } else { amount = amount.setScale(invoiceTypeDecimals, ROUNDING); } } else if (adj.get("sourcePercentage") != null) { // pro-rate the amount // set decimals = 100 means we don't round this intermediate value, which is very important BigDecimal percent = adj.getBigDecimal("sourcePercentage"); percent = percent.divide(new BigDecimal(100), 100, ROUNDING); amount = billingAmount.multiply(percent); amount = amount.divide(originalOrderItemQuantity, 100, ROUNDING); amount = amount.multiply(billingQuantity); amount = amount.setScale(invoiceTypeDecimals, ROUNDING); } } if (amount.signum() != 0) { Map<String, Object> createInvoiceItemAdjContext = new HashMap<String, Object>(); createInvoiceItemAdjContext.put("invoiceId", invoiceId); createInvoiceItemAdjContext.put("invoiceItemSeqId", invoiceItemSeqId); createInvoiceItemAdjContext.put("invoiceItemTypeId", getInvoiceItemType(delegator, adj.getString("orderAdjustmentTypeId"), null, invoiceType, "INVOICE_ITM_ADJ")); createInvoiceItemAdjContext.put("quantity", BigDecimal.ONE); createInvoiceItemAdjContext.put("amount", amount); createInvoiceItemAdjContext.put("productId", orderItem.get("productId")); createInvoiceItemAdjContext.put("productFeatureId", orderItem.get("productFeatureId")); createInvoiceItemAdjContext.put("overrideGlAccountId", adj.get("overrideGlAccountId")); createInvoiceItemAdjContext.put("parentInvoiceId", invoiceId); createInvoiceItemAdjContext.put("parentInvoiceItemSeqId", parentInvoiceItemSeqId); createInvoiceItemAdjContext.put("userLogin", userLogin); createInvoiceItemAdjContext.put("taxAuthPartyId", adj.get("taxAuthPartyId")); createInvoiceItemAdjContext.put("taxAuthGeoId", adj.get("taxAuthGeoId")); createInvoiceItemAdjContext.put("taxAuthorityRateSeqId", adj.get("taxAuthorityRateSeqId")); // some adjustments fill out the comments field instead String description = (UtilValidate.isEmpty(adj.getString("description")) ? adj.getString("comments") : adj.getString("description")); createInvoiceItemAdjContext.put("description", description); // invoice items for sales tax are not taxable themselves // TODO: This is not an ideal solution. Instead, we need to use OrderAdjustment.includeInTax when it is implemented if (!(adj.getString("orderAdjustmentTypeId").equals("SALES_TAX"))) { createInvoiceItemAdjContext.put("taxableFlag", product.get("taxable")); } // If the OrderAdjustment is associated to a ProductPromo, // and the field ProductPromo.overrideOrgPartyId is set, // copy the value to InvoiceItem.overrideOrgPartyId: this // represent an organization override for the payToPartyId if (UtilValidate.isNotEmpty(adj.getString("productPromoId"))) { try { GenericValue productPromo = adj.getRelatedOne("ProductPromo", false); if (UtilValidate.isNotEmpty(productPromo.getString("overrideOrgPartyId"))) { createInvoiceItemAdjContext.put("overrideOrgPartyId", productPromo.getString("overrideOrgPartyId")); } } catch (GenericEntityException e) { Debug.logError(e, "Error looking up ProductPromo with id [" + adj.getString("productPromoId") + "]", module); } } Map<String, Object> createInvoiceItemAdjResult = dispatcher.runSync("createInvoiceItem", createInvoiceItemAdjContext); if (ServiceUtil.isError(createInvoiceItemAdjResult)) { return ServiceUtil.returnError( UtilProperties.getMessage(resource, "AccountingErrorCreatingInvoiceItemFromOrder", locale), null, null, createInvoiceItemAdjResult); } // Create the OrderAdjustmentBilling record Map<String, Object> createOrderAdjustmentBillingContext = new HashMap<String, Object>(); createOrderAdjustmentBillingContext.put("orderAdjustmentId", adj.getString("orderAdjustmentId")); createOrderAdjustmentBillingContext.put("invoiceId", invoiceId); createOrderAdjustmentBillingContext.put("invoiceItemSeqId", invoiceItemSeqId); createOrderAdjustmentBillingContext.put("amount", amount); createOrderAdjustmentBillingContext.put("userLogin", userLogin); Map<String, Object> createOrderAdjustmentBillingResult = dispatcher .runSync("createOrderAdjustmentBilling", createOrderAdjustmentBillingContext); if (ServiceUtil.isError(createOrderAdjustmentBillingResult)) { return ServiceUtil.returnError( UtilProperties.getMessage(resource, "AccountingErrorCreatingOrderAdjustmentBillingFromOrder", locale), null, null, createOrderAdjustmentBillingContext); } // this adjustment amount BigDecimal thisAdjAmount = amount; // adjustments only apply to totals when they are not tax or shipping adjustments if (!"SALES_TAX".equals(adj.getString("orderAdjustmentTypeId")) && !"SHIPPING_ADJUSTMENT".equals(adj.getString("orderAdjustmentTypeId"))) { // increment the invoice subtotal invoiceSubTotal = invoiceSubTotal.add(thisAdjAmount).setScale(100, ROUNDING); // add to the ship amount only if it applies to this item if (shippingApplies) { invoiceShipProRateAmount = invoiceShipProRateAmount.add(thisAdjAmount) .setScale(invoiceTypeDecimals, ROUNDING); } } // increment the counter invoiceItemSeqNum++; invoiceItemSeqId = UtilFormatOut.formatPaddedNumber(invoiceItemSeqNum, INVOICE_ITEM_SEQUENCE_ID_DIGITS); } } } // create header adjustments as line items -- always to tax/shipping last Map<GenericValue, BigDecimal> shipAdjustments = new HashMap<GenericValue, BigDecimal>(); Map<GenericValue, BigDecimal> taxAdjustments = new HashMap<GenericValue, BigDecimal>(); List<GenericValue> headerAdjustments = orh.getOrderHeaderAdjustments(); for (GenericValue adj : headerAdjustments) { // Check against OrderAdjustmentBilling to see how much of this adjustment has already been invoiced BigDecimal adjAlreadyInvoicedAmount = null; try { Map<String, Object> checkResult = dispatcher.runSync("calculateInvoicedAdjustmentTotal", UtilMisc.toMap("orderAdjustment", adj)); adjAlreadyInvoicedAmount = ((BigDecimal) checkResult.get("invoicedTotal")) .setScale(invoiceTypeDecimals, ROUNDING); } catch (GenericServiceException e) { Debug.logError(e, "Accounting trouble calling calculateInvoicedAdjustmentTotal service", module); return ServiceUtil.returnError(UtilProperties.getMessage(resource, "AccountingTroubleCallingCalculateInvoicedAdjustmentTotalService", locale)); } // if (null == adj.get("amount")) { TODO check usage with webPos. Was: fix a bug coming from POS in case of use of a discount (on item(s) or sale, sale here) and a cash amount higher than total (hence issuing change) // continue; // } // If the absolute invoiced amount >= the abs of the adjustment amount, the full amount has already been invoiced, so skip this adjustment if (adjAlreadyInvoicedAmount.abs().compareTo( adj.getBigDecimal("amount").setScale(invoiceTypeDecimals, ROUNDING).abs()) >= 0) { continue; } if ("SHIPPING_CHARGES".equals(adj.getString("orderAdjustmentTypeId"))) { shipAdjustments.put(adj, adjAlreadyInvoicedAmount); } else if ("SALES_TAX".equals(adj.getString("orderAdjustmentTypeId"))) { taxAdjustments.put(adj, adjAlreadyInvoicedAmount); } else { // these will effect the shipping pro-rate (unless commented) // other adjustment type BigDecimal divisor = orderSubTotal; BigDecimal multiplier = invoiceSubTotal; if (BigDecimal.ZERO.compareTo(multiplier) == 0 && BigDecimal.ZERO.compareTo(divisor) == 0) { // if multiplier and divisor are equal to zero then use the quantities instead of the amounts // this is useful when the order has free items and misc charges divisor = orderQuantity; multiplier = invoiceQuantity; } calcHeaderAdj(delegator, adj, invoiceType, invoiceId, invoiceItemSeqId, divisor, multiplier, adj.getBigDecimal("amount").setScale(invoiceTypeDecimals, ROUNDING), invoiceTypeDecimals, ROUNDING, userLogin, dispatcher, locale); // invoiceShipProRateAmount += adjAmount; // do adjustments compound or are they based off subtotal? Here we will (unless commented) // invoiceSubTotal += adjAmount; // increment the counter invoiceItemSeqNum++; invoiceItemSeqId = UtilFormatOut.formatPaddedNumber(invoiceItemSeqNum, INVOICE_ITEM_SEQUENCE_ID_DIGITS); } } // next do the shipping adjustments. Note that we do not want to add these to the invoiceSubTotal or orderSubTotal for pro-rating tax later, as that would cause // numerator/denominator problems when the shipping is not pro-rated but rather charged all on the first invoice for (GenericValue adj : shipAdjustments.keySet()) { BigDecimal adjAlreadyInvoicedAmount = shipAdjustments.get(adj); if ("N".equalsIgnoreCase(prorateShipping)) { // Set the divisor and multiplier to 1 to avoid prorating BigDecimal divisor = BigDecimal.ONE; BigDecimal multiplier = BigDecimal.ONE; // The base amount in this case is the adjustment amount minus the total already invoiced for that adjustment, since // it won't be prorated BigDecimal baseAmount = adj.getBigDecimal("amount").setScale(invoiceTypeDecimals, ROUNDING) .subtract(adjAlreadyInvoicedAmount); calcHeaderAdj(delegator, adj, invoiceType, invoiceId, invoiceItemSeqId, divisor, multiplier, baseAmount, invoiceTypeDecimals, ROUNDING, userLogin, dispatcher, locale); } else { // Pro-rate the shipping amount based on shippable information BigDecimal divisor = shippableAmount; BigDecimal multiplier = invoiceShipProRateAmount; if (BigDecimal.ZERO.compareTo(multiplier) == 0 && BigDecimal.ZERO.compareTo(divisor) == 0) { // if multiplier and divisor are equal to zero then use the quantities instead of the amounts // this is useful when the order has free items and shipping charges divisor = shippableQuantity; multiplier = invoiceShippableQuantity; } // The base amount in this case is the adjustment amount, since we want to prorate based on the full amount BigDecimal baseAmount = adj.getBigDecimal("amount").setScale(invoiceTypeDecimals, ROUNDING); calcHeaderAdj(delegator, adj, invoiceType, invoiceId, invoiceItemSeqId, divisor, multiplier, baseAmount, invoiceTypeDecimals, ROUNDING, userLogin, dispatcher, locale); } // Increment the counter invoiceItemSeqNum++; invoiceItemSeqId = UtilFormatOut.formatPaddedNumber(invoiceItemSeqNum, INVOICE_ITEM_SEQUENCE_ID_DIGITS); } // last do the tax adjustments String prorateTaxes = productStore != null ? productStore.getString("prorateTaxes") : "Y"; if (prorateTaxes == null) { prorateTaxes = "Y"; } for (Map.Entry<GenericValue, BigDecimal> entry : taxAdjustments.entrySet()) { GenericValue adj = entry.getKey(); BigDecimal adjAlreadyInvoicedAmount = entry.getValue(); BigDecimal adjAmount = null; if ("N".equalsIgnoreCase(prorateTaxes)) { // Set the divisor and multiplier to 1 to avoid prorating BigDecimal divisor = BigDecimal.ONE; BigDecimal multiplier = BigDecimal.ONE; // The base amount in this case is the adjustment amount minus the total already invoiced for that adjustment, since // it won't be prorated BigDecimal baseAmount = adj.getBigDecimal("amount").setScale(TAX_DECIMALS, TAX_ROUNDING) .subtract(adjAlreadyInvoicedAmount); adjAmount = calcHeaderAdj(delegator, adj, invoiceType, invoiceId, invoiceItemSeqId, divisor, multiplier, baseAmount, TAX_DECIMALS, TAX_ROUNDING, userLogin, dispatcher, locale); } else { // Pro-rate the tax amount based on shippable information BigDecimal divisor = orderSubTotal; BigDecimal multiplier = invoiceSubTotal; // The base amount in this case is the adjustment amount, since we want to prorate based on the full amount BigDecimal baseAmount = adj.getBigDecimal("amount"); adjAmount = calcHeaderAdj(delegator, adj, invoiceType, invoiceId, invoiceItemSeqId, divisor, multiplier, baseAmount, TAX_DECIMALS, TAX_ROUNDING, userLogin, dispatcher, locale); } invoiceSubTotal = invoiceSubTotal.add(adjAmount).setScale(invoiceTypeDecimals, ROUNDING); // Increment the counter invoiceItemSeqNum++; invoiceItemSeqId = UtilFormatOut.formatPaddedNumber(invoiceItemSeqNum, INVOICE_ITEM_SEQUENCE_ID_DIGITS); } // check for previous order payments List<GenericValue> orderPaymentPrefs = EntityQuery.use(delegator).from("OrderPaymentPreference").where( EntityCondition.makeCondition("orderId", EntityOperator.EQUALS, orderId), EntityCondition.makeCondition("statusId", EntityOperator.NOT_EQUAL, "PAYMENT_CANCELLED")) .queryList(); List<GenericValue> currentPayments = new LinkedList<GenericValue>(); for (GenericValue paymentPref : orderPaymentPrefs) { List<GenericValue> payments = paymentPref.getRelated("Payment", null, null, false); currentPayments.addAll(payments); } // apply these payments to the invoice if they have any remaining amount to apply for (GenericValue payment : currentPayments) { if ("PMNT_VOID".equals(payment.getString("statusId")) || "PMNT_CANCELLED".equals(payment.getString("statusId"))) { continue; } BigDecimal notApplied = PaymentWorker.getPaymentNotApplied(payment); if (notApplied.signum() > 0) { Map<String, Object> appl = new HashMap<String, Object>(); appl.put("paymentId", payment.get("paymentId")); appl.put("invoiceId", invoiceId); appl.put("billingAccountId", billingAccountId); appl.put("amountApplied", notApplied); appl.put("userLogin", userLogin); Map<String, Object> createPayApplResult = dispatcher.runSync("createPaymentApplication", appl); if (ServiceUtil.isError(createPayApplResult)) { return ServiceUtil .returnError( UtilProperties.getMessage(resource, "AccountingErrorCreatingInvoiceFromOrder", locale), null, null, createPayApplResult); } } } // Should all be in place now. Depending on the ProductStore.autoApproveInvoice setting, set status to INVOICE_READY (unless it's a purchase invoice, which we set to INVOICE_IN_PROCESS) String autoApproveInvoice = productStore != null ? productStore.getString("autoApproveInvoice") : "Y"; if (!"N".equals(autoApproveInvoice)) { String nextStatusId = "PURCHASE_INVOICE".equals(invoiceType) ? "INVOICE_IN_PROCESS" : "INVOICE_READY"; Map<String, Object> setInvoiceStatusResult = dispatcher.runSync("setInvoiceStatus", UtilMisc.<String, Object>toMap("invoiceId", invoiceId, "statusId", nextStatusId, "userLogin", userLogin)); if (ServiceUtil.isError(setInvoiceStatusResult)) { return ServiceUtil.returnError( UtilProperties.getMessage(resource, "AccountingErrorCreatingInvoiceFromOrder", locale), null, null, setInvoiceStatusResult); } } Map<String, Object> resp = ServiceUtil.returnSuccess(); resp.put("invoiceId", invoiceId); resp.put("invoiceTypeId", invoiceType); return resp; } catch (GenericEntityException e) { Debug.logError(e, "Entity/data problem creating invoice from order items: " + e.toString(), module); return ServiceUtil.returnError( UtilProperties.getMessage(resource, "AccountingEntityDataProblemCreatingInvoiceFromOrderItems", UtilMisc.toMap("reason", e.toString()), locale)); } catch (GenericServiceException e) { Debug.logError(e, "Service/other problem creating invoice from order items: " + e.toString(), module); return ServiceUtil.returnError(UtilProperties.getMessage(resource, "AccountingServiceOtherProblemCreatingInvoiceFromOrderItems", UtilMisc.toMap("reason", e.toString()), locale)); } }
From source file:com.ugam.collage.plus.service.people_count.impl.PeopleAccountingServiceImpl.java
/** * *///from www . ja v a 2s .c o m private void getRevenueCountProportion(List<EmpcntClientProjectData> empOpenCntClientProjectDataList, List<EmpcntClientProjectData> empCloseCntClientProjectDataList, EmployeeMaster employee, TabMonth month, TabYear year, CostCentre costCentre, CountClassification countType, BigDecimal remainProportion, Map<Integer, BigDecimal> unAssignedProjects, Integer countTypeId, Map<String, EmployeePcTagsTeamStruct> employeePcTagsTeamStructMap) { logger.debug("<====getRevenueCountProportion Start====>"); logger.debug("unAssignedProjects:" + unAssignedProjects.size()); // get the EmpCntPcApportionApproach for the employee Integer employeeId = employee.getEmployeeId(); Integer yearId = year.getYearId(); Integer monthId = month.getMonthId(); String costCentreId = costCentre.getCostCentreId(); BigDecimal deviderHour = new BigDecimal(Constants.TOTAL_WORKING_HOURS); Integer apportionApproach = 0; BigDecimal allignedTimeZero = BigDecimal.ZERO; BigDecimal asistededTimeZero = BigDecimal.ZERO; List<EmpCntPcApportionApproach> empCntPcApportionApproachList = empCntPcApportionApproachDao .findByYearIdMonthIdEmployeeId(yearId, monthId, employeeId); if (!empCntPcApportionApproachList.isEmpty()) { apportionApproach = empCntPcApportionApproachList.get(0).getApportionApproach(); } else { return; } // logger.debug("1363 : apportionApproach===> "+apportionApproach); // get the EmployeePcTagsTeamStruct for the employee List<EmployeePcTagsTeamStruct> employeePcTagsTeamStructList = employeePcTagsTeamStructDao .findByYearIdMonthIdEmployeeId(yearId, monthId, employeeId); if (apportionApproach == 1) { for (EmployeePcTagsTeamStruct employeePcTagsTeamStruct : employeePcTagsTeamStructList) { BigDecimal count = BigDecimal.ZERO; Map<Integer, CollageProjectRevenue> revenueMap = new HashMap<Integer, CollageProjectRevenue>(); Map<Integer, ProjectMaster> projectMap = new HashMap<Integer, ProjectMaster>(); BigDecimal proportion = employeePcTagsTeamStruct.getProportion(); String profitcentreId = employeePcTagsTeamStruct.getProfitCentre().getProfitCentreId(); // Calculate for each profit centre BigDecimal pcProportion = proportion.multiply(remainProportion); // asissted projects on count List<CollageProjectRevenue> collageProjectRevenueList = collageProjectRevenueDao .findByYearIdMonthIdProfitCentreIdCostCentreId(yearId, monthId, profitcentreId, costCentreId); if (!collageProjectRevenueList.isEmpty()) { // Select valid project id for (CollageProjectRevenue proRevenue : collageProjectRevenueList) { Integer projectId = proRevenue.getProjectMaster().getProjectId(); if (unAssignedProjects.isEmpty()) { revenueMap.put(projectId, proRevenue); List<ProjectMaster> projectList = projectMasterDao.findByProjectId(projectId); projectMap.put(projectId, projectList.get(0)); } else { if (unAssignedProjects.containsKey(projectId) == false) { revenueMap.put(projectId, proRevenue); List<ProjectMaster> projectList = projectMasterDao.findByProjectId(projectId); projectMap.put(projectId, projectList.get(0)); } } } Integer projectCount = revenueMap.size(); count = new BigDecimal(projectCount); if (projectCount > 0) { for (Integer key : revenueMap.keySet()) { BigDecimal projectValue = BigDecimal.ONE.divide(count, 2, RoundingMode.HALF_EVEN); projectValue = projectValue.multiply(pcProportion); ProjectMaster projectMaster = projectMap.get(key); CompanyMaster companyMaster = projectMaster.getCompanyMaster(); projectValue = projectValue.setScale(2, RoundingMode.CEILING); // logger.debug("1406 projectValue:======>"+projectValue); EmpcntClientProjectData empcntClientProjectData = new EmpcntClientProjectData(employee, companyMaster, countType, month, projectMaster, year, costCentre, allignedTimeZero, asistededTimeZero, projectValue, projectValue); if (countTypeId == 1) { empOpenCntClientProjectDataList.add(empcntClientProjectData); } if (countTypeId == 2) { empCloseCntClientProjectDataList.add(empcntClientProjectData); } // copy proprotion String mapId = yearId + "-" + monthId + "-" + employeeId + "-" + profitcentreId; EmployeePcTagsTeamStruct employeePcTagsTeamStructCopy = employeePcTagsTeamStruct; employeePcTagsTeamStructCopy.setApportionedCnt(projectValue); employeePcTagsTeamStructMap.put(mapId, employeePcTagsTeamStructCopy); } } } } } else if (apportionApproach == 2) { for (EmployeePcTagsTeamStruct employeePcTagsTeamStruct : employeePcTagsTeamStructList) { BigDecimal count = BigDecimal.ZERO; Map<Integer, BigDecimal> hoursMap = new HashMap<Integer, BigDecimal>(); Map<Integer, Integer> companyMap = new HashMap<Integer, Integer>(); BigDecimal proportion = employeePcTagsTeamStruct.getProportion(); String profitcentreId = employeePcTagsTeamStruct.getProfitCentre().getProfitCentreId(); // Calculate for each profit centre BigDecimal pcProportion = proportion.multiply(remainProportion); BigDecimal hoursSum = BigDecimal.ZERO; List<Object[]> objectList = executionDataDao.findByYearIdMonthIdCostCentreIdProfitCentreId(yearId, monthId, costCentreId, profitcentreId); if (!objectList.isEmpty()) { for (Object[] result : objectList) { Integer projectId = (Integer) result[0]; BigDecimal hour = (BigDecimal) result[1]; Integer companyId = (Integer) result[2]; if (unAssignedProjects.isEmpty()) { hoursMap.put(projectId, hour); companyMap.put(projectId, companyId); hoursSum.add(hour); } else { if (unAssignedProjects.containsKey(projectId) == false) { hoursMap.put(projectId, hour); companyMap.put(projectId, companyId); hoursSum.add(hour); } } } for (Integer projectId : hoursMap.keySet()) { BigDecimal hour = hoursMap.get(projectId); ProjectMaster projectMaster = new ProjectMaster(); projectMaster.setProjectId(projectId); Integer companyId = companyMap.get(projectId); CompanyMaster companyMaster = new CompanyMaster(); companyMaster.setCompanyId(companyId); BigDecimal resultHour = hour.divide(hoursSum, 2, RoundingMode.HALF_EVEN); resultHour = resultHour.multiply(pcProportion); resultHour = resultHour.setScale(2, RoundingMode.CEILING); // logger.debug("1462 :resultHour=====>"+resultHour); EmpcntClientProjectData empcntClientProjectData = new EmpcntClientProjectData(employee, companyMaster, countType, month, projectMaster, year, costCentre, asistededTimeZero, allignedTimeZero, resultHour, resultHour); if (countTypeId == 1) { empOpenCntClientProjectDataList.add(empcntClientProjectData); } if (countTypeId == 2) { empCloseCntClientProjectDataList.add(empcntClientProjectData); } // copy proprotion String mapId = yearId + "-" + monthId + "-" + employeeId + "-" + profitcentreId; EmployeePcTagsTeamStruct employeePcTagsTeamStructCopy = employeePcTagsTeamStruct; employeePcTagsTeamStructCopy.setApportionedCnt(resultHour); employeePcTagsTeamStructMap.put(mapId, employeePcTagsTeamStructCopy); } } } } else if (apportionApproach == 3) { for (EmployeePcTagsTeamStruct employeePcTagsTeamStruct : employeePcTagsTeamStructList) { Map<Integer, CollageProjectRevenue> revenueMap = new HashMap<Integer, CollageProjectRevenue>(); Map<Integer, ProjectMaster> projectMap = new HashMap<Integer, ProjectMaster>(); BigDecimal proportion = employeePcTagsTeamStruct.getProportion(); BigDecimal devider = new BigDecimal(100); proportion = proportion.divide(devider); logger.debug("===========================================>" + proportion); String profitcentreId = employeePcTagsTeamStruct.getProfitCentre().getProfitCentreId(); // Calculate for each profit centre BigDecimal pcProportion = proportion.multiply(remainProportion); BigDecimal revenueSum = BigDecimal.ZERO; List<CollageProjectRevenue> collageProjectRevenueList = collageProjectRevenueDao .findByYearIdMonthIdProfitCentreIdCostCentreId(yearId, monthId, profitcentreId, costCentreId); if (!collageProjectRevenueList.isEmpty()) { for (CollageProjectRevenue revenue : collageProjectRevenueList) { if (unAssignedProjects.isEmpty()) { Integer projectId = revenue.getProjectMaster().getProjectId(); logger.debug("1497 =projectId====>" + projectId); revenueMap.put(projectId, revenue); List<ProjectMaster> projectList = projectMasterDao.findByProjectId(projectId); projectMap.put(projectId, projectList.get(0)); BigDecimal revenueVal = revenue.getRevenueValue(); // logger.debug("1503 =RevenueValue====>"+revenueVal); revenueSum = revenueSum.add(revenueVal); } else { Integer projectId = revenue.getProjectMaster().getProjectId(); if (unAssignedProjects.containsKey(projectId) == false) { // logger.debug("1507 =projectId====>"+projectId); revenueMap.put(projectId, revenue); List<ProjectMaster> projectList = projectMasterDao.findByProjectId(projectId); projectMap.put(projectId, projectList.get(0)); BigDecimal revenueVal = revenue.getRevenueValue(); // logger.debug("1514 =RevenueValue====>"+revenue.getRevenueValue() // +" : "+revenueVal); revenueSum = revenueSum.add(revenueVal); } } } logger.debug("1543 =revenueSum====>" + revenueSum); for (Integer projectId : revenueMap.keySet()) { CollageProjectRevenue collageProjectRevenue = revenueMap.get(projectId); ProjectMaster projectMaster = projectMap.get(projectId); CompanyMaster companyMaster = projectMaster.getCompanyMaster(); BigDecimal revenueValue = collageProjectRevenue.getRevenueValue(); logger.debug("1516 =revenueSum : revenueValue====>" + revenueSum + " : " + revenueValue); revenueValue = revenueValue.divide(revenueSum, 2, RoundingMode.HALF_EVEN); revenueValue = revenueValue.multiply(pcProportion); revenueValue = revenueValue.setScale(2, RoundingMode.CEILING); logger.debug("1515 :Aportioned Count======>" + revenueValue); EmpcntClientProjectData empcntClientProjectData = new EmpcntClientProjectData(employee, companyMaster, countType, month, projectMaster, year, costCentre, allignedTimeZero, asistededTimeZero, revenueValue, revenueValue); if (countTypeId == 1) { empOpenCntClientProjectDataList.add(empcntClientProjectData); } if (countTypeId == 2) { empCloseCntClientProjectDataList.add(empcntClientProjectData); } // copy proprotion String mapId = yearId + "-" + monthId + "-" + employeeId + "-" + profitcentreId; EmployeePcTagsTeamStruct employeePcTagsTeamStructCopy = employeePcTagsTeamStruct; employeePcTagsTeamStructCopy.setApportionedCnt(revenueValue); employeePcTagsTeamStructMap.put(mapId, employeePcTagsTeamStructCopy); } } } } // logger.debug("<====getRevenueCountProportion End====>"); }
From source file:com.yucheng.cmis.pvp.app.component.PvpAuthorizeComponent.java
/** * ??// ww w . j a v a2 s . c o m * * * * *120= * @param rate * @return */ public static String getCoreTradeRate(Double rate) { BigDecimal reality = new BigDecimal(rate); reality = reality.multiply(new BigDecimal(120)); reality = reality.divide(new BigDecimal(1), 5, BigDecimal.ROUND_HALF_UP); return reality.toPlainString(); }
From source file:org.openmrs.module.billing.web.controller.billingqueuedia.BillingService.java
@RequestMapping(value = "/module/billing/orderStoreSave.form", method = RequestMethod.POST) public String billSaveOrder(@RequestParam("patientId") Integer patientId, @RequestParam(value = "refDocId", required = false) Integer refDocId, @RequestParam(value = "refMarId", required = false) Integer refMarId, @RequestParam(value = "orderId", required = false) Integer orderId, @RequestParam(value = "refRmpId", required = false) Integer refRmpId, @RequestParam(value = "dDate", required = false) String dDate, @RequestParam(value = "dTime", required = false) String dTime, @RequestParam(value = "rem", required = false) String remarks, // @RequestParam(value = "discount", required = false) BigDecimal discount, @RequestParam(value = "discount", required = false) String discount, @RequestParam("indCount") Integer indCount, @RequestParam(value = "encounterId", required = false) String encounterId, HttpServletRequest request, Model model) throws ParseException, Exception { Patient patient = Context.getPatientService().getPatient(patientId); MedisunService ms = Context.getService(MedisunService.class); org.openmrs.module.hospitalcore.BillingService billingService = Context .getService(org.openmrs.module.hospitalcore.BillingService.class); //Date birthday = patient.getBirthdate(); // model.addAttribute("age", PatientUtils.estimateAge(birthday)); String fullPaid = request.getParameter("paid"); String fullFree = request.getParameter("free"); String freeReason = request.getParameter("freeReason"); BigDecimal doctorGivenPer = NumberUtils.createBigDecimal(request.getParameter("docGivPer")); BigDecimal p = new BigDecimal("0.00"); SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); Date deDate = null;//from ww w .ja v a 2s.c om if (StringUtils.isNotBlank(dDate)) { deDate = sdf.parse(dDate); } // System.out.println("***********ddddd"+doctorGivenPer); // if (doctorGivenPer == null) { // doctorGivenPer=p; // } // else{ // doctorGivenPer=doctorGivenPer; // } // DiaBillingQueue dbq = ms.getDiaBillingQueue(orderId); DiaReceipt dr = new DiaReceipt(); dr.setPaidDate(new Date()); dr.setDeliveryDate(deDate); dr.setDeliveryTime(dTime); dr.setServiceId(orderId); dr.setDoctorGiven(doctorGivenPer); // ms.saveDiaReceipt(dr); User user = Context.getAuthenticatedUser(); BillableService service; BigDecimal totalBill = NumberUtils.createBigDecimal(request.getParameter("totalBill")); BigDecimal netAmount = NumberUtils.createBigDecimal(request.getParameter("netamount")); BigDecimal paidAmount = NumberUtils.createBigDecimal(request.getParameter("paidamount")); BigDecimal payableAmount = NumberUtils.createBigDecimal(request.getParameter("payableamount")); BigDecimal dueAmount = NumberUtils.createBigDecimal(request.getParameter("dueamount")); BigDecimal discountAmount = NumberUtils.createBigDecimal(request.getParameter("discountamount")); BigDecimal unitPrice = NumberUtils.createBigDecimal(request.getParameter("unitprice")); // BigDecimal discount = NumberUtils.createBigDecimal(request.getParameter("discount")); if (paidAmount == null) { paidAmount = p; } else { paidAmount = paidAmount; } String due = null; boolean status; if ((StringUtils.equals(fullPaid, "1")) && (dueAmount.signum() < 1)) { due = "PAID"; status = false; totalBill = totalBill; } else if ((StringUtils.equals(fullPaid, null)) && (StringUtils.equals(fullFree, null)) && (dueAmount.signum() < 1)) { due = "PAID"; status = false; totalBill = totalBill; } else if ((!StringUtils.equalsIgnoreCase(fullFree, null))) { due = "FREE"; status = true; totalBill = p; } else { due = "DUE"; status = false; totalBill = totalBill; } DiaPatientServiceBill dpsb = new DiaPatientServiceBill(); dpsb.setPatient(patient); dpsb.setCreatedDate(new Date()); dpsb.setCreator(user); dpsb.setAmount(netAmount); dpsb.setPrinted(Boolean.FALSE); dpsb.setReceipt(dr); dpsb.setVoided(Boolean.FALSE); dpsb.setActualAmount(totalBill); /// if free actual amount is 0.00 dpsb.setDueAmount(dueAmount); dpsb.setBillingStatus(due); dpsb.setRefDocId(refDocId); dpsb.setRefMarId(refMarId); dpsb.setRefRmpId(refRmpId); dpsb.setComment(remarks); dpsb.setDiscountAmount(discountAmount); dpsb.setFreeReason(freeReason); //if (paidAmount.signum() > 0) { dpsb = ms.saveDiaPatientServiceBill(dpsb); //} // if (dpsb != null && dpsb.getBillId() != null ) { if (dpsb != null && dpsb.getBillId() != null && orderId != 0) { ms.removeDiaBillingQueue(dbq); } model.addAttribute("billId", dpsb.getBillId()); model.addAttribute("orderId", orderId); model.addAttribute("refDocId", refDocId); model.addAttribute("refRmpId", refRmpId); model.addAttribute("paid", paidAmount); model.addAttribute("dDate", dDate); model.addAttribute("dTime", dTime); DiaPatientServiceBillCollect dBillColl = new DiaPatientServiceBillCollect(); dBillColl.setPatientId(patientId); dBillColl.setDiaPatientServiceBill(dpsb); dBillColl.setUser(user); dBillColl.setCreatedDate(new Date()); dBillColl.setActualAmount(totalBill); dBillColl.setPaidAmount(paidAmount); dBillColl.setPayableAmount(netAmount); dBillColl.setDueAmount(dueAmount); dBillColl.setDiscountAmount(discountAmount); dBillColl.setDuePaidStatus(status); dBillColl.setDuePaid(0); //if (paidAmount.signum() > 0) { ms.saveDiaPatientServiceBillCollect(dBillColl); //} String sername = null; BigDecimal totCom = BigDecimal.ZERO; BigDecimal servicePrice = BigDecimal.ZERO; for (Integer i = 1; i <= indCount; i++) { String servicename = request.getParameter("service"); unitPrice = NumberUtils.createBigDecimal(request.getParameter(i.toString() + "unitprice")); // Quantity * unitPrice BigDecimal serviceprice = NumberUtils .createBigDecimal(request.getParameter(i.toString() + "serviceprice")); // Unit Price Integer qty = NumberUtils.createInteger(request.getParameter(i.toString() + "servicequantity")); // Quantity servicename = request.getParameter(i.toString() + "service"); service = billingService.getServiceByConceptName(servicename); if (((!StringUtils.equalsIgnoreCase(service.getCategory().getId().toString(), "5678")))) { sername = servicename + "," + sername; // for commison servicePrice = servicePrice.add(unitPrice); } DiaPatientServiceBillItem dBillItem = new DiaPatientServiceBillItem(); dBillItem.setService(service); dBillItem.setDiaPatientServiceBill(dpsb); dBillItem.setUnitPrice(serviceprice); dBillItem.setAmount(unitPrice); dBillItem.setQuantity(qty); dBillItem.setName(servicename); dBillItem.setCreatedDate(new Date()); dBillItem.setCreator(user.getId()); dBillItem.setVoided(Boolean.FALSE); dBillItem.setActualAmount(unitPrice); // if (paidAmount.signum() > 0) { ms.saveDiaPatientServiceBillItem(dBillItem); //} BigDecimal ind = NumberUtils.createBigDecimal(indCount.toString()); BigDecimal da = discountAmount.divide(ind, 2, RoundingMode.CEILING); BigDecimal oneHundred = new BigDecimal(100); BigDecimal le = null; if (!StringUtils.isBlank(discount)) { BigDecimal dis; dis = new BigDecimal(discount); BigDecimal less = (unitPrice.multiply(dis)).divide(oneHundred, 0, RoundingMode.HALF_EVEN); le = less; } else { le = new BigDecimal(0); } //BigDecimal less = (unitPrice.multiply(discount)).divide(oneHundred, 0, RoundingMode.HALF_EVEN); if (dpsb.getBillingStatus() == "PAID") { if ((!StringUtils.equalsIgnoreCase(service.getCategory().getId().toString(), "5678"))) { DiaCommissionCal diaComCal = new DiaCommissionCal(); diaComCal.setDiaPatientServiceBill(dpsb); diaComCal.setPatient(patient); diaComCal.setServiceName(service.getName()); diaComCal.setServiceId(service.getServiceId()); diaComCal.setServicePrice(serviceprice); //diaComCal.setLessAmount(discountAmount); diaComCal.setLessAmount(le); diaComCal.setCommission(service.getCommission()); diaComCal.setCreatedDate(new Date()); diaComCal.setCreator(user.getId()); diaComCal.setRefId(dpsb.getRefDocId()); diaComCal.setRefRmpId(dpsb.getRefRmpId()); diaComCal.setHsStatus(Boolean.FALSE); ms.saveDiaComCal(diaComCal); } } DiaLabSampleid dls = new DiaLabSampleid(); dls.setPatient(patient); dls.setDiaPatientServiceBill(dpsb); dls.setSampleId(generateBarcode()); ms.saveDiaLabSam(dls); } if (sername != null && dpsb.getBillingStatus() == "PAID") { sername = sername.replace(",null", ""); DiaCommissionCalAll diaAll = new DiaCommissionCalAll(); diaAll.setDiaPatientServiceBill(dpsb); diaAll.setPatient(patient); //diaAll.setServiceName(sername); diaAll.setServicePrice(servicePrice); diaAll.setLessAmount(discountAmount); diaAll.setComAmount(totCom); diaAll.setCreatedDate(new Date()); diaAll.setCreator(Context.getAuthenticatedUser().getId()); diaAll.setRefId(refDocId); diaAll.setRefRmp(refRmpId); diaAll.setRefMar(refMarId); ms.saveDiaComAll(diaAll); } //// Generate Patient Id Barcode4j Code128Bean cod = new Code128Bean(); final int reso = 128; cod.setModuleWidth(UnitConv.in2mm(1.0f / reso)); //makes the narrow bar //width exactly one pixel cod.setHeight(10); cod.setFontSize(3); cod.setFontName("Times New Roman"); // cod.doQuietZone(true); cod.getBarWidth(2); // bean.setVerticalQuietZone(1); cod.setMsgPosition(HumanReadablePlacement.HRP_BOTTOM); File outputFilePatId = new File( request.getSession().getServletContext().getRealPath("/barcode/" + patient.getId() + ".png")); // File outputFilePatId = new File("C:\\tomcat6\\webapps\\MEDISUN_HEALTH_CARE_V2_Final\\barcode/" + patient.getId() + ".png"); //Mostofa bhi OutputStream out1 = new FileOutputStream(outputFilePatId); try { BitmapCanvasProvider canvas = new BitmapCanvasProvider(out1, "image/x-png", reso, BufferedImage.TYPE_BYTE_BINARY, false, 0); cod.generateBarcode(canvas, patient.getPatientIdentifier().getIdentifier()); canvas.finish(); } finally { out1.close(); } //// Generate Bill Id Barcode4j Code128Bean codBil = new Code128Bean(); final int resou = 128; codBil.setModuleWidth(UnitConv.in2mm(1.0f / resou)); //makes the narrow bar //width exactly one pixel codBil.setHeight(10); codBil.setFontSize(2); codBil.setFontName("Helvetica"); // cod.doQuietZone(true); codBil.getBarWidth(2); // bean.setVerticalQuietZone(1); codBil.setMsgPosition(HumanReadablePlacement.HRP_BOTTOM); // File outputFileBillId = new File("C:\\tomcat6\\webapps\\MEDISUN_HEALTH_CARE_V2_Final\\barcode/" + dpsb.getBillId() + ".png"); // Mostofa bhi File outputFileBillId = new File( request.getSession().getServletContext().getRealPath("/barcode/" + dpsb.getBillId() + ".png")); OutputStream outB = new FileOutputStream(outputFileBillId); try { BitmapCanvasProvider canvas = new BitmapCanvasProvider(outB, "image/x-png", reso, BufferedImage.TYPE_BYTE_BINARY, false, 0); codBil.generateBarcode(canvas, dpsb.getBillId().toString()); canvas.finish(); } finally { outB.close(); } ///// End model.addAttribute("discountAount", dBillColl.getDiscountAmount()); return "redirect:/module/billing/billprint.htm?patientId=" + patientId; //module/billing/directbillingqueue.form }
From source file:com.selfsoft.business.service.impl.TbFixEntrustServiceImpl.java
public void printTbFixEntrustTemplateBlank(OutputStream os, String tpl, Long tbFixEntrustId) { try {/* w ww .j a v a 2 s . c om*/ TbFixEntrust tbFixEntrust = this.findById(tbFixEntrustId); TbCustomer tbCustomer = tbCustomerService.findById(tbFixEntrust.getTbCustomer().getId()); TbCarInfo tbCarInfo = tbCarInfoService.findById(tbFixEntrust.getTbCarInfo().getId()); List<TbFixEntrustContent> tbFixEntrustContentList = tbFixEntrustContentService .findTbFixEnTrustContentListByTbFixEntrustId(tbFixEntrustId); /* * List<TbMaintainPartContent> maintainList = * tbMaintainPartContentService * .getViewEntrustMaintianContent(tbFixEntrustId); * * * List<TmStockOutDetVo> solePartList = * tmStockOutService.getSellByEntrustCode * (tbFixEntrust.getEntrustCode()); */ /** * ?? */ List<TbMaintianVo> maintianvos = tbMaintainPartContentService .getTbMaintianDetailVosByEntrustId(tbFixEntrust.getId(), Constants.BALANCE_ALL); /** * ? */ List<TmStockOutDetVo> tmStockOutDetVos = tmStockOutService .getSellDetailByEntrustCode(tbFixEntrust.getEntrustCode(), Constants.BALANCE_ALL); /** * ?? */ List<TbMaintianVo> partAll = new ArrayList<TbMaintianVo>(); if (null != maintianvos && maintianvos.size() > 0) { for (TbMaintianVo tbMaintianVo : maintianvos) { partAll.add(tbMaintianVo); } } if (null != tmStockOutDetVos && tmStockOutDetVos.size() > 0) { for (TmStockOutDetVo tmStockOutDetVo : tmStockOutDetVos) { TbMaintianVo tbMaintianVo = new TbMaintianVo(); tbMaintianVo.setPartId(tmStockOutDetVo.getPartinfoId()); tbMaintianVo.setHouseName(tmStockOutDetVo.getHouseName()); tbMaintianVo.setPartCode(tmStockOutDetVo.getPartCode()); tbMaintianVo.setPartName(tmStockOutDetVo.getPartName()); tbMaintianVo.setUnitName(tmStockOutDetVo.getUnitName()); tbMaintianVo.setPrice(tmStockOutDetVo.getPrice()); tbMaintianVo.setPartQuantity(tmStockOutDetVo.getQuantity()); tbMaintianVo.setTotal(tmStockOutDetVo.getTotal()); tbMaintianVo.setIsFree(tmStockOutDetVo.getIsFree()); tbMaintianVo.setProjectType(tmStockOutDetVo.getProjectType()); tbMaintianVo.setZl(tmStockOutDetVo.getZl()); tbMaintianVo.setXmlx(tmStockOutDetVo.getXmlx()); partAll.add(tbMaintianVo); } } int fixSize = (tbFixEntrustContentList == null ? 0 : tbFixEntrustContentList.size()); int maintainSize = (maintianvos == null ? 0 : maintianvos.size()); int solePartSize = (tmStockOutDetVos == null ? 0 : tmStockOutDetVos.size()); int partAllSize = (partAll == null ? 0 : partAll.size()); HSSFWorkbook workbook = new HSSFWorkbook(this.getClass().getResourceAsStream(tpl)); HSSFSheet sheet = workbook.getSheetAt(0); HSSFCellStyle style = workbook.createCellStyle(); style.setWrapText(true); style.setAlignment(HSSFCellStyle.ALIGN_LEFT); style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); HSSFFont font = workbook.createFont(); font.setFontName(""); font.setFontHeightInPoints((short) 9); // style.setFont(font); HSSFCellStyle style11 = workbook.createCellStyle(); style11.setWrapText(true); style11.setAlignment(HSSFCellStyle.ALIGN_LEFT); style11.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); HSSFFont font11 = workbook.createFont(); font11.setFontName(""); font11.setFontHeightInPoints((short) 11); // style11.setFont(font11); HSSFCellStyle style10 = workbook.createCellStyle(); style10.setWrapText(true); style10.setAlignment(HSSFCellStyle.ALIGN_LEFT); style10.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); HSSFFont font10 = workbook.createFont(); font10.setFontName(""); font10.setFontHeightInPoints((short) 10); // style10.setFont(font10); HSSFRow row = null; HSSFCell cell = null; row = sheet.getRow(10); cell = row.getCell(0); String entrustCode = tbFixEntrust.getEntrustCode(); String[] es = entrustCode.split("-"); String newCode = "RO" + es[0].substring(2, 6) + es[1]; // cell.setCellValue(tbFixEntrust.getEntrustCode()); cell.setCellValue(newCode); row = sheet.getRow(10); cell = row.getCell(8); cell.setCellValue(tbCarInfo.getPurchaseDate() == null ? "" : CommonMethod.parseDateToString(tbCarInfo.getPurchaseDate(), "yyyy-MM-dd")); row = sheet.getRow(10); cell = row.getCell(14); cell.setCellValue( tbFixEntrust.getTmUser().getUserRealName() == null ? tbFixEntrust.getTmUser().getUserName() : tbFixEntrust.getTmUser().getUserRealName()); row = sheet.getRow(10); cell = row.getCell(19); cell.setCellValue(tbCarInfo.getLicenseCode()); row = sheet.getRow(10); cell = row.getCell(27); // cell.setCellStyle(style); cell.setCellValue(tbCarInfo.getTmCarModelType().getModelName()); row = sheet.getRow(10); cell = row.getCell(32); cell.setCellValue( tbFixEntrust.getEnterStationKilo() == null ? "" : new BigDecimal(tbFixEntrust.getEnterStationKilo().toString()) .divide(new BigDecimal("1.00"), 0, BigDecimal.ROUND_HALF_UP).toString() + " Km"); row = sheet.getRow(10); cell = row.getCell(41); cell.setCellValue(tbCarInfo.getColor() == null ? "" : tbCarInfo.getColor().toString()); row = sheet.getRow(10); cell = row.getCell(45); cell.setCellValue(tbFixEntrust.getFixDate() == null ? "" : CommonMethod.parseDateToString(tbFixEntrust.getFixDate(), Constants.TIMEFORMATOFMINUTE)); row = sheet.getRow(15); cell = row.getCell(0); cell.setCellValue(tbCustomer.getCustomerName() == null ? "" : tbCustomer.getContractPerson()); row = sheet.getRow(15); cell = row.getCell(8); cell.setCellValue(tbCustomer.getTelephone() == null ? "" : tbCustomer.getTelephone()); row = sheet.getRow(15); cell = row.getCell(14); cell.setCellValue(tbCustomer.getPhone() == null ? "" : tbCustomer.getPhone()); row = sheet.getRow(15); cell = row.getCell(20); cell.setCellValue(tbCarInfo.getChassisCode() == null ? "" : tbCarInfo.getChassisCode()); row = sheet.getRow(15); cell = row.getCell(32); // cell.setCellStyle(style); cell.setCellValue(tbCarInfo.getEngineCode() == null ? "" : tbCarInfo.getEngineCode()); row = sheet.getRow(15); cell = row.getCell(45); // cell.setCellStyle(style); cell.setCellValue(tbFixEntrust.getEstimateDate() == null ? "" : CommonMethod.parseDateToString(tbFixEntrust.getEstimateDate(), Constants.TIMEFORMATOFMINUTE)); row = sheet.getRow(18); cell = row.getCell(8); cell.setCellValue(tbCustomer.getCustomerName() == null ? "" : tbCustomer.getCustomerName()); row = sheet.getRow(20); cell = row.getCell(8); // cell.setCellStyle(style); cell.setCellValue(tbCustomer.getAddress() == null ? "" : tbCustomer.getAddress()); row = sheet.getRow(25); cell = row.getCell(8); cell.setCellValue(tbCustomer.getZipCode() == null ? "" : tbCustomer.getZipCode()); row = sheet.getRow(20); cell = row.getCell(23); // cell.setCellStyle(style); cell.setCellValue((tbFixEntrust.getWrongDescribe() == null || "".equals(tbFixEntrust.getWrongDescribe()) ? "" : tbFixEntrust.getWrongDescribe() + ";") + (tbFixEntrust.getBeforeFixState() == null || "".equals(tbFixEntrust.getBeforeFixState()) ? "" : tbFixEntrust.getBeforeFixState() + ";")); Double fixCount = tbFixEntrustContentService.countTbFixEnTrustContentByTbFixEntrustId(tbFixEntrustId); row = sheet.getRow(70); cell = row.getCell(32); // cell.setCellStyle(style); cell.setCellValue(new BigDecimal(fixCount).divide(new BigDecimal("1.00"), 2, BigDecimal.ROUND_HALF_UP) .toString()); row = sheet.getRow(70); cell = row.getCell(48); // cell.setCellStyle(style); cell.setCellValue("0.00"); BigDecimal partPriceAll = new BigDecimal("0.00"); if (partAllSize > 0) { for (int i = 0; i < partAllSize; i++) { TbMaintianVo tbMaintianVo = partAll.get(i); BigDecimal total = new BigDecimal(tbMaintianVo.getPrice()) .multiply(new BigDecimal(tbMaintianVo.getPartQuantity())); partPriceAll = partPriceAll.add(total); } } row = sheet.getRow(73); cell = row.getCell(34); // cell.setCellStyle(style); cell.setCellValue(partPriceAll.divide(new BigDecimal("1.00"), 2, BigDecimal.ROUND_HALF_UP).toString()); BigDecimal total = new BigDecimal(fixCount).add(partPriceAll).divide(new BigDecimal("1.00"), 2, BigDecimal.ROUND_HALF_UP); row = sheet.getRow(76); cell = row.getCell(35); // cell.setCellStyle(style); cell.setCellValue(total.toString()); int page = 1; if (fixSize / 5 >= (maintainSize + solePartSize) / 13) { page = fixSize / 5; } else { page = (maintainSize + solePartSize) / 13; } for (int i = 0; i < page; i++) { int p = 0; int k = 0; HSSFSheet sheetClone = workbook.cloneSheet(0); if (fixSize > 5) { int printFixSize = (fixSize > (i + 2) * 5 ? (i + 2) * 5 : fixSize); for (int j = 5 * (i + 1); j < printFixSize; j++) { TbFixEntrustContent content = tbFixEntrustContentList.get(j); List<TbFixShare> tbFixShareList = tbFixShareService .findTbFixShareListByTbFixEntrustContentId(content.getId()); String fixPersons = ""; if (null != tbFixShareList && tbFixShareList.size() > 0) { for (TbFixShare tbFixShare : tbFixShareList) { if (null != tbFixShare.getTmUser()) { TmUser tmUser = tmUserService.findById(tbFixShare.getTmUser().getId()); fixPersons += (tmUser.getUserRealName() == null || "".equals(tmUser.getUserRealName()) ? tmUser.getUserName() : tmUser.getUserRealName()) + " "; } } } row = sheetClone.getRow(31 + p * 6); cell = row.getCell(0); // cell.setCellStyle(style11); cell.setCellValue(content.getStationCode() + " " + content.getStationName()); cell = row.getCell(20); // cell.setCellStyle(style11); cell.setCellValue(content.getWxlx() == null ? "" : content.getWxlx()); cell = row.getCell(26); // cell.setCellStyle(style11); cell.setCellValue(fixPersons); p++; } } if (partAllSize > 13) { int prinPartSize = (partAllSize > (i + 2) * 13 ? (i + 2) * 13 : partAllSize); for (int j = 13 * (i + 1); j < prinPartSize; j++) { TbMaintianVo t = partAll.get(j); row = sheetClone.getRow(31 + k * 3); cell = row.getCell(32); // cell.setCellStyle(style10); cell.setCellValue(t.getPartName()); cell = row.getCell(40); // cell.setCellStyle(style10); cell.setCellValue(new BigDecimal(t.getPartQuantity()) .divide(new BigDecimal("1.00"), 2, BigDecimal.ROUND_HALF_UP).toString()); cell = row.getCell(44); // cell.setCellStyle(style10); cell.setCellValue(new BigDecimal(t.getPrice()) .divide(new BigDecimal("1.00"), 2, BigDecimal.ROUND_HALF_UP).toString()); k++; } } } if (fixSize > 0) { int printFixSize = (fixSize > 5 ? 5 : fixSize); for (int j = 0; j < printFixSize; j++) { TbFixEntrustContent content = tbFixEntrustContentList.get(j); List<TbFixShare> tbFixShareList = tbFixShareService .findTbFixShareListByTbFixEntrustContentId(content.getId()); String fixPersons = ""; if (null != tbFixShareList && tbFixShareList.size() > 0) { for (TbFixShare tbFixShare : tbFixShareList) { if (null != tbFixShare.getTmUser()) { TmUser tmUser = tmUserService.findById(tbFixShare.getTmUser().getId()); fixPersons += (tmUser.getUserRealName() == null || "".equals(tmUser.getUserRealName()) ? tmUser.getUserName() : tmUser.getUserRealName()) + " "; } } } row = sheet.getRow(31 + j * 6); cell = row.getCell(0); // cell.setCellStyle(style11); cell.setCellValue(content.getStationCode() + " " + content.getStationName()); cell = row.getCell(20); // cell.setCellStyle(style11); cell.setCellValue(content.getWxlx() == null ? "" : content.getWxlx()); cell = row.getCell(26); // cell.setCellStyle(style11); cell.setCellValue(fixPersons); } } if (partAllSize > 0) { int printPartSize = (partAllSize > 13 ? 13 : partAllSize); for (int j = 0; j < printPartSize; j++) { TbMaintianVo t = partAll.get(j); row = sheet.getRow(31 + j * 3); cell = row.getCell(32); // cell.setCellStyle(style10); cell.setCellValue(t.getPartName()); cell = row.getCell(40); // cell.setCellStyle(style10); cell.setCellValue(new BigDecimal(t.getPartQuantity()) .divide(new BigDecimal("1.00"), 2, BigDecimal.ROUND_HALF_UP).toString()); cell = row.getCell(44); // cell.setCellStyle(style10); cell.setCellValue(new BigDecimal(t.getPrice()) .divide(new BigDecimal("1.00"), 2, BigDecimal.ROUND_HALF_UP).toString()); } } workbook.write(os); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:com.selfsoft.business.service.impl.TbBusinessBalanceServiceImpl.java
public List<TbBusinessBalance> findTbBusinessBalanceToGroup(TbBusinessBalance tbBusinessBalance) { String sql = "select new TbBusinessBalance(max(tbBusinessBalance.id),tbBusinessBalance.balanceCode,max(tbBusinessBalance.bananceDate),sum(tbBusinessBalance.balanceTotalAll),sum(tbBusinessBalance.shouldPayAmount),sum(tbBusinessBalance.workingHourTotalAll),sum(tbBusinessBalance.fixPartTotalAll),sum(tbBusinessBalance.solePartTotalAll)) from TbBusinessBalance tbBusinessBalance WHERE 1=1"; String sqlConditionSelect = "select tbBusinessBalance from TbBusinessBalance tbBusinessBalance where 1=1"; String sqlCondition = ""; String sqlGroup = " group by tbBusinessBalance.balanceCode"; if (null != tbBusinessBalance) { if (null != tbBusinessBalance.getId()) { /*/* www . ja v a2s . c om*/ * sqlCondition +=" and tbBusinessBalance.id = " + * tbBusinessBalance.getId(); */ TbBusinessBalance t = this.findById(tbBusinessBalance.getId()); tbBusinessBalance.setBalanceCode(t.getBalanceCode()); } if (null != tbBusinessBalance.getBalanceCode() && !"".equals(tbBusinessBalance.getBalanceCode())) { sqlCondition += " and tbBusinessBalance.balanceCode like '%" + tbBusinessBalance.getBalanceCode() + "%'"; } if (null != tbBusinessBalance.getEntrustCode() && !"".equals(tbBusinessBalance.getEntrustCode())) { sqlCondition += " and tbBusinessBalance.tbFixEntrust.entrustCode like '%" + tbBusinessBalance.getEntrustCode() + "%'"; } if (null != tbBusinessBalance.getBananceDateStart()) { sqlCondition += " and tbBusinessBalance.bananceDate>='" + CommonMethod.parseDateToString(tbBusinessBalance.getBananceDateStart(), "yyyy-MM-dd") + "'"; } if (null != tbBusinessBalance.getBananceDateEnd()) { sqlCondition += " and tbBusinessBalance.bananceDate<='" + CommonMethod.parseDateToString( CommonMethod.addDate(tbBusinessBalance.getBananceDateEnd(), 1), "yyyy-MM-dd") + "'"; } if (null != tbBusinessBalance.getTmUser()) { if (null != tbBusinessBalance.getTmUser().getId()) { sqlCondition += " and tbBusinessBalance.tmUser.id=" + tbBusinessBalance.getTmUser().getId(); } } if (null != tbBusinessBalance.getUserId()) { sqlCondition += " and tbBusinessBalance.tbFixEntrust.tmUser.id =" + tbBusinessBalance.getUserId() + ""; } if (null != tbBusinessBalance.getLicenseCode() && !"".equals(tbBusinessBalance.getLicenseCode())) { sqlCondition += " and tbBusinessBalance.tbFixEntrust.tbCarInfo.licenseCode like '%" + tbBusinessBalance.getLicenseCode() + "%'"; } if (null != tbBusinessBalance.getChassisCode() && !"".equals(tbBusinessBalance.getChassisCode())) { sqlCondition += " and tbBusinessBalance.tbFixEntrust.tbCarInfo.chassisCode like '%" + tbBusinessBalance.getChassisCode() + "%'"; } if (null != tbBusinessBalance.getCustomerName() && !"".equals(tbBusinessBalance.getCustomerName())) { sqlCondition += " and tbBusinessBalance.tbFixEntrust.tbCustomer.customerName = '" + tbBusinessBalance.getCustomerName() + "'"; } if (null != tbBusinessBalance.getCustomerCode() && !"".equals(tbBusinessBalance.getCustomerCode())) { sqlCondition += " and tbBusinessBalance.tbFixEntrust.tbCustomer.customerCode = '" + tbBusinessBalance.getCustomerCode() + "'"; } if (null != tbBusinessBalance.getTelephone() && !"".equals(tbBusinessBalance.getTelephone())) { sqlCondition += " and tbBusinessBalance.tbFixEntrust.tbCustomer.telephone = '" + tbBusinessBalance.getTelephone() + "'"; } if (null != tbBusinessBalance.getTmModelTypeId()) { sqlCondition += " and tbBusinessBalance.tbFixEntrust.tbCarInfo.tmCarModelType.id =" + tbBusinessBalance.getTmModelTypeId(); } if (null != tbBusinessBalance.getPayPattern()) { sqlCondition += " and tbBusinessBalance.payPattern = '" + tbBusinessBalance.getPayPattern() + "'"; } if (null != tbBusinessBalance.getTmFixTypeId()) { sqlCondition += " and tbBusinessBalance.tbFixEntrust.tmFixType.id =" + tbBusinessBalance.getTmFixTypeId() + ""; } } List<TbBusinessBalance> listCondition = tbBusinessBalanceDao.findBySQL(sqlConditionSelect + sqlCondition, null); List<TbBusinessBalance> list = tbBusinessBalanceDao.findBySQL(sql + sqlGroup, null); List<TbBusinessBalance> listReturn = new ArrayList<TbBusinessBalance>(); BigDecimal pjCostAll = new BigDecimal("0.00"); if (null != listCondition && listCondition.size() > 0 && null != list && list.size() > 0) { for (int i = list.size() - 1; i >= 0; i--) { TbBusinessBalance ti = list.get(i); for (int j = listCondition.size() - 1; j >= 0; j--) { TbBusinessBalance tj = listCondition.get(j); if (ti.getId().equals(tj.getId())) { ti.setPayPattern(tj.getPayPattern()); ti.setTbFixEntrust(tj.getTbFixEntrust()); ti.setTmStockOut(tj.getTmStockOut()); ti.setOldPartDeal(tj.getOldPartDeal()); ti.setRemark(tj.getRemark()); ti.setTmUser(tj.getTmUser()); TbCustomer tbCustomer = null; if (null != ti.getTbFixEntrust()) { tbCustomer = ti.getTbFixEntrust().getTbCarInfo().getTbCustomer(); ti.setLicenseCode(ti.getTbFixEntrust().getTbCarInfo().getLicenseCode()); Double pjCost = statisticsStockInOutService .sumStockDetailByEntrustId(ti.getTbFixEntrust().getId()); ti.setPjCost(new BigDecimal(pjCost).divide(new BigDecimal("1.00"), 2, BigDecimal.ROUND_HALF_UP)); pjCostAll = pjCostAll.add(new BigDecimal(pjCost)).divide(new BigDecimal("1.00"), 2, BigDecimal.ROUND_HALF_UP); ti.setPjCostAll(pjCostAll); BigDecimal djCost = tbFixEntrustCostService .sumTbFixEntrustCostByTbFixEntrustId(ti.getTbFixEntrust().getId()); ti.setDjCost(djCost.divide(new BigDecimal("1.00"), 2, BigDecimal.ROUND_HALF_UP)); ti.setUserRealNameServer(ti.getTbFixEntrust().getTmUser().getUserRealName()); } else { tbCustomer = tbCustomerService.findById(ti.getTmStockOut().getCustomerBill()); Double pjCost = tmStockOutService.sumSingleSellByBanalceCode(ti.getBalanceCode()); ti.setPjCost(new BigDecimal(pjCost).divide(new BigDecimal("1.00"), 2, BigDecimal.ROUND_HALF_UP)); pjCostAll = pjCostAll.add(new BigDecimal(pjCost)).divide(new BigDecimal("1.00"), 2, BigDecimal.ROUND_HALF_UP); ti.setPjCostAll(pjCostAll); } ti.setTbCustomer(tbCustomer); ti.setXlgsfFavourAmount(this.calcItemFavourAmount(ti, "XLGSF")); ti.setXlclfFavourAmount(this.calcItemFavourAmount(ti, "XLCLF")); ti.setXsjeFavourAmount(this.calcItemFavourAmount(ti, "XSJE")); String bananceDateStart_s = CommonMethod.parseDateToString(ti.getBananceDate(), "yyyy-MM-dd HH:ss:mm"); ti.setBananceDateStart_s(bananceDateStart_s); // if (ti.getOweAmount() > 0D) { BigDecimal d = new BigDecimal("0.00"); List<TbReceiveFree> tbReceiveFreeList = tbReceiveFreeService .findByBalanceId(ti.getId()); /** * ???? */ if (null != tbReceiveFreeList && tbReceiveFreeList.size() > 0) { for (TbReceiveFree tf : tbReceiveFreeList) { if (Constants.AMOUNTS.equals(tf.getAmountType())) { d = d.add(new BigDecimal(tf.getFeeAmount())); ti.setFreeAmount(tf.getFeeAmount()); } } } } listReturn.add(ti); break; } } } } return listReturn; }