From 3929ff1bd7fd3e04b7c2dbe16a01cd24e19d86d3 Mon Sep 17 00:00:00 2001 From: Suraj Khurana Date: Sun, 26 Jul 2020 20:25:35 +0530 Subject: [PATCH] Improved: Corrected all incorrect indentation level issues in application component, also fixed some case indentation checkstyle issues. (OFBIZ-11922) --- .../org/apache/ofbiz/accounting/GlEvents.java | 166 +-- .../accounting/invoice/InvoiceServices.java | 948 ++++++++++-------- .../accounting/invoice/InvoiceWorker.java | 60 +- .../payment/GiftCertificateServices.java | 18 +- .../payment/PaymentGatewayServices.java | 40 +- .../payment/PaymentMethodServices.java | 29 +- .../accounting/tax/TaxAuthorityServices.java | 26 +- .../authorizedotnet/AIMPaymentServices.java | 45 +- .../orbital/OrbitalPaymentServices.java | 18 +- .../thirdparty/paypal/PayPalEvents.java | 14 +- .../thirdparty/paypal/PayPalServices.java | 2 +- .../sagepay/SagePayPaymentServices.java | 2 +- .../thirdparty/sagepay/SagePayServices.java | 163 ++- .../thirdparty/sagepay/SagePayUtil.java | 152 ++- .../securepay/SecurePayServiceTest.java | 2 +- .../thirdparty/valuelink/ValueLinkApi.java | 2 +- .../thirdparty/verisign/PayflowPro.java | 18 +- .../content/ContentManagementEvents.java | 20 +- .../content/ContentManagementServices.java | 66 +- .../content/ContentManagementWorker.java | 32 +- .../apache/ofbiz/content/cms/CmsEvents.java | 411 ++++---- .../ofbiz/content/cms/ContentJsonEvents.java | 22 +- .../ofbiz/content/compdoc/CompDocEvents.java | 4 +- .../content/ContentPermissionServices.java | 59 +- .../content/ContentServicesComplex.java | 46 +- .../ofbiz/content/content/ContentWorker.java | 41 +- .../ofbiz/content/content/ContentWrapper.java | 2 +- .../apache/ofbiz/content/data/DataEvents.java | 6 +- .../content/data/DataResourceWorker.java | 37 +- .../ofbiz/content/data/DataServices.java | 2 +- .../content/survey/PdfSurveyServices.java | 6 +- .../ofbiz/content/survey/SurveyWrapper.java | 51 +- .../view/SimpleContentViewHandler.java | 2 +- .../EditRenderSubContentCacheTransform.java | 2 +- .../ftl/InjectNodeTrailCsvTransform.java | 14 +- .../webapp/ftl/RenderContentAsText.java | 2 +- .../webapp/ftl/RenderSubContentAsText.java | 2 +- .../ftl/TraverseSubContentCacheTransform.java | 2 +- .../ftl/WrapSubContentCacheTransform.java | 2 +- .../ofbiz/manufacturing/bom/BOMHelper.java | 93 +- .../ofbiz/manufacturing/bom/BOMNode.java | 4 +- .../ofbiz/manufacturing/bom/BOMServices.java | 2 +- .../ofbiz/manufacturing/bom/BOMTree.java | 4 +- .../jobshopmgt/ProductionRun.java | 2 +- .../jobshopmgt/ProductionRunServices.java | 471 +++++---- .../mrp/InventoryEventPlannedServices.java | 4 +- .../ofbiz/manufacturing/mrp/MrpServices.java | 199 ++-- .../manufacturing/mrp/ProposedOrder.java | 4 +- .../techdata/TechDataServices.java | 15 +- .../tracking/TrackingCodeEvents.java | 3 +- .../order/finaccount/FinAccountHelper.java | 229 +++-- .../ofbiz/order/order/OrderChangeHelper.java | 48 +- .../apache/ofbiz/order/order/OrderEvents.java | 2 +- .../ofbiz/order/order/OrderListState.java | 2 +- .../order/order/OrderLookupServices.java | 2 +- .../ofbiz/order/order/OrderReadHelper.java | 10 +- .../order/order/OrderReturnServices.java | 4 +- .../ofbiz/order/order/OrderServices.java | 169 ++-- .../order/shoppingcart/CheckOutEvents.java | 2 +- .../order/shoppingcart/CheckOutHelper.java | 102 +- .../order/shoppingcart/ShoppingCart.java | 235 +++-- .../shoppingcart/ShoppingCartHelper.java | 59 +- .../order/shoppingcart/ShoppingCartItem.java | 110 +- .../product/ProductDisplayWorker.java | 20 +- .../CommunicationEventServices.java | 14 +- .../party/content/PartyContentWrapper.java | 4 +- .../ofbiz/party/party/PartyServices.java | 2 +- .../apache/ofbiz/party/party/PartyWorker.java | 4 +- .../product/category/CatalogUrlServlet.java | 112 ++- .../category/CategoryContentWrapper.java | 2 +- .../product/category/CategoryWorker.java | 2 +- .../ProductConfigItemContentWrapper.java | 4 +- .../product/config/ProductConfigWorker.java | 6 +- .../product/config/ProductConfigWrapper.java | 44 +- .../product/imagemanagement/FrameImage.java | 16 +- .../ImageManagementServices.java | 2 +- .../product/inventory/InventoryServices.java | 102 +- .../ofbiz/product/price/PriceServices.java | 53 +- .../product/ProductContentWrapper.java | 35 +- .../product/ProductPromoContentWrapper.java | 4 +- .../ofbiz/product/product/ProductSearch.java | 10 +- .../product/product/ProductSearchEvents.java | 351 ++++--- .../product/product/ProductServices.java | 2 +- .../ofbiz/product/product/ProductWorker.java | 26 +- .../ofbiz/product/promo/PromoServices.java | 3 +- .../subscription/SubscriptionServices.java | 11 +- .../ofbiz/shipment/packing/PackingEvent.java | 16 +- .../shipment/packing/PackingServices.java | 2 +- .../shipment/packing/PackingSession.java | 32 +- .../shipment/shipment/ShipmentServices.java | 46 +- .../shipment/thirdparty/dhl/DhlServices.java | 7 +- .../thirdparty/fedex/FedexServices.java | 25 +- .../shipment/thirdparty/ups/UpsServices.java | 693 ++++++++----- .../thirdparty/usps/UspsServices.java | 2 +- .../shipment/verify/VerifyPickSession.java | 2 +- .../content/WorkEffortContentWrapper.java | 8 +- .../workeffort/WorkEffortSearch.java | 25 +- .../workeffort/WorkEffortSearchSession.java | 19 +- 98 files changed, 3395 insertions(+), 2622 deletions(-) diff --git a/applications/accounting/src/main/java/org/apache/ofbiz/accounting/GlEvents.java b/applications/accounting/src/main/java/org/apache/ofbiz/accounting/GlEvents.java index e8ce54b287..232ffc0157 100644 --- a/applications/accounting/src/main/java/org/apache/ofbiz/accounting/GlEvents.java +++ b/applications/accounting/src/main/java/org/apache/ofbiz/accounting/GlEvents.java @@ -38,94 +38,100 @@ import org.apache.ofbiz.service.ServiceUtil; public class GlEvents { -private static final String MODULE = GlEvents.class.getName(); -public static String createReconcileAccount(HttpServletRequest request, HttpServletResponse response) { - LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher"); - final Delegator delegator = (Delegator) request.getAttribute("delegator"); - GenericValue userLogin = (GenericValue) request.getSession().getAttribute("userLogin"); - Map ctx = UtilHttp.getParameterMap(request); - String acctgTransId; - String acctgTransEntrySeqId; - String glAccountId = null; - String organizationPartyId = null; - BigDecimal reconciledBalance = BigDecimal.ZERO; - boolean isSelected; - String debitCreditFlag; - // The number of multi form rows is retrieved - int rowCount = UtilHttp.getMultiFormRowCount(ctx); - for (int i = 0; i < rowCount; i++) { //for calculating amount per glAccountId - String suffix = UtilHttp.getMultiRowDelimiter() + i; - isSelected = (ctx.containsKey("_rowSubmit" + suffix) && "Y".equalsIgnoreCase((String) ctx.get("_rowSubmit" + suffix))); - if (!isSelected) { - continue; - } - acctgTransId = (String) ctx.get("acctgTransId" + suffix); - acctgTransEntrySeqId = (String) ctx.get("acctgTransEntrySeqId" + suffix); - organizationPartyId = (String) ctx.get("organizationPartyId" + suffix); - glAccountId = (String) ctx.get("glAccountId" + suffix); - try { - GenericValue acctgTransEntry = EntityQuery.use(delegator).from("AcctgTransEntry").where("acctgTransId", acctgTransId, "acctgTransEntrySeqId", acctgTransEntrySeqId).queryOne(); - if (acctgTransEntry != null) { - //calculate amount for each AcctgTransEntry according to glAccountId based on debit and credit - debitCreditFlag = acctgTransEntry.getString("debitCreditFlag"); - if ("D".equalsIgnoreCase(debitCreditFlag)) { - reconciledBalance = reconciledBalance.add(acctgTransEntry.getBigDecimal("amount")); //total balance per glAccountId - } else { - reconciledBalance = reconciledBalance.subtract(acctgTransEntry.getBigDecimal("amount")); //total balance per glAccountId - } + private static final String MODULE = GlEvents.class.getName(); + + public static String createReconcileAccount(HttpServletRequest request, HttpServletResponse response) { + LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher"); + final Delegator delegator = (Delegator) request.getAttribute("delegator"); + GenericValue userLogin = (GenericValue) request.getSession().getAttribute("userLogin"); + Map ctx = UtilHttp.getParameterMap(request); + String acctgTransId; + String acctgTransEntrySeqId; + String glAccountId = null; + String organizationPartyId = null; + BigDecimal reconciledBalance = BigDecimal.ZERO; + boolean isSelected; + String debitCreditFlag; + // The number of multi form rows is retrieved + int rowCount = UtilHttp.getMultiFormRowCount(ctx); + for (int i = 0; i < rowCount; i++) { //for calculating amount per glAccountId + String suffix = UtilHttp.getMultiRowDelimiter() + i; + isSelected = (ctx.containsKey("_rowSubmit" + suffix) && "Y".equalsIgnoreCase((String) ctx.get("_rowSubmit" + suffix))); + if (!isSelected) { + continue; } - } catch (GenericEntityException e) { + acctgTransId = (String) ctx.get("acctgTransId" + suffix); + acctgTransEntrySeqId = (String) ctx.get("acctgTransEntrySeqId" + suffix); + organizationPartyId = (String) ctx.get("organizationPartyId" + suffix); + glAccountId = (String) ctx.get("glAccountId" + suffix); + try { + GenericValue acctgTransEntry = EntityQuery.use(delegator).from("AcctgTransEntry").where("acctgTransId", acctgTransId, + "acctgTransEntrySeqId", acctgTransEntrySeqId).queryOne(); + if (acctgTransEntry != null) { + //calculate amount for each AcctgTransEntry according to glAccountId based on debit and credit + debitCreditFlag = acctgTransEntry.getString("debitCreditFlag"); + if ("D".equalsIgnoreCase(debitCreditFlag)) { + reconciledBalance = reconciledBalance.add(acctgTransEntry.getBigDecimal("amount")); //total balance per glAccountId + } else { + reconciledBalance = reconciledBalance.subtract(acctgTransEntry.getBigDecimal("amount")); //total balance per glAccountId + } + } + } catch (GenericEntityException e) { + Debug.logError(e, MODULE); + return "error"; + } + + } + Map fieldMap = UtilMisc.toMap("glReconciliationName", "Reconciliation at date " + UtilDateTime.nowTimestamp(), "glAccountId" + , glAccountId, "organizationPartyId", organizationPartyId, "reconciledDate", UtilDateTime.nowTimestamp(), "reconciledBalance", + reconciledBalance, "userLogin", userLogin); + Map glReconResult = null; + try { + glReconResult = dispatcher.runSync("createGlReconciliation", fieldMap); //create GlReconciliation for the glAccountId + if (ServiceUtil.isError(glReconResult)) { + return "error"; + } + } catch (GenericServiceException e) { Debug.logError(e, MODULE); return "error"; } - - } - Map fieldMap = UtilMisc.toMap("glReconciliationName", "Reconciliation at date " + UtilDateTime.nowTimestamp(), "glAccountId", glAccountId, "organizationPartyId", organizationPartyId, "reconciledDate", UtilDateTime.nowTimestamp(), "reconciledBalance", reconciledBalance, "userLogin", userLogin); - Map glReconResult = null; - try { - glReconResult = dispatcher.runSync("createGlReconciliation", fieldMap); //create GlReconciliation for the glAccountId - if (ServiceUtil.isError(glReconResult)) { - return "error"; - } - } catch (GenericServiceException e) { - Debug.logError(e, MODULE); - return "error"; - } - String glReconciliationId = (String) glReconResult.get("glReconciliationId"); - String reconciledAmount; - for (int i = 0; i < rowCount; i++) { - String suffix = UtilHttp.getMultiRowDelimiter() + i; - isSelected = (ctx.containsKey("_rowSubmit" + suffix) && "Y".equalsIgnoreCase((String) ctx.get("_rowSubmit" + suffix))); - if (!isSelected) { - continue; - } - acctgTransId = (String) ctx.get("acctgTransId" + suffix); - acctgTransEntrySeqId = (String) ctx.get("acctgTransEntrySeqId" + suffix); - try { - GenericValue acctgTransEntry = EntityQuery.use(delegator).from("AcctgTransEntry").where("acctgTransId", acctgTransId, "acctgTransEntrySeqId", acctgTransEntrySeqId).queryOne(); - if (acctgTransEntry != null) { - reconciledAmount = acctgTransEntry.getString("amount"); - acctgTransId = acctgTransEntry.getString("acctgTransId"); - acctgTransEntrySeqId = acctgTransEntry.getString("acctgTransEntrySeqId"); - Map glReconEntryMap = UtilMisc.toMap("glReconciliationId", glReconciliationId, "acctgTransId", acctgTransId, "acctgTransEntrySeqId", acctgTransEntrySeqId, "reconciledAmount", reconciledAmount, "userLogin", userLogin); - Map glReconEntryResult = null; - try { - glReconEntryResult = dispatcher.runSync("createGlReconciliationEntry", glReconEntryMap); - if (ServiceUtil.isError(glReconEntryResult)) { + String glReconciliationId = (String) glReconResult.get("glReconciliationId"); + String reconciledAmount; + for (int i = 0; i < rowCount; i++) { + String suffix = UtilHttp.getMultiRowDelimiter() + i; + isSelected = (ctx.containsKey("_rowSubmit" + suffix) && "Y".equalsIgnoreCase((String) ctx.get("_rowSubmit" + suffix))); + if (!isSelected) { + continue; + } + acctgTransId = (String) ctx.get("acctgTransId" + suffix); + acctgTransEntrySeqId = (String) ctx.get("acctgTransEntrySeqId" + suffix); + try { + GenericValue acctgTransEntry = EntityQuery.use(delegator).from("AcctgTransEntry").where("acctgTransId", acctgTransId, + "acctgTransEntrySeqId", acctgTransEntrySeqId).queryOne(); + if (acctgTransEntry != null) { + reconciledAmount = acctgTransEntry.getString("amount"); + acctgTransId = acctgTransEntry.getString("acctgTransId"); + acctgTransEntrySeqId = acctgTransEntry.getString("acctgTransEntrySeqId"); + Map glReconEntryMap = UtilMisc.toMap("glReconciliationId", glReconciliationId, "acctgTransId", acctgTransId, + "acctgTransEntrySeqId", acctgTransEntrySeqId, "reconciledAmount", reconciledAmount, "userLogin", userLogin); + Map glReconEntryResult = null; + try { + glReconEntryResult = dispatcher.runSync("createGlReconciliationEntry", glReconEntryMap); + if (ServiceUtil.isError(glReconEntryResult)) { + return "error"; + } + } catch (GenericServiceException e) { + Debug.logError(e, MODULE); return "error"; } - } catch (GenericServiceException e) { - Debug.logError(e, MODULE); - return "error"; } + } catch (GenericEntityException e) { + Debug.logError(e, MODULE); + return "error"; } - } catch (GenericEntityException e) { - Debug.logError(e, MODULE); - return "error"; } + ctx.put("glReconciliationId", glReconciliationId); + request.setAttribute("glReconciliationId", glReconciliationId); + return "success"; } - ctx.put("glReconciliationId", glReconciliationId); - request.setAttribute("glReconciliationId", glReconciliationId); - return "success"; - } } diff --git a/applications/accounting/src/main/java/org/apache/ofbiz/accounting/invoice/InvoiceServices.java b/applications/accounting/src/main/java/org/apache/ofbiz/accounting/invoice/InvoiceServices.java index 3330108b0a..198c58f498 100644 --- a/applications/accounting/src/main/java/org/apache/ofbiz/accounting/invoice/InvoiceServices.java +++ b/applications/accounting/src/main/java/org/apache/ofbiz/accounting/invoice/InvoiceServices.java @@ -68,39 +68,39 @@ import org.apache.ofbiz.service.ServiceUtil; /** * InvoiceServices - Services for creating invoices - * + *

* Note that throughout this file we use BigDecimal to do arithmetic. It is * critical to understand the way BigDecimal works if you wish to modify the * computations in this file. The most important things to keep in mind: - * + *

* Critically important: BigDecimal arithmetic methods like add(), * multiply(), divide() do not modify the BigDecimal itself. Instead, they * return a new BigDecimal. For example, to keep a running total of an * amount, make sure you do this: - * - * amount = amount.add(subAmount); - * + *

+ * amount = amount.add(subAmount); + *

* and not this, - * - * amount.add(subAmount); - * + *

+ * amount.add(subAmount); + *

* Use .setScale(scale, roundingMode) after every computation to scale and * round off the decimals. Check the code to see how the scale and * roundingMode are obtained and how the function is used. - * + *

* use .compareTo() to compare big decimals - * - * ex. (amountOne.compareTo(amountTwo) == 1) - * checks if amountOne is greater than amountTwo - * + *

+ * ex. (amountOne.compareTo(amountTwo) == 1) + * checks if amountOne is greater than amountTwo + *

* Use .signum() to test if value is negative, zero, or positive - * - * ex. (amountOne.signum() == 1) - * checks if the amount is a positive non-zero number - * + *

+ * ex. (amountOne.signum() == 1) + * checks if the amount is a positive non-zero number + *

* Never use the .equals() function becaues it considers 2.0 not equal to 2.00 (the scale is different) * Instead, use .compareTo() or .signum(), which handles scale correctly. - * + *

* For reference, check the official Sun Javadoc on java.math.BigDecimal. */ public class InvoiceServices { @@ -140,7 +140,7 @@ public class InvoiceServices { result.remove("invoiceTypeId"); //remove extra parameter return result; } catch (GenericServiceException | GenericEntityException e) { - Debug.logError (e, "Entity/data problem creating invoice from order items: " + e.toString(), MODULE); + 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)); @@ -296,11 +296,12 @@ public class InvoiceServices { createInvoiceTerms(delegator, dispatcher, invoiceId, billingAccountTerms, userLogin, locale); */ // set the invoice bill_to_customer from the billing account - List billToRoles = billingAccount.getRelated("BillingAccountRole", UtilMisc.toMap("roleTypeId", "BILL_TO_CUSTOMER"), null, false); + List 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); + "roleTypeId", "BILL_TO_CUSTOMER", "userLogin", userLogin); Map createInvoiceRoleResult = dispatcher.runSync("createInvoiceRole", createInvoiceRoleContext); if (ServiceUtil.isError(createInvoiceRoleResult)) { return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, @@ -311,9 +312,11 @@ public class InvoiceServices { // set the bill-to contact mech as the contact mech of the billing account if (UtilValidate.isNotEmpty(billingAccount.getString("contactMechId"))) { - Map createBillToContactMechContext = UtilMisc.toMap("invoiceId", invoiceId, "contactMechId", billingAccount.getString("contactMechId"), - "contactMechPurposeTypeId", "BILLING_LOCATION", "userLogin", userLogin); - Map createBillToContactMechResult = dispatcher.runSync("createInvoiceContactMech", createBillToContactMechContext); + Map createBillToContactMechContext = UtilMisc.toMap("invoiceId", invoiceId, "contactMechId", + billingAccount.getString("contactMechId"), + "contactMechPurposeTypeId", "BILLING_LOCATION", "userLogin", userLogin); + Map createBillToContactMechResult = dispatcher.runSync("createInvoiceContactMech", + createBillToContactMechContext); if (ServiceUtil.isError(createBillToContactMechResult)) { return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "AccountingErrorCreatingInvoiceContactMechFromOrder", locale), null, null, createBillToContactMechResult); @@ -323,16 +326,19 @@ public class InvoiceServices { List billingLocations = orh.getBillingLocations(); if (UtilValidate.isNotEmpty(billingLocations)) { for (GenericValue ocm : billingLocations) { - Map createBillToContactMechContext = UtilMisc.toMap("invoiceId", invoiceId, "contactMechId", ocm.getString("contactMechId"), - "contactMechPurposeTypeId", "BILLING_LOCATION", "userLogin", userLogin); - Map createBillToContactMechResult = dispatcher.runSync("createInvoiceContactMech", createBillToContactMechContext); + Map createBillToContactMechContext = UtilMisc.toMap("invoiceId", invoiceId, "contactMechId", ocm.getString( + "contactMechId"), + "contactMechPurposeTypeId", "BILLING_LOCATION", "userLogin", userLogin); + Map 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); + Debug.logWarning("No billing locations found for order [" + orderId + "] and none were created for Invoice [" + invoiceId + "]" + , MODULE); } } @@ -345,7 +351,8 @@ public class InvoiceServices { // 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 billingContactMechs = billFromVendor.getRelatedOne("Party", false).getRelated("PartyContactMechPurpose", UtilMisc.toMap("contactMechPurposeTypeId", "BILLING_LOCATION"), null, false); + List billingContactMechs = billFromVendor.getRelatedOne("Party", false).getRelated("PartyContactMechPurpose", + UtilMisc.toMap("contactMechPurposeTypeId", "BILLING_LOCATION"), null, false); if (UtilValidate.isNotEmpty(billingContactMechs)) { payToAddress = EntityUtil.getFirst(EntityUtil.filterByDate(billingContactMechs)); } @@ -355,8 +362,9 @@ public class InvoiceServices { payToAddress = PaymentWorker.getPaymentAddress(delegator, productStore.getString("payToPartyId")); } if (payToAddress != null) { - Map createPayToContactMechContext = UtilMisc.toMap("invoiceId", invoiceId, "contactMechId", payToAddress.getString("contactMechId"), - "contactMechPurposeTypeId", "PAYMENT_LOCATION", "userLogin", userLogin); + Map createPayToContactMechContext = UtilMisc.toMap("invoiceId", invoiceId, "contactMechId", payToAddress.getString( + "contactMechId"), + "contactMechPurposeTypeId", "PAYMENT_LOCATION", "userLogin", userLogin); Map createPayToContactMechResult = dispatcher.runSync("createInvoiceContactMech", createPayToContactMechContext); if (ServiceUtil.isError(createPayToContactMechResult)) { return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, @@ -430,14 +438,16 @@ public class InvoiceServices { } BigDecimal billingAmount = BigDecimal.ZERO; - GenericValue OrderAdjustment = EntityUtil.getFirst(orderItem.getRelated("OrderAdjustment", UtilMisc.toMap("orderAdjustmentTypeId", "VAT_TAX"), null, false)); + 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); + billingAmount = + orderItem.getBigDecimal("unitPrice").divide(sourcePercentageTotal, 100, ROUNDING).multiply(new BigDecimal(100)).setScale(invoiceTypeDecimals, ROUNDING); } else { billingAmount = orderItem.getBigDecimal("unitPrice").setScale(invoiceTypeDecimals, ROUNDING); } @@ -445,7 +455,8 @@ public class InvoiceServices { Map createInvoiceItemContext = new HashMap<>(); 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("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); @@ -511,7 +522,8 @@ public class InvoiceServices { In that case ShipmentItemBilling was creating only for one invoice item. Fixed under OFBIZ-6806. */ List shipmentItemBillings = EntityQuery.use(delegator).from("ShipmentItemBilling") - .where("shipmentId", currentValue.get("shipmentId"), "shipmentItemSeqId", currentValue.get("shipmentItemSeqId"), "invoiceId", invoiceId, "invoiceItemSeqId", invoiceItemSeqId) + .where("shipmentId", currentValue.get("shipmentId"), "shipmentItemSeqId", currentValue.get("shipmentItemSeqId"), + "invoiceId", invoiceId, "invoiceItemSeqId", invoiceItemSeqId) .queryList(); if (UtilValidate.isEmpty(shipmentItemBillings)) { @@ -535,7 +547,8 @@ public class InvoiceServices { 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(); + GenericValue originalOrderItem = EntityQuery.use(delegator).from("OrderItem").where("orderId", orderId, "orderItemSeqId", + orderItem.get("orderItemSeqId")).queryOne(); // create the item adjustment as line items List itemAdjustments = OrderReadHelper.getOrderItemAdjustmentList(orderItem, orh.getAdjustments()); @@ -544,11 +557,12 @@ public class InvoiceServices { // Check against OrderAdjustmentBilling to see how much of this adjustment has already been invoiced BigDecimal adjAlreadyInvoicedAmount = null; try { - Map checkResult = dispatcher.runSync("calculateInvoicedAdjustmentTotal", UtilMisc.toMap("orderAdjustment", adj)); + Map checkResult = dispatcher.runSync("calculateInvoicedAdjustmentTotal", UtilMisc.toMap("orderAdjustment", + adj)); if (ServiceUtil.isError(checkResult)) { Debug.logError("Accounting trouble calling calculateInvoicedAdjustmentTotal service", MODULE); return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, - "AccountingTroubleCallingCalculateInvoicedAdjustmentTotalService", locale)); + "AccountingTroubleCallingCalculateInvoicedAdjustmentTotalService", locale)); } adjAlreadyInvoicedAmount = (BigDecimal) checkResult.get("invoicedTotal"); } catch (GenericServiceException e) { @@ -558,12 +572,15 @@ public class InvoiceServices { } // Set adjustment amount as amountAlreadyIncluded to continue invoice item creation process - Boolean isTaxIncludedInPrice = "VAT_TAX".equals(adj.getString("orderAdjustmentTypeId")) && UtilValidate.isNotEmpty(adj.getBigDecimal("amountAlreadyIncluded")) && adj.getBigDecimal("amountAlreadyIncluded").signum() != 0; + Boolean isTaxIncludedInPrice = + "VAT_TAX".equals(adj.getString("orderAdjustmentTypeId")) && UtilValidate.isNotEmpty(adj.getBigDecimal("amountAlreadyIncluded")) && adj.getBigDecimal("amountAlreadyIncluded").signum() != 0; if (isTaxIncludedInPrice && (adj.getBigDecimal("amount").signum() == 0)) { 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 (isTaxIncludedInPrice && adjAlreadyInvoicedAmount.abs().compareTo(adj.getBigDecimal("amount").setScale(invoiceTypeDecimals, ROUNDING).abs()) > 0) { + // If the absolute invoiced amount >= the abs of the adjustment amount, the full amount has already been invoiced, so skip this + // adjustment + if (isTaxIncludedInPrice && adjAlreadyInvoicedAmount.abs().compareTo(adj.getBigDecimal("amount").setScale(invoiceTypeDecimals, + ROUNDING).abs()) > 0) { continue; } @@ -571,52 +588,61 @@ public class InvoiceServices { BigDecimal amount = BigDecimal.ZERO; if (originalOrderItemQuantity.signum() != 0) { if (adj.get("amount") != null) { - if ("PROMOTION_ADJUSTMENT".equals(adj.getString("orderAdjustmentTypeId")) && adj.get("productPromoId") != 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. + As we stored negative sales tax amount in order adjustment for discounted + item. */ - List 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"); - } + List 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 { - // 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) + 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 = EntityQuery.use(delegator).from("OrderAdjustmentBilling").where("orderAdjustmentId", adj.getString("orderAdjustmentId")).queryFirst(); - if (UtilValidate.isNotEmpty(orderAdjBilling)) { - //FIXME: Need to check here isTaxIncludedInPrice pass to use cache - List invoiceItems = EntityQuery.use(delegator).from("InvoiceItem").where("invoiceId", orderAdjBilling.getString("invoiceId"), "invoiceItemTypeId", "ITM_SALES_TAX", "productId", originalOrderItem.getString("productId")).cache(isTaxIncludedInPrice).queryList(); - 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); - } + BigDecimal otherInvoiceTaxAmount = BigDecimal.ZERO; + GenericValue orderAdjBilling = EntityQuery.use(delegator).from("OrderAdjustmentBilling").where( + "orderAdjustmentId", adj.getString("orderAdjustmentId")).queryFirst(); + if (UtilValidate.isNotEmpty(orderAdjBilling)) { + //FIXME: Need to check here isTaxIncludedInPrice pass to use cache + List invoiceItems = EntityQuery.use(delegator).from("InvoiceItem").where("invoiceId", + orderAdjBilling.getString("invoiceId"), "invoiceItemTypeId", "ITM_SALES_TAX", "productId", + originalOrderItem.getString("productId")).cache(isTaxIncludedInPrice).queryList(); + 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); } + 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 ("SALES_TAX".equals(adj.getString("orderAdjustmentTypeId"))) { amount = amount.setScale(TAX_DECIMALS, TAX_ROUNDING); @@ -638,7 +664,8 @@ public class InvoiceServices { Map createInvoiceItemAdjContext = new HashMap<>(); createInvoiceItemAdjContext.put("invoiceId", invoiceId); createInvoiceItemAdjContext.put("invoiceItemSeqId", invoiceItemSeqId); - createInvoiceItemAdjContext.put("invoiceItemTypeId", getInvoiceItemType(delegator, adj.getString("orderAdjustmentTypeId"), null, invoiceType, "INVOICE_ITM_ADJ")); + 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")); @@ -652,7 +679,8 @@ public class InvoiceServices { 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")); + 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 @@ -690,10 +718,12 @@ public class InvoiceServices { createOrderAdjustmentBillingContext.put("amount", amount); createOrderAdjustmentBillingContext.put("userLogin", userLogin); - Map createOrderAdjustmentBillingResult = dispatcher.runSync("createOrderAdjustmentBilling", createOrderAdjustmentBillingContext); + Map createOrderAdjustmentBillingResult = dispatcher.runSync("createOrderAdjustmentBilling", + createOrderAdjustmentBillingContext); if (ServiceUtil.isError(createOrderAdjustmentBillingResult)) { return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, - "AccountingErrorCreatingOrderAdjustmentBillingFromOrder", locale), null, null, createOrderAdjustmentBillingContext); + "AccountingErrorCreatingOrderAdjustmentBillingFromOrder", locale), null, null, + createOrderAdjustmentBillingContext); } // this adjustment amount @@ -731,7 +761,7 @@ public class InvoiceServices { Map checkResult = dispatcher.runSync("calculateInvoicedAdjustmentTotal", UtilMisc.toMap("orderAdjustment", adj)); if (ServiceUtil.isError(checkResult)) { return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, - "AccountingTroubleCallingCalculateInvoicedAdjustmentTotalService", locale)); + "AccountingTroubleCallingCalculateInvoicedAdjustmentTotalService", locale)); } adjAlreadyInvoicedAmount = ((BigDecimal) checkResult.get("invoicedTotal")).setScale(invoiceTypeDecimals, ROUNDING); } catch (GenericServiceException e) { @@ -740,7 +770,8 @@ public class InvoiceServices { "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 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; } @@ -762,7 +793,8 @@ public class InvoiceServices { } calcHeaderAdj(delegator, adj, invoiceType, invoiceId, invoiceItemSeqId, divisor, multiplier, - adj.getBigDecimal("amount").setScale(invoiceTypeDecimals, ROUNDING), invoiceTypeDecimals, ROUNDING, userLogin, dispatcher, locale); + 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; @@ -773,7 +805,8 @@ public class InvoiceServices { } } - // 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 + // 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 (Map.Entry set : shipAdjustments.entrySet()) { BigDecimal adjAlreadyInvoicedAmount = set.getValue(); @@ -833,7 +866,7 @@ public class InvoiceServices { // 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); + divisor, multiplier, baseAmount, TAX_DECIMALS, TAX_ROUNDING, userLogin, dispatcher, locale); } else { // Pro-rate the tax amount based on shippable information @@ -882,11 +915,13 @@ public class InvoiceServices { } } - // 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) + // 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 setInvoiceStatusResult = dispatcher.runSync("setInvoiceStatus", UtilMisc.toMap("invoiceId", invoiceId, "statusId", nextStatusId, "userLogin", userLogin)); + Map setInvoiceStatusResult = dispatcher.runSync("setInvoiceStatus", UtilMisc.toMap("invoiceId", + invoiceId, "statusId", nextStatusId, "userLogin", userLogin)); if (ServiceUtil.isError(setInvoiceStatusResult)) { return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "AccountingErrorCreatingInvoiceFromOrder", locale), null, null, setInvoiceStatusResult); @@ -923,7 +958,8 @@ public class InvoiceServices { List salesRepPartyIds = UtilGenerics.cast(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); + 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)); } @@ -947,10 +983,11 @@ public class InvoiceServices { 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)); + "No party found with role sales representative for sales invoice " + salesInvoiceId, locale)); } } else { - List salesInvoiceRolePartyIds = EntityUtil.getFieldListFromEntityList(roleQuery.where(invoiceRoleConds).queryList(), "partyId", true); + List salesInvoiceRolePartyIds = EntityUtil.getFieldListFromEntityList(roleQuery.where(invoiceRoleConds).queryList(), + "partyId", true); if (UtilValidate.isNotEmpty(salesInvoiceRolePartyIds)) { salesRepPartyIds = UtilGenerics.cast(CollectionUtils.intersection(salesRepPartyIds, salesInvoiceRolePartyIds)); } @@ -1053,7 +1090,7 @@ public class InvoiceServices { createInvoiceResult = dispatcher.runSync("createInvoice", createInvoiceMap); if (ServiceUtil.isError(createInvoiceResult)) { return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, - "AccountingInvoiceCommissionError", locale), null, null, null); + "AccountingInvoiceCommissionError", locale), null, null, null); } } catch (GenericServiceException e) { return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, @@ -1154,7 +1191,8 @@ public class InvoiceServices { String nextStatusId = "INVOICE_READY"; try { for (String invoiceId : invoicesCreated) { - Map setInvoiceStatusResult = dispatcher.runSync("setInvoiceStatus", UtilMisc.toMap("invoiceId", invoiceId, "statusId", nextStatusId, "userLogin", userLogin)); + Map setInvoiceStatusResult = dispatcher.runSync("setInvoiceStatus", UtilMisc.toMap("invoiceId", + invoiceId, "statusId", nextStatusId, "userLogin", userLogin)); if (ServiceUtil.isError(setInvoiceStatusResult)) { return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "AccountingInvoiceCommissionError", locale), null, null, setInvoiceStatusResult); @@ -1203,17 +1241,19 @@ public class InvoiceServices { } if ("Y".equals(invoicePerShipment)) { - Map serviceContext = UtilMisc.toMap("shipmentIds", UtilMisc.toList(shipmentId), "eventDate", context.get("eventDate"), "userLogin", context.get("userLogin")); + Map serviceContext = UtilMisc.toMap("shipmentIds", UtilMisc.toList(shipmentId), "eventDate", context.get("eventDate"), + "userLogin", context.get("userLogin")); try { Map result = dispatcher.runSync("createInvoicesFromShipments", serviceContext); if (ServiceUtil.isError(result)) { return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, - "AccountingTroubleCallingCreateInvoicesFromShipmentService", - UtilMisc.toMap("shipmentId", shipmentId), locale)); + "AccountingTroubleCallingCreateInvoicesFromShipmentService", + UtilMisc.toMap("shipmentId", shipmentId), locale)); } invoicesCreated = UtilGenerics.cast(result.get("invoicesCreated")); } catch (GenericServiceException e) { - Debug.logError(e, "Trouble calling createInvoicesFromShipment service; invoice not created for shipment [" + shipmentId + "]", MODULE); + Debug.logError(e, "Trouble calling createInvoicesFromShipment service; invoice not created for shipment [" + shipmentId + "]", + MODULE); return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "AccountingTroubleCallingCreateInvoicesFromShipmentService", UtilMisc.toMap("shipmentId", shipmentId), locale)); @@ -1298,12 +1338,13 @@ public class InvoiceServices { } } - // For In-Process invoice, move the status to ready and capture the payment + // For In-Process invoice, move the status to ready and capture the payment for (GenericValue invoice : ordersWithInProcessInvoice.values()) { String invoiceId = invoice.getString("invoiceId"); Map setInvoiceStatusResult; try { - setInvoiceStatusResult = dispatcher.runSync("setInvoiceStatus", UtilMisc.toMap("invoiceId", invoiceId, "statusId", "INVOICE_READY", "userLogin", userLogin)); + setInvoiceStatusResult = dispatcher.runSync("setInvoiceStatus", UtilMisc.toMap("invoiceId", invoiceId, "statusId", + "INVOICE_READY", "userLogin", userLogin)); } catch (GenericServiceException e) { Debug.logError(e, MODULE); return ServiceUtil.returnError(e.getMessage()); @@ -1321,15 +1362,16 @@ public class InvoiceServices { String shipmentId = (String) context.get("shipmentId"); Locale locale = (Locale) context.get("locale"); - Map serviceContext = UtilMisc.toMap("shipmentIds", UtilMisc.toList(shipmentId), "createSalesInvoicesForDropShipments", Boolean.TRUE, "userLogin", context.get("userLogin")); + Map serviceContext = UtilMisc.toMap("shipmentIds", UtilMisc.toList(shipmentId), "createSalesInvoicesForDropShipments", + Boolean.TRUE, "userLogin", context.get("userLogin")); Map serviceResult; try { serviceResult = dispatcher.runSync("createInvoicesFromShipments", serviceContext); if (ServiceUtil.isError(serviceResult)) { return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, - "AccountingTroubleCallingCreateInvoicesFromShipmentService", - UtilMisc.toMap("shipmentId", shipmentId), locale)); + "AccountingTroubleCallingCreateInvoicesFromShipmentService", + UtilMisc.toMap("shipmentId", shipmentId), locale)); } } catch (GenericServiceException e) { Debug.logError(e, "Trouble calling createInvoicesFromShipment service; invoice not created for shipment " + shipmentId, MODULE); @@ -1381,7 +1423,8 @@ public class InvoiceServices { UtilMisc.toMap("tmpShipmentId", tmpShipmentId), locale)); } } - EntityQuery shipmentQuery = EntityQuery.use(delegator).where(EntityCondition.makeCondition("shipmentId", EntityOperator.IN, shipmentIds)).orderBy("shipmentId"); + EntityQuery shipmentQuery = + EntityQuery.use(delegator).where(EntityCondition.makeCondition("shipmentId", EntityOperator.IN, shipmentIds)).orderBy("shipmentId"); // check the status of the shipment // get the items of the shipment. They can come from ItemIssuance if the shipment were from a sales order, ShipmentReceipt @@ -1391,7 +1434,8 @@ public class InvoiceServices { try { if (purchaseShipmentFound) { items = shipmentQuery.from("ShipmentReceipt").queryList(); - // filter out items which have been received but are not actually owned by an internal organization, so they should not be on a purchase invoice + // filter out items which have been received but are not actually owned by an internal organization, so they should not be on a + // purchase invoice Iterator itemsIter = items.iterator(); while (itemsIter.hasNext()) { GenericValue item = itemsIter.next(); @@ -1523,7 +1567,8 @@ public class InvoiceServices { if (dropShipmentFound && createSalesInvoicesForDropShipments) { // Override the issueQty with the quantity from the purchase order item - GenericValue orderItemAssoc = EntityUtil.getFirst(EntityUtil.filterByAnd(orderItemAssocs, UtilMisc.toMap("orderId", issue.getString("orderId"), "orderItemSeqId", issue.getString("orderItemSeqId")))); + GenericValue orderItemAssoc = EntityUtil.getFirst(EntityUtil.filterByAnd(orderItemAssocs, UtilMisc.toMap("orderId", + issue.getString("orderId"), "orderItemSeqId", issue.getString("orderItemSeqId")))); GenericValue purchaseOrderItem = orderItemAssoc.getRelatedOne("ToOrderItem", false); orderItem.set("quantity", purchaseOrderItem.getBigDecimal("quantity")); issueQty = purchaseOrderItem.getBigDecimal("quantity"); @@ -1600,9 +1645,11 @@ public class InvoiceServices { // Get the IDs for orders which have billable items List invoiceableLinkedOrderIds = EntityUtil.getFieldListFromEntityList(toBillItems, "orderId", true); - // Get back the IDs of the purchase orders - this will be a list of the purchase order items which are billable by virtue of not having been + // Get back the IDs of the purchase orders - this will be a list of the purchase order items which are billable by + // virtue of not having been // invoiced in a previous sales invoice - List reverseOrderItemAssocs = EntityUtil.filterByCondition(orderItemAssocs, EntityCondition.makeCondition("orderId", EntityOperator.IN, invoiceableLinkedOrderIds)); + List reverseOrderItemAssocs = EntityUtil.filterByCondition(orderItemAssocs, + EntityCondition.makeCondition("orderId", EntityOperator.IN, invoiceableLinkedOrderIds)); invoiceablePrimaryOrderIds = EntityUtil.getFieldListFromEntityList(reverseOrderItemAssocs, "toOrderId", true); } else { @@ -1622,7 +1669,8 @@ public class InvoiceServices { } else { List invoiceableShipmentIds = EntityUtil.getFieldListFromEntityList(toBillItems, "shipmentId", true); if (UtilValidate.isNotEmpty(invoiceableShipmentIds)) { - invoiceableShipments = EntityQuery.use(delegator).from("Shipment").where(EntityCondition.makeCondition("shipmentId", EntityOperator.IN, invoiceableShipmentIds)).queryList(); + invoiceableShipments = EntityQuery.use(delegator).from("Shipment").where(EntityCondition.makeCondition("shipmentId", + EntityOperator.IN, invoiceableShipmentIds)).queryList(); } } } catch (GenericEntityException e) { @@ -1639,7 +1687,8 @@ public class InvoiceServices { if (shipment.get("additionalShippingCharge") == null) { continue; } - BigDecimal shipmentAdditionalShippingCharges = shipment.getBigDecimal("additionalShippingCharge").setScale(DECIMALS, ROUNDING); + BigDecimal shipmentAdditionalShippingCharges = shipment.getBigDecimal("additionalShippingCharge").setScale(DECIMALS, + ROUNDING); additionalShippingCharges.put(shipment, shipmentAdditionalShippingCharges); totalAdditionalShippingCharges = totalAdditionalShippingCharges.add(shipmentAdditionalShippingCharges); } @@ -1658,7 +1707,8 @@ public class InvoiceServices { createOrderAdjustmentContext.put("orderAdjustmentTypeId", "SHIPPING_CHARGES"); String addtlChargeDescription = shipment.getString("addtlShippingChargeDesc"); if (UtilValidate.isEmpty(addtlChargeDescription)) { - addtlChargeDescription = UtilProperties.getMessage(RESOURCE, "AccountingAdditionalShippingChargeForShipment", UtilMisc.toMap("shipmentId", shipmentId), locale); + addtlChargeDescription = UtilProperties.getMessage(RESOURCE, "AccountingAdditionalShippingChargeForShipment", + UtilMisc.toMap("shipmentId", shipmentId), locale); } createOrderAdjustmentContext.put("description", addtlChargeDescription); createOrderAdjustmentContext.put("sourceReferenceId", shipmentId); @@ -1666,7 +1716,8 @@ public class InvoiceServices { createOrderAdjustmentContext.put("userLogin", context.get("userLogin")); String shippingOrderAdjustmentId = null; try { - Map createOrderAdjustmentResult = dispatcher.runSync("createOrderAdjustment", createOrderAdjustmentContext); + Map createOrderAdjustmentResult = dispatcher.runSync("createOrderAdjustment", + createOrderAdjustmentContext); if (ServiceUtil.isError(createOrderAdjustmentResult)) { return ServiceUtil.returnError(ServiceUtil.getErrorMessage(createOrderAdjustmentResult)); } @@ -1684,7 +1735,8 @@ public class InvoiceServices { try { destinationContactMech = shipment.getRelatedOne("DestinationPostalAddress", false); } catch (GenericEntityException e) { - Debug.logError(e, "Trouble calling createInvoicesFromShipment service; invoice not created for shipment " + shipmentId, MODULE); + Debug.logError(e, "Trouble calling createInvoicesFromShipment service; invoice not created for shipment " + shipmentId, + MODULE); return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "AccountingTroubleCallingCreateInvoicesFromShipmentService", locale)); } @@ -1709,7 +1761,7 @@ public class InvoiceServices { calcTaxResult = dispatcher.runSync("calcTax", calcTaxContext); if (ServiceUtil.isError(calcTaxResult)) { return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, - "AccountingTroubleCallingCalcTaxService", locale)); + "AccountingTroubleCallingCalcTaxService", locale)); } } catch (GenericServiceException e) { Debug.logError(e, "Trouble calling calcTaxService", MODULE); @@ -1721,7 +1773,8 @@ public class InvoiceServices { // If we have any OrderAdjustments due to tax on shipping, store them and add them to the total if (orderAdjustments != null) { for (GenericValue orderAdjustment : orderAdjustments) { - totalAdditionalShippingCharges = totalAdditionalShippingCharges.add(orderAdjustment.getBigDecimal("amount").setScale(DECIMALS, ROUNDING)); + totalAdditionalShippingCharges = + totalAdditionalShippingCharges.add(orderAdjustment.getBigDecimal("amount").setScale(DECIMALS, ROUNDING)); orderAdjustment.set("orderAdjustmentId", delegator.getNextSeqId("OrderAdjustment")); orderAdjustment.set("orderId", orderId); orderAdjustment.set("orderItemSeqId", "_NA_"); @@ -1768,12 +1821,15 @@ public class InvoiceServices { if (authTransaction != null && authTransaction.get("amount") != null) { // Update the total authorized amount - totalNewAuthAmount = totalNewAuthAmount.add(authTransaction.getBigDecimal("amount").setScale(DECIMALS, ROUNDING)); + totalNewAuthAmount = totalNewAuthAmount.add(authTransaction.getBigDecimal("amount").setScale(DECIMALS, + ROUNDING)); // Release the authorization for the OrderPaymentPreference Map prefReleaseResult = null; try { - prefReleaseResult = dispatcher.runSync("releaseOrderPaymentPreference", UtilMisc.toMap("orderPaymentPreferenceId", orderPaymentPreference.getString("orderPaymentPreferenceId"), "userLogin", context.get("userLogin"))); + prefReleaseResult = dispatcher.runSync("releaseOrderPaymentPreference", UtilMisc.toMap( + "orderPaymentPreferenceId", orderPaymentPreference.getString("orderPaymentPreferenceId"), + "userLogin", context.get("userLogin"))); } catch (GenericServiceException e) { Debug.logError(e, "Trouble calling releaseOrderPaymentPreference service", MODULE); return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, @@ -1790,13 +1846,14 @@ public class InvoiceServices { // Create a new OrderPaymentPreference for the order to handle the new (totalled) charge. Don't // set the maxAmount so that it doesn't interfere with other authorizations - Map serviceContext = UtilMisc.toMap("orderId", orderId, "paymentMethodId", paymentMethodId, "paymentMethodTypeId", "CREDIT_CARD", "userLogin", context.get("userLogin")); + Map serviceContext = UtilMisc.toMap("orderId", orderId, "paymentMethodId", paymentMethodId, + "paymentMethodTypeId", "CREDIT_CARD", "userLogin", context.get("userLogin")); String orderPaymentPreferenceId = null; try { Map result = dispatcher.runSync("createOrderPaymentPreference", serviceContext); if (ServiceUtil.isError(result)) { return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, - "AccountingTroubleCallingCreateOrderPaymentPreferenceService", locale)); + "AccountingTroubleCallingCreateOrderPaymentPreferenceService", locale)); } orderPaymentPreferenceId = (String) result.get("orderPaymentPreferenceId"); } catch (GenericServiceException e) { @@ -1809,10 +1866,11 @@ public class InvoiceServices { Map authResult = null; try { // Use an overrideAmount because the maxAmount wasn't set on the OrderPaymentPreference - authResult = dispatcher.runSync("authOrderPaymentPreference", UtilMisc.toMap("orderPaymentPreferenceId", orderPaymentPreferenceId, "overrideAmount", totalNewAuthAmount, "userLogin", context.get("userLogin"))); + authResult = dispatcher.runSync("authOrderPaymentPreference", UtilMisc.toMap("orderPaymentPreferenceId", + orderPaymentPreferenceId, "overrideAmount", totalNewAuthAmount, "userLogin", context.get("userLogin"))); if (ServiceUtil.isError(authResult)) { return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, - "AccountingTroubleCallingAuthOrderPaymentPreferenceService", locale)); + "AccountingTroubleCallingAuthOrderPaymentPreferenceService", locale)); } } catch (GenericServiceException e) { Debug.logError(e, "Trouble calling authOrderPaymentPreference service", MODULE); @@ -1824,7 +1882,9 @@ public class InvoiceServices { boolean authFinished = (Boolean) authResult.get("finished"); boolean authErrors = (Boolean) authResult.get("errors"); if (authErrors || !authFinished) { - String errMsg = UtilProperties.getMessage(RESOURCE, "AccountingUnableToAuthAdditionalShipCharges", UtilMisc.toMap("shipmentId", shipmentId, "paymentMethodId", paymentMethodId, "orderPaymentPreferenceId", orderPaymentPreferenceId), locale); + String errMsg = UtilProperties.getMessage(RESOURCE, "AccountingUnableToAuthAdditionalShipCharges", UtilMisc.toMap( + "shipmentId", shipmentId, "paymentMethodId", paymentMethodId, "orderPaymentPreferenceId", + orderPaymentPreferenceId), locale); Debug.logError(errMsg, MODULE); } @@ -1832,7 +1892,8 @@ public class InvoiceServices { } } } else { - Debug.logInfo(UtilProperties.getMessage(RESOURCE, "AccountingIgnoringAdditionalShipCharges", UtilMisc.toMap("productStoreId", orh.getProductStoreId()), locale), MODULE); + Debug.logInfo(UtilProperties.getMessage(RESOURCE, "AccountingIgnoringAdditionalShipCharges", UtilMisc.toMap("productStoreId", + orh.getProductStoreId()), locale), MODULE); } String invoiceId = null; @@ -1849,12 +1910,13 @@ public class InvoiceServices { } // call the createInvoiceForOrder service for each order - Map serviceContext = UtilMisc.toMap("orderId", orderId, "billItems", toBillItems, "invoiceId", invoiceId, "eventDate", context.get("eventDate"), "userLogin", context.get("userLogin")); + Map serviceContext = UtilMisc.toMap("orderId", orderId, "billItems", toBillItems, "invoiceId", invoiceId, "eventDate", + context.get("eventDate"), "userLogin", context.get("userLogin")); try { Map result = dispatcher.runSync("createInvoiceForOrder", serviceContext); if (ServiceUtil.isError(result)) { return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, - "AccountingTroubleCallingCreateInvoiceForOrderService", locale)); + "AccountingTroubleCallingCreateInvoiceForOrderService", locale)); } invoicesCreated.add((String) result.get("invoiceId")); } catch (GenericServiceException e) { @@ -1873,10 +1935,12 @@ public class InvoiceServices { GenericValue itemMap = null; try { if (UtilValidate.isNotEmpty(key1)) { - itemMap = EntityQuery.use(delegator).from("InvoiceItemTypeMap").where("invoiceItemMapKey", key1, "invoiceTypeId", invoiceTypeId).cache().queryOne(); + itemMap = + EntityQuery.use(delegator).from("InvoiceItemTypeMap").where("invoiceItemMapKey", key1, "invoiceTypeId", invoiceTypeId).cache().queryOne(); } if (itemMap == null && UtilValidate.isNotEmpty(key2)) { - itemMap = EntityQuery.use(delegator).from("InvoiceItemTypeMap").where("invoiceItemMapKey", key2, "invoiceTypeId", invoiceTypeId).cache().queryOne(); + itemMap = + EntityQuery.use(delegator).from("InvoiceItemTypeMap").where("invoiceItemMapKey", key2, "invoiceTypeId", invoiceTypeId).cache().queryOne(); } } catch (GenericEntityException e) { Debug.logError(e, "Trouble getting InvoiceItemTypeMap entity record", MODULE); @@ -1914,10 +1978,11 @@ public class InvoiceServices { purchaseReturnFound = true; } if (!(salesReturnFound || purchaseReturnFound)) { - return ServiceUtil.returnError(errorMsg + UtilProperties.getMessage(RESOURCE, - "AccountingShipmentNotSalesReturnAndPurchaseReturn", locale)); + return ServiceUtil.returnError(errorMsg + UtilProperties.getMessage(RESOURCE, + "AccountingShipmentNotSalesReturnAndPurchaseReturn", locale)); } - // get the items of the shipment. They can come from ItemIssuance if the shipment were from a purchase return, ShipmentReceipt if it were from a sales return + // get the items of the shipment. They can come from ItemIssuance if the shipment were from a purchase return, ShipmentReceipt if it + // were from a sales return List shippedItems = null; if (salesReturnFound) { shippedItems = shipment.getRelated("ShipmentReceipt", null, null, false); @@ -1952,9 +2017,10 @@ public class InvoiceServices { .where("shipmentReceiptId", item.get("receiptId"), "returnId", returnId, "returnItemSeqId", item.get("returnItemSeqId")) - .queryCount(); + .queryCount(); } else if ("ItemIssuance".equals(item.getEntityName())) { - billingCount = EntityQuery.use(delegator).from("ReturnItemBilling").where("returnId", returnId, "returnItemSeqId", returnItemSeqId).queryCount(); + billingCount = EntityQuery.use(delegator).from("ReturnItemBilling").where("returnId", returnId, "returnItemSeqId", + returnItemSeqId).queryCount(); } // if there are billings, we have already billed the item, so skip it if (billingCount > 0) { @@ -2004,9 +2070,10 @@ public class InvoiceServices { GenericValue userLogin = (GenericValue) context.get("userLogin"); Locale locale = (Locale) context.get("locale"); - String returnId= (String) context.get("returnId"); + String returnId = (String) context.get("returnId"); List billItems = UtilGenerics.cast(context.get("billItems")); - String errorMsg = UtilProperties.getMessage(RESOURCE, "AccountingErrorCreatingInvoiceForReturn", UtilMisc.toMap("returnId", returnId), locale); + String errorMsg = UtilProperties.getMessage(RESOURCE, "AccountingErrorCreatingInvoiceForReturn", UtilMisc.toMap("returnId", returnId), + locale); // List invoicesCreated = new ArrayList(); try { String invoiceTypeId; @@ -2014,7 +2081,7 @@ public class InvoiceServices { // get the return header GenericValue returnHeader = EntityQuery.use(delegator).from("ReturnHeader").where("returnId", returnId).queryOne(); if (returnHeader == null || returnHeader.get("returnHeaderTypeId") == null) { - return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "AccountingReturnTypeCannotBeNull", locale)); + return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "AccountingReturnTypeCannotBeNull", locale)); } if (returnHeader.getString("returnHeaderTypeId").startsWith("CUSTOMER_")) { @@ -2057,174 +2124,231 @@ public class InvoiceServices { Map results = ServiceUtil.returnSuccess(); if (UtilValidate.isNotEmpty(billItems)) { - // set the invoice data - Map input = UtilMisc.toMap("invoiceTypeId", invoiceTypeId, "statusId", "INVOICE_IN_PROCESS"); - input.put("partyId", returnHeader.get("toPartyId")); - input.put("partyIdFrom", returnHeader.get("fromPartyId")); - input.put("currencyUomId", returnHeader.get("currencyUomId")); - input.put("invoiceDate", UtilDateTime.nowTimestamp()); - input.put("description", description); - input.put("billingAccountId", returnHeader.get("billingAccountId")); - input.put("userLogin", userLogin); - - // call the service to create the invoice - Map serviceResults = dispatcher.runSync("createInvoice", input); - if (ServiceUtil.isError(serviceResults)) { - return ServiceUtil.returnError(ServiceUtil.getErrorMessage(serviceResults)); - } - String invoiceId = (String) serviceResults.get("invoiceId"); - - // keep track of the invoice total vs the promised return total (how much the customer promised to return) - BigDecimal invoiceTotal = BigDecimal.ZERO; - BigDecimal promisedTotal = BigDecimal.ZERO; - - // loop through shipment receipts to create invoice items and return item billings for each item and adjustment - int invoiceItemSeqNum = 1; - String invoiceItemSeqId = UtilFormatOut.formatPaddedNumber(invoiceItemSeqNum, INVOICE_ITEM_SEQUENCE_ID_DIGITS); - - for (GenericValue item : billItems) { - boolean shipmentReceiptFound = false; - boolean itemIssuanceFound = false; - GenericValue returnItem = null; - BigDecimal quantity = BigDecimal.ZERO; - - if ("ShipmentReceipt".equals(item.getEntityName())) { - shipmentReceiptFound = true; - } else if ("ItemIssuance".equals(item.getEntityName())) { - itemIssuanceFound = true; - } else if ("ReturnItem".equals(item.getEntityName())) { - quantity = item.getBigDecimal("returnQuantity"); - returnItem = item; - } else { - Debug.logError("Unexpected entity " + item + " of type " + item.getEntityName(), MODULE); - } - // we need the related return item and product - if (shipmentReceiptFound) { - returnItem = item.getRelatedOne("ReturnItem", true); - } else if (itemIssuanceFound) { - GenericValue shipmentItem = item.getRelatedOne("ShipmentItem", true); - GenericValue returnItemShipment = EntityUtil.getFirst(shipmentItem.getRelated("ReturnItemShipment", null, null, false)); - returnItem = returnItemShipment.getRelatedOne("ReturnItem", true); - } - if (returnItem == null) - { - continue; // Just to prevent NPE - } - GenericValue product = returnItem.getRelatedOne("Product", true); - - // extract the return price as a big decimal for convenience - BigDecimal returnPrice = returnItem.getBigDecimal("returnPrice"); - - // determine invoice item type from the return item type - String invoiceItemTypeId = getInvoiceItemType(delegator, returnItem.getString("returnItemTypeId"), null, invoiceTypeId, null); - if (invoiceItemTypeId == null) { - return ServiceUtil.returnError(errorMsg + UtilProperties.getMessage(RESOURCE, - "AccountingNoKnownInvoiceItemTypeReturnItemType", - UtilMisc.toMap("returnItemTypeId", returnItem.getString("returnItemTypeId")), locale)); - } - if (shipmentReceiptFound) { - quantity = item.getBigDecimal("quantityAccepted"); - } else if (itemIssuanceFound) { - quantity = item.getBigDecimal("quantity"); - } - - // create the invoice item for this shipment receipt - input = UtilMisc.toMap("invoiceId", invoiceId, "invoiceItemTypeId", invoiceItemTypeId, "quantity", quantity); - input.put("invoiceItemSeqId", "" + invoiceItemSeqId); // turn the int into a string with ("" + int) hack - input.put("amount", returnItem.get("returnPrice")); - input.put("productId", returnItem.get("productId")); - input.put("taxableFlag", product.get("taxable")); - input.put("description", returnItem.get("description")); - // TODO: what about the productFeatureId? + // set the invoice data + Map input = UtilMisc.toMap("invoiceTypeId", invoiceTypeId, "statusId", "INVOICE_IN_PROCESS"); + input.put("partyId", returnHeader.get("toPartyId")); + input.put("partyIdFrom", returnHeader.get("fromPartyId")); + input.put("currencyUomId", returnHeader.get("currencyUomId")); + input.put("invoiceDate", UtilDateTime.nowTimestamp()); + input.put("description", description); + input.put("billingAccountId", returnHeader.get("billingAccountId")); input.put("userLogin", userLogin); - serviceResults = dispatcher.runSync("createInvoiceItem", input); + + // call the service to create the invoice + Map serviceResults = dispatcher.runSync("createInvoice", input); if (ServiceUtil.isError(serviceResults)) { return ServiceUtil.returnError(ServiceUtil.getErrorMessage(serviceResults)); } + String invoiceId = (String) serviceResults.get("invoiceId"); - // copy the return item information into ReturnItemBilling - input = UtilMisc.toMap("returnId", returnId, "returnItemSeqId", returnItem.get("returnItemSeqId"), - "invoiceId", invoiceId); - input.put("invoiceItemSeqId", "" + invoiceItemSeqId); // turn the int into a string with ("" + int) hack - input.put("quantity", quantity); - input.put("amount", returnItem.get("returnPrice")); - input.put("userLogin", userLogin); - if (shipmentReceiptFound) { - input.put("shipmentReceiptId", item.get("receiptId")); - } - serviceResults = dispatcher.runSync("createReturnItemBilling", input); - if (ServiceUtil.isError(serviceResults)) { - return ServiceUtil.returnError(ServiceUtil.getErrorMessage(serviceResults)); - } - if (Debug.verboseOn()) { - Debug.logVerbose("Creating Invoice Item with amount " + returnPrice + " and quantity " + quantity - + " for shipment [" + item.getString("shipmentId") + ":" + item.getString("shipmentItemSeqId") + "]", MODULE); - } + // keep track of the invoice total vs the promised return total (how much the customer promised to return) + BigDecimal invoiceTotal = BigDecimal.ZERO; + BigDecimal promisedTotal = BigDecimal.ZERO; - String parentInvoiceItemSeqId = invoiceItemSeqId; - // increment the seqId counter after creating the invoice item and return item billing - invoiceItemSeqNum += 1; - invoiceItemSeqId = UtilFormatOut.formatPaddedNumber(invoiceItemSeqNum, INVOICE_ITEM_SEQUENCE_ID_DIGITS); + // loop through shipment receipts to create invoice items and return item billings for each item and adjustment + int invoiceItemSeqNum = 1; + String invoiceItemSeqId = UtilFormatOut.formatPaddedNumber(invoiceItemSeqNum, INVOICE_ITEM_SEQUENCE_ID_DIGITS); - // keep a running total (note: a returnItem may have many receipts. hence, the promised total quantity is the receipt quantityAccepted + quantityRejected) - BigDecimal cancelQuantity = BigDecimal.ZERO; - if (shipmentReceiptFound) { - cancelQuantity = item.getBigDecimal("quantityRejected"); - } else if (itemIssuanceFound) { - cancelQuantity = item.getBigDecimal("cancelQuantity"); - } - if (cancelQuantity == null) { - cancelQuantity = BigDecimal.ZERO; - } - BigDecimal actualAmount = returnPrice.multiply(quantity).setScale(DECIMALS, ROUNDING); - BigDecimal promisedAmount = returnPrice.multiply(quantity.add(cancelQuantity)).setScale(DECIMALS, ROUNDING); - invoiceTotal = invoiceTotal.add(actualAmount).setScale(DECIMALS, ROUNDING); - promisedTotal = promisedTotal.add(promisedAmount).setScale(DECIMALS, ROUNDING); + for (GenericValue item : billItems) { + boolean shipmentReceiptFound = false; + boolean itemIssuanceFound = false; + GenericValue returnItem = null; + BigDecimal quantity = BigDecimal.ZERO; - // for each adjustment related to this ReturnItem, create a separate invoice item - List adjustments = returnItem.getRelated("ReturnAdjustment", null, null, true); - for (GenericValue adjustment : adjustments) { - - if (adjustment.get("amount") == null) { - Debug.logWarning("Return adjustment [" + adjustment.get("returnAdjustmentId") + "] has null amount and will be skipped", MODULE); - continue; + if ("ShipmentReceipt".equals(item.getEntityName())) { + shipmentReceiptFound = true; + } else if ("ItemIssuance".equals(item.getEntityName())) { + itemIssuanceFound = true; + } else if ("ReturnItem".equals(item.getEntityName())) { + quantity = item.getBigDecimal("returnQuantity"); + returnItem = item; + } else { + Debug.logError("Unexpected entity " + item + " of type " + item.getEntityName(), MODULE); } + // we need the related return item and product + if (shipmentReceiptFound) { + returnItem = item.getRelatedOne("ReturnItem", true); + } else if (itemIssuanceFound) { + GenericValue shipmentItem = item.getRelatedOne("ShipmentItem", true); + GenericValue returnItemShipment = EntityUtil.getFirst(shipmentItem.getRelated("ReturnItemShipment", null, null, false)); + returnItem = returnItemShipment.getRelatedOne("ReturnItem", true); + } + if (returnItem == null) { + continue; // Just to prevent NPE + } + GenericValue product = returnItem.getRelatedOne("Product", true); + + // extract the return price as a big decimal for convenience + BigDecimal returnPrice = returnItem.getBigDecimal("returnPrice"); // determine invoice item type from the return item type - invoiceItemTypeId = getInvoiceItemType(delegator, adjustment.getString("returnAdjustmentTypeId"), null, invoiceTypeId, null); + String invoiceItemTypeId = getInvoiceItemType(delegator, returnItem.getString("returnItemTypeId"), null, invoiceTypeId, null); + if (invoiceItemTypeId == null) { + return ServiceUtil.returnError(errorMsg + UtilProperties.getMessage(RESOURCE, + "AccountingNoKnownInvoiceItemTypeReturnItemType", + UtilMisc.toMap("returnItemTypeId", returnItem.getString("returnItemTypeId")), locale)); + } + if (shipmentReceiptFound) { + quantity = item.getBigDecimal("quantityAccepted"); + } else if (itemIssuanceFound) { + quantity = item.getBigDecimal("quantity"); + } + + // create the invoice item for this shipment receipt + input = UtilMisc.toMap("invoiceId", invoiceId, "invoiceItemTypeId", invoiceItemTypeId, "quantity", quantity); + input.put("invoiceItemSeqId", "" + invoiceItemSeqId); // turn the int into a string with ("" + int) hack + input.put("amount", returnItem.get("returnPrice")); + input.put("productId", returnItem.get("productId")); + input.put("taxableFlag", product.get("taxable")); + input.put("description", returnItem.get("description")); + // TODO: what about the productFeatureId? + input.put("userLogin", userLogin); + serviceResults = dispatcher.runSync("createInvoiceItem", input); + if (ServiceUtil.isError(serviceResults)) { + return ServiceUtil.returnError(ServiceUtil.getErrorMessage(serviceResults)); + } + + // copy the return item information into ReturnItemBilling + input = UtilMisc.toMap("returnId", returnId, "returnItemSeqId", returnItem.get("returnItemSeqId"), + "invoiceId", invoiceId); + input.put("invoiceItemSeqId", "" + invoiceItemSeqId); // turn the int into a string with ("" + int) hack + input.put("quantity", quantity); + input.put("amount", returnItem.get("returnPrice")); + input.put("userLogin", userLogin); + if (shipmentReceiptFound) { + input.put("shipmentReceiptId", item.get("receiptId")); + } + serviceResults = dispatcher.runSync("createReturnItemBilling", input); + if (ServiceUtil.isError(serviceResults)) { + return ServiceUtil.returnError(ServiceUtil.getErrorMessage(serviceResults)); + } + if (Debug.verboseOn()) { + Debug.logVerbose("Creating Invoice Item with amount " + returnPrice + " and quantity " + quantity + + " for shipment [" + item.getString("shipmentId") + ":" + item.getString("shipmentItemSeqId") + "]", MODULE); + } + + String parentInvoiceItemSeqId = invoiceItemSeqId; + // increment the seqId counter after creating the invoice item and return item billing + invoiceItemSeqNum += 1; + invoiceItemSeqId = UtilFormatOut.formatPaddedNumber(invoiceItemSeqNum, INVOICE_ITEM_SEQUENCE_ID_DIGITS); + + // keep a running total (note: a returnItem may have many receipts. hence, the promised total quantity is the receipt + // quantityAccepted + quantityRejected) + BigDecimal cancelQuantity = BigDecimal.ZERO; + if (shipmentReceiptFound) { + cancelQuantity = item.getBigDecimal("quantityRejected"); + } else if (itemIssuanceFound) { + cancelQuantity = item.getBigDecimal("cancelQuantity"); + } + if (cancelQuantity == null) { + cancelQuantity = BigDecimal.ZERO; + } + BigDecimal actualAmount = returnPrice.multiply(quantity).setScale(DECIMALS, ROUNDING); + BigDecimal promisedAmount = returnPrice.multiply(quantity.add(cancelQuantity)).setScale(DECIMALS, ROUNDING); + invoiceTotal = invoiceTotal.add(actualAmount).setScale(DECIMALS, ROUNDING); + promisedTotal = promisedTotal.add(promisedAmount).setScale(DECIMALS, ROUNDING); + + // for each adjustment related to this ReturnItem, create a separate invoice item + List adjustments = returnItem.getRelated("ReturnAdjustment", null, null, true); + for (GenericValue adjustment : adjustments) { + + if (adjustment.get("amount") == null) { + Debug.logWarning("Return adjustment [" + adjustment.get("returnAdjustmentId") + "] has null amount and will be skipped" + , MODULE); + continue; + } + + // determine invoice item type from the return item type + invoiceItemTypeId = getInvoiceItemType(delegator, adjustment.getString("returnAdjustmentTypeId"), null, invoiceTypeId, null); + if (invoiceItemTypeId == null) { + return ServiceUtil.returnError(errorMsg + UtilProperties.getMessage(RESOURCE, + "AccountingNoKnownInvoiceItemTypeReturnAdjustmentType", + UtilMisc.toMap("returnAdjustmentTypeId", adjustment.getString("returnAdjustmentTypeId")), locale)); + } + + // prorate the adjustment amount by the returned amount; do not round ratio + BigDecimal ratio = quantity.divide(returnItem.getBigDecimal("returnQuantity"), 100, ROUNDING); + BigDecimal amount = adjustment.getBigDecimal("amount"); + amount = amount.multiply(ratio).setScale(DECIMALS, ROUNDING); + if (Debug.verboseOn()) { + Debug.logVerbose("Creating Invoice Item with amount " + adjustment.getBigDecimal("amount") + " prorated to " + amount + + " for return adjustment [" + adjustment.getString("returnAdjustmentId") + "]", MODULE); + } + + // prepare invoice item data for this adjustment + input = UtilMisc.toMap("invoiceId", invoiceId, "invoiceItemTypeId", invoiceItemTypeId, "quantity", BigDecimal.ONE); + input.put("amount", amount); + input.put("invoiceItemSeqId", "" + invoiceItemSeqId); // turn the int into a string with ("" + int) hack + input.put("productId", returnItem.get("productId")); + input.put("description", adjustment.get("description")); + input.put("overrideGlAccountId", adjustment.get("overrideGlAccountId")); + input.put("parentInvoiceId", invoiceId); + input.put("parentInvoiceItemSeqId", parentInvoiceItemSeqId); + input.put("taxAuthPartyId", adjustment.get("taxAuthPartyId")); + input.put("taxAuthGeoId", adjustment.get("taxAuthGeoId")); + input.put("userLogin", userLogin); + + // only set taxable flag when the adjustment is not a tax + // TODO: Note that we use the value of Product.taxable here. This is not an ideal solution. Instead, use returnAdjustment + // .includeInTax + if ("RET_SALES_TAX_ADJ".equals(adjustment.get("returnAdjustmentTypeId"))) { + input.put("taxableFlag", "N"); + } + + // create the invoice item + serviceResults = dispatcher.runSync("createInvoiceItem", input); + if (ServiceUtil.isError(serviceResults)) { + return ServiceUtil.returnError(ServiceUtil.getErrorMessage(serviceResults)); + } + + // increment the seqId counter + invoiceItemSeqNum += 1; + invoiceItemSeqId = UtilFormatOut.formatPaddedNumber(invoiceItemSeqNum, INVOICE_ITEM_SEQUENCE_ID_DIGITS); + + // keep a running total (promised adjustment in this case is the same as the invoice adjustment) + invoiceTotal = invoiceTotal.add(amount).setScale(DECIMALS, ROUNDING); + promisedTotal = promisedTotal.add(amount).setScale(DECIMALS, ROUNDING); + } + } + + // ratio of the invoice total to the promised total so far or zero if the amounts were zero + BigDecimal actualToPromisedRatio = BigDecimal.ZERO; + if (invoiceTotal.signum() != 0) { + actualToPromisedRatio = invoiceTotal.divide(promisedTotal, 100, ROUNDING); // do not round ratio + } + + // loop through return-wide adjustments and create invoice items for each + List adjustments = returnHeader.getRelated("ReturnAdjustment", UtilMisc.toMap("returnItemSeqId", "_NA_"), null, true); + for (GenericValue adjustment : adjustments) { + + // determine invoice item type from the return item type + String invoiceItemTypeId = getInvoiceItemType(delegator, adjustment.getString("returnAdjustmentTypeId"), null, invoiceTypeId, + null); if (invoiceItemTypeId == null) { return ServiceUtil.returnError(errorMsg + UtilProperties.getMessage(RESOURCE, "AccountingNoKnownInvoiceItemTypeReturnAdjustmentType", UtilMisc.toMap("returnAdjustmentTypeId", adjustment.getString("returnAdjustmentTypeId")), locale)); } - // prorate the adjustment amount by the returned amount; do not round ratio - BigDecimal ratio = quantity.divide(returnItem.getBigDecimal("returnQuantity"), 100, ROUNDING); - BigDecimal amount = adjustment.getBigDecimal("amount"); - amount = amount.multiply(ratio).setScale(DECIMALS, ROUNDING); + // prorate the adjustment amount by the actual to promised ratio + BigDecimal amount = adjustment.getBigDecimal("amount").multiply(actualToPromisedRatio).setScale(DECIMALS, ROUNDING); if (Debug.verboseOn()) { Debug.logVerbose("Creating Invoice Item with amount " + adjustment.getBigDecimal("amount") + " prorated to " + amount + " for return adjustment [" + adjustment.getString("returnAdjustmentId") + "]", MODULE); } - // prepare invoice item data for this adjustment + // prepare the invoice item for the return-wide adjustment input = UtilMisc.toMap("invoiceId", invoiceId, "invoiceItemTypeId", invoiceItemTypeId, "quantity", BigDecimal.ONE); input.put("amount", amount); input.put("invoiceItemSeqId", "" + invoiceItemSeqId); // turn the int into a string with ("" + int) hack - input.put("productId", returnItem.get("productId")); input.put("description", adjustment.get("description")); input.put("overrideGlAccountId", adjustment.get("overrideGlAccountId")); - input.put("parentInvoiceId", invoiceId); - input.put("parentInvoiceItemSeqId", parentInvoiceItemSeqId); input.put("taxAuthPartyId", adjustment.get("taxAuthPartyId")); input.put("taxAuthGeoId", adjustment.get("taxAuthGeoId")); input.put("userLogin", userLogin); - // only set taxable flag when the adjustment is not a tax - // TODO: Note that we use the value of Product.taxable here. This is not an ideal solution. Instead, use returnAdjustment.includeInTax - if ("RET_SALES_TAX_ADJ".equals(adjustment.get("returnAdjustmentTypeId"))) { - input.put("taxableFlag", "N"); - } + // XXX TODO Note: we need to implement ReturnAdjustment.includeInTax for this to work properly + input.put("taxableFlag", adjustment.get("includeInTax")); // create the invoice item serviceResults = dispatcher.runSync("createInvoiceItem", input); @@ -2235,70 +2359,17 @@ public class InvoiceServices { // increment the seqId counter invoiceItemSeqNum += 1; invoiceItemSeqId = UtilFormatOut.formatPaddedNumber(invoiceItemSeqNum, INVOICE_ITEM_SEQUENCE_ID_DIGITS); - - // keep a running total (promised adjustment in this case is the same as the invoice adjustment) - invoiceTotal = invoiceTotal.add(amount).setScale(DECIMALS, ROUNDING); - promisedTotal = promisedTotal.add(amount).setScale(DECIMALS, ROUNDING); - } - } - - // ratio of the invoice total to the promised total so far or zero if the amounts were zero - BigDecimal actualToPromisedRatio = BigDecimal.ZERO; - if (invoiceTotal.signum() != 0) { - actualToPromisedRatio = invoiceTotal.divide(promisedTotal, 100, ROUNDING); // do not round ratio - } - - // loop through return-wide adjustments and create invoice items for each - List adjustments = returnHeader.getRelated("ReturnAdjustment", UtilMisc.toMap("returnItemSeqId", "_NA_"), null, true); - for (GenericValue adjustment : adjustments) { - - // determine invoice item type from the return item type - String invoiceItemTypeId = getInvoiceItemType(delegator, adjustment.getString("returnAdjustmentTypeId"), null, invoiceTypeId, null); - if (invoiceItemTypeId == null) { - return ServiceUtil.returnError(errorMsg + UtilProperties.getMessage(RESOURCE, - "AccountingNoKnownInvoiceItemTypeReturnAdjustmentType", - UtilMisc.toMap("returnAdjustmentTypeId", adjustment.getString("returnAdjustmentTypeId")), locale)); } - // prorate the adjustment amount by the actual to promised ratio - BigDecimal amount = adjustment.getBigDecimal("amount").multiply(actualToPromisedRatio).setScale(DECIMALS, ROUNDING); - if (Debug.verboseOn()) { - Debug.logVerbose("Creating Invoice Item with amount " + adjustment.getBigDecimal("amount") + " prorated to " + amount - + " for return adjustment [" + adjustment.getString("returnAdjustmentId") + "]", MODULE); - } - - // prepare the invoice item for the return-wide adjustment - input = UtilMisc.toMap("invoiceId", invoiceId, "invoiceItemTypeId", invoiceItemTypeId, "quantity", BigDecimal.ONE); - input.put("amount", amount); - input.put("invoiceItemSeqId", "" + invoiceItemSeqId); // turn the int into a string with ("" + int) hack - input.put("description", adjustment.get("description")); - input.put("overrideGlAccountId", adjustment.get("overrideGlAccountId")); - input.put("taxAuthPartyId", adjustment.get("taxAuthPartyId")); - input.put("taxAuthGeoId", adjustment.get("taxAuthGeoId")); - input.put("userLogin", userLogin); - - // XXX TODO Note: we need to implement ReturnAdjustment.includeInTax for this to work properly - input.put("taxableFlag", adjustment.get("includeInTax")); - - // create the invoice item - serviceResults = dispatcher.runSync("createInvoiceItem", input); + // Set the invoice to READY + serviceResults = dispatcher.runSync("setInvoiceStatus", UtilMisc.toMap("invoiceId", invoiceId, "statusId", + "INVOICE_READY", "userLogin", userLogin)); if (ServiceUtil.isError(serviceResults)) { return ServiceUtil.returnError(ServiceUtil.getErrorMessage(serviceResults)); } - // increment the seqId counter - invoiceItemSeqNum += 1; - invoiceItemSeqId = UtilFormatOut.formatPaddedNumber(invoiceItemSeqNum, INVOICE_ITEM_SEQUENCE_ID_DIGITS); - } - - // Set the invoice to READY - serviceResults = dispatcher.runSync("setInvoiceStatus", UtilMisc.toMap("invoiceId", invoiceId, "statusId", "INVOICE_READY", "userLogin", userLogin)); - if (ServiceUtil.isError(serviceResults)) { - return ServiceUtil.returnError(ServiceUtil.getErrorMessage(serviceResults)); - } - - // return the invoiceId - results.put("invoiceId", invoiceId); + // return the invoiceId + results.put("invoiceId", invoiceId); } return results; } catch (GenericServiceException | GenericEntityException e) { @@ -2337,8 +2408,9 @@ public class InvoiceServices { List paymentAppl = null; try { paymentAppl = EntityQuery.use(delegator).from("PaymentAndApplication").where("invoiceId", invoiceId).queryList(); - // For each payment application, select only those that are RECEIVED or SENT based on whether the payment is a RECEIPT or DISBURSEMENT respectively - for (Iterator iter = paymentAppl.iterator(); iter.hasNext();) { + // For each payment application, select only those that are RECEIVED or SENT based on whether the payment is a RECEIPT or DISBURSEMENT + // respectively + for (Iterator iter = paymentAppl.iterator(); iter.hasNext(); ) { GenericValue payment = iter.next(); if ("PMNT_RECEIVED".equals(payment.get("statusId")) && UtilAccounting.isReceipt(payment)) { continue; // keep @@ -2392,8 +2464,8 @@ public class InvoiceServices { Map serviceResults = dispatcher.runSync("setInvoiceStatus", svcCtx); if (ServiceUtil.isError(serviceResults)) { return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, - "AccountingProblemChangingInvoiceStatusTo", - UtilMisc.toMap("newStatus", "INVOICE_PAID"), locale)); + "AccountingProblemChangingInvoiceStatusTo", + UtilMisc.toMap("newStatus", "INVOICE_PAID"), locale)); } } catch (GenericServiceException e) { Debug.logError(e, "Problem changing invoice status to INVOICE_PAID" + svcCtx, MODULE); @@ -2410,15 +2482,17 @@ public class InvoiceServices { } private static BigDecimal calcHeaderAdj(Delegator delegator, GenericValue adj, String invoiceTypeId, String invoiceId, String invoiceItemSeqId, - BigDecimal divisor, BigDecimal multiplier, BigDecimal baseAmount, int decimals, RoundingMode rounding, GenericValue userLogin, LocalDispatcher dispatcher, Locale locale) { + BigDecimal divisor, BigDecimal multiplier, BigDecimal baseAmount, int decimals, RoundingMode rounding, + GenericValue userLogin, LocalDispatcher dispatcher, Locale locale) { BigDecimal adjAmount = BigDecimal.ZERO; if (adj.get("amount") != null) { // pro-rate the amount BigDecimal amount = BigDecimal.ZERO; if ("DONATION_ADJUSTMENT".equals(adj.getString("orderAdjustmentTypeId"))) { - amount=baseAmount; - } else if (divisor.signum() != 0) { // make sure the divisor is not 0 to avoid NaN problems; just leave the amount as 0 and skip it in essense + amount = baseAmount; + } else if (divisor.signum() != 0) { // make sure the divisor is not 0 to avoid NaN problems; just leave the amount as 0 and skip it in + // essense // multiply first then divide to avoid rounding errors amount = baseAmount.multiply(multiplier).divide(divisor, decimals, rounding); } @@ -2426,7 +2500,8 @@ public class InvoiceServices { Map createInvoiceItemContext = new HashMap<>(); createInvoiceItemContext.put("invoiceId", invoiceId); createInvoiceItemContext.put("invoiceItemSeqId", invoiceItemSeqId); - createInvoiceItemContext.put("invoiceItemTypeId", getInvoiceItemType(delegator, adj.getString("orderAdjustmentTypeId"), null, invoiceTypeId, "INVOICE_ADJ")); + createInvoiceItemContext.put("invoiceItemTypeId", getInvoiceItemType(delegator, adj.getString("orderAdjustmentTypeId"), null, + invoiceTypeId, "INVOICE_ADJ")); createInvoiceItemContext.put("description", adj.get("description")); createInvoiceItemContext.put("quantity", BigDecimal.ONE); createInvoiceItemContext.put("amount", amount); @@ -2461,13 +2536,13 @@ public class InvoiceServices { return adjAmount; } } catch (GenericServiceException e) { - return adjAmount; } + return adjAmount; + } } amount = amount.setScale(decimals, rounding); adjAmount = amount; - } - else if (adj.get("sourcePercentage") != null) { + } else if (adj.get("sourcePercentage") != null) { // pro-rate the amount BigDecimal percent = adj.getBigDecimal("sourcePercentage"); percent = percent.divide(new BigDecimal(100), 100, rounding); @@ -2481,7 +2556,8 @@ public class InvoiceServices { Map createInvoiceItemContext = new HashMap<>(); createInvoiceItemContext.put("invoiceId", invoiceId); createInvoiceItemContext.put("invoiceItemSeqId", invoiceItemSeqId); - createInvoiceItemContext.put("invoiceItemTypeId", getInvoiceItemType(delegator, adj.getString("orderAdjustmentTypeId"), null, invoiceTypeId, "INVOICE_ADJ")); + createInvoiceItemContext.put("invoiceItemTypeId", getInvoiceItemType(delegator, adj.getString("orderAdjustmentTypeId"), null, + invoiceTypeId, "INVOICE_ADJ")); createInvoiceItemContext.put("description", adj.get("description")); createInvoiceItemContext.put("quantity", BigDecimal.ONE); createInvoiceItemContext.put("amount", amount); @@ -2524,14 +2600,15 @@ public class InvoiceServices { adjAmount = amount; } - Debug.logInfo("adjAmount: " + adjAmount + ", divisor: " + divisor + ", multiplier: " + multiplier + - ", invoiceTypeId: " + invoiceTypeId + ", invoiceId: " + invoiceId + ", itemSeqId: " + invoiceItemSeqId + - ", decimals: " + decimals + ", rounding: " + rounding + ", adj: " + adj, MODULE); + Debug.logInfo("adjAmount: " + adjAmount + ", divisor: " + divisor + ", multiplier: " + multiplier + + ", invoiceTypeId: " + invoiceTypeId + ", invoiceId: " + invoiceId + ", itemSeqId: " + invoiceItemSeqId + + ", decimals: " + decimals + ", rounding: " + rounding + ", adj: " + adj, MODULE); return adjAmount; } /* Creates InvoiceTerm entries for a list of terms, which can be BillingAccountTerms, OrderTerms, etc. */ - private static void createInvoiceTerms(Delegator delegator, LocalDispatcher dispatcher, String invoiceId, List terms, GenericValue userLogin, Locale locale) { + private static void createInvoiceTerms(Delegator delegator, LocalDispatcher dispatcher, String invoiceId, List terms, + GenericValue userLogin, Locale locale) { if (terms != null) { for (GenericValue term : terms) { @@ -2586,7 +2663,7 @@ public class InvoiceServices { * have been paid/received. For invoice processing, this service works on * the invoice level when 'invoiceProcessing' parameter is set to "Y" else * it works on the invoice item level. - * + *

* This version will apply as much as possible when no amountApplied is provided. */ public static Map updatePaymentApplicationDef(DispatchContext dctx, Map context) { @@ -2740,7 +2817,8 @@ public class InvoiceServices { "AccountingPaymentRecordNotFound", UtilMisc.toMap("paymentId", toPaymentId), locale)); return ServiceUtil.returnError(errorMessageList); } - toPaymentApplyAvailable = toPayment.getBigDecimal("amount").subtract(PaymentWorker.getPaymentApplied(toPayment)).setScale(DECIMALS, ROUNDING); + toPaymentApplyAvailable = toPayment.getBigDecimal("amount").subtract(PaymentWorker.getPaymentApplied(toPayment)).setScale(DECIMALS, + ROUNDING); if ("PMNT_CANCELLED".equals(toPayment.getString("statusId"))) { errorMessageList.add(UtilProperties.getMessage(RESOURCE, @@ -2760,18 +2838,18 @@ public class InvoiceServices { // check here for too much application if a new record is // added (paymentApplicationId == null) if (amountApplied.compareTo(toPaymentApplyAvailable) > 0) { - errorMessageList.add(UtilProperties.getMessage(RESOURCE, - "AccountingPaymentLessRequested", - UtilMisc.toMap("paymentId", toPaymentId, - "paymentApplyAvailable", toPaymentApplyAvailable, - "amountApplied", amountApplied, "isoCode", currencyUomId), locale)); + errorMessageList.add(UtilProperties.getMessage(RESOURCE, + "AccountingPaymentLessRequested", + UtilMisc.toMap("paymentId", toPaymentId, + "paymentApplyAvailable", toPaymentApplyAvailable, + "amountApplied", amountApplied, "isoCode", currencyUomId), locale)); } } } // check if at least one send is the same as one receiver on the other payment if (!payment.getString("partyIdFrom").equals(toPayment.getString("partyIdTo")) - && !payment.getString("partyIdTo").equals(toPayment.getString("partyIdFrom"))) { + && !payment.getString("partyIdTo").equals(toPayment.getString("partyIdFrom"))) { errorMessageList.add(UtilProperties.getMessage(RESOURCE, "AccountingFromPartySameToParty", locale)); } @@ -2855,7 +2933,8 @@ public class InvoiceServices { if (currencyUomId != null && invoice.get("currencyUomId") != null && !currencyUomId.equals(invoice.getString("currencyUomId"))) { Debug.logInfo(UtilProperties.getMessage(RESOURCE, "AccountingInvoicePaymentCurrencyProblem", - UtilMisc.toMap("invoiceCurrency", invoice.getString("currencyUomId"), "paymentCurrency", payment.getString("currencyUomId")), locale), MODULE); + UtilMisc.toMap("invoiceCurrency", invoice.getString("currencyUomId"), "paymentCurrency", payment.getString( + "currencyUomId")), locale), MODULE); Debug.logInfo("will try to apply payment on the actualCurrency amount on payment", MODULE); if (payment.get("actualCurrencyAmount") == null || payment.get("actualCurrencyUomId") == null) { @@ -2866,7 +2945,8 @@ public class InvoiceServices { errorMessageList.add("actual currency on payment (" + currencyUomId + ") not the same as original invoice currency (" + invoice.getString("currencyUomId") + ")"); } } - paymentApplyAvailable = payment.getBigDecimal("actualCurrencyAmount").subtract(PaymentWorker.getPaymentApplied(payment)).setScale(DECIMALS, ROUNDING); + paymentApplyAvailable = + payment.getBigDecimal("actualCurrencyAmount").subtract(PaymentWorker.getPaymentApplied(payment)).setScale(DECIMALS, ROUNDING); } // check if the invoice already covered by payments @@ -2887,15 +2967,15 @@ public class InvoiceServices { else if (amountApplied.compareTo(invoiceApplyAvailable) > 0) { errorMessageList.add(UtilProperties.getMessage(RESOURCE, "AccountingInvoiceLessRequested", UtilMisc.toMap("invoiceId", invoiceId, - "invoiceApplyAvailable", invoiceApplyAvailable, - "amountApplied", amountApplied, - "isoCode", invoice.getString("currencyUomId")), locale)); + "invoiceApplyAvailable", invoiceApplyAvailable, + "amountApplied", amountApplied, + "isoCode", invoice.getString("currencyUomId")), locale)); } } // check if at least one sender is the same as one receiver on the invoice if (!payment.getString("partyIdFrom").equals(invoice.getString("partyId")) - && !payment.getString("partyIdTo").equals(invoice.getString("partyIdFrom"))) { + && !payment.getString("partyIdTo").equals(invoice.getString("partyIdFrom"))) { errorMessageList.add(UtilProperties.getMessage(RESOURCE, "AccountingFromPartySameToParty", locale)); } @@ -2909,7 +2989,8 @@ public class InvoiceServices { if (invoiceItemSeqId != null) { // when itemSeqNr not provided delay checking on invoiceItemSeqId try { - invoiceItem = EntityQuery.use(delegator).from("InvoiceItem").where("invoiceId", invoiceId, "invoiceItemSeqId", invoiceItemSeqId).queryOne(); + invoiceItem = EntityQuery.use(delegator).from("InvoiceItem").where("invoiceId", invoiceId, "invoiceItemSeqId", + invoiceItemSeqId).queryOne(); } catch (GenericEntityException e) { return ServiceUtil.returnError(e.getMessage()); } @@ -2933,16 +3014,18 @@ public class InvoiceServices { } else { quantity = invoiceItem.getBigDecimal("quantity").setScale(DECIMALS, ROUNDING); } - invoiceItemApplyAvailable = invoiceItem.getBigDecimal("amount").multiply(quantity).setScale(DECIMALS, ROUNDING).subtract(InvoiceWorker.getInvoiceItemApplied(invoiceItem)); + invoiceItemApplyAvailable = + invoiceItem.getBigDecimal("amount").multiply(quantity).setScale(DECIMALS, ROUNDING).subtract(InvoiceWorker.getInvoiceItemApplied(invoiceItem)); // check here for too much application if a new record is added if (paymentApplicationId == null && amountApplied.compareTo(invoiceItemApplyAvailable) > 0) { // new record - errorMessageList.add("Invoice(" + invoiceId + ") item(" + invoiceItemSeqId + ") has " + invoiceItemApplyAvailable + " to apply but " + amountApplied + " is requested\n"); + errorMessageList.add("Invoice(" + invoiceId + ") item(" + invoiceItemSeqId + ") has " + invoiceItemApplyAvailable + " to " + + "apply but " + amountApplied + " is requested\n"); String uomId = invoice.getString("currencyUomId"); errorMessageList.add(UtilProperties.getMessage(RESOURCE, "AccountingInvoiceItemLessRequested", UtilMisc.toMap("invoiceId", invoiceId, "invoiceItemSeqId", invoiceItemSeqId, - "invoiceItemApplyAvailable", invoiceItemApplyAvailable, - "amountApplied", amountApplied, "isoCode", uomId), locale)); + "invoiceItemApplyAvailable", invoiceItemApplyAvailable, + "amountApplied", amountApplied, "isoCode", uomId), locale)); } } if (debug) { @@ -2963,8 +3046,8 @@ public class InvoiceServices { if (amountApplied.compareTo(paymentApplyAvailable) > 0) { errorMessageList.add(UtilProperties.getMessage(RESOURCE, "AccountingPaymentLessRequested", UtilMisc.toMap("paymentId", paymentId, - "paymentApplyAvailable", paymentApplyAvailable, - "amountApplied", amountApplied, "isoCode", currencyUomId), locale)); + "paymentApplyAvailable", paymentApplyAvailable, + "amountApplied", amountApplied, "isoCode", currencyUomId), locale)); } } } @@ -2984,7 +3067,8 @@ public class InvoiceServices { // prepare for creation } else { // retrieve existing paymentApplication try { - paymentApplication = EntityQuery.use(delegator).from("PaymentApplication").where("paymentApplicationId", paymentApplicationId).queryOne(); + paymentApplication = + EntityQuery.use(delegator).from("PaymentApplication").where("paymentApplicationId", paymentApplicationId).queryOne(); } catch (GenericEntityException e) { return ServiceUtil.returnError(e.getMessage()); } @@ -3023,7 +3107,9 @@ public class InvoiceServices { // check if the payment for too much application if an existing // application record is changed if (paymentApplyAvailable.compareTo(BigDecimal.ZERO) == 0) { - newPaymentApplyAvailable = paymentApplyAvailable.add(paymentApplication.getBigDecimal("amountApplied")).subtract(amountApplied).setScale(DECIMALS, ROUNDING); + newPaymentApplyAvailable = + paymentApplyAvailable.add(paymentApplication.getBigDecimal("amountApplied")).subtract(amountApplied).setScale(DECIMALS, + ROUNDING); } else { newPaymentApplyAvailable = paymentApplyAvailable.add(paymentApplyAvailable).subtract(amountApplied).setScale(DECIMALS, ROUNDING); } @@ -3038,11 +3124,13 @@ public class InvoiceServices { if (invoiceId != null) { // only when we are processing an invoice on existing paymentApplication check invoice item for to much application if the invoice // number did not change - if (invoiceId.equals(paymentApplication .getString("invoiceId"))) { + if (invoiceId.equals(paymentApplication.getString("invoiceId"))) { // check if both the itemNumbers are null then this is a // record for the whole invoice if (invoiceItemSeqId == null && paymentApplication.get("invoiceItemSeqId") == null) { - newInvoiceApplyAvailable = invoiceApplyAvailable.add(paymentApplication.getBigDecimal("amountApplied")).subtract(amountApplied).setScale(DECIMALS, ROUNDING); + newInvoiceApplyAvailable = + invoiceApplyAvailable.add(paymentApplication.getBigDecimal("amountApplied")).subtract(amountApplied).setScale(DECIMALS + , ROUNDING); if (invoiceApplyAvailable.compareTo(BigDecimal.ZERO) < 0) { errorMessageList.add(UtilProperties.getMessage(RESOURCE, "AccountingInvoiceNotEnough", @@ -3051,7 +3139,9 @@ public class InvoiceServices { } } else if (invoiceItemSeqId == null && paymentApplication.get("invoiceItemSeqId") != null) { // check if the item number changed from a real Item number to a null value - newInvoiceApplyAvailable = invoiceApplyAvailable.add(paymentApplication.getBigDecimal("amountApplied")).subtract(amountApplied).setScale(DECIMALS, ROUNDING); + newInvoiceApplyAvailable = + invoiceApplyAvailable.add(paymentApplication.getBigDecimal("amountApplied")).subtract(amountApplied).setScale(DECIMALS + , ROUNDING); if (invoiceApplyAvailable.compareTo(BigDecimal.ZERO) < 0) { errorMessageList.add(UtilProperties.getMessage(RESOURCE, "AccountingInvoiceNotEnough", @@ -3072,7 +3162,8 @@ public class InvoiceServices { } else if (invoiceItemSeqId.equals(paymentApplication.getString("invoiceItemSeqId"))) { // check if the real item numbers the same // item number the same numeric value - newInvoiceItemApplyAvailable = invoiceItemApplyAvailable.add(paymentApplication.getBigDecimal("amountApplied")).subtract(amountApplied).setScale(DECIMALS, ROUNDING); + newInvoiceItemApplyAvailable = + invoiceItemApplyAvailable.add(paymentApplication.getBigDecimal("amountApplied")).subtract(amountApplied).setScale(DECIMALS, ROUNDING); if (newInvoiceItemApplyAvailable.compareTo(BigDecimal.ZERO) < 0) { errorMessageList.add(UtilProperties.getMessage(RESOURCE, "AccountingItemInvoiceNotEnough", @@ -3105,11 +3196,14 @@ public class InvoiceServices { } // check the invoice - newInvoiceApplyAvailable = invoiceApplyAvailable.add(paymentApplication.getBigDecimal("amountApplied").subtract(amountApplied)).setScale(DECIMALS, ROUNDING); + newInvoiceApplyAvailable = + invoiceApplyAvailable.add(paymentApplication.getBigDecimal("amountApplied").subtract(amountApplied)).setScale(DECIMALS, + ROUNDING); if (newInvoiceApplyAvailable.compareTo(BigDecimal.ZERO) < 0) { errorMessageList.add(UtilProperties.getMessage(RESOURCE, "AccountingInvoiceNotEnough", - UtilMisc.toMap("tooMuch", invoiceApplyAvailable.add(paymentApplication.getBigDecimal("amountApplied")).subtract(amountApplied), + UtilMisc.toMap("tooMuch", invoiceApplyAvailable.add(paymentApplication.getBigDecimal( + "amountApplied")).subtract(amountApplied), "invoiceId", invoiceId), locale)); } } @@ -3118,7 +3212,9 @@ public class InvoiceServices { // check the toPayment account when only the amountApplied has // changed, if (toPaymentId != null && toPaymentId.equals(paymentApplication.getString("toPaymentId"))) { - newToPaymentApplyAvailable = toPaymentApplyAvailable.subtract(paymentApplication.getBigDecimal("amountApplied")).add(amountApplied).setScale(DECIMALS, ROUNDING); + newToPaymentApplyAvailable = + toPaymentApplyAvailable.subtract(paymentApplication.getBigDecimal("amountApplied")).add(amountApplied).setScale(DECIMALS, + ROUNDING); if (newToPaymentApplyAvailable.compareTo(BigDecimal.ZERO) < 0) { errorMessageList.add(UtilProperties.getMessage(RESOURCE, "AccountingPaymentNotEnough", @@ -3154,7 +3250,7 @@ public class InvoiceServices { } Debug.logInfo("checking finished, start processing with the following data... ", MODULE); if (invoiceId != null) { - Debug.logInfo(" Invoice(" + invoiceId + ") amount not yet applied: " + newInvoiceApplyAvailable + extra + " Payment(" + paymentId + ") amount not yet applied: " + newPaymentApplyAvailable + " Requested amount to apply:" + amountApplied, MODULE); + Debug.logInfo(" Invoice(" + invoiceId + ") amount not yet applied: " + newInvoiceApplyAvailable + extra + " Payment(" + paymentId + ") amount not yet applied: " + newPaymentApplyAvailable + " Requested amount to apply:" + amountApplied, MODULE); toMessage = UtilProperties.getMessage(RESOURCE, "AccountingApplicationToInvoice", UtilMisc.toMap("invoiceId", invoiceId), locale); @@ -3165,7 +3261,8 @@ public class InvoiceServices { } } if (toPaymentId != null) { - Debug.logInfo(" toPayment(" + toPaymentId + ") amount not yet applied: " + newToPaymentApplyAvailable + " Payment(" + paymentId + ") amount not yet applied: " + newPaymentApplyAvailable + " Requested amount to apply:" + amountApplied, MODULE); + Debug.logInfo(" toPayment(" + toPaymentId + ") amount not yet applied: " + newToPaymentApplyAvailable + " Payment(" + paymentId + + ") amount not yet applied: " + newPaymentApplyAvailable + " Requested amount to apply:" + amountApplied, MODULE); toMessage = UtilProperties.getMessage(RESOURCE, "AccountingApplicationToPayment", UtilMisc.toMap("paymentId", toPaymentId), locale); @@ -3178,7 +3275,7 @@ public class InvoiceServices { } } // if the amount to apply was not provided or was zero fill it with the maximum possible and provide information to the user - if (amountApplied.signum() == 0 && "Y".equals(useHighestAmount)) { + if (amountApplied.signum() == 0 && "Y".equals(useHighestAmount)) { amountApplied = newPaymentApplyAvailable; if (invoiceId != null && newInvoiceApplyAvailable.compareTo(amountApplied) < 0) { amountApplied = newInvoiceApplyAvailable; @@ -3211,7 +3308,7 @@ public class InvoiceServices { } // ============ start processing ====================== - // if the application is specified it is easy, update the existing record only + // if the application is specified it is easy, update the existing record only if (paymentApplicationId != null) { // record is already retrieved previously if (debug) { @@ -3261,11 +3358,12 @@ public class InvoiceServices { return ServiceUtil.returnError(e.getMessage()); } if (invoiceItems.size() == 0) { - errorMessageList.add(UtilProperties.getMessage(RESOURCE, "AccountingNoInvoiceItemsFoundForInvoice", UtilMisc.toMap("invoiceId", invoiceId), locale)); + errorMessageList.add(UtilProperties.getMessage(RESOURCE, "AccountingNoInvoiceItemsFoundForInvoice", UtilMisc.toMap("invoiceId", + invoiceId), locale)); return ServiceUtil.returnError(errorMessageList); } // check if the user want to apply a smaller amount than the maximum possible on the payment - if (amountApplied.signum() != 0 && amountApplied.compareTo(paymentApplyAvailable) < 0) { + if (amountApplied.signum() != 0 && amountApplied.compareTo(paymentApplyAvailable) < 0) { paymentApplyAvailable = amountApplied; } for (GenericValue currentInvoiceItem : invoiceItems) { @@ -3306,7 +3404,8 @@ public class InvoiceServices { tobeApplied = itemTotal; } if (debug) { - Debug.logInfo("tobeApplied:(" + tobeApplied + ") = " + "itemTotal(" + itemTotal + ") - alreadyApplied(" + alreadyApplied + ") but not more then (nonapplied) paymentAmount(" + paymentApplyAvailable + ")", MODULE); + Debug.logInfo("tobeApplied:(" + tobeApplied + ") = " + "itemTotal(" + itemTotal + ") - alreadyApplied(" + alreadyApplied + ") " + + "but not more then (nonapplied) paymentAmount(" + paymentApplyAvailable + ")", MODULE); } if (tobeApplied.signum() == 0) { @@ -3324,7 +3423,8 @@ public class InvoiceServices { // create application payment record but check currency // first if supplied if (invoice.get("currencyUomId") != null && currencyUomId != null && !invoice.getString("currencyUomId").equals(currencyUomId)) { - errorMessageList.add("Payment currency (" + currencyUomId + ") and invoice currency(" + invoice.getString("currencyUomId") + ") not the same\n"); + errorMessageList.add("Payment currency (" + currencyUomId + ") and invoice currency(" + invoice.getString("currencyUomId") + ")" + + " not the same\n"); } else { paymentApplication.set("paymentApplicationId", null); // make sure we get a new record @@ -3372,7 +3472,8 @@ public class InvoiceServices { BigDecimal invoicedTotal = BigDecimal.ZERO; List invoicedAdjustments = null; try { - invoicedAdjustments = EntityQuery.use(delegator).from("OrderAdjustmentBilling").where("orderAdjustmentId", orderAdjustment.get("orderAdjustmentId")).queryList(); + invoicedAdjustments = EntityQuery.use(delegator).from("OrderAdjustmentBilling").where("orderAdjustmentId", + orderAdjustment.get("orderAdjustmentId")).queryList(); } catch (GenericEntityException e) { Debug.logError(e, "Accounting trouble calling calculateInvoicedAdjustmentTotal service", MODULE); return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, @@ -3427,7 +3528,7 @@ public class InvoiceServices { // 1 record exists just update and if different ID delete other record and add together. GenericValue checkAppl = checkAppls.get(0); // if new record add to the already existing one. - if (paymentApplication.get("paymentApplicationId") == null) { + if (paymentApplication.get("paymentApplicationId") == null) { // add 2 amounts together checkAppl.set("amountApplied", paymentApplication.getBigDecimal("amountApplied"). add(checkAppl.getBigDecimal("amountApplied")).setScale(DECIMALS, ROUNDING)); @@ -3450,13 +3551,14 @@ public class InvoiceServices { } catch (GenericEntityException e) { return ServiceUtil.returnError(e.getMessage()); } - } else { // two existing records, an updated one added to the existing one + } else { // two existing records, an updated one added to the existing one // add 2 amounts together checkAppl.set("amountApplied", paymentApplication.getBigDecimal("amountApplied"). add(checkAppl.getBigDecimal("amountApplied")).setScale(DECIMALS, ROUNDING)); // delete paymentApplication record and update the checkAppls one. if (debug) { - Debug.logInfo("Delete paymentApplication record: " + paymentApplication.getString("paymentApplicationId") + " with appliedAmount:" + paymentApplication.getBigDecimal("amountApplied"), MODULE); + Debug.logInfo("Delete paymentApplication record: " + paymentApplication.getString("paymentApplicationId") + " with " + + "appliedAmount:" + paymentApplication.getBigDecimal("amountApplied"), MODULE); } try { paymentApplication.remove(); @@ -3480,18 +3582,21 @@ public class InvoiceServices { // create record if ID null; if (paymentApplication.get("paymentApplicationId") == null) { paymentApplication.set("paymentApplicationId", delegator.getNextSeqId("PaymentApplication")); - if (debug) { - Debug.logInfo("Create new paymentAppication record: " + paymentApplication.getString("paymentApplicationId") + " with appliedAmount:" + paymentApplication.getBigDecimal("amountApplied"), MODULE); - } + if (debug) { + Debug.logInfo("Create new paymentAppication record: " + paymentApplication.getString("paymentApplicationId") + " with " + + "appliedAmount:" + paymentApplication.getBigDecimal("amountApplied"), MODULE); + } try { paymentApplication.create(); } catch (GenericEntityException e) { return ServiceUtil.returnError(e.getMessage()); } } else { - // update existing record (could not be found because a non existing combination of paymentId/invoiceId/invoiceSeqId/ etc... was provided + // update existing record (could not be found because a non existing combination of paymentId/invoiceId/invoiceSeqId/ etc... was + // provided if (debug) { - Debug.logInfo("Update existing paymentApplication record: " + paymentApplication.getString("paymentApplicationId") + " with appliedAmount:" + paymentApplication.getBigDecimal("amountApplied"), MODULE); + Debug.logInfo("Update existing paymentApplication record: " + paymentApplication.getString("paymentApplicationId") + " with " + + "appliedAmount:" + paymentApplication.getBigDecimal("amountApplied"), MODULE); } try { paymentApplication.store(); @@ -3512,7 +3617,7 @@ public class InvoiceServices { try { GenericValue payment = EntityQuery.use(delegator).from("Payment").where("paymentId", paymentId).queryOne(); if (payment == null) { - throw new GenericServiceException("Payment with ID [" + paymentId + "] not found!"); + throw new GenericServiceException("Payment with ID [" + paymentId + "] not found!"); } List paymentApplications = payment.getRelated("PaymentApplication", null, null, false); @@ -3520,11 +3625,13 @@ public class InvoiceServices { return ServiceUtil.returnSuccess(); } - // TODO: this is inefficient -- instead use HashSet to construct a distinct Set of invoiceIds, then iterate over it and call checkInvoicePaymentAppls + // TODO: this is inefficient -- instead use HashSet to construct a distinct Set of invoiceIds, then iterate over it and call + // checkInvoicePaymentAppls for (GenericValue paymentApplication : paymentApplications) { String invoiceId = paymentApplication.getString("invoiceId"); if (invoiceId != null) { - Map serviceResult = dispatcher.runSync("checkInvoicePaymentApplications", UtilMisc.toMap("invoiceId", invoiceId, "userLogin", userLogin)); + Map serviceResult = dispatcher.runSync("checkInvoicePaymentApplications", UtilMisc.toMap( + "invoiceId", invoiceId, "userLogin", userLogin)); if (ServiceUtil.isError(serviceResult)) { return serviceResult; } @@ -3536,8 +3643,9 @@ public class InvoiceServices { return ServiceUtil.returnError(se.getMessage()); } } + public static Map importInvoice(DispatchContext dctx, Map context) { - Locale locale = (Locale) context.get("locale"); + Locale locale = (Locale) context.get("locale"); Delegator delegator = dctx.getDelegator(); LocalDispatcher dispatcher = dctx.getDispatcher(); GenericValue userLogin = (GenericValue) context.get("userLogin"); @@ -3585,28 +3693,36 @@ public class InvoiceServices { newErrMsgs = new LinkedList<>(); try { if (UtilValidate.isEmpty(invoice.get("partyIdFrom"))) { - newErrMsgs.add("Line number " + rec.getRecordNumber() + ": Mandatory Party Id From and Party Id From Trans missing for invoice: " + currentInvoiceId); + newErrMsgs.add("Line number " + rec.getRecordNumber() + ": Mandatory Party Id From and Party Id From Trans missing for " + + "invoice: " + currentInvoiceId); } else if (EntityQuery.use(delegator).from("Party").where("partyId", invoice.get("partyIdFrom")).queryOne() == null) { - newErrMsgs.add("Line number " + rec.getRecordNumber() + ": partyIdFrom: " + invoice.get("partyIdFrom") + " not found for invoice: " + currentInvoiceId); + newErrMsgs.add("Line number " + rec.getRecordNumber() + ": partyIdFrom: " + invoice.get("partyIdFrom") + " not found " + + "for invoice: " + currentInvoiceId); } if (UtilValidate.isEmpty(invoice.get("partyId"))) { newErrMsgs.add("Line number " + rec.getRecordNumber() + ": Mandatory Party Id and Party Id Trans missing for invoice: " + currentInvoiceId); } else if (EntityQuery.use(delegator).from("Party").where("partyId", invoice.get("partyId")).queryOne() == null) { - newErrMsgs.add("Line number " + rec.getRecordNumber() + ": partyId: " + invoice.get("partyId") + " not found for invoice: " + currentInvoiceId); + newErrMsgs.add("Line number " + rec.getRecordNumber() + ": partyId: " + invoice.get("partyId") + " not found for " + + "invoice: " + currentInvoiceId); } if (UtilValidate.isEmpty(invoice.get("invoiceTypeId"))) { newErrMsgs.add("Line number " + rec.getRecordNumber() + ": Mandatory Invoice Type missing for invoice: " + currentInvoiceId); } else if (EntityQuery.use(delegator).from("InvoiceType").where("invoiceTypeId", invoice.get("invoiceTypeId")).queryOne() == null) { - newErrMsgs.add("Line number " + rec.getRecordNumber() + ": InvoiceItem type id: " + invoice.get("invoiceTypeId") + " not found for invoice: " + currentInvoiceId); + newErrMsgs.add("Line number " + rec.getRecordNumber() + ": InvoiceItem type id: " + invoice.get("invoiceTypeId") + " " + + "not found for invoice: " + currentInvoiceId); } - Boolean isPurchaseInvoice = EntityTypeUtil.hasParentType(delegator, "InvoiceType", "invoiceTypeId", (String) invoice.get("invoiceTypeId"), "parentTypeId", "PURCHASE_INVOICE"); - Boolean isSalesInvoice = EntityTypeUtil.hasParentType(delegator, "InvoiceType", "invoiceTypeId", (String) invoice.get("invoiceTypeId"), "parentTypeId", "SALES_INVOICE"); + Boolean isPurchaseInvoice = EntityTypeUtil.hasParentType(delegator, "InvoiceType", "invoiceTypeId", (String) invoice.get( + "invoiceTypeId"), "parentTypeId", "PURCHASE_INVOICE"); + Boolean isSalesInvoice = EntityTypeUtil.hasParentType(delegator, "InvoiceType", "invoiceTypeId", (String) invoice.get( + "invoiceTypeId"), "parentTypeId", "SALES_INVOICE"); if (isPurchaseInvoice && !invoice.get("partyId").equals(organizationPartyId)) { - newErrMsgs.add("Line number " + rec.getRecordNumber() + ": A purchase type invoice should have the partyId 'To' being the organizationPartyId(=" + organizationPartyId + ")! however is " + invoice.get("partyId") +"! invoice: " + currentInvoiceId); + newErrMsgs.add("Line number " + rec.getRecordNumber() + ": A purchase type invoice should have the partyId 'To' being " + + "the organizationPartyId(=" + organizationPartyId + ")! however is " + invoice.get("partyId") + "! invoice: " + currentInvoiceId); } if (isSalesInvoice && !invoice.get("partyIdFrom").equals(organizationPartyId)) { - newErrMsgs.add("Line number " + rec.getRecordNumber() + ": A sales type invoice should have the partyId 'from' being the organizationPartyId(=" + organizationPartyId + ")! however is " + invoice.get("partyIdFrom") +"! invoice: " + currentInvoiceId); + newErrMsgs.add("Line number " + rec.getRecordNumber() + ": A sales type invoice should have the partyId 'from' being " + + "the organizationPartyId(=" + organizationPartyId + ")! however is " + invoice.get("partyIdFrom") + "! invoice: " + currentInvoiceId); } @@ -3621,7 +3737,7 @@ public class InvoiceServices { try { invoiceResult = dispatcher.runSync("createInvoice", invoice); if (ServiceUtil.isError(invoiceResult)) { - return ServiceUtil.returnError(ServiceUtil.getErrorMessage(invoiceResult)); + return ServiceUtil.returnError(ServiceUtil.getErrorMessage(invoiceResult)); } } catch (GenericServiceException e) { csvReader.close(); @@ -3657,17 +3773,23 @@ public class InvoiceServices { } if (UtilValidate.isEmpty(invoiceItem.get("invoiceItemTypeId"))) { newErrMsgs.add("Line number " + rec.getRecordNumber() + ": Mandatory invoice item type missing for invoice: " + currentInvoiceId); - } else if (EntityQuery.use(delegator).from("InvoiceItemType").where("invoiceItemTypeId", invoiceItem.get("invoiceItemTypeId")).queryOne() == null) { - newErrMsgs.add("Line number " + rec.getRecordNumber() + ": InvoiceItem Item type id: " + invoiceItem.get("invoiceItemTypeId") + " not found for invoice: " + currentInvoiceId + " Item seqId:" + invoiceItem.get("invoiceItemSeqId")); + } else if (EntityQuery.use(delegator).from("InvoiceItemType").where("invoiceItemTypeId", invoiceItem.get("invoiceItemTypeId" + )).queryOne() == null) { + newErrMsgs.add("Line number " + rec.getRecordNumber() + ": InvoiceItem Item type id: " + invoiceItem.get( + "invoiceItemTypeId") + " not found for invoice: " + currentInvoiceId + " Item seqId:" + invoiceItem.get( + "invoiceItemSeqId")); } if (UtilValidate.isEmpty(invoiceItem.get("productId")) && UtilValidate.isEmpty(invoiceItem.get("description"))) { newErrMsgs.add("Line number " + rec.getRecordNumber() + ": no Product Id given, no description given"); } - if (UtilValidate.isNotEmpty(invoiceItem.get("productId")) && EntityQuery.use(delegator).from("Product").where("productId", invoiceItem.get("productId")).queryOne() == null) { - newErrMsgs.add("Line number " + rec.getRecordNumber() + ": Product Id: " + invoiceItem.get("productId") + " not found for invoice: " + currentInvoiceId + " Item seqId:" + invoiceItem.get("invoiceItemSeqId")); + if (UtilValidate.isNotEmpty(invoiceItem.get("productId")) && EntityQuery.use(delegator).from("Product").where("productId", + invoiceItem.get("productId")).queryOne() == null) { + newErrMsgs.add("Line number " + rec.getRecordNumber() + ": Product Id: " + invoiceItem.get("productId") + " not found " + + "for invoice: " + currentInvoiceId + " Item seqId:" + invoiceItem.get("invoiceItemSeqId")); } if (UtilValidate.isEmpty(invoiceItem.get("amount")) && UtilValidate.isEmpty(invoiceItem.get("quantity"))) { - newErrMsgs.add("Line number " + rec.getRecordNumber() + ": Either or both quantity and amount is required for invoice: " + currentInvoiceId + " Item seqId:" + invoiceItem.get("invoiceItemSeqId")); + newErrMsgs.add("Line number " + rec.getRecordNumber() + ": Either or both quantity and amount is required for invoice: " + + currentInvoiceId + " Item seqId:" + invoiceItem.get("invoiceItemSeqId")); } } catch (GenericEntityException e) { Debug.logError("Validation checking problem against database. due to " + e.getMessage(), MODULE); @@ -3679,7 +3801,7 @@ public class InvoiceServices { try { Map result = dispatcher.runSync("createInvoiceItem", invoiceItem); if (ServiceUtil.isError(result)) { - return ServiceUtil.returnError(ServiceUtil.getErrorMessage(result)); + return ServiceUtil.returnError(ServiceUtil.getErrorMessage(result)); } } catch (GenericServiceException e) { csvReader.close(); diff --git a/applications/accounting/src/main/java/org/apache/ofbiz/accounting/invoice/InvoiceWorker.java b/applications/accounting/src/main/java/org/apache/ofbiz/accounting/invoice/InvoiceWorker.java index 22ab5f8bcc..df4ba2d71c 100644 --- a/applications/accounting/src/main/java/org/apache/ofbiz/accounting/invoice/InvoiceWorker.java +++ b/applications/accounting/src/main/java/org/apache/ofbiz/accounting/invoice/InvoiceWorker.java @@ -58,8 +58,8 @@ public final class InvoiceWorker { private static final int DECIMALS = UtilNumber.getBigDecimalScale("invoice.decimals"); private static final RoundingMode ROUNDING = UtilNumber.getRoundingMode("invoice.rounding"); - private static final int taxDecimals = UtilNumber.getBigDecimalScale("salestax.calc.decimals"); - private static final RoundingMode taxRounding = UtilNumber.getRoundingMode("salestax.rounding"); + private static final int TAX_DECIMALS = UtilNumber.getBigDecimalScale("salestax.calc.decimals"); + private static final RoundingMode TAX_ROUNDING = UtilNumber.getRoundingMode("salestax.rounding"); private InvoiceWorker() { } @@ -95,7 +95,7 @@ public final class InvoiceWorker { } if (invoice == null) { - throw new IllegalArgumentException("The passed invoiceId [" +invoiceId + "] does not match an existing invoice"); + throw new IllegalArgumentException("The passed invoiceId [" + invoiceId + "] does not match an existing invoice"); } return getInvoiceTotal(invoice, actualCurrency); @@ -162,7 +162,8 @@ public final class InvoiceWorker { return description; } - /** Method to get the taxable invoice item types as a List of invoiceItemTypeIds. These are identified in Enumeration with enumTypeId TAXABLE_INV_ITM_TY. */ + /** Method to get the taxable invoice item types as a List of invoiceItemTypeIds. + * These are identified in Enumeration with enumTypeId TAXABLE_INV_ITM_TY. */ public static List getTaxableInvoiceItemTypeIds(Delegator delegator) throws GenericEntityException { List typeIds = new LinkedList<>(); List invoiceItemTaxTypes = EntityQuery.use(delegator).from("Enumeration").where("enumTypeId", "TAXABLE_INV_ITM_TY") @@ -217,7 +218,7 @@ public final class InvoiceWorker { invoiceItems = invoice.getRelated("InvoiceItem", null, null, false); invoiceItems = EntityUtil.filterByAnd( invoiceItems, UtilMisc.toList( - EntityCondition.makeCondition("invoiceItemTypeId", EntityOperator.NOT_IN, getTaxableInvoiceItemTypeIds(invoice.getDelegator())))); + EntityCondition.makeCondition("invoiceItemTypeId", EntityOperator.NOT_IN, getTaxableInvoiceItemTypeIds(invoice.getDelegator())))); } catch (GenericEntityException e) { Debug.logError(e, "Trouble getting InvoiceItem list", MODULE); } @@ -251,7 +252,8 @@ public final class InvoiceWorker { // remaining code is the old method, which we leave here for compatibility purposes List billToRoles = null; try { - billToRoles = invoice.getRelated("InvoiceRole", UtilMisc.toMap("roleTypeId", "BILL_TO_CUSTOMER"), UtilMisc.toList("-datetimePerformed"), false); + billToRoles = invoice.getRelated("InvoiceRole", UtilMisc.toMap("roleTypeId", "BILL_TO_CUSTOMER"), + UtilMisc.toList("-datetimePerformed"), false); } catch (GenericEntityException e) { Debug.logError(e, "Trouble getting InvoiceRole list", MODULE); } @@ -330,7 +332,7 @@ public final class InvoiceWorker { .where("invoiceId", invoice.get("invoiceId")).queryFirst(); if (shipmentView != null) { GenericValue shipment = EntityQuery.use(delegator).from("Shipment") - .where("shipmentId", shipmentView.get("shipmentId")).queryOne(); + .where("shipmentId", shipmentView.get("shipmentId")).queryOne(); postalAddress = shipment.getRelatedOne("DestinationPostalAddress", false); } } catch (GenericEntityException e) { @@ -372,7 +374,7 @@ public final class InvoiceWorker { Debug.logError("Touble getting InvoiceContactMech entity list", MODULE); } - if (UtilValidate.isEmpty(locations) && fetchPartyAddress) { + if (UtilValidate.isEmpty(locations) && fetchPartyAddress) { // if no locations found get it from the PartyAndContactMech using the from and to party on the invoice String destinationPartyId = null; Timestamp now = UtilDateTime.nowTimestamp(); @@ -391,7 +393,7 @@ public final class InvoiceWorker { Debug.logError("Trouble getting contact party purpose list", MODULE); } //if still not found get it from the general location - if (UtilValidate.isEmpty(locations)) { + if (UtilValidate.isEmpty(locations)) { try { locations = EntityQuery.use(delegator).from("PartyContactWithPurpose") .where("partyId", destinationPartyId, "contactMechPurposeTypeId", "GENERAL_LOCATION").queryList(); @@ -413,7 +415,7 @@ public final class InvoiceWorker { Debug.logError(e, "Trouble getting Contact for contactMechId: " + locations.get(0).getString("contactMechId"), MODULE); } - if (contactMech != null && "POSTAL_ADDRESS".equals(contactMech.getString("contactMechTypeId"))) { + if (contactMech != null && "POSTAL_ADDRESS".equals(contactMech.getString("contactMechTypeId"))) { try { postalAddress = contactMech.getRelatedOne("PostalAddress", false); return postalAddress; @@ -433,7 +435,7 @@ public final class InvoiceWorker { * @return the invoice total as BigDecimal */ public static BigDecimal getInvoiceNotApplied(Delegator delegator, String invoiceId, Boolean actualCurrency) { - return InvoiceWorker.getInvoiceTotal(delegator, invoiceId, actualCurrency).subtract(getInvoiceApplied(delegator, invoiceId, UtilDateTime.nowTimestamp(), actualCurrency)); + return InvoiceWorker.getInvoiceTotal(delegator, invoiceId, actualCurrency).subtract(getInvoiceApplied(delegator, invoiceId, UtilDateTime.nowTimestamp(), actualCurrency)); } public static BigDecimal getInvoiceNotApplied(Delegator delegator, String invoiceId) { return InvoiceWorker.getInvoiceTotal(delegator, invoiceId).subtract(getInvoiceApplied(delegator, invoiceId)); @@ -580,9 +582,9 @@ public final class InvoiceWorker { String otherCurrencyUomId = null; // find the organization party currencyUomId which different from the invoice currency try { - GenericValue party = EntityQuery.use(delegator).from("PartyAcctgPreference").where("partyId", invoice.get("partyIdFrom")).queryOne(); + GenericValue party = EntityQuery.use(delegator).from("PartyAcctgPreference").where("partyId", invoice.get("partyIdFrom")).queryOne(); if (UtilValidate.isEmpty(party) || party.getString("baseCurrencyUomId").equals(invoice.getString("currencyUomId"))) { - party = EntityQuery.use(delegator).from("PartyAcctgPreference").where("partyId", invoice.get("partyId")).queryOne(); + party = EntityQuery.use(delegator).from("PartyAcctgPreference").where("partyId", invoice.get("partyId")).queryOne(); } if (UtilValidate.isNotEmpty(party) && party.getString("baseCurrencyUomId") != null) { otherCurrencyUomId = party.getString("baseCurrencyUomId"); @@ -703,9 +705,9 @@ public final class InvoiceWorker { if (amount == null) { amount = BigDecimal.ZERO; } - totalAmount = totalAmount.add(amount).setScale(taxDecimals, taxRounding); + totalAmount = totalAmount.add(amount).setScale(TAX_DECIMALS, TAX_ROUNDING); } - totalAmount = totalAmount.setScale(taxDecimals, taxRounding); + totalAmount = totalAmount.setScale(TAX_DECIMALS, TAX_ROUNDING); taxByTaxAuthGeoAndPartyList.add(UtilMisc.toMap("taxAuthPartyId", taxAuthPartyId, "taxAuthGeoId", taxAuthGeoId, "totalAmount", totalAmount)); taxGrandTotal = taxGrandTotal.add(totalAmount); } @@ -736,7 +738,7 @@ public final class InvoiceWorker { Delegator delegator = invoice.getDelegator(); invoiceTaxItems = EntityQuery.use(delegator).from("InvoiceItem") .where(EntityCondition.makeCondition("invoiceId", invoice.getString("invoiceId")), - EntityCondition.makeCondition("invoiceItemTypeId", EntityOperator.IN, getTaxableInvoiceItemTypeIds(delegator))).queryList(); + EntityCondition.makeCondition("invoiceItemTypeId", EntityOperator.IN, getTaxableInvoiceItemTypeIds(delegator))).queryList(); } catch (GenericEntityException e) { Debug.logError(e, "Trouble getting InvoiceItem list", MODULE); return null; @@ -779,7 +781,7 @@ public final class InvoiceWorker { Debug.logError(e, "Trouble getting InvoiceItem list", MODULE); return null; } - return getTaxTotalForInvoiceItems(invoiceTaxItems); + return getTaxTotalForInvoiceItems(invoiceTaxItems); } /** Returns the invoice tax total for unattributed tax items, that is items which have no taxAuthPartyId value @@ -787,17 +789,17 @@ public final class InvoiceWorker { * @return Returns the invoice tax total for unattributed tax items */ public static BigDecimal getInvoiceUnattributedTaxTotal(GenericValue invoice) { - List invoiceTaxItems = null; - try { - Delegator delegator = invoice.getDelegator(); - invoiceTaxItems = EntityQuery.use(delegator).from("InvoiceItem") - .where(EntityCondition.makeCondition("invoiceId", invoice.get("invoiceId")), - EntityCondition.makeCondition("invoiceItemTypeId", EntityOperator.IN, getTaxableInvoiceItemTypeIds(delegator)), - EntityCondition.makeCondition("taxAuthPartyId", null)).queryList(); - } catch (GenericEntityException e) { - Debug.logError(e, "Trouble getting InvoiceItem list", MODULE); - return null; - } + List invoiceTaxItems = null; + try { + Delegator delegator = invoice.getDelegator(); + invoiceTaxItems = EntityQuery.use(delegator).from("InvoiceItem") + .where(EntityCondition.makeCondition("invoiceId", invoice.get("invoiceId")), + EntityCondition.makeCondition("invoiceItemTypeId", EntityOperator.IN, getTaxableInvoiceItemTypeIds(delegator)), + EntityCondition.makeCondition("taxAuthPartyId", null)).queryList(); + } catch (GenericEntityException e) { + Debug.logError(e, "Trouble getting InvoiceItem list", MODULE); + return null; + } return getTaxTotalForInvoiceItems(invoiceTaxItems); } @@ -820,7 +822,7 @@ public final class InvoiceWorker { quantity = BigDecimal.ONE; } amount = amount.multiply(quantity); - amount = amount.setScale(taxDecimals, taxRounding); + amount = amount.setScale(TAX_DECIMALS, TAX_ROUNDING); taxTotal = taxTotal.add(amount); } return taxTotal.setScale(DECIMALS, ROUNDING); diff --git a/applications/accounting/src/main/java/org/apache/ofbiz/accounting/payment/GiftCertificateServices.java b/applications/accounting/src/main/java/org/apache/ofbiz/accounting/payment/GiftCertificateServices.java index caa759c60a..d6be139e70 100644 --- a/applications/accounting/src/main/java/org/apache/ofbiz/accounting/payment/GiftCertificateServices.java +++ b/applications/accounting/src/main/java/org/apache/ofbiz/accounting/payment/GiftCertificateServices.java @@ -120,7 +120,7 @@ public class GiftCertificateServices { createAccountCtx.put("finAccountTypeId", FinAccountHelper.getGiftCertFinAccountTypeId()); createAccountCtx.put("productStoreId", productStoreId); createAccountCtx.put("currencyUomId", currency); - createAccountCtx.put("finAccountName", accountName + " for party ["+partyId+"]"); + createAccountCtx.put("finAccountName", accountName + " for party [" + partyId + "]"); createAccountCtx.put("userLogin", userLogin); acctResult = dispatcher.runSync("createFinAccountForStore", createAccountCtx); if (ServiceUtil.isError(acctResult)) { @@ -460,7 +460,7 @@ public class GiftCertificateServices { "AccountingGiftCertificateNumberCannotProcess", UtilMisc.toMap("errorString", ex.getMessage()), locale)); } -} + } public static Map giftCertificateAuthorize(DispatchContext dctx, Map context) { @@ -496,13 +496,13 @@ public class GiftCertificateServices { finAccount = EntityQuery.use(delegator).from("FinAccount").where("finAccountId", finAccountId).queryOne(); } } else { - finAccount = FinAccountHelper.getFinAccountFromCode(giftCard.getString("cardNumber"), delegator); - if (finAccount == null) { - return ServiceUtil.returnError(UtilProperties.getMessage(RES_ERROR, - "AccountingGiftCertificateNumberNotFound", - UtilMisc.toMap("finAccountId", ""), locale)); - } - finAccountId = finAccount.getString("finAccountId"); + finAccount = FinAccountHelper.getFinAccountFromCode(giftCard.getString("cardNumber"), delegator); + if (finAccount == null) { + return ServiceUtil.returnError(UtilProperties.getMessage(RES_ERROR, + "AccountingGiftCertificateNumberNotFound", + UtilMisc.toMap("finAccountId", ""), locale)); + } + finAccountId = finAccount.getString("finAccountId"); } } else { return ServiceUtil.returnError(UtilProperties.getMessage(RES_ERROR, diff --git a/applications/accounting/src/main/java/org/apache/ofbiz/accounting/payment/PaymentGatewayServices.java b/applications/accounting/src/main/java/org/apache/ofbiz/accounting/payment/PaymentGatewayServices.java index 1ee57dea31..3e056fd7da 100644 --- a/applications/accounting/src/main/java/org/apache/ofbiz/accounting/payment/PaymentGatewayServices.java +++ b/applications/accounting/src/main/java/org/apache/ofbiz/accounting/payment/PaymentGatewayServices.java @@ -985,7 +985,7 @@ public class PaymentGatewayServices { releaseResult.put("orderPaymentPreference", paymentPref); releaseResult.put("userLogin", userLogin); Map resCtx = model.makeValid(releaseResult, ModelService.IN_PARAM); - releaseResRes = dispatcher.runSync(model.name, resCtx); + releaseResRes = dispatcher.runSync(model.name, resCtx); } catch (GenericServiceException e) { Debug.logError(e, "Trouble processing the release results", MODULE); return ServiceUtil.returnError(UtilProperties.getMessage(RES_ORDER, @@ -1392,21 +1392,21 @@ public class PaymentGatewayServices { try { amountCaptured = (BigDecimal) ObjectType.simpleTypeOrObjectConvert(captureResult.get("captureAmount"), "BigDecimal", null, locale); - if (amountCaptured == null) { - amountCaptured = (BigDecimal) captureResult.get("processAmount"); - } + if (amountCaptured == null) { + amountCaptured = (BigDecimal) captureResult.get("processAmount"); + } - amountCaptured = amountCaptured.setScale(DECIMALS, ROUNDING); + amountCaptured = amountCaptured.setScale(DECIMALS, ROUNDING); - // decrease amount of next payment preference to capture - amountToCapture = amountToCapture.subtract(amountCaptured); + // decrease amount of next payment preference to capture + amountToCapture = amountToCapture.subtract(amountCaptured); - // add the invoiceId to the result for processing, not for a replacement order - if (!isReplacementOrder(orderHeader)) { - captureResult.put("invoiceId", invoiceId); - } + // add the invoiceId to the result for processing, not for a replacement order + if (!isReplacementOrder(orderHeader)) { + captureResult.put("invoiceId", invoiceId); + } - // process the capture's results + // process the capture's results processResult(dctx, captureResult, userLogin, paymentPref, locale); } catch (GeneralException e) { Debug.logError(e, "Trouble processing the result; captureResult: " + captureResult, MODULE); @@ -3214,7 +3214,7 @@ public class PaymentGatewayServices { response.put("orderPaymentPreference", paymentPref); response.put("userLogin", userLogin); Map resCtx = model.makeValid(response, ModelService.IN_PARAM); - responseRes = dispatcher.runSync(model.name, resCtx); + responseRes = dispatcher.runSync(model.name, resCtx); } catch (GenericServiceException e) { Debug.logError(e, MODULE); return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, @@ -3244,7 +3244,7 @@ public class PaymentGatewayServices { } // Verify Credit Card (Manually) Service - public static MapverifyCreditCard(DispatchContext dctx, Map context) { + public static Map verifyCreditCard(DispatchContext dctx, Map context) { LocalDispatcher dispatcher = dctx.getDispatcher(); Delegator delegator = dctx.getDelegator(); String productStoreId = (String) context.get("productStoreId"); @@ -3319,8 +3319,8 @@ public class PaymentGatewayServices { if (processAmount != null && processAmount.compareTo(new BigDecimal("100.00")) < 0) { result.put("authResult", Boolean.FALSE); } - result.put("customerRespMsgs", UtilMisc.toList(UtilProperties.getMessage(RESOURCE, - "AccountingPaymentTestProcessorMinimumPurchase", locale))); + result.put("customerRespMsgs", UtilMisc.toList(UtilProperties.getMessage(RESOURCE, + "AccountingPaymentTestProcessorMinimumPurchase", locale))); if (processAmount == null) { result.put("authResult", null); } @@ -3349,13 +3349,13 @@ public class PaymentGatewayServices { if (processAmount != null && processAmount.compareTo(new BigDecimal("100.00")) >= 0) { result.put("authResult", Boolean.TRUE); } - result.put("captureResult", Boolean.TRUE); + result.put("captureResult", Boolean.TRUE); if (processAmount != null && processAmount.compareTo(new BigDecimal("100.00")) < 0) { result.put("authResult", Boolean.FALSE); } - result.put("captureResult", Boolean.FALSE); - result.put("customerRespMsgs", UtilMisc.toList(UtilProperties.getMessage(RESOURCE, - "AccountingPaymentTestProcessorMinimumPurchase", locale))); + result.put("captureResult", Boolean.FALSE); + result.put("customerRespMsgs", UtilMisc.toList(UtilProperties.getMessage(RESOURCE, + "AccountingPaymentTestProcessorMinimumPurchase", locale))); if (processAmount == null) { result.put("authResult", null); } diff --git a/applications/accounting/src/main/java/org/apache/ofbiz/accounting/payment/PaymentMethodServices.java b/applications/accounting/src/main/java/org/apache/ofbiz/accounting/payment/PaymentMethodServices.java index 35257404a9..97ad5c0faf 100644 --- a/applications/accounting/src/main/java/org/apache/ofbiz/accounting/payment/PaymentMethodServices.java +++ b/applications/accounting/src/main/java/org/apache/ofbiz/accounting/payment/PaymentMethodServices.java @@ -48,8 +48,8 @@ import org.apache.ofbiz.service.ServiceUtil; */ public class PaymentMethodServices { - public final static String MODULE = PaymentMethodServices.class.getName(); - public final static String RESOURCE = "AccountingUiLabels"; + private static final String MODULE = PaymentMethodServices.class.getName(); + private static final String RESOURCE = "AccountingUiLabels"; private static final String RES_ERROR = "AccountingUiLabels"; /** @@ -152,15 +152,15 @@ public class PaymentMethodServices { context.put("cardNumber", StringUtil.removeSpaces((String) context.get("cardNumber"))); if (!UtilValidate.isCardMatch((String) context.get("cardType"), (String) context.get("cardNumber"))) { messages.add( - UtilProperties.getMessage(RESOURCE, "AccountingCreditCardNumberInvalid", - UtilMisc.toMap("cardType", (String) context.get("cardType"), - "validCardType", UtilValidate.getCardType((String) context.get("cardNumber"))), locale)); + UtilProperties.getMessage(RESOURCE, "AccountingCreditCardNumberInvalid", + UtilMisc.toMap("cardType", (String) context.get("cardType"), + "validCardType", UtilValidate.getCardType((String) context.get("cardNumber"))), locale)); } if (!UtilValidate.isDateAfterToday((String) context.get("expireDate"))) { messages.add( - UtilProperties.getMessage(RESOURCE, "AccountingCreditCardExpireDateBeforeToday", - UtilMisc.toMap("expireDate", (String) context.get("expireDate")), locale)); + UtilProperties.getMessage(RESOURCE, "AccountingCreditCardExpireDateBeforeToday", + UtilMisc.toMap("expireDate", (String) context.get("expireDate")), locale)); } if (messages.size() > 0) { @@ -323,15 +323,15 @@ public class PaymentMethodServices { if (!UtilValidate.isCardMatch((String) context.get("cardType"), (String) context.get("cardNumber"))) { messages.add( - UtilProperties.getMessage(RESOURCE, "AccountingCreditCardNumberInvalid", - UtilMisc.toMap("cardType", (String) context.get("cardType"), - "validCardType", UtilValidate.getCardType((String) context.get("cardNumber"))), locale)); + UtilProperties.getMessage(RESOURCE, "AccountingCreditCardNumberInvalid", + UtilMisc.toMap("cardType", (String) context.get("cardType"), + "validCardType", UtilValidate.getCardType((String) context.get("cardNumber"))), locale)); } if (!UtilValidate.isDateAfterToday((String) context.get("expireDate"))) { messages.add( - UtilProperties.getMessage(RESOURCE, "AccountingCreditCardExpireDateBeforeToday", - UtilMisc.toMap("expireDate", (String) context.get("expireDate")), locale)); + UtilProperties.getMessage(RESOURCE, "AccountingCreditCardExpireDateBeforeToday", + UtilMisc.toMap("expireDate", (String) context.get("expireDate")), locale)); } if (messages.size() > 0) { @@ -921,12 +921,13 @@ public class PaymentMethodServices { result.put(ModelService.RESPONSE_MESSAGE, ModelService.RESPOND_SUCCESS); return result; } + public static Map createCheckAccount(DispatchContext ctx, Map context) { Map result = new HashMap<>(); Delegator delegator = ctx.getDelegator(); Security security = ctx.getSecurity(); - GenericValue userLogin = (GenericValue) context.get("userLogin"); - Locale locale = (Locale) context.get("locale"); + GenericValue userLogin = (GenericValue) context.get("userLogin"); + Locale locale = (Locale) context.get("locale"); Timestamp now = UtilDateTime.nowTimestamp(); String partyId = ServiceUtil.getPartyIdCheckSecurity(userLogin, security, context, result, "PAY_INFO", "_CREATE", "ACCOUNTING", "_CREATE"); diff --git a/applications/accounting/src/main/java/org/apache/ofbiz/accounting/tax/TaxAuthorityServices.java b/applications/accounting/src/main/java/org/apache/ofbiz/accounting/tax/TaxAuthorityServices.java index ac88d28786..b4eeb49679 100644 --- a/applications/accounting/src/main/java/org/apache/ofbiz/accounting/tax/TaxAuthorityServices.java +++ b/applications/accounting/src/main/java/org/apache/ofbiz/accounting/tax/TaxAuthorityServices.java @@ -280,11 +280,11 @@ public class TaxAuthorityServices { } if (orderShippingAmount != null && orderShippingAmount.compareTo(BigDecimal.ZERO) > 0) { - for (GenericValue prod : productWeight.keySet()) { - List taxList = getTaxAdjustments(delegator, prod, productStore, payToPartyId, billToPartyId, - taxAuthoritySet, ZERO_BASE, ZERO_BASE, ZERO_BASE, orderShippingAmount, null, productWeight.get(prod)); - orderAdjustments.addAll(taxList); - } + for (GenericValue prod : productWeight.keySet()) { + List taxList = getTaxAdjustments(delegator, prod, productStore, payToPartyId, billToPartyId, + taxAuthoritySet, ZERO_BASE, ZERO_BASE, ZERO_BASE, orderShippingAmount, null, productWeight.get(prod)); + orderAdjustments.addAll(taxList); + } } if (orderPromotionsAmount != null && orderPromotionsAmount.compareTo(BigDecimal.ZERO) != 0) { List taxList = getTaxAdjustments(delegator, null, productStore, payToPartyId, billToPartyId, @@ -300,7 +300,7 @@ public class TaxAuthorityServices { } private static void getTaxAuthorities(Delegator delegator, GenericValue shippingAddress, - Set taxAuthoritySet) throws GenericEntityException { + Set taxAuthoritySet) throws GenericEntityException { Map geoIdByTypeMap = new HashMap<>(); if (shippingAddress != null) { if (UtilValidate.isNotEmpty(shippingAddress.getString("countryGeoId"))) { @@ -332,13 +332,13 @@ public class TaxAuthorityServices { } private static List getTaxAdjustments(Delegator delegator, GenericValue product, - GenericValue productStore, - String payToPartyId, String billToPartyId, Set taxAuthoritySet, - BigDecimal itemPrice, BigDecimal itemQuantity, BigDecimal itemAmount, - BigDecimal shippingAmount, BigDecimal orderPromotionsAmount) { - return getTaxAdjustments(delegator, product, productStore, payToPartyId, billToPartyId, - taxAuthoritySet, itemPrice, itemQuantity, itemAmount, shippingAmount, - orderPromotionsAmount, null); + GenericValue productStore, + String payToPartyId, String billToPartyId, Set taxAuthoritySet, + BigDecimal itemPrice, BigDecimal itemQuantity, BigDecimal itemAmount, + BigDecimal shippingAmount, BigDecimal orderPromotionsAmount) { + return getTaxAdjustments(delegator, product, productStore, payToPartyId, billToPartyId, + taxAuthoritySet, itemPrice, itemQuantity, itemAmount, shippingAmount, + orderPromotionsAmount, null); } private static List getTaxAdjustments(Delegator delegator, GenericValue product, diff --git a/applications/accounting/src/main/java/org/apache/ofbiz/accounting/thirdparty/authorizedotnet/AIMPaymentServices.java b/applications/accounting/src/main/java/org/apache/ofbiz/accounting/thirdparty/authorizedotnet/AIMPaymentServices.java index 80eec2a255..c54429da9d 100644 --- a/applications/accounting/src/main/java/org/apache/ofbiz/accounting/thirdparty/authorizedotnet/AIMPaymentServices.java +++ b/applications/accounting/src/main/java/org/apache/ofbiz/accounting/thirdparty/authorizedotnet/AIMPaymentServices.java @@ -754,29 +754,29 @@ public class AIMPaymentServices { private static void processAuthCaptureTransResult(Map request, Map reply, Map results) { AuthorizeResponse ar = (AuthorizeResponse) reply.get("authorizeResponse"); try { - Boolean authResult = (Boolean) reply.get("authResult"); - results.put("authResult", authResult); - results.put("authFlag", ar.getReasonCode()); - results.put("authMessage", ar.getReasonText()); - results.put("captureResult", authResult); - results.put("captureFlag", ar.getReasonCode()); - results.put("captureMessage", ar.getReasonText()); - results.put("captureRefNum", ar.getTransactionId()); - if (authResult) { //passed - results.put("authCode", ar.getAuthorizationCode()); - results.put("authRefNum", ar.getTransactionId()); - results.put("cvCode", ar.getCvResult()); - results.put("avsCode", ar.getAvsResult()); - if (BigDecimal.ZERO.compareTo(ar.getAmount()) == 0) { - results.put("processAmount", getXAmount(request)); + Boolean authResult = (Boolean) reply.get("authResult"); + results.put("authResult", authResult); + results.put("authFlag", ar.getReasonCode()); + results.put("authMessage", ar.getReasonText()); + results.put("captureResult", authResult); + results.put("captureFlag", ar.getReasonCode()); + results.put("captureMessage", ar.getReasonText()); + results.put("captureRefNum", ar.getTransactionId()); + if (authResult) { //passed + results.put("authCode", ar.getAuthorizationCode()); + results.put("authRefNum", ar.getTransactionId()); + results.put("cvCode", ar.getCvResult()); + results.put("avsCode", ar.getAvsResult()); + if (BigDecimal.ZERO.compareTo(ar.getAmount()) == 0) { + results.put("processAmount", getXAmount(request)); + } else { + results.put("processAmount", ar.getAmount()); + } } else { - results.put("processAmount", ar.getAmount()); + results.put("authCode", ar.getResponseCode()); + results.put("processAmount", BigDecimal.ZERO); + results.put("authRefNum", AuthorizeResponse.ERROR); } - } else { - results.put("authCode", ar.getResponseCode()); - results.put("processAmount", BigDecimal.ZERO); - results.put("authRefNum", AuthorizeResponse.ERROR); - } } catch (Exception ex) { Debug.logError(ex, MODULE); results.put("authCode", ar.getResponseCode()); @@ -791,7 +791,8 @@ public class AIMPaymentServices { String returnValue = ""; if (UtilValidate.isNotEmpty(paymentGatewayConfigId)) { try { - GenericValue payflowPro = EntityQuery.use(delegator).from("PaymentGatewayAuthorizeNet").where("paymentGatewayConfigId", paymentGatewayConfigId).queryOne(); + GenericValue payflowPro = EntityQuery.use(delegator).from("PaymentGatewayAuthorizeNet").where("paymentGatewayConfigId", + paymentGatewayConfigId).queryOne(); if (payflowPro != null) { Object payflowProField = payflowPro.get(paymentGatewayConfigParameterName); if (payflowProField != null) { diff --git a/applications/accounting/src/main/java/org/apache/ofbiz/accounting/thirdparty/orbital/OrbitalPaymentServices.java b/applications/accounting/src/main/java/org/apache/ofbiz/accounting/thirdparty/orbital/OrbitalPaymentServices.java index 59da857f74..7feff8e2c6 100644 --- a/applications/accounting/src/main/java/org/apache/ofbiz/accounting/thirdparty/orbital/OrbitalPaymentServices.java +++ b/applications/accounting/src/main/java/org/apache/ofbiz/accounting/thirdparty/orbital/OrbitalPaymentServices.java @@ -598,17 +598,17 @@ public class OrbitalPaymentServices { private static void printTransResult(ResponseIF response) { Map generatedResponse = new HashMap<>(); - generatedResponse.put("isGood", response.isGood()); + generatedResponse.put("isGood", response.isGood()); generatedResponse.put("isError", response.isError()); - generatedResponse.put("isQuickResponse", response.isQuickResponse()); + generatedResponse.put("isQuickResponse", response.isQuickResponse()); generatedResponse.put("isApproved", response.isApproved()); - generatedResponse.put("isDeclined", response.isDeclined()); - generatedResponse.put("AuthCode", response.getAuthCode()); - generatedResponse.put("TxRefNum", response.getTxRefNum()); - generatedResponse.put("ResponseCode", response.getResponseCode()); - generatedResponse.put("Status", response.getStatus()); - generatedResponse.put("Message", response.getMessage()); - generatedResponse.put("AVSCode", response.getAVSResponseCode()); + generatedResponse.put("isDeclined", response.isDeclined()); + generatedResponse.put("AuthCode", response.getAuthCode()); + generatedResponse.put("TxRefNum", response.getTxRefNum()); + generatedResponse.put("ResponseCode", response.getResponseCode()); + generatedResponse.put("Status", response.getStatus()); + generatedResponse.put("Message", response.getMessage()); + generatedResponse.put("AVSCode", response.getAVSResponseCode()); generatedResponse.put("CVV2ResponseCode", response.getCVV2RespCode()); Debug.logInfo("printTransResult === " + generatedResponse.toString(), MODULE); diff --git a/applications/accounting/src/main/java/org/apache/ofbiz/accounting/thirdparty/paypal/PayPalEvents.java b/applications/accounting/src/main/java/org/apache/ofbiz/accounting/thirdparty/paypal/PayPalEvents.java index 33e3bc2e08..607cd3a211 100644 --- a/applications/accounting/src/main/java/org/apache/ofbiz/accounting/thirdparty/paypal/PayPalEvents.java +++ b/applications/accounting/src/main/java/org/apache/ofbiz/accounting/thirdparty/paypal/PayPalEvents.java @@ -135,15 +135,17 @@ public class PayPalEvents { String imageUrl = getPaymentGatewayConfigValue(delegator, paymentGatewayConfigId, "imageUrl", configString, "payment.paypal.image"); // get the paypal account - String payPalAccount = getPaymentGatewayConfigValue(delegator, paymentGatewayConfigId, "businessEmail", configString, "payment.paypal.business"); + String payPalAccount = getPaymentGatewayConfigValue(delegator, paymentGatewayConfigId, "businessEmail", configString, "payment.paypal" + + ".business"); if (UtilValidate.isEmpty(redirectUrl) - || UtilValidate.isEmpty(notifyUrl) - || UtilValidate.isEmpty(returnUrl) - || UtilValidate.isEmpty(imageUrl) - || UtilValidate.isEmpty(payPalAccount)) { + || UtilValidate.isEmpty(notifyUrl) + || UtilValidate.isEmpty(returnUrl) + || UtilValidate.isEmpty(imageUrl) + || UtilValidate.isEmpty(payPalAccount)) { Debug.logError("Payment properties is not configured properly, some notify URL from PayPal is not correctly defined!", MODULE); - request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(RES_ERROR, "payPalEvents.problemsGettingMerchantConfiguration", locale)); + request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(RES_ERROR, "payPalEvents.problemsGettingMerchantConfiguration", + locale)); return "error"; } diff --git a/applications/accounting/src/main/java/org/apache/ofbiz/accounting/thirdparty/paypal/PayPalServices.java b/applications/accounting/src/main/java/org/apache/ofbiz/accounting/thirdparty/paypal/PayPalServices.java index 31759a1a6e..bab1e676be 100644 --- a/applications/accounting/src/main/java/org/apache/ofbiz/accounting/thirdparty/paypal/PayPalServices.java +++ b/applications/accounting/src/main/java/org/apache/ofbiz/accounting/thirdparty/paypal/PayPalServices.java @@ -714,7 +714,7 @@ public class PayPalServices { Map errorMessages = getErrorMessageMap(decoder); if (UtilValidate.isNotEmpty(errorMessages)) { if (errorMessages.containsKey("10417")) { - // "The transaction cannot complete successfully, Instruct the customer to use an alternative payment method" + // "The transaction cannot complete successfully, Instruct the customer to use an alternative payment method" // I've only encountered this once and there's no indication of the cause so the temporary solution is to try again boolean retry = context.get("_RETRY_") == null || (Boolean) context.get("_RETRY_"); if (retry) { diff --git a/applications/accounting/src/main/java/org/apache/ofbiz/accounting/thirdparty/sagepay/SagePayPaymentServices.java b/applications/accounting/src/main/java/org/apache/ofbiz/accounting/thirdparty/sagepay/SagePayPaymentServices.java index 56d9ebbe1d..2e7a8b9402 100644 --- a/applications/accounting/src/main/java/org/apache/ofbiz/accounting/thirdparty/sagepay/SagePayPaymentServices.java +++ b/applications/accounting/src/main/java/org/apache/ofbiz/accounting/thirdparty/sagepay/SagePayPaymentServices.java @@ -138,7 +138,7 @@ public class SagePayPaymentServices { billingInfo.put("currency", currency); billingInfo.put("description", orderId); billingInfo.put("cardNumber", cardNumber); - billingInfo.put("cardHolder", nameOnCard); + billingInfo.put("cardHolder", nameOnCard); billingInfo.put("expiryDate", expireDate); billingInfo.put("cardType", cardType); billingInfo.put("cv2", securityCode); diff --git a/applications/accounting/src/main/java/org/apache/ofbiz/accounting/thirdparty/sagepay/SagePayServices.java b/applications/accounting/src/main/java/org/apache/ofbiz/accounting/thirdparty/sagepay/SagePayServices.java index 4f57a94acd..9dfde0b1b7 100644 --- a/applications/accounting/src/main/java/org/apache/ofbiz/accounting/thirdparty/sagepay/SagePayServices.java +++ b/applications/accounting/src/main/java/org/apache/ofbiz/accounting/thirdparty/sagepay/SagePayServices.java @@ -42,8 +42,7 @@ import org.apache.ofbiz.service.DispatchContext; import org.apache.ofbiz.service.ModelService; import org.apache.ofbiz.service.ServiceUtil; -public class SagePayServices -{ +public class SagePayServices { private static final String MODULE = SagePayServices.class.getName(); private static final String RESOURCE = "AccountingUiLabels"; @@ -147,58 +146,138 @@ public class SagePayServices parameters.put("TxType", txType); parameters.put("Vendor", vendor); - if (vendorTxCode != null) {parameters.put("VendorTxCode", vendorTxCode); } - if (amount != null) {parameters.put("Amount", amount); } - if (currency != null) {parameters.put("Currency", currency); } //GBP/USD - if (description != null) {parameters.put("Description", description); } - if (cardHolder != null) {parameters.put("CardHolder", cardHolder); } - if (cardNumber != null) {parameters.put("CardNumber", cardNumber); } - if (expiryDate != null) {parameters.put("ExpiryDate", expiryDate); } - if (cardType != null) {parameters.put("CardType", cardType); } + if (vendorTxCode != null) { + parameters.put("VendorTxCode", vendorTxCode); + } + if (amount != null) { + parameters.put("Amount", amount); + } + if (currency != null) { + parameters.put("Currency", currency); + } //GBP/USD + if (description != null) { + parameters.put("Description", description); + } + if (cardHolder != null) { + parameters.put("CardHolder", cardHolder); + } + if (cardNumber != null) { + parameters.put("CardNumber", cardNumber); + } + if (cardType != null) { + parameters.put("CardType", cardType); + } + if (expiryDate != null) { + parameters.put("ExpiryDate", expiryDate); + } //start - billing details - if (billingSurname != null) {parameters.put("BillingSurname", billingSurname); } - if (billingFirstnames != null) {parameters.put("BillingFirstnames", billingFirstnames); } - if (billingAddress != null) {parameters.put("BillingAddress", billingAddress); } - if (billingAddress2 != null) {parameters.put("BillingAddress2", billingAddress2); } - if (billingCity != null) {parameters.put("BillingCity", billingCity); } - if (billingPostCode != null) {parameters.put("BillingPostCode", billingPostCode); } - if (billingCountry != null) {parameters.put("BillingCountry", billingCountry); } - if (billingState != null) {parameters.put("BillingState", billingState); } - if (billingPhone != null) {parameters.put("BillingPhone", billingPhone); } + if (billingSurname != null) { + parameters.put("BillingSurname", billingSurname); + } + if (billingFirstnames != null) { + parameters.put("BillingFirstnames", billingFirstnames); + } + if (billingAddress != null) { + parameters.put("BillingAddress", billingAddress); + } + if (billingAddress2 != null) { + parameters.put("BillingAddress2", billingAddress2); + } + if (billingCity != null) { + parameters.put("BillingCity", billingCity); + } + if (billingPostCode != null) { + parameters.put("BillingPostCode", billingPostCode); + } + if (billingCountry != null) { + parameters.put("BillingCountry", billingCountry); + } + if (billingState != null) { + parameters.put("BillingState", billingState); + } + if (billingPhone != null) { + parameters.put("BillingPhone", billingPhone); + } //end - billing details //start - delivery details if (isBillingSameAsDelivery != null && isBillingSameAsDelivery) { - if (billingSurname != null) {parameters.put("DeliverySurname", billingSurname); } - if (billingFirstnames != null) {parameters.put("DeliveryFirstnames", billingFirstnames); } - if (billingAddress != null) {parameters.put("DeliveryAddress", billingAddress); } - if (billingAddress2 != null) {parameters.put("DeliveryAddress2", billingAddress2); } - if (billingCity != null) {parameters.put("DeliveryCity", billingCity); } - if (billingPostCode != null) {parameters.put("DeliveryPostCode", billingPostCode); } - if (billingCountry != null) {parameters.put("DeliveryCountry", billingCountry); } - if (billingState != null) {parameters.put("DeliveryState", billingState); } - if (billingPhone != null) {parameters.put("DeliveryPhone", billingPhone); } + if (billingSurname != null) { + parameters.put("DeliverySurname", billingSurname); + } + if (billingFirstnames != null) { + parameters.put("DeliveryFirstnames", billingFirstnames); + } + if (billingAddress != null) { + parameters.put("DeliveryAddress", billingAddress); + } + if (billingAddress2 != null) { + parameters.put("DeliveryAddress2", billingAddress2); + } + if (billingCity != null) { + parameters.put("DeliveryCity", billingCity); + } + if (billingPostCode != null) { + parameters.put("DeliveryPostCode", billingPostCode); + } + if (billingCountry != null) { + parameters.put("DeliveryCountry", billingCountry); + } + if (billingState != null) { + parameters.put("DeliveryState", billingState); + } + if (billingPhone != null) { + parameters.put("DeliveryPhone", billingPhone); + } } else { - if (deliverySurname != null) {parameters.put("DeliverySurname", deliverySurname); } - if (deliveryFirstnames != null) {parameters.put("DeliveryFirstnames", deliveryFirstnames); } - if (deliveryAddress != null) {parameters.put("DeliveryAddress", deliveryAddress); } - if (deliveryAddress2 != null) {parameters.put("DeliveryAddress2", deliveryAddress2); } - if (deliveryCity != null) {parameters.put("DeliveryCity", deliveryCity); } - if (deliveryPostCode != null) {parameters.put("DeliveryPostCode", deliveryPostCode); } - if (deliveryCountry != null) {parameters.put("DeliveryCountry", deliveryCountry); } - if (deliveryState != null) {parameters.put("DeliveryState", deliveryState); } - if (deliveryPhone != null) {parameters.put("DeliveryPhone", deliveryPhone); } + if (deliverySurname != null) { + parameters.put("DeliverySurname", deliverySurname); + } + if (deliveryFirstnames != null) { + parameters.put("DeliveryFirstnames", deliveryFirstnames); + } + if (deliveryAddress != null) { + parameters.put("DeliveryAddress", deliveryAddress); + } + if (deliveryAddress2 != null) { + parameters.put("DeliveryAddress2", deliveryAddress2); + } + if (deliveryCity != null) { + parameters.put("DeliveryCity", deliveryCity); + } + if (deliveryPostCode != null) { + parameters.put("DeliveryPostCode", deliveryPostCode); + } + if (deliveryCountry != null) { + parameters.put("DeliveryCountry", deliveryCountry); + } + if (deliveryState != null) { + parameters.put("DeliveryState", deliveryState); + } + if (deliveryPhone != null) { + parameters.put("DeliveryPhone", deliveryPhone); + } } //end - delivery details //end - required parameters //start - optional parameters - if (cv2 != null) {parameters.put("CV2", cv2); } - if (startDate != null) {parameters.put("StartDate", startDate); } - if (issueNumber != null) {parameters.put("IssueNumber", issueNumber); } - if (basket != null) {parameters.put("Basket", basket); } - if (clientIPAddress != null) {parameters.put("ClientIPAddress", clientIPAddress); } + if (cv2 != null) { + parameters.put("CV2", cv2); + } + if (startDate != null) { + parameters.put("StartDate", startDate); + } + if (issueNumber != null) { + parameters.put("IssueNumber", issueNumber); + } + if (basket != null) { + parameters.put("Basket", basket); + } + if (clientIPAddress != null) { + parameters.put("ClientIPAddress", clientIPAddress); + } //end - optional parameters //end - authentication parameters diff --git a/applications/accounting/src/main/java/org/apache/ofbiz/accounting/thirdparty/sagepay/SagePayUtil.java b/applications/accounting/src/main/java/org/apache/ofbiz/accounting/thirdparty/sagepay/SagePayUtil.java index 57a247b810..c351f709bb 100644 --- a/applications/accounting/src/main/java/org/apache/ofbiz/accounting/thirdparty/sagepay/SagePayUtil.java +++ b/applications/accounting/src/main/java/org/apache/ofbiz/accounting/thirdparty/sagepay/SagePayUtil.java @@ -31,6 +31,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; + import org.apache.http.HttpEntity; import org.apache.http.HttpHost; import org.apache.http.HttpResponse; @@ -46,79 +47,144 @@ import org.apache.ofbiz.base.util.Debug; public final class SagePayUtil { private static final String MODULE = SagePayUtil.class.getName(); - private SagePayUtil() { } - public static Map buildCardAuthorisationPaymentResponse - (Boolean authResult, String authCode, String authFlag, BigDecimal processAmount, String authRefNum, String authAltRefNum, String authMessage) { + private SagePayUtil() { + } + + public static Map buildCardAuthorisationPaymentResponse(Boolean authResult, + String authCode, String authFlag, BigDecimal processAmount, String authRefNum, String authAltRefNum, String authMessage) { Map result = new HashMap<>(); - if (authResult != null) {result.put("authResult", authResult); } - if (authCode != null) {result.put("authCode", authCode); } - if (authFlag != null) {result.put("authFlag", authFlag); } - if (processAmount != null) {result.put("processAmount", processAmount); } - if (authRefNum != null) {result.put("authRefNum", authRefNum); } - if (authAltRefNum != null) {result.put("authAltRefNum", authAltRefNum); } - if (authMessage != null) {result.put("authMessage", authMessage); } + if (authResult != null) { + result.put("authResult", authResult); + } + if (authCode != null) { + result.put("authCode", authCode); + } + if (authFlag != null) { + result.put("authFlag", authFlag); + } + if (processAmount != null) { + result.put("processAmount", processAmount); + } + if (authRefNum != null) { + result.put("authRefNum", authRefNum); + } + if (authAltRefNum != null) { + result.put("authAltRefNum", authAltRefNum); + } + if (authMessage != null) { + result.put("authMessage", authMessage); + } return result; } - public static Map buildCardCapturePaymentResponse - (Boolean captureResult, String captureCode, String captureFlag, BigDecimal captureAmount, String captureRefNum, String captureAltRefNum, String captureMessage) { + public static Map buildCardCapturePaymentResponse(Boolean captureResult, + String captureCode, String captureFlag, BigDecimal captureAmount, String captureRefNum, String captureAltRefNum, String captureMessage) { Map result = new HashMap<>(); - if (captureResult != null) {result.put("captureResult", captureResult); } - if (captureCode != null) {result.put("captureCode", captureCode); } - if (captureFlag != null) {result.put("captureFlag", captureFlag); } - if (captureAmount != null) {result.put("captureAmount", captureAmount); } - if (captureRefNum != null) {result.put("captureRefNum", captureRefNum); } - if (captureAltRefNum != null) {result.put("captureAltRefNum", captureAltRefNum); } - if (captureMessage != null) {result.put("captureMessage", captureMessage); } + if (captureResult != null) { + result.put("captureResult", captureResult); + } + if (captureCode != null) { + result.put("captureCode", captureCode); + } + if (captureFlag != null) { + result.put("captureFlag", captureFlag); + } + if (captureAmount != null) { + result.put("captureAmount", captureAmount); + } + if (captureRefNum != null) { + result.put("captureRefNum", captureRefNum); + } + if (captureAltRefNum != null) { + result.put("captureAltRefNum", captureAltRefNum); + } + if (captureMessage != null) { + result.put("captureMessage", captureMessage); + } return result; } - public static Map buildCardReleasePaymentResponse - (Boolean releaseResult, String releaseCode, BigDecimal releaseAmount, String releaseRefNum, String releaseAltRefNum, String releaseMessage) { + public static Map buildCardReleasePaymentResponse(Boolean releaseResult, + String releaseCode, BigDecimal releaseAmount, String releaseRefNum, String releaseAltRefNum, String releaseMessage) { Map result = new HashMap<>(); - if (releaseResult != null) {result.put("releaseResult", releaseResult); } - if (releaseCode != null) {result.put("releaseCode", releaseCode); } - if (releaseAmount != null) {result.put("releaseAmount", releaseAmount); } - if (releaseRefNum != null) {result.put("releaseRefNum", releaseRefNum); } - if (releaseAltRefNum != null) {result.put("releaseAltRefNum", releaseAltRefNum); } - if (releaseMessage != null) {result.put("releaseMessage", releaseMessage); } + if (releaseResult != null) { + result.put("releaseResult", releaseResult); + } + if (releaseCode != null) { + result.put("releaseCode", releaseCode); + } + if (releaseAmount != null) { + result.put("releaseAmount", releaseAmount); + } + if (releaseRefNum != null) { + result.put("releaseRefNum", releaseRefNum); + } + if (releaseAltRefNum != null) { + result.put("releaseAltRefNum", releaseAltRefNum); + } + if (releaseMessage != null) { + result.put("releaseMessage", releaseMessage); + } return result; } - public static Map buildCardVoidPaymentResponse - (Boolean refundResult, BigDecimal refundAmount, String refundRefNum, String refundAltRefNum, String refundMessage) { + public static Map buildCardVoidPaymentResponse(Boolean refundResult, + BigDecimal refundAmount, String refundRefNum, String refundAltRefNum, String refundMessage) { Map result = new HashMap<>(); - if (refundResult != null) {result.put("refundResult", refundResult); } - if (refundAmount != null) {result.put("refundAmount", refundAmount); } - if (refundRefNum != null) {result.put("refundRefNum", refundRefNum); } - if (refundAltRefNum != null) {result.put("refundAltRefNum", refundAltRefNum); } - if (refundMessage != null) {result.put("refundMessage", refundMessage); } + if (refundResult != null) { + result.put("refundResult", refundResult); + } + if (refundAmount != null) { + result.put("refundAmount", refundAmount); + } + if (refundRefNum != null) { + result.put("refundRefNum", refundRefNum); + } + if (refundAltRefNum != null) { + result.put("refundAltRefNum", refundAltRefNum); + } + if (refundMessage != null) { + result.put("refundMessage", refundMessage); + } return result; } - public static Map buildCardRefundPaymentResponse - (Boolean refundResult, String refundCode, BigDecimal refundAmount, String refundRefNum, String refundAltRefNum, String refundMessage) { + public static Map buildCardRefundPaymentResponse(Boolean refundResult, + String refundCode, BigDecimal refundAmount, String refundRefNum, String refundAltRefNum, String refundMessage) { Map result = new HashMap<>(); - if (refundResult != null) {result.put("refundResult", refundResult); } - if (refundCode != null) {result.put("refundCode", refundCode); } - if (refundAmount != null) {result.put("refundAmount", refundAmount); } - if (refundRefNum != null) {result.put("refundRefNum", refundRefNum); } - if (refundAltRefNum != null) {result.put("refundAltRefNum", refundAltRefNum); } - if (refundMessage != null) {result.put("refundMessage", refundMessage); } + if (refundResult != null) { + result.put("refundResult", refundResult); + } + if (refundCode != null) { + result.put("refundCode", refundCode); + } + if (refundAmount != null) { + result.put("refundAmount", refundAmount); + } + if (refundRefNum != null) { + result.put("refundRefNum", refundRefNum); + } + if (refundAltRefNum != null) { + result.put("refundAltRefNum", refundAltRefNum); + } + if (refundMessage != null) { + result.put("refundMessage", refundMessage); + } return result; } /** * Builds HttpHost with the given SagePayProperties. + * * @param props SagePay properties - * @throws IllegalArgumentException if neither productionHost nor testingHost found in properties. * @return + * @throws IllegalArgumentException if neither productionHost nor testingHost found in properties. */ public static HttpHost getHost(Map props) { String hostUrl = null; diff --git a/applications/accounting/src/main/java/org/apache/ofbiz/accounting/thirdparty/securepay/SecurePayServiceTest.java b/applications/accounting/src/main/java/org/apache/ofbiz/accounting/thirdparty/securepay/SecurePayServiceTest.java index 26e561cb8a..5aedd27a48 100644 --- a/applications/accounting/src/main/java/org/apache/ofbiz/accounting/thirdparty/securepay/SecurePayServiceTest.java +++ b/applications/accounting/src/main/java/org/apache/ofbiz/accounting/thirdparty/securepay/SecurePayServiceTest.java @@ -67,7 +67,7 @@ public class SecurePayServiceTest extends OFBizTestCase { orderId = "Demo1002"; creditCard = delegator.makeValue("CreditCard", UtilMisc.toMap( "cardType", "CCT_VISA", - "expireDate", "10/2011", // mm/yyyy, gets converted to mm/yy + "expireDate", "10/2011", // mm/yyyy, gets converted to mm/yy "cardNumber", "4444333322221111")); billingAddress = delegator.makeValue("PostalAddress", UtilMisc.toMap( "toName", "The customer Name", diff --git a/applications/accounting/src/main/java/org/apache/ofbiz/accounting/thirdparty/valuelink/ValueLinkApi.java b/applications/accounting/src/main/java/org/apache/ofbiz/accounting/thirdparty/valuelink/ValueLinkApi.java index e1dd58dc97..f042f80191 100644 --- a/applications/accounting/src/main/java/org/apache/ofbiz/accounting/thirdparty/valuelink/ValueLinkApi.java +++ b/applications/accounting/src/main/java/org/apache/ofbiz/accounting/thirdparty/valuelink/ValueLinkApi.java @@ -419,7 +419,7 @@ public class ValueLinkApi { byte[] secretKey = ka.generateSecret(); if (debug) { - Debug.logInfo("Secret Key : " + StringUtil.toHexString(secretKey) + " / " + secretKey.length, MODULE); + Debug.logInfo("Secret Key : " + StringUtil.toHexString(secretKey) + " / " + secretKey.length, MODULE); } // generate 3DES from secret key using VL algorithm (KEK) diff --git a/applications/accounting/src/main/java/org/apache/ofbiz/accounting/thirdparty/verisign/PayflowPro.java b/applications/accounting/src/main/java/org/apache/ofbiz/accounting/thirdparty/verisign/PayflowPro.java index f6a5755d2a..a4a74c8fdc 100644 --- a/applications/accounting/src/main/java/org/apache/ofbiz/accounting/thirdparty/verisign/PayflowPro.java +++ b/applications/accounting/src/main/java/org/apache/ofbiz/accounting/thirdparty/verisign/PayflowPro.java @@ -108,7 +108,7 @@ public class PayflowPro { data.put("CUSTCODE", party.getString("partyId")); // transaction type - if (comparePaymentGatewayConfigValue(delegator, paymentGatewayConfigId, "preAuth", configString, "payment.verisign.preAuth", "Y")) { + if (comparePaymentGatewayConfigValue(delegator, paymentGatewayConfigId, "preAuth", configString, "payment.verisign.preAuth", "Y")) { data.put("TRXTYPE", "A"); // only support re-auth for auth types; sale types don't do it if (authTrans != null) { @@ -147,7 +147,7 @@ public class PayflowPro { // gather the address info if (ps != null) { String street = ps.getString("address1") + ((UtilValidate.isNotEmpty(ps.getString("address2"))) ? " " + ps.getString("address2") : ""); - data.put("STREET"+"["+street.length()+"]", street); + data.put("STREET" + "[" + street.length() + "]", street); data.put("ZIP", ps.getString("postalCode")); } } @@ -168,7 +168,7 @@ public class PayflowPro { Debug.logVerbose("Sending to Verisign: " + params.toString(), MODULE); } String resp; - if (!comparePaymentGatewayConfigValue(delegator, paymentGatewayConfigId, "enableTransmit", configString, "payment.verisign.enable_transmit", "false")) { + if (!comparePaymentGatewayConfigValue(delegator, paymentGatewayConfigId, "enableTransmit", configString, "payment.verisign.enable_transmit", "false")) { resp = pfp.submitTransaction(params.toString(), pfp.generateRequestId()); } else { resp = "RESULT=0&AUTHCODE=T&PNREF=" + (new Date()).getTime() + "&RESPMSG=Testing"; @@ -253,7 +253,7 @@ public class PayflowPro { Debug.logVerbose("Sending to Verisign: " + params.toString(), MODULE); } String resp; - if (!comparePaymentGatewayConfigValue(delegator, paymentGatewayConfigId, "enableTransmit", configString, "payment.verisign.enable_transmit", "false")) { + if (!comparePaymentGatewayConfigValue(delegator, paymentGatewayConfigId, "enableTransmit", configString, "payment.verisign.enable_transmit", "false")) { resp = pfp.submitTransaction(params.toString(), pfp.generateRequestId()); } else { resp = "RESULT=0&AUTHCODE=T&PNREF=" + (new Date()).getTime() + "&RESPMSG=Testing"; @@ -335,7 +335,7 @@ public class PayflowPro { Debug.logVerbose("Sending to Verisign: " + params.toString(), MODULE); } String resp; - if (!comparePaymentGatewayConfigValue(delegator, paymentGatewayConfigId, "enableTransmit", configString, "payment.verisign.enable_transmit", "false")) { + if (!comparePaymentGatewayConfigValue(delegator, paymentGatewayConfigId, "enableTransmit", configString, "payment.verisign.enable_transmit", "false")) { resp = pfp.submitTransaction(params.toString(), pfp.generateRequestId()); } else { resp = "RESULT=0&AUTHCODE=T&PNREF=" + (new Date()).getTime() + "&RESPMSG=Testing"; @@ -416,7 +416,7 @@ public class PayflowPro { Debug.logVerbose("Sending to Verisign: " + params.toString(), MODULE); } String resp; - if (!comparePaymentGatewayConfigValue(delegator, paymentGatewayConfigId, "enableTransmit", configString, "payment.verisign.enable_transmit", "false")) { + if (!comparePaymentGatewayConfigValue(delegator, paymentGatewayConfigId, "enableTransmit", configString, "payment.verisign.enable_transmit", "false")) { resp = pfp.submitTransaction(params.toString(), pfp.generateRequestId()); } else { resp = "RESULT=0&AUTHCODE=T&PNREF=" + (new Date()).getTime() + "&RESPMSG=Testing"; @@ -480,7 +480,7 @@ public class PayflowPro { Debug.logVerbose("Sending to Verisign: " + params.toString(), MODULE); } String resp; - if (!comparePaymentGatewayConfigValue(delegator, paymentGatewayConfigId, "enableTransmit", configString, "payment.verisign.enable_transmit", "false")) { + if (!comparePaymentGatewayConfigValue(delegator, paymentGatewayConfigId, "enableTransmit", configString, "payment.verisign.enable_transmit", "false")) { resp = pfp.submitTransaction(params.toString(), pfp.generateRequestId()); } else { resp = "RESULT=0&TOKEN=" + (new Date()).getTime() + "&RESPMSG=Testing"; @@ -583,7 +583,7 @@ public class PayflowPro { Debug.logVerbose("Sending to Verisign: " + params.toString(), MODULE); } String resp; - if (!comparePaymentGatewayConfigValue(delegator, paymentGatewayConfigId, "enableTransmit", configString, "payment.verisign.enable_transmit", "false")) { + if (!comparePaymentGatewayConfigValue(delegator, paymentGatewayConfigId, "enableTransmit", configString, "payment.verisign.enable_transmit", "false")) { resp = pfp.submitTransaction(params.toString(), pfp.generateRequestId()); } else { resp = "RESULT=0&PAYERID=" + (new Date()).getTime() + "&RESPMSG=Testing"; @@ -664,7 +664,7 @@ public class PayflowPro { Debug.logVerbose("Sending to Verisign: " + params.toString(), MODULE); } String resp; - if (!comparePaymentGatewayConfigValue(delegator, paymentGatewayConfigId, "enableTransmit", configString, "payment.verisign.enable_transmit", "false")) { + if (!comparePaymentGatewayConfigValue(delegator, paymentGatewayConfigId, "enableTransmit", configString, "payment.verisign.enable_transmit", "false")) { resp = pfp.submitTransaction(params.toString(), pfp.generateRequestId()); } else { resp = "RESULT=0&PAYERID=" + (new Date()).getTime() + "&RESPMSG=Testing"; diff --git a/applications/content/src/main/java/org/apache/ofbiz/content/ContentManagementEvents.java b/applications/content/src/main/java/org/apache/ofbiz/content/ContentManagementEvents.java index 0a3151d963..cf126b23b9 100644 --- a/applications/content/src/main/java/org/apache/ofbiz/content/ContentManagementEvents.java +++ b/applications/content/src/main/java/org/apache/ofbiz/content/ContentManagementEvents.java @@ -120,16 +120,16 @@ public class ContentManagementEvents { } } else if (UtilValidate.isNotEmpty(pubValue)) { if ("Y".equalsIgnoreCase(pubValue)) { - serviceIn.put("thruDate", UtilDateTime.nowTimestamp()); - Timestamp fromDate = (Timestamp) map.get(pubContentId + "FromDate"); - serviceIn.put("fromDate", fromDate); - result = dispatcher.runSync("updateContentAssoc", serviceIn); - if (ServiceUtil.isError(result)) { - String errorMessage = ServiceUtil.getErrorMessage(result); - request.setAttribute("_ERROR_MESSAGE_", errorMessage); - Debug.logError(errorMessage, MODULE); - return "error"; - } + serviceIn.put("thruDate", UtilDateTime.nowTimestamp()); + Timestamp fromDate = (Timestamp) map.get(pubContentId + "FromDate"); + serviceIn.put("fromDate", fromDate); + result = dispatcher.runSync("updateContentAssoc", serviceIn); + if (ServiceUtil.isError(result)) { + String errorMessage = ServiceUtil.getErrorMessage(result); + request.setAttribute("_ERROR_MESSAGE_", errorMessage); + Debug.logError(errorMessage, MODULE); + return "error"; + } } } } catch (GenericServiceException e) { diff --git a/applications/content/src/main/java/org/apache/ofbiz/content/ContentManagementServices.java b/applications/content/src/main/java/org/apache/ofbiz/content/ContentManagementServices.java index 284c1e3dba..8d91954783 100644 --- a/applications/content/src/main/java/org/apache/ofbiz/content/ContentManagementServices.java +++ b/applications/content/src/main/java/org/apache/ofbiz/content/ContentManagementServices.java @@ -282,7 +282,7 @@ public class ContentManagementServices { Map thisResult = dispatcher.runSync("updateContent", contentContext); if (ServiceUtil.isError(thisResult) || ServiceUtil.isFailure(thisResult)) { return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ContentContentUpdatingError", UtilMisc.toMap("serviceName", - "persistContentAndAssoc"), locale), null, null, thisResult); + "persistContentAndAssoc"), locale), null, null, thisResult); } } else { Map contentContext = new HashMap<>(); @@ -295,7 +295,7 @@ public class ContentManagementServices { Map thisResult = dispatcher.runSync("createContent", contentContext); if (ServiceUtil.isError(thisResult) || ServiceUtil.isFailure(thisResult)) { return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ContentContentCreatingError", UtilMisc.toMap("serviceName", - "persistContentAndAssoc"), locale), null, null, thisResult); + "persistContentAndAssoc"), locale), null, null, thisResult); } contentId = (String) thisResult.get("contentId"); } @@ -309,7 +309,7 @@ public class ContentManagementServices { Set contentPurposeSet = new LinkedHashSet<>(contentPurposeList); for (String contentPurposeTypeId : contentPurposeSet) { GenericValue contentPurpose = delegator.makeValue("ContentPurpose", UtilMisc.toMap("contentId", contentId, - "contentPurposeTypeId", contentPurposeTypeId)); + "contentPurposeTypeId", contentPurposeTypeId)); contentPurpose.create(); } } catch (GenericEntityException e) { @@ -830,12 +830,12 @@ public class ContentManagementServices { } EntityCondition conditionType = EntityCondition.makeCondition("contentAssocTypeId", EntityOperator.IN, typeList); EntityCondition conditionMain = EntityCondition.makeCondition(UtilMisc.toList(EntityCondition.makeCondition("contentIdTo", - EntityOperator.EQUALS, contentIdTo), conditionType), EntityOperator.AND); + EntityOperator.EQUALS, contentIdTo), conditionType), EntityOperator.AND); try { List listAll = EntityQuery.use(delegator).from("ContentAssoc") - .where(conditionMain) - .orderBy("sequenceNum", "fromDate", "createdDate") - .filterByDate().queryList(); + .where(conditionMain) + .orderBy("sequenceNum", "fromDate", "createdDate") + .filterByDate().queryList(); String contentId = (String) context.get("contentId"); String dir = (String) context.get("dir"); int seqNum = seqIncrement; @@ -994,7 +994,7 @@ public class ContentManagementServices { thisContent = EntityQuery.use(delegator).from("Content").where("contentId", contentId).queryOne(); if (thisContent == null) { return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ContentNoContentFound", UtilMisc.toMap("contentId", contentId), - locale)); + locale)); } thisContent.set("contentTypeId", contentTypeId); thisContent.store(); @@ -1035,7 +1035,7 @@ public class ContentManagementServices { thisContent = EntityQuery.use(delegator).from("Content").where("contentId", contentId).queryOne(); if (thisContent == null) { return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, - "ContentNoContentFound", UtilMisc.toMap("contentId", contentId), locale)); + "ContentNoContentFound", UtilMisc.toMap("contentId", contentId), locale)); } thisContent.set("contentTypeId", "OUTLINE_NODE"); thisContent.store(); @@ -1047,7 +1047,7 @@ public class ContentManagementServices { kidContent.put("contentTypeId", "PAGE_NODE"); kidContent.store(); List kids2 = ContentWorker.getAssociatedContent(kidContent, "from", UtilMisc.toList("SUB_CONTENT"), null, null, - null); + null); for (GenericValue kidContent2 : kids2) { updatePageNodeChildren(kidContent2, context); } @@ -1162,11 +1162,11 @@ public class ContentManagementServices { String contentIdTo = (String) context.get("contentId"); try { List lst = EntityQuery.use(delegator).from("ContentAssocDataResourceViewFrom") - .where("caContentIdTo", contentIdTo, - "caContentAssocTypeId", "SUB_CONTENT", - "caThruDate", null) - .orderBy("caSequenceNum", "caFromDate", "createdDate") - .queryList(); + .where("caContentIdTo", contentIdTo, + "caContentAssocTypeId", "SUB_CONTENT", + "caThruDate", null) + .orderBy("caSequenceNum", "caFromDate", "createdDate") + .queryList(); results.put("_LIST_", lst); } catch (GenericEntityException e) { Debug.logError(e, MODULE); @@ -1221,7 +1221,7 @@ public class ContentManagementServices { GenericValue content = EntityQuery.use(delegator).from("Content").where("contentId", contentId).cache().queryOne(); if (content == null) { return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ContentNoContentFound", UtilMisc.toMap("contentId", contentId), - locale)); + locale)); } Long leafCount = (Long) content.get("childLeafCount"); if (leafCount == null) { @@ -1231,7 +1231,7 @@ public class ContentManagementServices { int changeBranchCount = 1; ContentManagementWorker.updateStatsBottomUp(delegator, contentId, UtilMisc.toList(contentAssocTypeId), changeBranchCount, - changeLeafCount); + changeLeafCount); } catch (GenericEntityException e) { return ServiceUtil.returnError(e.toString()); } @@ -1249,7 +1249,7 @@ public class ContentManagementServices { GenericValue content = EntityQuery.use(delegator).from("Content").where("contentId", contentId).cache().queryOne(); if (content == null) { return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ContentNoContentFound", UtilMisc.toMap("contentId", contentId), - locale)); + locale)); } Long leafCount = (Long) content.get("childLeafCount"); if (leafCount == null) { @@ -1259,7 +1259,7 @@ public class ContentManagementServices { int changeBranchCount = -1; ContentManagementWorker.updateStatsBottomUp(delegator, contentId, UtilMisc.toList(contentAssocTypeId), changeBranchCount, - changeLeafCount); + changeLeafCount); } catch (GenericEntityException e) { return ServiceUtil.returnError(e.toString()); } @@ -1303,10 +1303,10 @@ public class ContentManagementServices { GenericValue contentRole = null; try { contentRole = EntityQuery.use(delegator).from("ContentRole") - .where("partyId", partyId, "contentId", webPubPt, "roleTypeId", roleTypeId) - .orderBy("fromDate DESC") - .cache().filterByDate() - .queryFirst(); + .where("partyId", partyId, "contentId", webPubPt, "roleTypeId", roleTypeId) + .orderBy("fromDate DESC") + .cache().filterByDate() + .queryFirst(); if (contentRole != null) { hasExistingContentRole = true; } @@ -1386,12 +1386,12 @@ public class ContentManagementServices { GenericValue productContent = null; try { List lst = EntityQuery.use(delegator).from("ProductContent") - .where("productId", productId, "productContentTypeId", "ONLINE_ACCESS") - .orderBy("purchaseFromDate", "purchaseThruDate") - .filterByDate("purchaseFromDate", "purchaseThruDate") - .cache().queryList(); + .where("productId", productId, "productContentTypeId", "ONLINE_ACCESS") + .orderBy("purchaseFromDate", "purchaseThruDate") + .filterByDate("purchaseFromDate", "purchaseThruDate") + .cache().queryList(); List listThrusOnly = EntityUtil.filterOutByCondition(lst, EntityCondition.makeCondition("purchaseThruDate", - EntityOperator.EQUALS, null)); + EntityOperator.EQUALS, null)); if (listThrusOnly.size() > 0) { productContent = listThrusOnly.get(0); } else if (lst.size() > 0) { @@ -1437,8 +1437,8 @@ public class ContentManagementServices { GenericValue orderHeader = null; try { GenericValue orderRole = EntityQuery.use(delegator).from("OrderRole") - .where("orderId", orderId, "roleTypeId", "END_USER_CUSTOMER") - .queryFirst(); + .where("orderId", orderId, "roleTypeId", "END_USER_CUSTOMER") + .queryFirst(); if (orderRole != null) { String partyId = (String) orderRole.get("partyId"); context.put("partyId", partyId); @@ -1460,8 +1460,8 @@ public class ContentManagementServices { BigDecimal qty = orderItem.getBigDecimal("quantity"); String productId = (String) orderItem.get("productId"); long productContentCount = EntityQuery.use(delegator).from("ProductContent") - .where("productId", productId, "productContentTypeId", "ONLINE_ACCESS") - .filterByDate().queryCount(); + .where("productId", productId, "productContentTypeId", "ONLINE_ACCESS") + .filterByDate().queryCount(); if (productContentCount > 0) { context.put("productId", productId); context.put("quantity", qty.intValue()); @@ -1514,7 +1514,7 @@ public class ContentManagementServices { } public static Map followNodeChildrenMethod(GenericValue content, LocalDispatcher dispatcher, String serviceName, Map context) throws GenericEntityException, GenericServiceException { + Object> context) throws GenericEntityException, GenericServiceException { Map result = null; String contentId = content.getString("contentId"); List contentAssocTypeIdList = UtilGenerics.cast(context.get("contentAssocTypeIdList")); diff --git a/applications/content/src/main/java/org/apache/ofbiz/content/ContentManagementWorker.java b/applications/content/src/main/java/org/apache/ofbiz/content/ContentManagementWorker.java index 218dc35583..3fd62b7092 100644 --- a/applications/content/src/main/java/org/apache/ofbiz/content/ContentManagementWorker.java +++ b/applications/content/src/main/java/org/apache/ofbiz/content/ContentManagementWorker.java @@ -303,7 +303,7 @@ public final class ContentManagementWorker { } Map results = null; results = EntityPermissionChecker.checkPermission(content, statusId, userLogin, passedPurposes, targetOperationList, roles, delegator, - security, entityAction); + security, entityAction); String permissionStatus = (String) results.get("permissionStatus"); if (permissionStatus != null && "granted".equalsIgnoreCase(permissionStatus)) { String[] arr = {contentId, templateTitle}; @@ -323,8 +323,8 @@ public final class ContentManagementWorker { List relatedPubPts = null; try { relatedPubPts = EntityQuery.use(delegator).from("ContentAssoc") - .where("contentIdTo", parentPubPt, "contentAssocTypeId", "SUBSITE") - .cache().queryList(); + .where("contentIdTo", parentPubPt, "contentAssocTypeId", "SUBSITE") + .cache().queryList(); } catch (GenericEntityException e) { throw new GeneralException(e.getMessage()); } @@ -451,8 +451,8 @@ public final class ContentManagementWorker { public static String getParentWebSitePublishPointId(Delegator delegator, String contentId) throws GenericEntityException { String contentIdTo = null; GenericValue contentAssoc = EntityQuery.use(delegator).from("ContentAssoc") - .where("contentId", contentId, "contentAssocTypeId", "SUBSITE") - .filterByDate().cache().queryFirst(); + .where("contentId", contentId, "contentAssocTypeId", "SUBSITE") + .filterByDate().cache().queryFirst(); if (contentAssoc != null) { contentIdTo = contentAssoc.getString("contentIdTo"); } @@ -478,7 +478,7 @@ public final class ContentManagementWorker { // and another map (publishPointMapAll) that points to one of the top-level points. List allPublishPointList = getAllPublishPoints(delegator, rootPubId); List publishPointList = getPermittedPublishPoints(delegator, allPublishPointList, userLogin, security, permittedAction, - permittedOperations, passedRoles); + permittedOperations, passedRoles); Map publishPointMap = new HashMap<>(); Map publishPointMapAll = new HashMap<>(); for (String[] arr : publishPointList) { @@ -500,8 +500,8 @@ public final class ContentManagementWorker { List assocValueList = null; try { assocValueList = EntityQuery.use(delegator).from("ContentAssoc") - .where("contentId", targContentId, "contentAssocTypeId", "PUBLISH_LINK") - .filterByDate().cache().queryList(); + .where("contentId", targContentId, "contentAssocTypeId", "PUBLISH_LINK") + .filterByDate().cache().queryList(); } catch (GenericEntityException e) { throw new GeneralException(e.getMessage()); } @@ -544,7 +544,7 @@ public final class ContentManagementWorker { // TODO check if we want contentTypes to be filled/used, else this should be removed List contentTypes = null; Map results = ContentServicesComplex.getAssocAndContentAndDataResourceCacheMethod(delegator, contentId, null, "To", - null, null, assocTypes, contentTypes, Boolean.TRUE, null, null); + null, null, assocTypes, contentTypes, Boolean.TRUE, null, null); List valueList = UtilGenerics.cast(results.get("entityList")); if (valueList.size() > 0) { GenericValue value = valueList.get(0); @@ -583,7 +583,7 @@ public final class ContentManagementWorker { } Map results = null; results = EntityPermissionChecker.checkPermission(content, statusId, userLogin, passedPurposes, targetOperationList, roles, delegator, - security, entityAction); + security, entityAction); String permissionStatus = (String) results.get("permissionStatus"); if (permissionStatus != null && "granted".equalsIgnoreCase(permissionStatus)) { String[] arr = {contentId, contentName}; @@ -603,8 +603,8 @@ public final class ContentManagementWorker { List relatedPubPts = null; try { relatedPubPts = EntityQuery.use(delegator).from("ContentAssoc") - .where("contentIdTo", parentPubPt, "contentAssocTypeId", "DEPARTMENT") - .cache().queryList(); + .where("contentIdTo", parentPubPt, "contentAssocTypeId", "DEPARTMENT") + .cache().queryList(); } catch (GenericEntityException e) { throw new GeneralException(e.getMessage()); @@ -640,7 +640,7 @@ public final class ContentManagementWorker { conditionMain.add(EntityCondition.makeCondition("contentAssocTypeId", EntityOperator.IN, typeList)); } List contentAssocs = EntityQuery.use(delegator).from("ContentAssoc").where(conditionMain) - .filterByDate().cache().queryList(); + .filterByDate().cache().queryList(); for (GenericValue contentAssoc : contentAssocs) { String subContentId = contentAssoc.getString("contentId"); subLeafCount += updateStatsTopDown(delegator, subContentId, typeList); @@ -663,9 +663,9 @@ public final class ContentManagementWorker { throw new RuntimeException("No entity found for id=" + contentId); List contentAssocs = EntityQuery.use(delegator).from("ContentAssoc") - .where(EntityCondition.makeCondition("contentAssocTypeId", EntityOperator.IN, typeList), - EntityCondition.makeCondition("contentId", EntityOperator.EQUALS, contentId)) - .cache().filterByDate().queryList(); + .where(EntityCondition.makeCondition("contentAssocTypeId", EntityOperator.IN, typeList), + EntityCondition.makeCondition("contentId", EntityOperator.EQUALS, contentId)) + .cache().filterByDate().queryList(); for (GenericValue contentAssoc : contentAssocs) { String contentIdTo = contentAssoc.getString("contentIdTo"); GenericValue contentTo = EntityQuery.use(delegator).from("Content").where("contentId", contentIdTo).queryOne(); diff --git a/applications/content/src/main/java/org/apache/ofbiz/content/cms/CmsEvents.java b/applications/content/src/main/java/org/apache/ofbiz/content/cms/CmsEvents.java index 324928151c..048337815a 100644 --- a/applications/content/src/main/java/org/apache/ofbiz/content/cms/CmsEvents.java +++ b/applications/content/src/main/java/org/apache/ofbiz/content/cms/CmsEvents.java @@ -118,240 +118,239 @@ public class CmsEvents { throw new GeneralRuntimeException("Error in the response writer/output stream while rendering content.", e); } catch (GeneralException e) { throw new GeneralRuntimeException("Error rendering content", e); - } + } } else { - // If an override view is present then use that in place of request.getPathInfo() - String overrideViewUri = (String) request.getAttribute("_CURRENT_CHAIN_VIEW_"); - if (UtilValidate.isNotEmpty(overrideViewUri)) { - pathInfo = overrideViewUri; - } else { - pathInfo = request.getPathInfo(); - if (targetRequest.equals(actualRequest) && pathInfo != null) { - // was called directly -- path info is everything after the request - String[] pathParsed = pathInfo.split("/", 3); - if (pathParsed.length > 2) { - pathInfo = pathParsed[2]; - } else { - pathInfo = null; - } - } // if called through the default request, there is no request in pathinfo - } - - // if path info is null or path info is / (i.e application mounted on root); check for a default content - if (pathInfo == null || "/".equals(pathInfo)) { - GenericValue defaultContent = null; - try { - defaultContent = EntityQuery.use(delegator).from("WebSiteContent") - .where("webSiteId", webSiteId, "webSiteContentTypeId", "DEFAULT_PAGE") - .orderBy("-fromDate").filterByDate().cache().queryFirst(); - } catch (GenericEntityException e) { - Debug.logError(e, MODULE); - } - if (defaultContent != null) { - pathInfo = defaultContent.getString("contentId"); - } - } - - // check for path alias first - if (pathInfo != null) { - // clean up the pathinfo for parsing - pathInfo = pathInfo.trim(); - if (pathInfo.startsWith("/")) { - pathInfo = pathInfo.substring(1); - } - if (pathInfo.endsWith("/")) { - pathInfo = pathInfo.substring(0, pathInfo.length() - 1); - } - - GenericValue pathAlias = null; - try { - pathAlias = EntityQuery.use(delegator).from("WebSitePathAlias").where("webSiteId", webSiteId, "pathAlias", pathInfo).orderBy("-fromDate").cache().filterByDate().queryFirst(); - } catch (GenericEntityException e) { - Debug.logError(e, MODULE); - } - if (pathAlias != null) { - String alias = pathAlias.getString("aliasTo"); - contentId = pathAlias.getString("contentId"); - mapKey = pathAlias.getString("mapKey"); - if (contentId == null && UtilValidate.isNotEmpty(alias)) { - if (!alias.startsWith("/")) { - alias = "/" + alias; - } - - String context = request.getContextPath(); - String location = context + request.getServletPath(); - GenericValue webSite = WebSiteWorker.getWebSite(request); - if (webSite != null && webSite.getString("hostedPathAlias") != null && !"ROOT".equals(pathInfo)) - location += "/" + webSite.getString("hostedPathAlias"); - - String uriWithContext = request.getRequestURI(); - String uri = uriWithContext.substring(context.length()); - uri = uri.substring(0, uri.lastIndexOf('/')); - - response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY); - response.setHeader("Location", location + uri + alias); - response.setHeader("Connection", "close"); - - return null; // null to not process any views - } - } - - // get the contentId/mapKey from URL - if (contentId == null) { - if (Debug.verboseOn()) { - Debug.logVerbose("Current PathInfo: " + pathInfo, MODULE); - } - String[] pathSplit = pathInfo.split("/"); - if (Debug.verboseOn()) { - Debug.logVerbose("Split pathinfo: " + pathSplit.length, MODULE); - } - contentId = pathSplit[0]; - if (pathSplit.length > 1) { - mapKey = pathSplit[1]; - } - } - - - // verify the request content is associated with the current website - int statusCode = -1; - boolean hasErrorPage = false; - - if (contentId != null) { - try { - statusCode = verifyContentToWebSite(delegator, webSiteId, contentId); - } catch (GeneralException e) { - Debug.logError(e, MODULE); - throw new GeneralRuntimeException(e.getMessage(), e); - } + // If an override view is present then use that in place of request.getPathInfo() + String overrideViewUri = (String) request.getAttribute("_CURRENT_CHAIN_VIEW_"); + if (UtilValidate.isNotEmpty(overrideViewUri)) { + pathInfo = overrideViewUri; } else { - statusCode = HttpServletResponse.SC_NOT_FOUND; + pathInfo = request.getPathInfo(); + if (targetRequest.equals(actualRequest) && pathInfo != null) { + // was called directly -- path info is everything after the request + String[] pathParsed = pathInfo.split("/", 3); + if (pathParsed.length > 2) { + pathInfo = pathParsed[2]; + } else { + pathInfo = null; + } + } // if called through the default request, there is no request in pathinfo } - // We try to find a specific Error page for this website concerning the status code - if (statusCode != HttpServletResponse.SC_OK) { - GenericValue errorContainer = null; + // if path info is null or path info is / (i.e application mounted on root); check for a default content + if (pathInfo == null || "/".equals(pathInfo)) { + GenericValue defaultContent = null; try { - errorContainer = EntityQuery.use(delegator).from("WebSiteContent") - .where("webSiteId", webSiteId, "webSiteContentTypeId", "ERROR_ROOT") - .orderBy("fromDate").filterByDate().cache().queryFirst(); + defaultContent = EntityQuery.use(delegator).from("WebSiteContent") + .where("webSiteId", webSiteId, "webSiteContentTypeId", "DEFAULT_PAGE") + .orderBy("-fromDate").filterByDate().cache().queryFirst(); } catch (GenericEntityException e) { Debug.logError(e, MODULE); } + if (defaultContent != null) { + pathInfo = defaultContent.getString("contentId"); + } + } - if (errorContainer != null) { - if (Debug.verboseOn()) { - Debug.logVerbose("Found error containers: " + errorContainer, MODULE); + // check for path alias first + if (pathInfo != null) { + // clean up the pathinfo for parsing + pathInfo = pathInfo.trim(); + if (pathInfo.startsWith("/")) { + pathInfo = pathInfo.substring(1); + } + if (pathInfo.endsWith("/")) { + pathInfo = pathInfo.substring(0, pathInfo.length() - 1); + } + + GenericValue pathAlias = null; + try { + pathAlias = EntityQuery.use(delegator).from("WebSitePathAlias").where("webSiteId", webSiteId, "pathAlias", pathInfo).orderBy("-fromDate").cache().filterByDate().queryFirst(); + } catch (GenericEntityException e) { + Debug.logError(e, MODULE); + } + if (pathAlias != null) { + String alias = pathAlias.getString("aliasTo"); + contentId = pathAlias.getString("contentId"); + mapKey = pathAlias.getString("mapKey"); + if (contentId == null && UtilValidate.isNotEmpty(alias)) { + if (!alias.startsWith("/")) { + alias = "/" + alias; + } + + String context = request.getContextPath(); + String location = context + request.getServletPath(); + GenericValue webSite = WebSiteWorker.getWebSite(request); + if (webSite != null && webSite.getString("hostedPathAlias") != null && !"ROOT".equals(pathInfo)) + location += "/" + webSite.getString("hostedPathAlias"); + + String uriWithContext = request.getRequestURI(); + String uri = uriWithContext.substring(context.length()); + uri = uri.substring(0, uri.lastIndexOf('/')); + + response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY); + response.setHeader("Location", location + uri + alias); + response.setHeader("Connection", "close"); + + return null; // null to not process any views } + } - GenericValue errorPage = null; + // get the contentId/mapKey from URL + if (contentId == null) { + if (Debug.verboseOn()) { + Debug.logVerbose("Current PathInfo: " + pathInfo, MODULE); + } + String[] pathSplit = pathInfo.split("/"); + if (Debug.verboseOn()) { + Debug.logVerbose("Split pathinfo: " + pathSplit.length, MODULE); + } + contentId = pathSplit[0]; + if (pathSplit.length > 1) { + mapKey = pathSplit[1]; + } + } + + + // verify the request content is associated with the current website + int statusCode = -1; + boolean hasErrorPage = false; + + if (contentId != null) { try { - errorPage = EntityQuery.use(delegator).from("ContentAssocViewTo") - .where("contentIdStart", errorContainer.getString("contentId"), - "caContentAssocTypeId", "TREE_CHILD", - "contentTypeId", "DOCUMENT", - "caMapKey", String.valueOf(statusCode)) - .filterByDate().queryFirst(); + statusCode = verifyContentToWebSite(delegator, webSiteId, contentId); + } catch (GeneralException e) { + Debug.logError(e, MODULE); + throw new GeneralRuntimeException(e.getMessage(), e); + } + } else { + statusCode = HttpServletResponse.SC_NOT_FOUND; + } + + // We try to find a specific Error page for this website concerning the status code + if (statusCode != HttpServletResponse.SC_OK) { + GenericValue errorContainer = null; + try { + errorContainer = EntityQuery.use(delegator).from("WebSiteContent") + .where("webSiteId", webSiteId, "webSiteContentTypeId", "ERROR_ROOT") + .orderBy("fromDate").filterByDate().cache().queryFirst(); } catch (GenericEntityException e) { Debug.logError(e, MODULE); } - if (errorPage != null) { + + if (errorContainer != null) { if (Debug.verboseOn()) { - Debug.logVerbose("Found error pages " + statusCode + " : " + errorPage, MODULE); + Debug.logVerbose("Found error containers: " + errorContainer, MODULE); } - contentId = errorPage.getString("contentId"); - } else { - if (Debug.verboseOn()) { - Debug.logVerbose("No specific error page, falling back to the Error Container for " + statusCode, MODULE); + + GenericValue errorPage = null; + try { + errorPage = EntityQuery.use(delegator).from("ContentAssocViewTo") + .where("contentIdStart", errorContainer.getString("contentId"), + "caContentAssocTypeId", "TREE_CHILD", + "contentTypeId", "DOCUMENT", + "caMapKey", String.valueOf(statusCode)) + .filterByDate().queryFirst(); + } catch (GenericEntityException e) { + Debug.logError(e, MODULE); } - contentId = errorContainer.getString("contentId"); - } - mapKey = null; - hasErrorPage = true; - } - // We try to find a generic content Error page concerning the status code - if (!hasErrorPage) { - try { - GenericValue errorPage = EntityQuery.use(delegator).from("Content").where("contentId", "CONTENT_ERROR_" + statusCode).cache().queryOne(); if (errorPage != null) { if (Debug.verboseOn()) { - Debug.logVerbose("Found generic page " + statusCode, MODULE); + Debug.logVerbose("Found error pages " + statusCode + " : " + errorPage, MODULE); } contentId = errorPage.getString("contentId"); - mapKey = null; - hasErrorPage = true; + } else { + if (Debug.verboseOn()) { + Debug.logVerbose("No specific error page, falling back to the Error Container for " + statusCode, MODULE); + } + contentId = errorContainer.getString("contentId"); } + mapKey = null; + hasErrorPage = true; + } + // We try to find a generic content Error page concerning the status code + if (!hasErrorPage) { + try { + GenericValue errorPage = EntityQuery.use(delegator).from("Content").where("contentId", "CONTENT_ERROR_" + statusCode).cache().queryOne(); + if (errorPage != null) { + if (Debug.verboseOn()) { + Debug.logVerbose("Found generic page " + statusCode, MODULE); + } + contentId = errorPage.getString("contentId"); + mapKey = null; + hasErrorPage = true; + } + } catch (GenericEntityException e) { + Debug.logError(e, MODULE); + } + } + } + + if (statusCode == HttpServletResponse.SC_OK || hasErrorPage) { + // create the template map + MapStack templateMap = MapStack.create(); + ScreenRenderer.populateContextForRequest(templateMap, null, request, response, servletContext); + templateMap.put("statusCode", statusCode); + + // make the link prefix + templateMap.put("_REQUEST_HANDLER_", RequestHandler.from(request)); + + //Cache Headers + UtilHttp.setResponseBrowserProxyNoCache(response); + //Security Headers + UtilHttp.setResponseBrowserDefaultSecurityHeaders(response, null); + + response.setStatus(statusCode); + + try { + writer = response.getWriter(); + // TODO: replace "screen" to support dynamic rendering of different output + if (visualTheme == null) { + String defaultVisualThemeId = EntityUtilProperties.getPropertyValue("general", "VISUAL_THEME", delegator); + visualTheme = ThemeFactory.getVisualThemeFromId(defaultVisualThemeId); + } + FormStringRenderer formStringRenderer = new MacroFormRenderer(visualTheme.getModelTheme().getFormRendererLocation("screen"), request, response); + templateMap.put("formStringRenderer", formStringRenderer); + + // if use web analytics + List webAnalytics = EntityQuery.use(delegator).from("WebAnalyticsConfig").where("webSiteId", webSiteId).queryList(); + // render + if (UtilValidate.isNotEmpty(webAnalytics) && hasErrorPage) { + ContentWorker.renderContentAsText(dispatcher, contentId, writer, templateMap, locale, "text/html", null, null, true, webAnalytics); + } else if (UtilValidate.isEmpty(mapKey)) { + ContentWorker.renderContentAsText(dispatcher, contentId, writer, templateMap, locale, "text/html", null, null, true); + } else { + ContentWorker.renderSubContentAsText(dispatcher, contentId, writer, mapKey, templateMap, locale, "text/html", true); + } + + } catch (TemplateException e) { + throw new GeneralRuntimeException(String.format("Error creating form renderer while rendering content [%s] with path alias [%s]", contentId, pathInfo), e); + } catch (IOException e) { + throw new GeneralRuntimeException(String.format("Error in the response writer/output stream while rendering content [%s] with path alias [%s]", contentId, pathInfo), e); + } catch (GeneralException e) { + throw new GeneralRuntimeException(String.format("Error rendering content [%s] with path alias [%s]", contentId, pathInfo), e); + } + + return "success"; + } else { + String contentName = null; + String siteName = null; + try { + GenericValue content = EntityQuery.use(delegator).from("Content").where("contentId", contentId).cache().queryOne(); + if (content != null && UtilValidate.isNotEmpty(content.getString("contentName"))) { + contentName = content.getString("contentName"); + } else { + request.setAttribute("_ERROR_MESSAGE_", "Content: [" + contentId + "] is not a publish point for the current website: [" + webSiteId + "]"); + return "error"; + } + siteName = EntityQuery.use(delegator).from("WebSite").where("webSiteId", webSiteId).cache().queryOne().getString("siteName"); } catch (GenericEntityException e) { Debug.logError(e, MODULE); } + request.setAttribute("_ERROR_MESSAGE_", "Content: " + contentName + " [" + contentId + "] is not a publish point for the current website: " + siteName + " [" + webSiteId + "]"); + return "error"; } - } - - if (statusCode == HttpServletResponse.SC_OK || hasErrorPage) { - // create the template map - MapStack templateMap = MapStack.create(); - ScreenRenderer.populateContextForRequest(templateMap, null, request, response, servletContext); - templateMap.put("statusCode", statusCode); - - // make the link prefix - templateMap.put("_REQUEST_HANDLER_", RequestHandler.from(request)); - - //Cache Headers - UtilHttp.setResponseBrowserProxyNoCache(response); - //Security Headers - UtilHttp.setResponseBrowserDefaultSecurityHeaders(response, null); - - response.setStatus(statusCode); - - try { - writer = response.getWriter(); - // TODO: replace "screen" to support dynamic rendering of different output - if (visualTheme == null) { - String defaultVisualThemeId = EntityUtilProperties.getPropertyValue("general", "VISUAL_THEME", delegator); - visualTheme = ThemeFactory.getVisualThemeFromId(defaultVisualThemeId); - } - FormStringRenderer formStringRenderer = new MacroFormRenderer(visualTheme.getModelTheme().getFormRendererLocation("screen"), request, response); - templateMap.put("formStringRenderer", formStringRenderer); - - // if use web analytics - List webAnalytics = EntityQuery.use(delegator).from("WebAnalyticsConfig").where("webSiteId", webSiteId).queryList(); - // render - if (UtilValidate.isNotEmpty(webAnalytics) && hasErrorPage) { - ContentWorker.renderContentAsText(dispatcher, contentId, writer, templateMap, locale, "text/html", null, null, true, webAnalytics); - } else if (UtilValidate.isEmpty(mapKey)) { - ContentWorker.renderContentAsText(dispatcher, contentId, writer, templateMap, locale, "text/html", null, null, true); - } else { - ContentWorker.renderSubContentAsText(dispatcher, contentId, writer, mapKey, templateMap, locale, "text/html", true); - } - - } catch (TemplateException e) { - throw new GeneralRuntimeException(String.format("Error creating form renderer while rendering content [%s] with path alias [%s]", contentId, pathInfo), e); - } catch (IOException e) { - throw new GeneralRuntimeException(String.format("Error in the response writer/output stream while rendering content [%s] with path alias [%s]", contentId, pathInfo), e); - } catch (GeneralException e) { - throw new GeneralRuntimeException(String.format("Error rendering content [%s] with path alias [%s]", contentId, pathInfo), e); - } - - return "success"; - } else { - String contentName = null; - String siteName = null; - try { - GenericValue content = EntityQuery.use(delegator).from("Content").where("contentId", contentId).cache().queryOne(); - if (content != null && UtilValidate.isNotEmpty(content.getString("contentName"))) { - contentName = content.getString("contentName"); - } else { - request.setAttribute("_ERROR_MESSAGE_", "Content: [" + contentId + "] is not a publish point for the current website: [" + webSiteId + "]"); - return "error"; - } - siteName = EntityQuery.use(delegator).from("WebSite").where("webSiteId", webSiteId).cache().queryOne().getString("siteName"); - } catch (GenericEntityException e) { - Debug.logError(e, MODULE); - } - request.setAttribute("_ERROR_MESSAGE_", "Content: " + contentName + " [" + contentId + "] is not a publish point for the current website: " + siteName + " [" + webSiteId + "]"); - return "error"; - } - } } String siteName = null; GenericValue webSite = null; diff --git a/applications/content/src/main/java/org/apache/ofbiz/content/cms/ContentJsonEvents.java b/applications/content/src/main/java/org/apache/ofbiz/content/cms/ContentJsonEvents.java index fa1235ef29..229fcf3731 100644 --- a/applications/content/src/main/java/org/apache/ofbiz/content/cms/ContentJsonEvents.java +++ b/applications/content/src/main/java/org/apache/ofbiz/content/cms/ContentJsonEvents.java @@ -56,8 +56,8 @@ public class ContentJsonEvents { String contentId = request.getParameter("contentId"); EntityCondition condition = EntityCondition.makeCondition( - EntityCondition.makeCondition(UtilMisc.toMap("contentId", contentId)), - EntityUtil.getFilterByDateExpr()); + EntityCondition.makeCondition(UtilMisc.toMap("contentId", contentId)), + EntityUtil.getFilterByDateExpr()); List assocs = delegator.findList("ContentAssoc", condition, null, null, null, false); List> nodes = new LinkedList<>(); @@ -133,8 +133,8 @@ public class ContentJsonEvents { public static void deleteContent(Delegator delegator, String contentId) throws GenericEntityException { Timestamp now = UtilDateTime.nowTimestamp(); EntityCondition condition = EntityCondition.makeCondition( - EntityCondition.makeCondition(UtilMisc.toMap("contentIdTo", contentId)), - EntityUtil.getFilterByDateExpr()); + EntityCondition.makeCondition(UtilMisc.toMap("contentIdTo", contentId)), + EntityUtil.getFilterByDateExpr()); List assocs = delegator.findList("ContentAssoc", condition, null, null, null, true); for (GenericValue assoc : assocs) { assoc.set("thruDate", now); @@ -146,8 +146,8 @@ public class ContentJsonEvents { private static void deleteWebPathAliases(Delegator delegator, String contentId) throws GenericEntityException { Timestamp now = UtilDateTime.nowTimestamp(); EntityCondition condition = EntityCondition.makeCondition( - EntityCondition.makeCondition(UtilMisc.toMap("contentId", contentId)), - EntityUtil.getFilterByDateExpr()); + EntityCondition.makeCondition(UtilMisc.toMap("contentId", contentId)), + EntityUtil.getFilterByDateExpr()); List pathAliases = delegator.findList("WebSitePathAlias", condition, null, null, null, true); for (GenericValue alias : pathAliases) { alias.set("thruDate", now); @@ -172,14 +172,14 @@ public class ContentJsonEvents { Map data = UtilMisc.toMap("title", (Object) contentName); Map attr = UtilMisc.toMap( - "id", assoc.get("contentIdTo"), - "contentId", assoc.get("contentId"), - "fromDate", assoc.getTimestamp("fromDate").toString(), - "contentAssocTypeId", assoc.get("contentAssocTypeId")); + "id", assoc.get("contentIdTo"), + "contentId", assoc.get("contentId"), + "fromDate", assoc.getTimestamp("fromDate").toString(), + "contentAssocTypeId", assoc.get("contentAssocTypeId")); Map node = UtilMisc.toMap("data", (Object) data, "attr", (Object) attr); - List assocChildren = content != null ? content.getRelated("FromContentAssoc", null, null, true) : null; + List assocChildren = content != null ? content.getRelated("FromContentAssoc", null, null, true) : null; assocChildren = EntityUtil.filterByDate(assocChildren); if (!CollectionUtils.isEmpty(assocChildren)) { node.put("state", "closed"); diff --git a/applications/content/src/main/java/org/apache/ofbiz/content/compdoc/CompDocEvents.java b/applications/content/src/main/java/org/apache/ofbiz/content/compdoc/CompDocEvents.java index 455c355c86..fa7d648de3 100644 --- a/applications/content/src/main/java/org/apache/ofbiz/content/compdoc/CompDocEvents.java +++ b/applications/content/src/main/java/org/apache/ofbiz/content/compdoc/CompDocEvents.java @@ -102,7 +102,7 @@ public class CompDocEvents { Map persistResult = dispatcher.runSync("persistContentAndAssoc", persistMap); if (ServiceUtil.isError(persistResult)) { String errMsg = "Error running serviceName, 'persistContentAndAssoc'. " + ServiceUtil.getErrorMessage(persistResult); - request.setAttribute("_ERROR_MESSAGE_", "

  • " + errMsg + "
  • "); + request.setAttribute("_ERROR_MESSAGE_", "
  • " + errMsg + "
  • "); Debug.logError(errMsg, MODULE); return "error"; } @@ -121,7 +121,7 @@ public class CompDocEvents { Map result = dispatcher.runSync("persistContentRevisionAndItem", contentRevisionMap); if (ServiceUtil.isError(result)) { String errMsg = "Error running serviceName, 'persistContentRevisionAndItem'. " + ServiceUtil.getErrorMessage(result); - request.setAttribute("_ERROR_MESSAGE_", "
  • " + errMsg + "
  • "); + request.setAttribute("_ERROR_MESSAGE_", "
  • " + errMsg + "
  • "); Debug.logError(errMsg, MODULE); return "error"; } diff --git a/applications/content/src/main/java/org/apache/ofbiz/content/content/ContentPermissionServices.java b/applications/content/src/main/java/org/apache/ofbiz/content/content/ContentPermissionServices.java index fa5464b28a..e7274a462c 100644 --- a/applications/content/src/main/java/org/apache/ofbiz/content/content/ContentPermissionServices.java +++ b/applications/content/src/main/java/org/apache/ofbiz/content/content/ContentPermissionServices.java @@ -105,13 +105,13 @@ public class ContentPermissionServices { Boolean bDisplayFailCond = (Boolean) context.get("displayFailCond"); boolean displayFailCond = false; if (bDisplayFailCond != null && bDisplayFailCond) { - displayFailCond = true; + displayFailCond = true; } - Debug.logInfo("displayFailCond(0):" + displayFailCond, ""); + Debug.logInfo("displayFailCond(0):" + displayFailCond, ""); Boolean bDisplayPassCond = (Boolean) context.get("displayPassCond"); boolean displayPassCond = false; if (bDisplayPassCond != null && bDisplayPassCond) { - displayPassCond = true; + displayPassCond = true; } Debug.logInfo("displayPassCond(0):" + displayPassCond, ""); Map results = new HashMap<>(); @@ -150,7 +150,7 @@ public class ContentPermissionServices { passedPurposes.addAll(purposesFromString); } - EntityPermissionChecker.StdAuxiliaryValueGetter auxGetter = new EntityPermissionChecker.StdAuxiliaryValueGetter("ContentPurpose", "contentPurposeTypeId", "contentId"); + EntityPermissionChecker.StdAuxiliaryValueGetter auxGetter = new EntityPermissionChecker.StdAuxiliaryValueGetter("ContentPurpose", "contentPurposeTypeId", "contentId"); // Sometimes permissions need to be checked before an entity is created, so // there needs to be a method for setting a purpose list auxGetter.setList(passedPurposes); @@ -163,10 +163,10 @@ public class ContentPermissionServices { } targetOperations.addAll(operationsFromString); } - EntityPermissionChecker.StdPermissionConditionGetter permCondGetter = new EntityPermissionChecker.StdPermissionConditionGetter("ContentPurposeOperation", "contentOperationId", "roleTypeId", "statusId", "contentPurposeTypeId", "privilegeEnumId"); + EntityPermissionChecker.StdPermissionConditionGetter permCondGetter = new EntityPermissionChecker.StdPermissionConditionGetter("ContentPurposeOperation", "contentOperationId", "roleTypeId", "statusId", "contentPurposeTypeId", "privilegeEnumId"); permCondGetter.setOperationList(targetOperations); - EntityPermissionChecker.StdRelatedRoleGetter roleGetter = new EntityPermissionChecker.StdRelatedRoleGetter("Content", "roleTypeId", "contentId", "partyId", "ownerContentId", "ContentRole"); + EntityPermissionChecker.StdRelatedRoleGetter roleGetter = new EntityPermissionChecker.StdRelatedRoleGetter("Content", "roleTypeId", "contentId", "partyId", "ownerContentId", "ContentRole"); List passedRoles = UtilGenerics.cast(context.get("roleTypeList")); if (passedRoles == null) passedRoles = new LinkedList<>(); String roleTypeString = (String) context.get("roleTypeString"); @@ -189,23 +189,26 @@ public class ContentPermissionServices { results.put("permissionStatus", "granted"); permissionStatus = "granted"; if (displayPassCond) { - errBuf.append("\n hasEntityPermission(" + entityAction + "): PASSED"); + errBuf.append("\n hasEntityPermission(" + entityAction + "): PASSED"); } } else { if (displayFailCond) { - errBuf.append("\n hasEntityPermission(" + entityAction + "): FAILED"); + errBuf.append("\n hasEntityPermission(" + entityAction + "): FAILED"); } - if (content != null) + if (content != null) { entityIds.add(content); + } String quickCheckContentId = (String) context.get("quickCheckContentId"); if (UtilValidate.isNotEmpty(quickCheckContentId)) { - List quickList = StringUtil.split(quickCheckContentId, "|"); - if (UtilValidate.isNotEmpty(quickList)) entityIds.addAll(quickList); + List quickList = StringUtil.split(quickCheckContentId, "|"); + if (UtilValidate.isNotEmpty(quickList)) { + entityIds.addAll(quickList); + } } try { - boolean check = EntityPermissionChecker.checkPermissionMethod(delegator, partyId, "Content", entityIds, auxGetter, roleGetter, permCondGetter); + boolean check = EntityPermissionChecker.checkPermissionMethod(delegator, partyId, "Content", entityIds, auxGetter, roleGetter, permCondGetter); if (check) { results.put("permissionStatus", "granted"); } else { @@ -220,27 +223,27 @@ public class ContentPermissionServices { } if (("granted".equals(permissionStatus) && displayPassCond) - || ("rejected".equals(permissionStatus) && displayFailCond)) { + || ("rejected".equals(permissionStatus) && displayFailCond)) { // Don't show this if passed on 'hasEntityPermission' if (displayFailCond || displayPassCond) { - if (!passed) { - errBuf.append("\n targetOperations:"); - errBuf.append(targetOperations); + if (!passed) { + errBuf.append("\n targetOperations:"); + errBuf.append(targetOperations); - String errMsg = permCondGetter.dumpAsText(); - errBuf.append("\n"); - errBuf.append(errMsg); - errBuf.append("\n partyId:"); - errBuf.append(partyId); - errBuf.append("\n entityIds:"); - errBuf.append(entityIds); + String errMsg = permCondGetter.dumpAsText(); + errBuf.append("\n"); + errBuf.append(errMsg); + errBuf.append("\n partyId:"); + errBuf.append(partyId); + errBuf.append("\n entityIds:"); + errBuf.append(entityIds); - errBuf.append("\n auxList:"); - errBuf.append(auxGetter.getList()); + errBuf.append("\n auxList:"); + errBuf.append(auxGetter.getList()); - errBuf.append("\n roleList:"); - errBuf.append(roleGetter.getList()); - } + errBuf.append("\n roleList:"); + errBuf.append(roleGetter.getList()); + } } } diff --git a/applications/content/src/main/java/org/apache/ofbiz/content/content/ContentServicesComplex.java b/applications/content/src/main/java/org/apache/ofbiz/content/content/ContentServicesComplex.java index 8cd4a5ee92..0a79c42a0b 100644 --- a/applications/content/src/main/java/org/apache/ofbiz/content/content/ContentServicesComplex.java +++ b/applications/content/src/main/java/org/apache/ofbiz/content/content/ContentServicesComplex.java @@ -243,30 +243,34 @@ public class ContentServicesComplex { List contentAssocDataResourceList = new LinkedList<>(); Locale locale = Locale.getDefault(); // TODO: this needs to be passed in try { - for (GenericValue contentAssocView : contentAssocsTypeFiltered) { - GenericValue contentAssoc = EntityQuery.use(delegator).from("ContentAssoc").where(UtilMisc.toMap("contentId", contentAssocView.getString("contentId"), - "contentIdTo", contentAssocView.getString(contentFieldName), "contentAssocTypeId", contentAssocView.getString("caContentAssocTypeId"), - "fromDate", contentAssocView.getTimestamp("caFromDate"))).queryOne(); - content = contentAssoc.getRelatedOne(assocRelationName, true); - if (UtilValidate.isNotEmpty(contentTypes)) { - String contentTypeId = (String) content.get("contentTypeId"); - if (contentTypes.contains(contentTypeId)) { + for (GenericValue contentAssocView : contentAssocsTypeFiltered) { + GenericValue contentAssoc = EntityQuery.use(delegator).from("ContentAssoc").where(UtilMisc.toMap("contentId", + contentAssocView.getString("contentId"), + "contentIdTo", contentAssocView.getString(contentFieldName), "contentAssocTypeId", contentAssocView.getString( + "caContentAssocTypeId"), + "fromDate", contentAssocView.getTimestamp("caFromDate"))).queryOne(); + content = contentAssoc.getRelatedOne(assocRelationName, true); + if (UtilValidate.isNotEmpty(contentTypes)) { + String contentTypeId = (String) content.get("contentTypeId"); + if (contentTypes.contains(contentTypeId)) { + contentAssocDataResourceView = delegator.makeValue(viewName); + contentAssocDataResourceView.setAllFields(content, true, null, null); + } + } else { contentAssocDataResourceView = delegator.makeValue(viewName); contentAssocDataResourceView.setAllFields(content, true, null, null); } - } else { - contentAssocDataResourceView = delegator.makeValue(viewName); - contentAssocDataResourceView.setAllFields(content, true, null, null); + SimpleMapProcessor.runSimpleMapProcessor("component://content/minilang/ContentManagementMapProcessors.xml", "contentAssocOut", + contentAssoc, contentAssocDataResourceView, new LinkedList<>(), locale); + String dataResourceId = content.getString("dataResourceId"); + if (UtilValidate.isNotEmpty(dataResourceId)) + dataResource = content.getRelatedOne("DataResource", true); + if (dataResource != null) { + SimpleMapProcessor.runSimpleMapProcessor("component://content/minilang/ContentManagementMapProcessors.xml", "dataResourceOut", + dataResource, contentAssocDataResourceView, new LinkedList<>(), locale); + } + contentAssocDataResourceList.add(contentAssocDataResourceView); } - SimpleMapProcessor.runSimpleMapProcessor("component://content/minilang/ContentManagementMapProcessors.xml", "contentAssocOut", contentAssoc, contentAssocDataResourceView, new LinkedList<>(), locale); - String dataResourceId = content.getString("dataResourceId"); - if (UtilValidate.isNotEmpty(dataResourceId)) - dataResource = content.getRelatedOne("DataResource", true); - if (dataResource != null) { - SimpleMapProcessor.runSimpleMapProcessor("component://content/minilang/ContentManagementMapProcessors.xml", "dataResourceOut", dataResource, contentAssocDataResourceView, new LinkedList<>(), locale); - } - contentAssocDataResourceList.add(contentAssocDataResourceView); - } } catch (GenericEntityException e) { Debug.logError(e, MODULE); return ServiceUtil.returnError(e.getMessage()); @@ -274,7 +278,7 @@ public class ContentServicesComplex { if (UtilValidate.isNotEmpty(orderBy)) { List orderByList = StringUtil.split(orderBy, "|"); - contentAssocDataResourceList = EntityUtil.orderBy(contentAssocDataResourceList, orderByList); + contentAssocDataResourceList = EntityUtil.orderBy(contentAssocDataResourceList, orderByList); } Map results = new HashMap<>(); results.put("entityList", contentAssocDataResourceList); diff --git a/applications/content/src/main/java/org/apache/ofbiz/content/content/ContentWorker.java b/applications/content/src/main/java/org/apache/ofbiz/content/content/ContentWorker.java index 3cef6e81b3..f06a36c3b0 100644 --- a/applications/content/src/main/java/org/apache/ofbiz/content/content/ContentWorker.java +++ b/applications/content/src/main/java/org/apache/ofbiz/content/content/ContentWorker.java @@ -719,13 +719,13 @@ public class ContentWorker implements org.apache.ofbiz.widget.content.ContentWor boolean isPick = booleanDataType(thisNode.get("isPick")); kids.add(thisNode); if (isPick) { - Integer count = (Integer) currentNode.get("count"); - if (count == null) { - count = 1; - } else { - count = count + 1; - } - currentNode.put("count", count); + Integer count = (Integer) currentNode.get("count"); + if (count == null) { + count = 1; + } else { + count = count + 1; + } + currentNode.put("count", count); } } } @@ -971,22 +971,23 @@ public class ContentWorker implements org.apache.ofbiz.widget.content.ContentWor } } - public static List> getContentAncestryNodeTrail(Delegator delegator, String contentId, String contentAssocTypeId, String direction) throws GenericEntityException { - List contentAncestorList = new LinkedList<>(); - List> nodeTrail = new LinkedList<>(); - getContentAncestry(delegator, contentId, contentAssocTypeId, direction, contentAncestorList); - for (GenericValue value : contentAncestorList) { - Map thisNode = ContentWorker.makeNode(value); - nodeTrail.add(thisNode); - } - return nodeTrail; + public static List> getContentAncestryNodeTrail(Delegator delegator, String contentId, String contentAssocTypeId, + String direction) throws GenericEntityException { + List contentAncestorList = new LinkedList<>(); + List> nodeTrail = new LinkedList<>(); + getContentAncestry(delegator, contentId, contentAssocTypeId, direction, contentAncestorList); + for (GenericValue value : contentAncestorList) { + Map thisNode = ContentWorker.makeNode(value); + nodeTrail.add(thisNode); + } + return nodeTrail; } public static String getContentAncestryNodeTrailCsv(Delegator delegator, String contentId, String contentAssocTypeId, String direction) throws GenericEntityException { - List contentAncestorList = new LinkedList<>(); - getContentAncestry(delegator, contentId, contentAssocTypeId, direction, contentAncestorList); - String csv = StringUtil.join(contentAncestorList, ","); - return csv; + List contentAncestorList = new LinkedList<>(); + getContentAncestry(delegator, contentId, contentAssocTypeId, direction, contentAncestorList); + String csv = StringUtil.join(contentAncestorList, ","); + return csv; } public static void getContentAncestryValues(Delegator delegator, String contentId, String contentAssocTypeId, String direction, List contentAncestorList) throws GenericEntityException { diff --git a/applications/content/src/main/java/org/apache/ofbiz/content/content/ContentWrapper.java b/applications/content/src/main/java/org/apache/ofbiz/content/content/ContentWrapper.java index 3c01d413c4..15115c90e1 100644 --- a/applications/content/src/main/java/org/apache/ofbiz/content/content/ContentWrapper.java +++ b/applications/content/src/main/java/org/apache/ofbiz/content/content/ContentWrapper.java @@ -26,6 +26,6 @@ import org.apache.ofbiz.base.util.StringUtil; public interface ContentWrapper { - public StringUtil.StringWrapper get(String contentTypeId, String encoderType); + StringUtil.StringWrapper get(String contentTypeId, String encoderType); } diff --git a/applications/content/src/main/java/org/apache/ofbiz/content/data/DataEvents.java b/applications/content/src/main/java/org/apache/ofbiz/content/data/DataEvents.java index 9d6b80c0aa..2abf58d4b5 100644 --- a/applications/content/src/main/java/org/apache/ofbiz/content/data/DataEvents.java +++ b/applications/content/src/main/java/org/apache/ofbiz/content/data/DataEvents.java @@ -359,10 +359,10 @@ public class DataEvents { request.setAttribute("dataResourceId", result.get("dataResourceId")); String dataResourceTypeId = (String) serviceInMap.get("dataResourceTypeId"); if (dataResourceTypeId != null) { - if ("ELECTRONIC_TEXT".equals(dataResourceTypeId) - || "IMAGE_OBJECT".equals(dataResourceTypeId)) { + if ("ELECTRONIC_TEXT".equals(dataResourceTypeId) + || "IMAGE_OBJECT".equals(dataResourceTypeId)) { returnStr = dataResourceTypeId; - } + } } } diff --git a/applications/content/src/main/java/org/apache/ofbiz/content/data/DataResourceWorker.java b/applications/content/src/main/java/org/apache/ofbiz/content/data/DataResourceWorker.java index f14142b905..a166c4b1d8 100644 --- a/applications/content/src/main/java/org/apache/ofbiz/content/data/DataResourceWorker.java +++ b/applications/content/src/main/java/org/apache/ofbiz/content/data/DataResourceWorker.java @@ -153,9 +153,9 @@ public class DataResourceWorker implements org.apache.ofbiz.widget.content.Data // The other test is to only get all the children if the "leaf" node where all the // children of the leaf are wanted for expansion. if (parentCategoryId == null - || "ROOT".equals(parentCategoryId) - || (currentDataCategoryId != null && currentDataCategoryId.equals(parentCategoryId)) - || getAll) { + || "ROOT".equals(parentCategoryId) + || (currentDataCategoryId != null && currentDataCategoryId.equals(parentCategoryId)) + || getAll) { categoryNode.put("kids", subCategoryIds); } return errorMsg; @@ -482,8 +482,8 @@ public class DataResourceWorker implements org.apache.ofbiz.widget.content.Data mimeType = view.getString("drMimeTypeId"); } if (UtilValidate.isEmpty(mimeType) && UtilValidate.isNotEmpty(dataResourceId)) { - GenericValue dataResource = EntityQuery.use(delegator).from("DataResource").where("dataResourceId", dataResourceId).cache().queryOne(); - mimeType = dataResource.getString("mimeTypeId"); + GenericValue dataResource = EntityQuery.use(delegator).from("DataResource").where("dataResourceId", dataResourceId).cache().queryOne(); + mimeType = dataResource.getString("mimeTypeId"); } return mimeType; @@ -623,19 +623,20 @@ public class DataResourceWorker implements org.apache.ofbiz.widget.content.Data } } - public static String renderDataResourceAsText(LocalDispatcher dispatcher, Delegator delegator, String dataResourceId, Map templateContext, - Locale locale, String targetMimeTypeId, boolean cache) throws GeneralException, IOException { + public static String renderDataResourceAsText(LocalDispatcher dispatcher, Delegator delegator, String dataResourceId, + Map templateContext, + Locale locale, String targetMimeTypeId, boolean cache) throws GeneralException, IOException { try (Writer writer = new StringWriter()) { - renderDataResourceAsText(dispatcher, delegator, dataResourceId, writer, templateContext, locale, targetMimeTypeId, cache, null); - return writer.toString(); + renderDataResourceAsText(dispatcher, delegator, dataResourceId, writer, templateContext, locale, targetMimeTypeId, cache, null); + return writer.toString(); } } public static String renderDataResourceAsText(LocalDispatcher dispatcher, String dataResourceId, Appendable out, - Map templateContext, Locale locale, String targetMimeTypeId, boolean cache) throws GeneralException, IOException { - renderDataResourceAsText(dispatcher, null, dataResourceId, out, templateContext, locale, targetMimeTypeId, cache, null); - return out.toString(); - } + Map templateContext, Locale locale, String targetMimeTypeId, boolean cache) throws GeneralException, IOException { + renderDataResourceAsText(dispatcher, null, dataResourceId, out, templateContext, locale, targetMimeTypeId, cache, null); + return out.toString(); + } public static void renderDataResourceAsText(LocalDispatcher dispatcher, Delegator delegator, String dataResourceId, Appendable out, Map templateContext, Locale locale, String targetMimeTypeId, boolean cache, List webAnalytics) throws GeneralException, IOException { @@ -720,7 +721,7 @@ public class DataResourceWorker implements org.apache.ofbiz.widget.content.Data } } else if ("XSLT".equals(dataTemplateTypeId)) { - File targetFileLocation = new File(System.getProperty("ofbiz.home")+"/runtime/tempfiles/docbook.css"); + File targetFileLocation = new File(System.getProperty("ofbiz.home") + "/runtime/tempfiles/docbook.css"); String defaultVisualThemeId = EntityUtilProperties.getPropertyValue("general", "VISUAL_THEME", delegator); visualTheme = ThemeFactory.getVisualThemeFromId(defaultVisualThemeId); modelTheme = visualTheme.getModelTheme(); @@ -885,10 +886,10 @@ public class DataResourceWorker implements org.apache.ofbiz.widget.content.Data if (url.getHost() != null) { // is absolute int c; try (InputStream in = url.openStream(); StringWriter sw = new StringWriter()) { - while ((c = in.read()) != -1) { - sw.write(c); - } - text = sw.toString(); + while ((c = in.read()) != -1) { + sw.write(c); + } + text = sw.toString(); } } else { String prefix = DataResourceWorker.buildRequestPrefix(delegator, locale, webSiteId, https); diff --git a/applications/content/src/main/java/org/apache/ofbiz/content/data/DataServices.java b/applications/content/src/main/java/org/apache/ofbiz/content/data/DataServices.java index de484f5945..0476440a5f 100644 --- a/applications/content/src/main/java/org/apache/ofbiz/content/data/DataServices.java +++ b/applications/content/src/main/java/org/apache/ofbiz/content/data/DataServices.java @@ -140,7 +140,7 @@ public class DataServices { try { GenericValue statusItem = EntityQuery.use(delegator).from("StatusItem").where("statusTypeId", "CONTENT_STATUS").orderBy("sequenceId").queryFirst(); if (statusItem != null) { - dataResource.put("statusId", statusItem.get("statusId")); + dataResource.put("statusId", statusItem.get("statusId")); } } catch (GenericEntityException e) { return ServiceUtil.returnError(e.getMessage()); diff --git a/applications/content/src/main/java/org/apache/ofbiz/content/survey/PdfSurveyServices.java b/applications/content/src/main/java/org/apache/ofbiz/content/survey/PdfSurveyServices.java index 63e6a76579..74b8c0edf5 100644 --- a/applications/content/src/main/java/org/apache/ofbiz/content/survey/PdfSurveyServices.java +++ b/applications/content/src/main/java/org/apache/ofbiz/content/survey/PdfSurveyServices.java @@ -304,9 +304,9 @@ public class PdfSurveyServices { return ServiceUtil.returnError(e.getMessage()); } - Map results = ServiceUtil.returnSuccess(); - results.put("acroFieldMap", acroFieldMap); - return results; + Map results = ServiceUtil.returnSuccess(); + results.put("acroFieldMap", acroFieldMap); + return results; } /** diff --git a/applications/content/src/main/java/org/apache/ofbiz/content/survey/SurveyWrapper.java b/applications/content/src/main/java/org/apache/ofbiz/content/survey/SurveyWrapper.java index 33952a9783..acc482cd9d 100644 --- a/applications/content/src/main/java/org/apache/ofbiz/content/survey/SurveyWrapper.java +++ b/applications/content/src/main/java/org/apache/ofbiz/content/survey/SurveyWrapper.java @@ -83,9 +83,9 @@ public class SurveyWrapper { this.checkParameters(); } - public SurveyWrapper(Delegator delegator, String responseId, String partyId, String surveyId, Map passThru) { - this(delegator, responseId, partyId, surveyId, passThru, null); - } + public SurveyWrapper(Delegator delegator, String responseId, String partyId, String surveyId, Map passThru) { + this(delegator, responseId, partyId, surveyId, passThru, null); + } public SurveyWrapper(Delegator delegator, String surveyId) { this(delegator, null, null, surveyId, null); @@ -223,9 +223,8 @@ public class SurveyWrapper { Configuration config = FreeMarkerWorker.getDefaultOfbizConfig(); Template template = null; - try ( - InputStream templateStream = templateUrl.openStream(); - InputStreamReader templateReader = new InputStreamReader(templateStream, StandardCharsets.UTF_8);) { + try (InputStream templateStream = templateUrl.openStream(); + InputStreamReader templateReader = new InputStreamReader(templateStream, StandardCharsets.UTF_8);) { template = new Template(templateUrl.toExternalForm(), templateReader, config); } catch (IOException e) { Debug.logError(e, "Unable to get template from URL :" + templateUrl.toExternalForm(), MODULE); @@ -460,27 +459,27 @@ public class SurveyWrapper { // note this will need to be updated as new types are added if ("OPTION".equals(questionType)) { Map thisResult = getOptionResult(question); - Long questionTotal = (Long) thisResult.remove("_total"); - if (questionTotal == null) { - questionTotal = 0L; - } - // set the total responses - resultMap.put("_total", questionTotal); + Long questionTotal = (Long) thisResult.remove("_total"); + if (questionTotal == null) { + questionTotal = 0L; + } + // set the total responses + resultMap.put("_total", questionTotal); - // create the map of option info ("_total", "_percent") + // create the map of option info ("_total", "_percent") for (Entry entry : thisResult.entrySet()) { - Map optMap = new HashMap<>(); - Long optTotal = (Long) entry.getValue(); - String optId = entry.getKey(); - if (optTotal == null) { - optTotal = 0L; - } - Long percent = (long) (((double) optTotal / (double) questionTotal) * 100); - optMap.put("_total", optTotal); - optMap.put("_percent", percent); - resultMap.put(optId, optMap); + Map optMap = new HashMap<>(); + Long optTotal = (Long) entry.getValue(); + String optId = entry.getKey(); + if (optTotal == null) { + optTotal = 0L; } - resultMap.put("_a_type", "option"); + Long percent = (long) (((double) optTotal / (double) questionTotal) * 100); + optMap.put("_total", optTotal); + optMap.put("_percent", percent); + resultMap.put(optId, optMap); + } + resultMap.put("_a_type", "option"); } else if ("BOOLEAN".equals(questionType)) { long[] thisResult = getBooleanResult(question); long yesPercent = thisResult[1] > 0 ? (long) (((double) thisResult[1] / (double) thisResult[0]) * 100) : 0; @@ -527,7 +526,7 @@ public class SurveyWrapper { try { beganTransaction = TransactionUtil.begin(); - long[] result = { 0, 0, 0 }; + long[] result = {0, 0, 0 }; // index 0 = total responses // index 1 = total yes // index 2 = total no @@ -566,7 +565,7 @@ public class SurveyWrapper { } private double[] getNumberResult(GenericValue question, int type) throws SurveyWrapperException { - double[] result = { 0, 0, 0 }; + double[] result = {0, 0, 0 }; // index 0 = total responses // index 1 = tally // index 2 = average diff --git a/applications/content/src/main/java/org/apache/ofbiz/content/view/SimpleContentViewHandler.java b/applications/content/src/main/java/org/apache/ofbiz/content/view/SimpleContentViewHandler.java index 6a9f3801ec..b8a722762a 100644 --- a/applications/content/src/main/java/org/apache/ofbiz/content/view/SimpleContentViewHandler.java +++ b/applications/content/src/main/java/org/apache/ofbiz/content/view/SimpleContentViewHandler.java @@ -155,7 +155,7 @@ public class SimpleContentViewHandler extends AbstractViewHandler { } } // setup content type - String contentType2 = UtilValidate.isNotEmpty(mimeTypeId) ? mimeTypeId + "; charset=" +charset : contentType; + String contentType2 = UtilValidate.isNotEmpty(mimeTypeId) ? mimeTypeId + "; charset=" + charset : contentType; String fileName = null; if (UtilValidate.isNotEmpty(dataResource.getString("dataResourceName"))) { fileName = dataResource.getString("dataResourceName").replace(" ", "_"); // spaces in filenames can be a problem diff --git a/applications/content/src/main/java/org/apache/ofbiz/content/webapp/ftl/EditRenderSubContentCacheTransform.java b/applications/content/src/main/java/org/apache/ofbiz/content/webapp/ftl/EditRenderSubContentCacheTransform.java index 83695d0a2b..d5ee911358 100644 --- a/applications/content/src/main/java/org/apache/ofbiz/content/webapp/ftl/EditRenderSubContentCacheTransform.java +++ b/applications/content/src/main/java/org/apache/ofbiz/content/webapp/ftl/EditRenderSubContentCacheTransform.java @@ -50,7 +50,7 @@ import freemarker.template.TemplateTransformModel; public class EditRenderSubContentCacheTransform implements TemplateTransformModel { private static final String MODULE = EditRenderSubContentCacheTransform.class.getName(); - static final String[] saveKeyNames = {"contentId", "subContentId", "subDataResourceTypeId", "mimeTypeId", "whenMap", "locale", "wrapTemplateId", "encloseWrapText", "nullThruDatesOnly"}; + static final String[] saveKeyNames = {"contentId", "subContentId", "subDataResourceTypeId", "mimeTypeId", "whenMap", "locale", "wrapTemplateId", "encloseWrapText", "nullThruDatesOnly"}; /** * @deprecated use FreeMarkerWorker.getWrappedObject() diff --git a/applications/content/src/main/java/org/apache/ofbiz/content/webapp/ftl/InjectNodeTrailCsvTransform.java b/applications/content/src/main/java/org/apache/ofbiz/content/webapp/ftl/InjectNodeTrailCsvTransform.java index c813ef70f7..4f7f632be2 100644 --- a/applications/content/src/main/java/org/apache/ofbiz/content/webapp/ftl/InjectNodeTrailCsvTransform.java +++ b/applications/content/src/main/java/org/apache/ofbiz/content/webapp/ftl/InjectNodeTrailCsvTransform.java @@ -107,7 +107,7 @@ public class InjectNodeTrailCsvTransform implements TemplateTransformModel { List> trail = UtilGenerics.cast(templateCtx.get("globalNodeTrail")); if (Debug.infoOn()) { - Debug.logInfo("in InjectNodeTrailCsv(0), trail:"+trail, MODULE); + Debug.logInfo("in InjectNodeTrailCsv(0), trail:" + trail, MODULE); } // This will build a nodeTrail if none exists // Maybe only contentId or subContentId are passed in @@ -116,15 +116,15 @@ public class InjectNodeTrailCsvTransform implements TemplateTransformModel { if (UtilValidate.isEmpty(trail) || (redo != null && "true".equalsIgnoreCase(redo))) { String subContentId = (String) templateCtx.get("subContentId"); if (Debug.infoOn()) { - Debug.logInfo("in InjectNodeTrailCsv(0), subContentId:"+subContentId, MODULE); + Debug.logInfo("in InjectNodeTrailCsv(0), subContentId:" + subContentId, MODULE); } String contentId = (String) templateCtx.get("contentId"); if (Debug.infoOn()) { - Debug.logInfo("in InjectNodeTrailCsv(0), contentId:"+contentId, MODULE); + Debug.logInfo("in InjectNodeTrailCsv(0), contentId:" + contentId, MODULE); } String contentAssocTypeId = (String) templateCtx.get("contentAssocTypeId"); if (Debug.infoOn()) { - Debug.logInfo("in InjectNodeTrailCsv(0), contentAssocTypeId:"+contentAssocTypeId, MODULE); + Debug.logInfo("in InjectNodeTrailCsv(0), contentAssocTypeId:" + contentAssocTypeId, MODULE); } try { if (UtilValidate.isNotEmpty(subContentId)) { @@ -144,7 +144,7 @@ public class InjectNodeTrailCsvTransform implements TemplateTransformModel { throw new RuntimeException("Error getting current content. " + e.toString()); } if (Debug.infoOn()) { - Debug.logInfo("in InjectNodeTrailCsv(0), csvTrail:"+csvTrail, MODULE); + Debug.logInfo("in InjectNodeTrailCsv(0), csvTrail:" + csvTrail, MODULE); } } else { // Build nodeTrail if one does not exist @@ -163,8 +163,8 @@ public class InjectNodeTrailCsvTransform implements TemplateTransformModel { Map nd = trail.get(0); String firstTrailContentId = (String) nd.get("contentId"); if (UtilValidate.isNotEmpty(firstTrailContentId) - && UtilValidate.isNotEmpty(lastPassedContentId) - && firstTrailContentId.equals(lastPassedContentId)) { + && UtilValidate.isNotEmpty(lastPassedContentId) + && firstTrailContentId.equals(lastPassedContentId)) { csvTrail += "," + ContentWorker.nodeTrailToCsv(trail.subList(1, trail.size())); } else { csvTrail += "," + ContentWorker.nodeTrailToCsv(trail); diff --git a/applications/content/src/main/java/org/apache/ofbiz/content/webapp/ftl/RenderContentAsText.java b/applications/content/src/main/java/org/apache/ofbiz/content/webapp/ftl/RenderContentAsText.java index f672f2893c..70c1eb8632 100644 --- a/applications/content/src/main/java/org/apache/ofbiz/content/webapp/ftl/RenderContentAsText.java +++ b/applications/content/src/main/java/org/apache/ofbiz/content/webapp/ftl/RenderContentAsText.java @@ -53,7 +53,7 @@ public class RenderContentAsText implements TemplateTransformModel { private static final String MODULE = RenderContentAsText.class.getName(); static final String[] upSaveKeyNames = {"globalNodeTrail"}; - static final String[] saveKeyNames = {"contentId", "subContentId", "subDataResourceTypeId", "mimeTypeId", "whenMap", "locale", "wrapTemplateId", "encloseWrapText", "nullThruDatesOnly", "globalNodeTrail"}; + static final String[] saveKeyNames = {"contentId", "subContentId", "subDataResourceTypeId", "mimeTypeId", "whenMap", "locale", "wrapTemplateId", "encloseWrapText", "nullThruDatesOnly", "globalNodeTrail"}; @Override @SuppressWarnings("unchecked") diff --git a/applications/content/src/main/java/org/apache/ofbiz/content/webapp/ftl/RenderSubContentAsText.java b/applications/content/src/main/java/org/apache/ofbiz/content/webapp/ftl/RenderSubContentAsText.java index 29342e1b29..ceb02b2bfd 100644 --- a/applications/content/src/main/java/org/apache/ofbiz/content/webapp/ftl/RenderSubContentAsText.java +++ b/applications/content/src/main/java/org/apache/ofbiz/content/webapp/ftl/RenderSubContentAsText.java @@ -49,7 +49,7 @@ public class RenderSubContentAsText implements TemplateTransformModel { private static final String MODULE = RenderSubContentAsText.class.getName(); public static final String[] upSaveKeyNames = {"globalNodeTrail"}; - public static final String[] saveKeyNames = {"contentId", "subContentId", "subDataResourceTypeId", "mimeTypeId", "whenMap", "locale", "wrapTemplateId", "encloseWrapText", "nullThruDatesOnly", "globalNodeTrail"}; + public static final String[] saveKeyNames = {"contentId", "subContentId", "subDataResourceTypeId", "mimeTypeId", "whenMap", "locale", "wrapTemplateId", "encloseWrapText", "nullThruDatesOnly", "globalNodeTrail"}; @Override @SuppressWarnings("unchecked") diff --git a/applications/content/src/main/java/org/apache/ofbiz/content/webapp/ftl/TraverseSubContentCacheTransform.java b/applications/content/src/main/java/org/apache/ofbiz/content/webapp/ftl/TraverseSubContentCacheTransform.java index 7d673e8c77..47b8524d86 100644 --- a/applications/content/src/main/java/org/apache/ofbiz/content/webapp/ftl/TraverseSubContentCacheTransform.java +++ b/applications/content/src/main/java/org/apache/ofbiz/content/webapp/ftl/TraverseSubContentCacheTransform.java @@ -50,7 +50,7 @@ public class TraverseSubContentCacheTransform implements TemplateTransformModel private static final String MODULE = TraverseSubContentCacheTransform.class.getName(); static final String[] upSaveKeyNames = {"globalNodeTrail"}; - static final String[] saveKeyNames = {"contentId", "subContentId", "subDataResourceTypeId", "mimeTypeId", "whenMap", "locale", "wrapTemplateId", "encloseWrapText", "nullThruDatesOnly", "globalNodeTrail"}; + static final String[] saveKeyNames = {"contentId", "subContentId", "subDataResourceTypeId", "mimeTypeId", "whenMap", "locale", "wrapTemplateId", "encloseWrapText", "nullThruDatesOnly", "globalNodeTrail"}; /** * @deprecated use FreeMarkerWorker.getWrappedObject() diff --git a/applications/content/src/main/java/org/apache/ofbiz/content/webapp/ftl/WrapSubContentCacheTransform.java b/applications/content/src/main/java/org/apache/ofbiz/content/webapp/ftl/WrapSubContentCacheTransform.java index da6869739a..23b9e90a9b 100644 --- a/applications/content/src/main/java/org/apache/ofbiz/content/webapp/ftl/WrapSubContentCacheTransform.java +++ b/applications/content/src/main/java/org/apache/ofbiz/content/webapp/ftl/WrapSubContentCacheTransform.java @@ -50,7 +50,7 @@ public class WrapSubContentCacheTransform implements TemplateTransformModel { private static final String MODULE = WrapSubContentCacheTransform.class.getName(); static final String[] upSaveKeyNames = {"globalNodeTrail"}; - static final String[] saveKeyNames = {"contentId", "subContentId", "subDataResourceTypeId", "mimeTypeId", "whenMap", "locale", "wrapTemplateId", "encloseWrapText", "nullThruDatesOnly"}; + static final String[] saveKeyNames = {"contentId", "subContentId", "subDataResourceTypeId", "mimeTypeId", "whenMap", "locale", "wrapTemplateId", "encloseWrapText", "nullThruDatesOnly"}; /** * @deprecated use FreeMarkerWorker.getWrappedObject() diff --git a/applications/manufacturing/src/main/java/org/apache/ofbiz/manufacturing/bom/BOMHelper.java b/applications/manufacturing/src/main/java/org/apache/ofbiz/manufacturing/bom/BOMHelper.java index fa419442f9..3ff500bde1 100644 --- a/applications/manufacturing/src/main/java/org/apache/ofbiz/manufacturing/bom/BOMHelper.java +++ b/applications/manufacturing/src/main/java/org/apache/ofbiz/manufacturing/bom/BOMHelper.java @@ -34,7 +34,8 @@ import org.apache.ofbiz.service.GenericServiceException; import org.apache.ofbiz.service.LocalDispatcher; import org.apache.ofbiz.service.ServiceUtil; -/** Helper class containing static method useful when dealing +/** + * Helper class containing static method useful when dealing * with product's bills of materials. * These methods are also available as services (see {@link BOMServices}). */ @@ -42,18 +43,21 @@ public final class BOMHelper { private static final String MODULE = BOMHelper.class.getName(); - /** Creates a new instance of BOMHelper */ - private BOMHelper() { - } + /** + * Creates a new instance of BOMHelper + */ + private BOMHelper() { } - /** Returns the product's low level code (llc) i.e. the maximum depth + /** + * Returns the product's low level code (llc) i.e. the maximum depth * in which the productId can be found in any of the * bills of materials of bomType type. - * @return The low level code for the productId. (0 = root, 1 = first level, etc...) + * * @param productId The product id - * @param bomType The bill of materials type (e.g. manufacturing, engineering,...) + * @param bomType The bill of materials type (e.g. manufacturing, engineering,...) * @param delegator Validity date (if null, today is used). - * @param inDate The delegator + * @param inDate The delegator + * @return The low level code for the productId. (0 = root, 1 = first level, etc...) * @throws GenericEntityException If a db problem occurs. */ /* @@ -84,26 +88,29 @@ public final class BOMHelper { return maxDepth; } - /** Returns the ProductAssoc generic value for a duplicate productIdKey + /** + * Returns the ProductAssoc generic value for a duplicate productIdKey * ancestor if present, null otherwise. * Useful to avoid loops when adding new assocs (components) * to a bill of materials. - * @param productId The product to which we want to add a new child. - * @param productIdKey The new component we want to add to the existing bom. - * @param bomType The bill of materials type (e.g. manufacturing, engineering). - * @param inDate Validity date (if null, today is used). * - * @param delegator The delegator used - * @throws GenericEntityException If a db problem occurs + * @param productId The product to which we want to add a new child. + * @param productIdKey The new component we want to add to the existing bom. + * @param bomType The bill of materials type (e.g. manufacturing, engineering). + * @param inDate Validity date (if null, today is used). + * @param delegator The delegator used * @return the ProductAssoc generic value for a duplicate productIdKey * ancestor if present, null otherwise. + * @throws GenericEntityException If a db problem occurs */ - public static GenericValue searchDuplicatedAncestor(String productId, String productIdKey, String bomType, Date inDate, Delegator delegator, LocalDispatcher dispatcher, GenericValue userLogin) throws GenericEntityException { + public static GenericValue searchDuplicatedAncestor(String productId, String productIdKey, String bomType, Date inDate, Delegator delegator, + LocalDispatcher dispatcher, GenericValue userLogin) throws GenericEntityException { return searchDuplicatedAncestor(productId, productIdKey, null, bomType, inDate, delegator, dispatcher, userLogin); } private static GenericValue searchDuplicatedAncestor(String productId, String productIdKey, List productIdKeys, - String bomType, Date inDate, Delegator delegator, LocalDispatcher dispatcher, GenericValue userLogin) throws GenericEntityException { + String bomType, Date inDate, Delegator delegator, LocalDispatcher dispatcher, + GenericValue userLogin) throws GenericEntityException { // If the date is null, set it to today. if (inDate == null) inDate = new Date(); if (productIdKeys == null) { @@ -122,7 +129,8 @@ public final class BOMHelper { return oneNode; } } - duplicatedNode = searchDuplicatedAncestor(oneNode.getString("productId"), productIdKey, productIdKeys, bomType, inDate, delegator, dispatcher, userLogin); + duplicatedNode = searchDuplicatedAncestor(oneNode.getString("productId"), productIdKey, productIdKeys, bomType, inDate, delegator, + dispatcher, userLogin); if (duplicatedNode != null) { break; } @@ -130,7 +138,8 @@ public final class BOMHelper { return duplicatedNode; } - public static String createProductionRunsForShipment(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) { + public static String createProductionRunsForShipment(javax.servlet.http.HttpServletRequest request, + javax.servlet.http.HttpServletResponse response) { Delegator delegator = (Delegator) request.getAttribute("delegator"); LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher"); GenericValue userLogin = (GenericValue) request.getSession().getAttribute("userLogin"); @@ -138,30 +147,32 @@ public final class BOMHelper { String shipmentId = request.getParameter("shipmentId"); try { - List shipmentPlans = EntityQuery.use(delegator).from("OrderShipment") - .where("shipmentId", shipmentId).queryList(); - for (GenericValue shipmentPlan : shipmentPlans) { - GenericValue orderItem = shipmentPlan.getRelatedOne("OrderItem", false); + List shipmentPlans = EntityQuery.use(delegator).from("OrderShipment") + .where("shipmentId", shipmentId).queryList(); + for (GenericValue shipmentPlan : shipmentPlans) { + GenericValue orderItem = shipmentPlan.getRelatedOne("OrderItem", false); - List productionRuns = EntityQuery.use(delegator).from("WorkOrderItemFulfillment") - .where("orderId", shipmentPlan.get("orderId"), - "orderItemSeqId", shipmentPlan.get("orderItemSeqId"), - "shipGroupSeqId", shipmentPlan.get("shipGroupSeqId")) - .cache().queryList(); - if (UtilValidate.isNotEmpty(productionRuns)) { - Debug.logError("Production Run for order item (" + orderItem.getString("orderId") + "/" + orderItem.getString("orderItemSeqId") + ") not created.", MODULE); - continue; + List productionRuns = EntityQuery.use(delegator).from("WorkOrderItemFulfillment") + .where("orderId", shipmentPlan.get("orderId"), + "orderItemSeqId", shipmentPlan.get("orderItemSeqId"), + "shipGroupSeqId", shipmentPlan.get("shipGroupSeqId")) + .cache().queryList(); + if (UtilValidate.isNotEmpty(productionRuns)) { + Debug.logError("Production Run for order item (" + orderItem.getString("orderId") + "/" + orderItem.getString("orderItemSeqId") + ") not created.", MODULE); + continue; + } + Map result = dispatcher.runSync("createProductionRunsForOrder", UtilMisc.toMap("quantity", + shipmentPlan.getBigDecimal("quantity"), "orderId", + shipmentPlan.getString("orderId"), "orderItemSeqId", shipmentPlan.getString("orderItemSeqId"), "shipGroupSeqId", + shipmentPlan.getString("shipGroupSeqId"), "shipmentId", + shipmentId, "userLogin", userLogin)); + if (ServiceUtil.isError(result)) { + String errorMessage = ServiceUtil.getErrorMessage(result); + request.setAttribute("_ERROR_MESSAGE_", errorMessage); + Debug.logError(errorMessage, MODULE); + return "error"; + } } - Map result = dispatcher.runSync("createProductionRunsForOrder", UtilMisc.toMap("quantity", shipmentPlan.getBigDecimal("quantity"), "orderId", - shipmentPlan.getString("orderId"), "orderItemSeqId", shipmentPlan.getString("orderItemSeqId"), "shipGroupSeqId", shipmentPlan.getString("shipGroupSeqId"), "shipmentId", - shipmentId, "userLogin", userLogin)); - if (ServiceUtil.isError(result)) { - String errorMessage = ServiceUtil.getErrorMessage(result); - request.setAttribute("_ERROR_MESSAGE_", errorMessage); - Debug.logError(errorMessage, MODULE); - return "error"; - } - } } catch (GenericEntityException | GenericServiceException ge) { Debug.logWarning(ge, MODULE); } diff --git a/applications/manufacturing/src/main/java/org/apache/ofbiz/manufacturing/bom/BOMNode.java b/applications/manufacturing/src/main/java/org/apache/ofbiz/manufacturing/bom/BOMNode.java index 7afd6b2deb..3448182fbf 100644 --- a/applications/manufacturing/src/main/java/org/apache/ofbiz/manufacturing/bom/BOMNode.java +++ b/applications/manufacturing/src/main/java/org/apache/ofbiz/manufacturing/bom/BOMNode.java @@ -367,7 +367,7 @@ public class BOMNode { } public BOMNode getRootNode() { - return (parentNode != null? getParentNode(): this); + return (parentNode != null ? getParentNode() : this); } /** Setter for property parentNode. * @param parentNode New value of property parentNode. @@ -675,7 +675,7 @@ public class BOMNode { } public boolean isVirtual() { - return (product.get("isVirtual") != null? "Y".equals(product.get("isVirtual")): false); + return (product.get("isVirtual") != null ? "Y".equals(product.get("isVirtual")) : false); } public void isConfigured(List arr) { diff --git a/applications/manufacturing/src/main/java/org/apache/ofbiz/manufacturing/bom/BOMServices.java b/applications/manufacturing/src/main/java/org/apache/ofbiz/manufacturing/bom/BOMServices.java index fcef0b3bdd..9a2ef39bd6 100644 --- a/applications/manufacturing/src/main/java/org/apache/ofbiz/manufacturing/bom/BOMServices.java +++ b/applications/manufacturing/src/main/java/org/apache/ofbiz/manufacturing/bom/BOMServices.java @@ -524,7 +524,7 @@ public class BOMServices { OrderReadHelper orderReadHelper = (OrderReadHelper) orderReadHelpers.get(orderShipment.getString("orderId")); if (orderReadHelper != null) { Map orderShipmentReadMap = UtilMisc.toMap("orderShipment", orderShipment, "orderReadHelper", orderReadHelper); - String partyId = (orderReadHelper.getPlacingParty() != null? orderReadHelper.getPlacingParty().getString("partyId"): null); // FIXME: is it the customer? + String partyId = (orderReadHelper.getPlacingParty() != null ? orderReadHelper.getPlacingParty().getString("partyId") : null); // FIXME: is it the customer? if (partyId != null) { if (!partyOrderShipments.containsKey(partyId)) { List> orderShipmentReadMapList = new LinkedList<>(); diff --git a/applications/manufacturing/src/main/java/org/apache/ofbiz/manufacturing/bom/BOMTree.java b/applications/manufacturing/src/main/java/org/apache/ofbiz/manufacturing/bom/BOMTree.java index 1a5a78f08e..bbe2a576c2 100644 --- a/applications/manufacturing/src/main/java/org/apache/ofbiz/manufacturing/bom/BOMTree.java +++ b/applications/manufacturing/src/main/java/org/apache/ofbiz/manufacturing/bom/BOMTree.java @@ -117,7 +117,7 @@ public class BOMTree { // We load the information about the product that needs to be manufactured // from Product entity GenericValue product = EntityQuery.use(delegator).from("Product") - .where("productId", (manufacturedAsProduct != null? manufacturedAsProduct.getString("productIdTo"): productId)) + .where("productId", (manufacturedAsProduct != null ? manufacturedAsProduct.getString("productIdTo") : productId)) .queryOne(); if (product == null) return; BOMNode originalNode = new BOMNode(product, dispatcher, userLogin); @@ -135,7 +135,7 @@ public class BOMTree { productIdForRules = virtualProduct.getString("productId"); manufacturedAsProduct = manufacturedAsProduct(virtualProduct.getString("productId"), inDate); product = EntityQuery.use(delegator).from("Product") - .where("productId", (manufacturedAsProduct != null? manufacturedAsProduct.getString("productIdTo"): virtualProduct.get("productId"))) + .where("productId", (manufacturedAsProduct != null ? manufacturedAsProduct.getString("productIdTo") : virtualProduct.get("productId"))) .queryOne(); } } diff --git a/applications/manufacturing/src/main/java/org/apache/ofbiz/manufacturing/jobshopmgt/ProductionRun.java b/applications/manufacturing/src/main/java/org/apache/ofbiz/manufacturing/jobshopmgt/ProductionRun.java index 4f056fc147..46d244a00f 100644 --- a/applications/manufacturing/src/main/java/org/apache/ofbiz/manufacturing/jobshopmgt/ProductionRun.java +++ b/applications/manufacturing/src/main/java/org/apache/ofbiz/manufacturing/jobshopmgt/ProductionRun.java @@ -376,7 +376,7 @@ public class ProductionRun { Debug.logWarning(e.getMessage(), MODULE); } } - return (UtilValidate.isNotEmpty(productionRunRoutingTasks) ? productionRunRoutingTasks.get(productionRunRoutingTasks.size() - 1): null); + return (UtilValidate.isNotEmpty(productionRunRoutingTasks) ? productionRunRoutingTasks.get(productionRunRoutingTasks.size() - 1) : null); } return null; } diff --git a/applications/manufacturing/src/main/java/org/apache/ofbiz/manufacturing/jobshopmgt/ProductionRunServices.java b/applications/manufacturing/src/main/java/org/apache/ofbiz/manufacturing/jobshopmgt/ProductionRunServices.java index a8f6da2409..24391585a8 100644 --- a/applications/manufacturing/src/main/java/org/apache/ofbiz/manufacturing/jobshopmgt/ProductionRunServices.java +++ b/applications/manufacturing/src/main/java/org/apache/ofbiz/manufacturing/jobshopmgt/ProductionRunServices.java @@ -59,9 +59,9 @@ import org.apache.ofbiz.service.GenericServiceException; import org.apache.ofbiz.service.LocalDispatcher; import org.apache.ofbiz.service.ModelService; import org.apache.ofbiz.service.ServiceUtil; + /** * Services for Production Run maintenance - * */ public class ProductionRunServices { @@ -76,7 +76,8 @@ public class ProductionRunServices { /** * Cancels a ProductionRun. - * @param ctx The DispatchContext that this service is operating in. + * + * @param ctx The DispatchContext that this service is operating in. * @param context Map containing the input parameters. * @return Map with the result of the service, the output parameters. */ @@ -104,7 +105,8 @@ public class ProductionRunServices { for (int i = 1; i < mandatoryWorkEfforts.size(); i++) { GenericValue mandatoryWorkEffort = (mandatoryWorkEfforts.get(i)).getGenericValue(); if (!("PRUN_CANCELLED".equals(mandatoryWorkEffort.getString("currentStatusId")))) { - return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunStatusNotChangedMandatoryProductionRunFound", locale)); + return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, + "ManufacturingProductionRunStatusNotChangedMandatoryProductionRunFound", locale)); } } Map serviceContext = new HashMap<>(); @@ -159,7 +161,8 @@ public class ProductionRunServices { Debug.logError(e, "Problem accessing WorkEffortGoodStandard entity", MODULE); return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunStatusNotChanged", locale)); } - result.put(ModelService.SUCCESS_MESSAGE, UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunStatusChanged", UtilMisc.toMap("newStatusId", "PRUN_DOC_PRINTED"), locale)); + result.put(ModelService.SUCCESS_MESSAGE, UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunStatusChanged", UtilMisc.toMap( + "newStatusId", "PRUN_DOC_PRINTED"), locale)); return result; } return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunCannotBeCancelled", locale)); @@ -168,16 +171,17 @@ public class ProductionRunServices { /** * Creates a Production Run. *
      - *
    • check if routing - product link exist
    • - *
    • check if product have a Bill Of Material
    • - *
    • check if routing have routingTask
    • - *
    • create the workEffort for ProductionRun
    • - *
    • create the WorkEffortGoodStandard for link between ProductionRun and the product it will produce
    • - *
    • for each valid routingTask of the routing create a workeffort-task
    • - *
    • for the first routingTask, create for all the valid productIdTo with no associateRoutingTask a WorkEffortGoodStandard
    • - *
    • for each valid routingTask of the routing and valid productIdTo associate with this RoutingTask create a WorkEffortGoodStandard
    • + *
    • check if routing - product link exist
    • + *
    • check if product have a Bill Of Material
    • + *
    • check if routing have routingTask
    • + *
    • create the workEffort for ProductionRun
    • + *
    • create the WorkEffortGoodStandard for link between ProductionRun and the product it will produce
    • + *
    • for each valid routingTask of the routing create a workeffort-task
    • + *
    • for the first routingTask, create for all the valid productIdTo with no associateRoutingTask a WorkEffortGoodStandard
    • + *
    • for each valid routingTask of the routing and valid productIdTo associate with this RoutingTask create a WorkEffortGoodStandard
    • *
    - * @param ctx The DispatchContext that this service is operating in. + * + * @param ctx The DispatchContext that this service is operating in. * @param context Map containing the input parameters, productId, routingId, pRQuantity, startDate, workEffortName, description * @return Map with the result of the service, the output parameters. */ @@ -190,7 +194,7 @@ public class ProductionRunServices { // TODO: security management and finishing cleaning (ex copy from PartyServices.java) // Mandatory input fields String productId = (String) context.get("productId"); - Timestamp startDate = (Timestamp) context.get("startDate"); + Timestamp startDate = (Timestamp) context.get("startDate"); BigDecimal pRQuantity = (BigDecimal) context.get("pRQuantity"); String facilityId = (String) context.get("facilityId"); // Optional input fields @@ -261,8 +265,10 @@ public class ProductionRunServices { // ProductionRun header creation, if (workEffortName == null) { - String prdName = UtilValidate.isNotEmpty(product.getString("productName"))? product.getString("productName"): product.getString("productId"); - String wefName = UtilValidate.isNotEmpty(routing.getString("workEffortName"))? routing.getString("workEffortName"): routing.getString("workEffortId"); + String prdName = UtilValidate.isNotEmpty(product.getString("productName")) ? product.getString("productName") : product.getString( + "productId"); + String wefName = UtilValidate.isNotEmpty(routing.getString("workEffortName")) ? routing.getString("workEffortName") : + routing.getString("workEffortId"); workEffortName = prdName + "-" + wefName; } @@ -290,7 +296,7 @@ public class ProductionRunServices { Debug.logInfo("ProductionRun created: " + productionRunId, MODULE); } - // ProductionRun, product will be produce creation = WorkEffortGoodStandard for the productId + // ProductionRun, product will be produce creation = WorkEffortGoodStandard for the productId serviceContext.clear(); serviceContext.put("workEffortId", productionRunId); serviceContext.put("productId", productId); @@ -317,7 +323,7 @@ public class ProductionRunServices { try { routingTask = routingTaskAssoc.getRelatedOne("ToWorkEffort", false); } catch (GenericEntityException e) { - Debug.logError(e.getMessage(), MODULE); + Debug.logError(e.getMessage(), MODULE); } // Calculate the estimatedCompletionDate long totalTime = ProductionRun.getEstimatedTaskTime(routingTask, pRQuantity, dispatcher); @@ -372,8 +378,8 @@ public class ProductionRunServices { // clone associated objects from the routing task to the run task String routingTaskId = routingTaskAssoc.getString("workEffortIdTo"); try { - cloneWorkEffortPartyAssignments(ctx, userLogin, routingTaskId, productionRunTaskId); - cloneWorkEffortCostCalcs(ctx, userLogin, routingTaskId, productionRunTaskId); + cloneWorkEffortPartyAssignments(ctx, userLogin, routingTaskId, productionRunTaskId); + cloneWorkEffortCostCalcs(ctx, userLogin, routingTaskId, productionRunTaskId); } catch (GeneralException e) { return ServiceUtil.returnError(e.getMessage()); } @@ -433,7 +439,8 @@ public class ProductionRunServices { } result.put("productionRunId", productionRunId); result.put("estimatedCompletionDate", startDate); - result.put(ModelService.SUCCESS_MESSAGE, UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunCreated", UtilMisc.toMap("productionRunId", productionRunId), locale)); + result.put(ModelService.SUCCESS_MESSAGE, UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunCreated", UtilMisc.toMap( + "productionRunId", productionRunId), locale)); return result; } @@ -441,23 +448,23 @@ public class ProductionRunServices { * Make a copy of the party assignments that were defined on the template routing task to the new production run task. */ private static void cloneWorkEffortPartyAssignments(DispatchContext dctx, GenericValue userLogin, - String routingTaskId, String productionRunTaskId) throws GeneralException { + String routingTaskId, String productionRunTaskId) throws GeneralException { List workEffortPartyAssignments = null; try { workEffortPartyAssignments = EntityUtil.filterByDate( dctx.getDelegator().findByAnd("WorkEffortPartyAssignment", UtilMisc.toMap("workEffortId", routingTaskId), null, false)); } catch (GenericEntityException e) { - Debug.logError(e.getMessage(), MODULE); + Debug.logError(e.getMessage(), MODULE); } if (workEffortPartyAssignments != null) { for (GenericValue workEffortPartyAssignment : workEffortPartyAssignments) { Map partyToWorkEffort = UtilMisc.toMap( - "workEffortId", productionRunTaskId, - "partyId", workEffortPartyAssignment.getString("partyId"), - "roleTypeId", workEffortPartyAssignment.getString("roleTypeId"), - "fromDate", workEffortPartyAssignment.getTimestamp("fromDate"), - "statusId", workEffortPartyAssignment.getString("statusId"), + "workEffortId", productionRunTaskId, + "partyId", workEffortPartyAssignment.getString("partyId"), + "roleTypeId", workEffortPartyAssignment.getString("roleTypeId"), + "fromDate", workEffortPartyAssignment.getTimestamp("fromDate"), + "statusId", workEffortPartyAssignment.getString("statusId"), "userLogin", userLogin); try { Map result = dctx.getDispatcher().runSync("assignPartyToWorkEffort", partyToWorkEffort); @@ -485,7 +492,7 @@ public class ProductionRunServices { workEffortCostCalcs = EntityUtil.filterByDate( dctx.getDelegator().findByAnd("WorkEffortCostCalc", UtilMisc.toMap("workEffortId", routingTaskId), null, false)); } catch (GenericEntityException e) { - Debug.logError(e.getMessage(), MODULE); + Debug.logError(e.getMessage(), MODULE); } if (workEffortCostCalcs != null) { @@ -518,13 +525,14 @@ public class ProductionRunServices { /** * Update a Production Run. *
      - *
    • update field and after recalculate the entire ProductionRun data (routingTask and productComponent)
    • - *
    • create the WorkEffortGoodStandard for link between ProductionRun and the product it will produce
    • - *
    • for each valid routingTask of the routing create a workeffort-task
    • - *
    • for the first routingTask, create for all the valid productIdTo with no associateRoutingTask a WorkEffortGoodStandard
    • - *
    • for each valid routingTask of the routing and valid productIdTo associate with this RoutingTask create a WorkEffortGoodStandard
    • - *
    - * @param ctx The DispatchContext that this service is operating in. + *
  • update field and after recalculate the entire ProductionRun data (routingTask and productComponent)
  • + *
  • create the WorkEffortGoodStandard for link between ProductionRun and the product it will produce
  • + *
  • for each valid routingTask of the routing create a workeffort-task
  • + *
  • for the first routingTask, create for all the valid productIdTo with no associateRoutingTask a WorkEffortGoodStandard
  • + *
  • for each valid routingTask of the routing and valid productIdTo associate with this RoutingTask create a WorkEffortGoodStandard
  • + * + * + * @param ctx The DispatchContext that this service is operating in. * @param context Map containing the input parameters, productId, routingId, quantity, estimatedStartDate, workEffortName, description * @return Map with the result of the service, the output parameters. */ @@ -540,31 +548,31 @@ public class ProductionRunServices { if (productionRun.exist()) { if (!"PRUN_CREATED".equals(productionRun.getGenericValue().getString("currentStatusId")) && - !"PRUN_SCHEDULED".equals(productionRun.getGenericValue().getString("currentStatusId"))) { + !"PRUN_SCHEDULED".equals(productionRun.getGenericValue().getString("currentStatusId"))) { return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunPrinted", locale)); } BigDecimal quantity = (BigDecimal) context.get("quantity"); - if (quantity != null && quantity.compareTo(productionRun.getQuantity()) != 0) { + if (quantity != null && quantity.compareTo(productionRun.getQuantity()) != 0) { productionRun.setQuantity(quantity); } - Timestamp estimatedStartDate = (Timestamp) context.get("estimatedStartDate"); + Timestamp estimatedStartDate = (Timestamp) context.get("estimatedStartDate"); if (estimatedStartDate != null && !estimatedStartDate.equals(productionRun.getEstimatedStartDate())) { productionRun.setEstimatedStartDate(estimatedStartDate); } - String workEffortName = (String) context.get("workEffortName"); + String workEffortName = (String) context.get("workEffortName"); if (workEffortName != null) { productionRun.setProductionRunName(workEffortName); } - String description = (String) context.get("description"); + String description = (String) context.get("description"); if (description != null) { productionRun.setDescription(description); } - String facilityId = (String) context.get("facilityId"); + String facilityId = (String) context.get("facilityId"); if (facilityId != null) { productionRun.getGenericValue().set("facilityId", facilityId); } @@ -585,11 +593,11 @@ public class ProductionRunServices { } return ServiceUtil.returnSuccess(); } else { - Debug.logError("productionRun.store() fail for productionRunId ="+productionRunId, MODULE); + Debug.logError("productionRun.store() fail for productionRunId =" + productionRunId, MODULE); return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunNotUpdated", locale)); } } - Debug.logError("no productionRun for productionRunId ="+productionRunId, MODULE); + Debug.logError("no productionRun for productionRunId =" + productionRunId, MODULE); return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunNotUpdated", locale)); } Debug.logError("service updateProductionRun call with productionRunId empty", MODULE); @@ -614,7 +622,8 @@ public class ProductionRunServices { if (currentStatusId.equals(statusId)) { result.put("newStatusId", currentStatusId); - result.put(ModelService.SUCCESS_MESSAGE, UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunStatusChanged", UtilMisc.toMap("newStatusId", currentStatusId), locale)); + result.put(ModelService.SUCCESS_MESSAGE, UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunStatusChanged", UtilMisc.toMap( + "newStatusId", currentStatusId), locale)); return result; } @@ -652,7 +661,8 @@ public class ProductionRunServices { } } result.put("newStatusId", statusId); - result.put(ModelService.SUCCESS_MESSAGE, UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunStatusChanged", UtilMisc.toMap("newStatusId", "PRUN_CLOSED"), locale)); + result.put(ModelService.SUCCESS_MESSAGE, UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunStatusChanged", UtilMisc.toMap( + "newStatusId", "PRUN_CLOSED"), locale)); return result; } @@ -690,7 +700,8 @@ public class ProductionRunServices { } } result.put("newStatusId", "PRUN_DOC_PRINTED"); - result.put(ModelService.SUCCESS_MESSAGE, UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunStatusChanged", UtilMisc.toMap("newStatusId", "PRUN_DOC_PRINTED"), locale)); + result.put(ModelService.SUCCESS_MESSAGE, UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunStatusChanged", UtilMisc.toMap( + "newStatusId", "PRUN_DOC_PRINTED"), locale)); return result; } @@ -709,7 +720,8 @@ public class ProductionRunServices { if (!("PRUN_COMPLETED".equals(mandatoryWorkEffort.getString("currentStatusId")) || "PRUN_RUNNING".equals(mandatoryWorkEffort.getString("currentStatusId")) || "PRUN_CLOSED".equals(mandatoryWorkEffort.getString("currentStatusId")))) { - return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunStatusNotChangedMandatoryProductionRunNotCompleted", locale)); + return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, + "ManufacturingProductionRunStatusNotChangedMandatoryProductionRunNotCompleted", locale)); } } } catch (GenericEntityException gee) { @@ -732,7 +744,8 @@ public class ProductionRunServices { return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunStatusNotChanged", locale)); } result.put("newStatusId", "PRUN_RUNNING"); - result.put(ModelService.SUCCESS_MESSAGE, UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunStatusChanged", UtilMisc.toMap("newStatusId", "PRUN_DOC_PRINTED"), locale)); + result.put(ModelService.SUCCESS_MESSAGE, UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunStatusChanged", UtilMisc.toMap( + "newStatusId", "PRUN_DOC_PRINTED"), locale)); return result; } @@ -756,7 +769,8 @@ public class ProductionRunServices { return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunStatusNotChanged", locale)); } result.put("newStatusId", "PRUN_COMPLETED"); - result.put(ModelService.SUCCESS_MESSAGE, UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunStatusChanged", UtilMisc.toMap("newStatusId", "PRUN_DOC_PRINTED"), locale)); + result.put(ModelService.SUCCESS_MESSAGE, UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunStatusChanged", UtilMisc.toMap( + "newStatusId", "PRUN_DOC_PRINTED"), locale)); return result; } @@ -794,11 +808,13 @@ public class ProductionRunServices { } } result.put("newStatusId", "PRUN_CLOSED"); - result.put(ModelService.SUCCESS_MESSAGE, UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunStatusChanged", UtilMisc.toMap("newStatusId", "PRUN_CLOSED"), locale)); + result.put(ModelService.SUCCESS_MESSAGE, UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunStatusChanged", UtilMisc.toMap( + "newStatusId", "PRUN_CLOSED"), locale)); return result; } result.put("newStatusId", currentStatusId); - result.put(ModelService.SUCCESS_MESSAGE, UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunStatusChanged", UtilMisc.toMap("newStatusId", currentStatusId), locale)); + result.put(ModelService.SUCCESS_MESSAGE, UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunStatusChanged", UtilMisc.toMap( + "newStatusId", currentStatusId), locale)); return result; } @@ -831,7 +847,8 @@ public class ProductionRunServices { if (oneTask.getString("workEffortId").equals(taskId)) { theTask = oneTask; } else { - if (theTask == null && allPrecTaskCompletedOrRunning && (!"PRUN_COMPLETED".equals(oneTask.getString("currentStatusId")) && !"PRUN_RUNNING".equals(oneTask.getString("currentStatusId")))) { + if (theTask == null && allPrecTaskCompletedOrRunning && (!"PRUN_COMPLETED".equals(oneTask.getString("currentStatusId")) && ! + "PRUN_RUNNING".equals(oneTask.getString("currentStatusId")))) { allPrecTaskCompletedOrRunning = false; } if (allTaskCompleted && !"PRUN_COMPLETED".equals(oneTask.getString("currentStatusId"))) { @@ -849,7 +866,8 @@ public class ProductionRunServices { if (statusId != null && currentStatusId.equals(statusId)) { result.put("oldStatusId", oldStatusId); result.put("newStatusId", currentStatusId); - result.put(ModelService.SUCCESS_MESSAGE, UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunTaskStatusChanged", UtilMisc.toMap("newStatusId", currentStatusId), locale)); + result.put(ModelService.SUCCESS_MESSAGE, UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunTaskStatusChanged", + UtilMisc.toMap("newStatusId", currentStatusId), locale)); return result; } @@ -859,10 +877,12 @@ public class ProductionRunServices { // change the production run task status to PRUN_RUNNING // if necessary change the production run (header) status to PRUN_RUNNING if (!allPrecTaskCompletedOrRunning) { - return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunTaskCannotStartPrevTasksNotCompleted", locale)); + return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunTaskCannotStartPrevTasksNotCompleted" + , locale)); } if ("PRUN_CREATED".equals(productionRun.getGenericValue().getString("currentStatusId"))) { - return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunTaskCannotStartDocsNotPrinted", locale)); + return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunTaskCannotStartDocsNotPrinted", + locale)); } Map serviceContext = new HashMap<>(); serviceContext.clear(); @@ -896,7 +916,8 @@ public class ProductionRunServices { } result.put("oldStatusId", oldStatusId); result.put("newStatusId", "PRUN_RUNNING"); - result.put(ModelService.SUCCESS_MESSAGE, UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunStatusChanged", UtilMisc.toMap("newStatusId", "PRUN_DOC_PRINTED"), locale)); + result.put(ModelService.SUCCESS_MESSAGE, UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunStatusChanged", UtilMisc.toMap( + "newStatusId", "PRUN_DOC_PRINTED"), locale)); return result; } @@ -1008,7 +1029,8 @@ public class ProductionRunServices { if (partyAccountingPreference == null) { return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunUnableToFindCosts", locale)); } - outputMap = dispatcher.runSync("getProductionRunCost", UtilMisc.toMap("userLogin", userLogin, "workEffortId", productionRunId)); + outputMap = dispatcher.runSync("getProductionRunCost", UtilMisc.toMap("userLogin", userLogin, "workEffortId", + productionRunId)); if (ServiceUtil.isError(outputMap)) { return ServiceUtil.returnError(ServiceUtil.getErrorMessage(outputMap)); } @@ -1025,7 +1047,8 @@ public class ProductionRunServices { GenericValue customMethod = costComponentCalc.getRelatedOne("CustomMethod", false); if (customMethod == null) { // TODO: not supported for CostComponentCalc entries directly associated to a product - Debug.logWarning("Unable to create cost component for cost component calc with id [" + costComponentCalc.getString("costComponentCalcId") + "] because customMethod is not set", MODULE); + Debug.logWarning("Unable to create cost component for cost component calc with id [" + costComponentCalc.getString( + "costComponentCalcId") + "] because customMethod is not set", MODULE); } else { Map costMethodResult = dispatcher.runSync(customMethod.getString("customMethodName"), UtilMisc.toMap("productCostComponentCalc", productCostComponentCalc, @@ -1058,12 +1081,14 @@ public class ProductionRunServices { result.put("oldStatusId", oldStatusId); result.put("newStatusId", "PRUN_COMPLETED"); - result.put(ModelService.SUCCESS_MESSAGE, UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunStatusChanged", UtilMisc.toMap("newStatusId", "PRUN_DOC_PRINTED"), locale)); + result.put(ModelService.SUCCESS_MESSAGE, UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunStatusChanged", UtilMisc.toMap( + "newStatusId", "PRUN_DOC_PRINTED"), locale)); return result; } result.put("oldStatusId", oldStatusId); result.put("newStatusId", currentStatusId); - result.put(ModelService.SUCCESS_MESSAGE, UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunTaskStatusChanged", UtilMisc.toMap("newStatusId", currentStatusId), locale)); + result.put(ModelService.SUCCESS_MESSAGE, UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunTaskStatusChanged", UtilMisc.toMap( + "newStatusId", currentStatusId), locale)); return result; } @@ -1096,7 +1121,8 @@ public class ProductionRunServices { result.put("totalCost", totalCost); result.put("totalCostNoMaterials", totalCostNoMaterials); } catch (GenericEntityException gee) { - return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunUnableToFindCostsForWorkEffort", UtilMisc.toMap("workEffortId", workEffortId, "errorString", gee.getMessage()), locale)); + return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunUnableToFindCostsForWorkEffort", + UtilMisc.toMap("workEffortId", workEffortId, "errorString", gee.getMessage()), locale)); } return result; } @@ -1148,7 +1174,8 @@ public class ProductionRunServices { try { GenericValue workEffort = EntityQuery.use(delegator).from("WorkEffort").where("workEffortId", productionRunTaskId).queryOne(); if (UtilValidate.isEmpty(workEffort)) { - return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunTaskNotFound", UtilMisc.toMap("productionRunTaskId", productionRunTaskId), locale)); + return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunTaskNotFound", UtilMisc.toMap( + "productionRunTaskId", productionRunTaskId), locale)); } double actualTotalMilliSeconds = 0.0; Double actualSetupMillis = workEffort.getDouble("actualSetupMillis"); @@ -1165,7 +1192,7 @@ public class ProductionRunServices { GenericValue routingTaskAssoc = EntityQuery.use(delegator).from("WorkEffortAssoc") .where("workEffortIdTo", productionRunTaskId, "workEffortAssocTypeId", "WORK_EFF_TEMPLATE") - .filterByDate().queryFirst(); + .filterByDate().queryFirst(); GenericValue routingTask = null; if (routingTaskAssoc != null) { routingTask = routingTaskAssoc.getRelatedOne("FromWorkEffort", false); @@ -1229,10 +1256,11 @@ public class ProductionRunServices { List setupCosts = fixedAsset.getRelated("FixedAssetStdCost", UtilMisc.toMap("fixedAssetStdCostTypeId", "SETUP_COST"), null, false); GenericValue setupCost = EntityUtil.getFirst(EntityUtil.filterByDate(setupCosts)); - List usageCosts = fixedAsset.getRelated("FixedAssetStdCost", UtilMisc.toMap("fixedAssetStdCostTypeId", "USAGE_COST"), null, false); + List usageCosts = fixedAsset.getRelated("FixedAssetStdCost", UtilMisc.toMap("fixedAssetStdCostTypeId", "USAGE_COST"), + null, false); GenericValue usageCost = EntityUtil.getFirst(EntityUtil.filterByDate(usageCosts)); if (setupCost != null || usageCost != null) { - String currencyUomId = (setupCost != null? setupCost.getString("amountUomId"): usageCost.getString("amountUomId")); + String currencyUomId = (setupCost != null ? setupCost.getString("amountUomId") : usageCost.getString("amountUomId")); BigDecimal setupCostAmount = ZERO; if (setupCost != null) { setupCostAmount = setupCost.getBigDecimal("amount").multiply(BigDecimal.valueOf(actualSetupMillis)); @@ -1264,7 +1292,7 @@ public class ProductionRunServices { try { Map materialsCostByCurrency = new HashMap<>(); for (GenericValue inventoryConsumed : EntityQuery.use(delegator).from("WorkEffortAndInventoryAssign") - .where("workEffortId", productionRunTaskId).queryList()) { + .where("workEffortId", productionRunTaskId).queryList()) { BigDecimal quantity = inventoryConsumed.getBigDecimal("quantity"); BigDecimal unitCost = inventoryConsumed.getBigDecimal("unitCost"); if (UtilValidate.isEmpty(unitCost) || UtilValidate.isEmpty(quantity)) { @@ -1301,13 +1329,15 @@ public class ProductionRunServices { * Check if field for routingTask update are correct and if need recalculated data in Production Run. * Check *
      - *
    • if estimatedStartDate is not before Production Run estimatedStartDate.
    • - *
    • if there is not a another routingTask with the same priority
    • - *
    • If priority or estimatedStartDate has changed recalculated data for routingTask after that one.
    • + *
    • if estimatedStartDate is not before Production Run estimatedStartDate.
    • + *
    • if there is not a another routingTask with the same priority
    • + *
    • If priority or estimatedStartDate has changed recalculated data for routingTask after that one.
    • *
    * Update the productionRun - * @param ctx The DispatchContext that this service is operating in. - * @param context Map containing the input parameters, productId, routingId, priority, estimatedStartDate, estimatedSetupMillis, estimatedMilliSeconds + * + * @param ctx The DispatchContext that this service is operating in. + * @param context Map containing the input parameters, productId, routingId, priority, estimatedStartDate, estimatedSetupMillis, + * estimatedMilliSeconds * @return Map with the result of the service, the output parameters, estimatedCompletionDate. */ public static Map checkUpdatePrunRoutingTask(DispatchContext ctx, Map context) { @@ -1323,7 +1353,7 @@ public class ProductionRunServices { if (productionRun.exist()) { if (!"PRUN_CREATED".equals(productionRun.getGenericValue().getString("currentStatusId")) && - !"PRUN_SCHEDULED".equals(productionRun.getGenericValue().getString("currentStatusId"))) { + !"PRUN_SCHEDULED".equals(productionRun.getGenericValue().getString("currentStatusId"))) { return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunPrinted", locale)); } @@ -1331,7 +1361,8 @@ public class ProductionRunServices { Timestamp pRestimatedStartDate = productionRun.getEstimatedStartDate(); if (pRestimatedStartDate.after(estimatedStartDate)) { try { - serviceResult = dispatcher.runSync("updateProductionRun", UtilMisc.toMap("productionRunId", productionRunId, "estimatedStartDate", estimatedStartDate, "userLogin", userLogin)); + serviceResult = dispatcher.runSync("updateProductionRun", UtilMisc.toMap("productionRunId", productionRunId, + "estimatedStartDate", estimatedStartDate, "userLogin", userLogin)); if (ServiceUtil.isError(serviceResult)) { return ServiceUtil.returnError(ServiceUtil.getErrorMessage(serviceResult)); } @@ -1373,11 +1404,11 @@ public class ProductionRunServices { if (productionRun.store()) { return ServiceUtil.returnSuccess(); } else { - Debug.logError("productionRun.store() fail for productionRunId ="+productionRunId, MODULE); + Debug.logError("productionRun.store() fail for productionRunId =" + productionRunId, MODULE); return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunNotUpdated", locale)); } } - Debug.logError("no productionRun for productionRunId ="+productionRunId, MODULE); + Debug.logError("no productionRun for productionRunId =" + productionRunId, MODULE); return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunNotUpdated", locale)); } Debug.logError("service updateProductionRun call with productionRunId empty", MODULE); @@ -1478,7 +1509,7 @@ public class ProductionRunServices { } if (!"PRUN_CREATED".equals(productionRun.getGenericValue().getString("currentStatusId")) - && !"PRUN_SCHEDULED".equals(productionRun.getGenericValue().getString("currentStatusId"))) { + && !"PRUN_SCHEDULED".equals(productionRun.getGenericValue().getString("currentStatusId"))) { return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunPrinted", locale)); } @@ -1531,7 +1562,8 @@ public class ProductionRunServices { Debug.logError(e, "Problem calling the updateWorkEffortGoodStandard service", MODULE); return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunComponentNotAdded", locale)); } - result.put(ModelService.SUCCESS_MESSAGE, UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunComponentUpdated", UtilMisc.toMap("productionRunId", productionRunId), locale)); + result.put(ModelService.SUCCESS_MESSAGE, UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunComponentUpdated", UtilMisc.toMap( + "productionRunId", productionRunId), locale)); return result; } @@ -1553,12 +1585,12 @@ public class ProductionRunServices { Timestamp estimatedCompletionDate = (Timestamp) context.get("estimatedCompletionDate"); Double estimatedSetupMillis = null; - if (context.get("estimatedSetupMillis") != null) - estimatedSetupMillis = ((BigDecimal) context.get("estimatedSetupMillis")).doubleValue(); + if (context.get("estimatedSetupMillis") != null) + estimatedSetupMillis = ((BigDecimal) context.get("estimatedSetupMillis")).doubleValue(); Double estimatedMilliSeconds = null; - if (context.get("estimatedMilliSeconds") != null) - estimatedMilliSeconds = ((BigDecimal) context.get("estimatedMilliSeconds")).doubleValue(); + if (context.get("estimatedMilliSeconds") != null) + estimatedMilliSeconds = ((BigDecimal) context.get("estimatedMilliSeconds")).doubleValue(); // The production run is loaded ProductionRun productionRun = new ProductionRun(productionRunId, delegator, dispatcher); @@ -1568,7 +1600,7 @@ public class ProductionRunServices { } if (!"PRUN_CREATED".equals(productionRun.getGenericValue().getString("currentStatusId")) - && !"PRUN_SCHEDULED".equals(productionRun.getGenericValue().getString("currentStatusId"))) { + && !"PRUN_SCHEDULED".equals(productionRun.getGenericValue().getString("currentStatusId"))) { return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunPrinted", locale)); } @@ -1584,11 +1616,11 @@ public class ProductionRunServices { try { routingTask = EntityQuery.use(delegator).from("WorkEffort").where("workEffortId", routingTaskId).queryOne(); } catch (GenericEntityException e) { - Debug.logError(e.getMessage(), MODULE); + Debug.logError(e.getMessage(), MODULE); return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingRoutingTaskNotExists", locale)); } if (routingTask == null) { - Debug.logError("Routing task: " + routingTaskId + " is null.", MODULE); + Debug.logError("Routing task: " + routingTaskId + " is null.", MODULE); return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingRoutingTaskNotExists", locale)); } @@ -1657,16 +1689,16 @@ public class ProductionRunServices { .where("workEffortId", routingTaskId) .filterByDate().queryList(); } catch (GenericEntityException e) { - Debug.logError(e.getMessage(), MODULE); + Debug.logError(e.getMessage(), MODULE); } if (workEffortPartyAssignments != null) { for (GenericValue workEffortPartyAssignment : workEffortPartyAssignments) { Map partyToWorkEffort = UtilMisc.toMap( - "workEffortId", productionRunTaskId, - "partyId", workEffortPartyAssignment.getString("partyId"), - "roleTypeId", workEffortPartyAssignment.getString("roleTypeId"), - "fromDate", workEffortPartyAssignment.getTimestamp("fromDate"), - "statusId", workEffortPartyAssignment.getString("statusId"), + "workEffortId", productionRunTaskId, + "partyId", workEffortPartyAssignment.getString("partyId"), + "roleTypeId", workEffortPartyAssignment.getString("roleTypeId"), + "fromDate", workEffortPartyAssignment.getTimestamp("fromDate"), + "statusId", workEffortPartyAssignment.getString("statusId"), "userLogin", userLogin); try { serviceResult = dispatcher.runSync("assignPartyToWorkEffort", partyToWorkEffort); @@ -1759,27 +1791,27 @@ public class ProductionRunServices { if (lotId == null && autoCreateLot) { createLotIfNeeded = Boolean.TRUE; } - try { - // Find the lot - GenericValue lot = EntityQuery.use(delegator).from("Lot").where("lotId", lotId).queryOne(); - if (lot == null) { - if (createLotIfNeeded) { - Map createLotCtx = ctx.makeValidContext("createLot", ModelService.IN_PARAM, context); - createLotCtx.put("creationDate", UtilDateTime.nowTimestamp()); - Map serviceResults = dispatcher.runSync("createLot", createLotCtx); - if (ServiceUtil.isError(serviceResults)) { - Debug.logError(ServiceUtil.getErrorMessage(serviceResults), MODULE); - return ServiceUtil.returnError(ServiceUtil.getErrorMessage(serviceResults)); - } - lotId = (String) serviceResults.get("lotId"); - } else if (UtilValidate.isNotEmpty(lotId)) { - return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingLotNotExists", locale)); + try { + // Find the lot + GenericValue lot = EntityQuery.use(delegator).from("Lot").where("lotId", lotId).queryOne(); + if (lot == null) { + if (createLotIfNeeded) { + Map createLotCtx = ctx.makeValidContext("createLot", ModelService.IN_PARAM, context); + createLotCtx.put("creationDate", UtilDateTime.nowTimestamp()); + Map serviceResults = dispatcher.runSync("createLot", createLotCtx); + if (ServiceUtil.isError(serviceResults)) { + Debug.logError(ServiceUtil.getErrorMessage(serviceResults), MODULE); + return ServiceUtil.returnError(ServiceUtil.getErrorMessage(serviceResults)); } + lotId = (String) serviceResults.get("lotId"); + } else if (UtilValidate.isNotEmpty(lotId)) { + return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingLotNotExists", locale)); } - } catch (GenericEntityException | GenericServiceException e) { - Debug.logWarning(e.getMessage(), MODULE); - return ServiceUtil.returnError(e.getMessage()); } + } catch (GenericEntityException | GenericServiceException e) { + Debug.logWarning(e.getMessage(), MODULE); + return ServiceUtil.returnError(e.getMessage()); + } GenericValue orderItem = null; try { @@ -1796,7 +1828,8 @@ public class ProductionRunServices { try { // get the currency facility = productionRun.getGenericValue().getRelatedOne("Facility", false); - Map outputMap = dispatcher.runSync("getPartyAccountingPreferences", UtilMisc.toMap("userLogin", userLogin, "organizationPartyId", facility.getString("ownerPartyId"))); + Map outputMap = dispatcher.runSync("getPartyAccountingPreferences", UtilMisc.toMap("userLogin", + userLogin, "organizationPartyId", facility.getString("ownerPartyId"))); if (ServiceUtil.isError(outputMap)) { return ServiceUtil.returnError(ServiceUtil.getErrorMessage(outputMap)); } @@ -1804,7 +1837,9 @@ public class ProductionRunServices { if (partyAccountingPreference == null) { return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunUnableToFindCosts", locale)); } - outputMap = dispatcher.runSync("getProductCost", UtilMisc.toMap("userLogin", userLogin, "productId", productionRun.getProductProduced().getString("productId"), "currencyUomId", (String) partyAccountingPreference.get("baseCurrencyUomId"), "costComponentTypePrefix", "EST_STD")); + outputMap = dispatcher.runSync("getProductCost", UtilMisc.toMap("userLogin", userLogin, "productId", + productionRun.getProductProduced().getString("productId"), "currencyUomId", + (String) partyAccountingPreference.get("baseCurrencyUomId"), "costComponentTypePrefix", "EST_STD")); if (ServiceUtil.isError(outputMap)) { return ServiceUtil.returnError(ServiceUtil.getErrorMessage(outputMap)); } @@ -1816,7 +1851,7 @@ public class ProductionRunServices { List actualGenCosts = EntityQuery.use(delegator) .from("CostComponent") .where("workEffortId", productionRunId, - "costUomId", partyAccountingPreference.get("baseCurrencyUomId")) + "costUomId", partyAccountingPreference.get("baseCurrencyUomId")) .queryList(); for (GenericValue actualGenCost : actualGenCosts) { totalCost = totalCost.add((BigDecimal) actualGenCost.get("cost")); @@ -1825,7 +1860,7 @@ public class ProductionRunServices { List otherCosts = EntityQuery.use(delegator) .from("CostComponent") .where("workEffortId", task.get("workEffortId"), - "costUomId", partyAccountingPreference.get("baseCurrencyUomId")) + "costUomId", partyAccountingPreference.get("baseCurrencyUomId")) .queryList(); for (GenericValue otherCost : otherCosts) { totalCost = totalCost.add((BigDecimal) otherCost.get("cost")); @@ -1837,8 +1872,9 @@ public class ProductionRunServices { unitCost = BigDecimal.ZERO; } } - // Before creating InvntoryItem and InventoryItemDetails, check weather the record of ProductFacility exist in the system or not - GenericValue productFacility = EntityQuery.use(delegator). from("ProductFacility").where("productId", productionRun.getProductProduced().getString("productId"), + // Before creating InvntoryItem and InventoryItemDetails, check weather the record of ProductFacility exist in the system or not + GenericValue productFacility = EntityQuery.use(delegator).from("ProductFacility").where("productId", + productionRun.getProductProduced().getString("productId"), "facilityId", facility.get("facilityId")).queryOne(); if (productFacility == null) { Map createProductFacilityCtx = new HashMap<>(); @@ -1860,7 +1896,8 @@ public class ProductionRunServices { try { int numOfItems = quantity.intValue(); for (int i = 0; i < numOfItems; i++) { - Map serviceContext = UtilMisc.toMap("productId", productionRun.getProductProduced().getString("productId"), + Map serviceContext = UtilMisc.toMap("productId", productionRun.getProductProduced().getString( + "productId"), "inventoryItemTypeId", "SERIALIZED_INV_ITEM", "statusId", "INV_AVAILABLE"); serviceContext.put("facilityId", productionRun.getGenericValue().getString("facilityId")); @@ -1912,7 +1949,8 @@ public class ProductionRunServices { } } else { try { - Map serviceContext = UtilMisc.toMap("productId", productionRun.getProductProduced().getString("productId"), + Map serviceContext = UtilMisc.toMap("productId", productionRun.getProductProduced().getString( + "productId"), "inventoryItemTypeId", "NON_SERIAL_INV_ITEM"); serviceContext.put("facilityId", productionRun.getGenericValue().getString("facilityId")); serviceContext.put("datetimeReceived", UtilDateTime.nowTimestamp()); @@ -2220,7 +2258,7 @@ public class ProductionRunServices { try { BigDecimal totalIssued = BigDecimal.ZERO; for (GenericValue issuance : EntityQuery.use(delegator).from("WorkEffortAndInventoryAssign") - .where("workEffortId", productionRunTaskId, "productId", productId).queryList()) { + .where("workEffortId", productionRunTaskId, "productId", productId).queryList()) { BigDecimal issued = issuance.getBigDecimal("quantity"); if (issued != null) { totalIssued = totalIssued.add(issued); @@ -2228,7 +2266,7 @@ public class ProductionRunServices { } BigDecimal totalReturned = BigDecimal.ZERO; for (GenericValue returned : EntityQuery.use(delegator).from("WorkEffortAndInventoryProduced") - .where("workEffortId", productionRunTaskId, "productId", productId).queryList()) { + .where("workEffortId", productionRunTaskId, "productId", productId).queryList()) { GenericValue returnDetail = EntityQuery.use(delegator).from("InventoryItemDetail") .where("inventoryItemId", returned.get("inventoryItemId")) .orderBy("inventoryItemDetailSeqId") @@ -2241,7 +2279,9 @@ public class ProductionRunServices { } } if (quantity.compareTo(totalIssued.subtract(totalReturned)) > 0) { - return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunTaskCannotReturnMoreItems", UtilMisc.toMap("productionRunTaskId", productionRunTaskId, "quantity", quantity, "quantityAllocated", totalIssued.subtract(totalReturned)), locale)); + return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunTaskCannotReturnMoreItems", + UtilMisc.toMap("productionRunTaskId", productionRunTaskId, "quantity", quantity, "quantityAllocated", + totalIssued.subtract(totalReturned)), locale)); } } catch (GenericEntityException gee) { return ServiceUtil.returnError(gee.getMessage()); @@ -2256,7 +2296,8 @@ public class ProductionRunServices { "productId", productId, "quantity", quantity, "lotId", lotId, "currencyUomId", uomId, "isReturned", "Y", "inventoryItemTypeId", inventoryItemTypeId, "userLogin", userLogin)); if (ServiceUtil.isError(inventoryResult)) { - return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunTaskProduceError" + ServiceUtil.getErrorMessage(inventoryResult), locale)); + return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, + "ManufacturingProductionRunTaskProduceError" + ServiceUtil.getErrorMessage(inventoryResult), locale)); } } catch (GenericServiceException exc) { return ServiceUtil.returnError(exc.getMessage()); @@ -2352,7 +2393,8 @@ public class ProductionRunServices { try { List components = theTask.getRelated("WorkEffortGoodStandard", null, null, false); for (GenericValue component : components) { - BigDecimal totalRequiredMaterialQuantity = component.getBigDecimal("estimatedQuantity").multiply(totalQuantityProduced).divide(quantityToProduce, ROUNDING); + BigDecimal totalRequiredMaterialQuantity = + component.getBigDecimal("estimatedQuantity").multiply(totalQuantityProduced).divide(quantityToProduce, ROUNDING); // now get the units that have been already issued and subtract them List issuances = EntityQuery.use(delegator).from("WorkEffortAndInventoryAssign") .where("workEffortId", workEffortId, @@ -2387,7 +2429,7 @@ public class ProductionRunServices { if (ServiceUtil.isError(serviceResult)) { return ServiceUtil.returnError(ServiceUtil.getErrorMessage(serviceResult)); } - } + } } } catch (GenericEntityException | GenericServiceException e) { String errMsg = "Problem calling the updateProductionRunTaskStatus service"; @@ -2525,7 +2567,8 @@ public class ProductionRunServices { String productionRunId = (String) serviceResult.get("productionRunId"); result.put("productionRunId", productionRunId); - result.put(ModelService.SUCCESS_MESSAGE, UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunCreated", UtilMisc.toMap("productionRunId", productionRunId), locale)); + result.put(ModelService.SUCCESS_MESSAGE, UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunCreated", UtilMisc.toMap( + "productionRunId", productionRunId), locale)); return result; } @@ -2549,7 +2592,8 @@ public class ProductionRunServices { } if (config == null && configId != null) { // TODO: load the configuration - return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunFromConfigurationNotYetImplemented", locale)); + return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunFromConfigurationNotYetImplemented", + locale)); } if (!config.isCompleted()) { return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunFromConfigurationNotValid", locale)); @@ -2637,7 +2681,8 @@ public class ProductionRunServices { } catch (GenericServiceException e) { return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunNotCreated", locale)); } catch (GenericEntityException e) { - return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunTryToCreateWorkEffortAssoc", locale)); + return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunTryToCreateWorkEffortAssoc", + locale)); } } else { @@ -2691,13 +2736,15 @@ public class ProductionRunServices { } try { if (productionRunId != null && orderId != null && orderItemSeqId != null) { - delegator.create("WorkOrderItemFulfillment", UtilMisc.toMap("workEffortId", productionRunId, "orderId", orderId, "orderItemSeqId", orderItemSeqId)); + delegator.create("WorkOrderItemFulfillment", UtilMisc.toMap("workEffortId", productionRunId, "orderId", orderId, "orderItemSeqId", + orderItemSeqId)); } } catch (GenericEntityException e) { return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingRequirementNotDeleted", locale)); } - result.put(ModelService.SUCCESS_MESSAGE, UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunCreated", UtilMisc.toMap("productionRunId", productionRunId), locale)); + result.put(ModelService.SUCCESS_MESSAGE, UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunCreated", UtilMisc.toMap( + "productionRunId", productionRunId), locale)); return result; } @@ -2720,20 +2767,23 @@ public class ProductionRunServices { GenericValue productStore = delegator.getRelatedOne("ProductStore", order, false); isImmediatelyFulfilled = "Y".equals(productStore.getString("isImmediatelyFulfilled")); } catch (GenericEntityException e) { - return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunForMarketingPackagesCreationError", UtilMisc.toMap("orderId", orderId, "orderItemSeqId", orderItemSeqId, "errorString", e.getMessage()), locale)); + return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunForMarketingPackagesCreationError", + UtilMisc.toMap("orderId", orderId, "orderItemSeqId", orderItemSeqId, "errorString", e.getMessage()), locale)); } GenericValue orderItem = null; try { orderItem = EntityQuery.use(delegator).from("OrderItem").where("orderId", orderId, "orderItemSeqId", orderItemSeqId).queryOne(); } catch (GenericEntityException e) { - return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunForMarketingPackagesCreationError", UtilMisc.toMap("orderId", orderId, "orderItemSeqId", orderItemSeqId, "errorString", e.getMessage()), locale)); + return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunForMarketingPackagesCreationError", + UtilMisc.toMap("orderId", orderId, "orderItemSeqId", orderItemSeqId, "errorString", e.getMessage()), locale)); } if (orderItem == null) { - return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunForMarketingPackagesOrderItemNotFound", UtilMisc.toMap("orderId", orderId, "orderItemSeqId", orderItemSeqId), locale)); + return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunForMarketingPackagesOrderItemNotFound", + UtilMisc.toMap("orderId", orderId, "orderItemSeqId", orderItemSeqId), locale)); } if (orderItem.get("quantity") == null) { - Debug.logWarning("No quantity found for orderItem [" + orderItem +"], skipping production run of this marketing package", MODULE); + Debug.logWarning("No quantity found for orderItem [" + orderItem + "], skipping production run of this marketing package", MODULE); return ServiceUtil.returnSuccess(); } @@ -2754,7 +2804,9 @@ public class ProductionRunServices { existingAtp = existingAtp.subtract(orderItem.getBigDecimal("quantity")); } - if (Debug.verboseOn()) { Debug.logVerbose("Order item [" + orderItem + "] Existing ATP = [" + existingAtp + "]", MODULE); } + if (Debug.verboseOn()) { + Debug.logVerbose("Order item [" + orderItem + "] Existing ATP = [" + existingAtp + "]", MODULE); + } // we only need to produce more marketing packages if there isn't enough in stock. if (existingAtp.compareTo(ZERO) < 0) { // how many should we produce? If there already is some inventory, then just produce enough to bring ATP back up to zero. @@ -2802,7 +2854,10 @@ public class ProductionRunServices { } if (qtyToProduce.compareTo(ZERO) > 0) { - if (Debug.verboseOn()) { Debug.logVerbose("Required quantity (all orders) = [" + qtyRequired + "] quantity to produce = [" + qtyToProduce + "]", MODULE); } + if (Debug.verboseOn()) { + Debug.logVerbose("Required quantity (all orders) = [" + qtyRequired + "] quantity to produce = [" + qtyToProduce + "]", + MODULE); + } serviceContext.put("pRQuantity", qtyToProduce); serviceContext.put("startDate", UtilDateTime.nowTimestamp()); @@ -2814,10 +2869,13 @@ public class ProductionRunServices { result.put("productionRunId", productionRunId); try { - delegator.create("WorkOrderItemFulfillment", UtilMisc.toMap("workEffortId", productionRunId, "orderId", orderId, "orderItemSeqId", orderItemSeqId)); + delegator.create("WorkOrderItemFulfillment", UtilMisc.toMap("workEffortId", productionRunId, "orderId", orderId, + "orderItemSeqId", orderItemSeqId)); } catch (GenericEntityException e) { - return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunForMarketingPackagesCreationError", UtilMisc.toMap("orderId", orderId, "orderItemSeqId", orderItemSeqId, "errorString", e.getMessage()), locale)); - } + return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, + "ManufacturingProductionRunForMarketingPackagesCreationError", UtilMisc.toMap("orderId", orderId, "orderItemSeqId", + orderItemSeqId, "errorString", e.getMessage()), locale)); + } try { serviceContext.clear(); @@ -2839,14 +2897,20 @@ public class ProductionRunServices { return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunNotCreated", locale)); } - result.put(ModelService.SUCCESS_MESSAGE, UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunCreated", UtilMisc.toMap("productionRunId", productionRunId), locale)); + result.put(ModelService.SUCCESS_MESSAGE, UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunCreated", + UtilMisc.toMap("productionRunId", productionRunId), locale)); return result; } else { - if (Debug.verboseOn()) { Debug.logVerbose("There are not enough components available to produce any marketing packages [" + orderItem.getString("productId") + "]", MODULE); } + if (Debug.verboseOn()) { + Debug.logVerbose("There are not enough components available to produce any marketing packages [" + orderItem.getString( + "productId") + "]", MODULE); + } return ServiceUtil.returnSuccess(); } } else { - if (Debug.verboseOn()) { Debug.logVerbose("No marketing packages need to be produced - ATP is [" + existingAtp + "]", MODULE); } + if (Debug.verboseOn()) { + Debug.logVerbose("No marketing packages need to be produced - ATP is [" + existingAtp + "]", MODULE); + } return ServiceUtil.returnSuccess(); } } catch (GenericServiceException e) { @@ -2884,28 +2948,33 @@ public class ProductionRunServices { try { GenericValue orderItem = null; if (UtilValidate.isNotEmpty(shipGroupSeqId)) { - orderItem = EntityQuery.use(delegator).from("OrderItemShipGroupAssoc").where("orderId", orderId, "orderItemSeqId", orderItemSeqId, "shipGroupSeqId", shipGroupSeqId).queryOne(); + orderItem = EntityQuery.use(delegator).from("OrderItemShipGroupAssoc").where("orderId", orderId, "orderItemSeqId", + orderItemSeqId, "shipGroupSeqId", shipGroupSeqId).queryOne(); } else { orderItem = EntityQuery.use(delegator).from("OrderItem").where("orderId", orderId, "orderItemSeqId", orderItemSeqId).queryOne(); } if (orderItem == null) { - return ServiceUtil.returnError(UtilProperties.getMessage(RES_ORDER, "OrderErrorOrderItemNotFound", UtilMisc.toMap("orderId", orderId, "orderItemSeqId", ""), locale)); + return ServiceUtil.returnError(UtilProperties.getMessage(RES_ORDER, "OrderErrorOrderItemNotFound", UtilMisc.toMap("orderId", + orderId, "orderItemSeqId", ""), locale)); } if (quantity != null) { orderItem.set("quantity", quantity); } orderItems = UtilMisc.toList(orderItem); } catch (GenericEntityException gee) { - return ServiceUtil.returnError(UtilProperties.getMessage(RES_ORDER, "OrderProblemsReadingOrderItemInformation", UtilMisc.toMap("errorString", gee.getMessage()), locale)); + return ServiceUtil.returnError(UtilProperties.getMessage(RES_ORDER, "OrderProblemsReadingOrderItemInformation", UtilMisc.toMap( + "errorString", gee.getMessage()), locale)); } } else { try { orderItems = EntityQuery.use(delegator).from("OrderItem").where("orderId", orderId).queryList(); if (orderItems == null) { - return ServiceUtil.returnError(UtilProperties.getMessage(RES_ORDER, "OrderErrorOrderItemNotFound", UtilMisc.toMap("orderId", orderId, "orderItemSeqId", ""), locale)); + return ServiceUtil.returnError(UtilProperties.getMessage(RES_ORDER, "OrderErrorOrderItemNotFound", UtilMisc.toMap("orderId", + orderId, "orderItemSeqId", ""), locale)); } } catch (GenericEntityException gee) { - return ServiceUtil.returnError(UtilProperties.getMessage(RES_ORDER, "OrderProblemsReadingOrderItemInformation", UtilMisc.toMap("errorString", gee.getMessage()), locale)); + return ServiceUtil.returnError(UtilProperties.getMessage(RES_ORDER, "OrderProblemsReadingOrderItemInformation", UtilMisc.toMap( + "errorString", gee.getMessage()), locale)); } } List productionRuns = new LinkedList<>(); @@ -2945,24 +3014,28 @@ public class ProductionRunServices { existingProductionRuns = EntityQuery.use(delegator).from("WorkAndOrderItemFulfillment") .where( EntityCondition.makeCondition("orderId", EntityOperator.EQUALS, orderItemOrShipGroupAssoc.get("orderId")), - EntityCondition.makeCondition("orderItemSeqId", EntityOperator.EQUALS, orderItemOrShipGroupAssoc.get("orderItemSeqId")), - EntityCondition.makeCondition("shipGroupSeqId", EntityOperator.EQUALS, orderItemOrShipGroupAssoc.get("shipGroupSeqId")), + EntityCondition.makeCondition("orderItemSeqId", EntityOperator.EQUALS, orderItemOrShipGroupAssoc.get( + "orderItemSeqId")), + EntityCondition.makeCondition("shipGroupSeqId", EntityOperator.EQUALS, orderItemOrShipGroupAssoc.get( + "shipGroupSeqId")), EntityCondition.makeCondition("currentStatusId", EntityOperator.NOT_EQUAL, "PRUN_CANCELLED")) - .cache().queryList(); + .cache().queryList(); } else { existingProductionRuns = EntityQuery.use(delegator).from("WorkAndOrderItemFulfillment") .where( EntityCondition.makeCondition("orderId", EntityOperator.EQUALS, orderItemOrShipGroupAssoc.get("orderId")), - EntityCondition.makeCondition("orderItemSeqId", EntityOperator.EQUALS, orderItemOrShipGroupAssoc.get("orderItemSeqId")), + EntityCondition.makeCondition("orderItemSeqId", EntityOperator.EQUALS, orderItemOrShipGroupAssoc.get( + "orderItemSeqId")), EntityCondition.makeCondition("currentStatusId", EntityOperator.NOT_EQUAL, "PRUN_CANCELLED")) - .cache().queryList(); + .cache().queryList(); } if (UtilValidate.isNotEmpty(existingProductionRuns)) { Debug.logWarning("Production Run for order item [" + orderItemOrShipGroupAssoc.getString("orderId") + "/" + orderItemOrShipGroupAssoc.getString("orderItemSeqId") + "] and ship group [" + shipGroupSeqId + "] already exists.", MODULE); continue; } } catch (GenericEntityException gee) { - return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturinWorkOrderItemFulfillmentError", UtilMisc.toMap("errorString", gee.getMessage()), locale)); + return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturinWorkOrderItemFulfillmentError", UtilMisc.toMap( + "errorString", gee.getMessage()), locale)); } try { List components = new LinkedList<>(); @@ -2970,9 +3043,11 @@ public class ProductionRunServices { tree.setRootQuantity(quantity); tree.setRootAmount(amount); tree.print(components); - productionRuns.add(tree.createManufacturingOrders(null, fromDate, null, null, null, orderId, orderItem.getString("orderItemSeqId"), shipGroupSeqId, shipmentId, userLogin)); + productionRuns.add(tree.createManufacturingOrders(null, fromDate, null, null, null, orderId, orderItem.getString("orderItemSeqId"), + shipGroupSeqId, shipmentId, userLogin)); } catch (GenericEntityException gee) { - return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingBomErrorCreatingBillOfMaterialsTree", UtilMisc.toMap("errorString", gee.getMessage()), locale)); + return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingBomErrorCreatingBillOfMaterialsTree", + UtilMisc.toMap("errorString", gee.getMessage()), locale)); } } result.put("productionRuns", productionRuns); @@ -2983,7 +3058,7 @@ public class ProductionRunServices { Map result = new HashMap<>(); Delegator delegator = dctx.getDelegator(); LocalDispatcher dispatcher = dctx.getDispatcher(); - GenericValue userLogin =(GenericValue) context.get("userLogin"); + GenericValue userLogin = (GenericValue) context.get("userLogin"); Locale locale = (Locale) context.get("locale"); String productId = (String) context.get("productId"); Timestamp startDate = (Timestamp) context.get("startDate"); @@ -3002,12 +3077,15 @@ public class ProductionRunServices { tree.setRootQuantity(quantity); tree.setRootAmount(BigDecimal.ZERO); tree.print(components); - workEffortId = tree.createManufacturingOrders(facilityId, startDate, workEffortName, description, routingId, null, null, null, null, userLogin); + workEffortId = tree.createManufacturingOrders(facilityId, startDate, workEffortName, description, routingId, null, null, null, null, + userLogin); } catch (GenericEntityException gee) { - return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingBomErrorCreatingBillOfMaterialsTree", UtilMisc.toMap("errorString", gee.getMessage()), locale)); + return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingBomErrorCreatingBillOfMaterialsTree", UtilMisc.toMap( + "errorString", gee.getMessage()), locale)); } if (workEffortId == null) { - return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunIsNotRequiredForProductId", UtilMisc.toMap("productId", productId, "startDate", startDate), locale)); + return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunIsNotRequiredForProductId", + UtilMisc.toMap("productId", productId, "startDate", startDate), locale)); } List productionRuns = new LinkedList<>(); result.put("productionRuns", productionRuns); @@ -3018,7 +3096,8 @@ public class ProductionRunServices { /** * Quick runs a ProductionRun task to the completed status, also issuing components * if necessary. - * @param ctx The DispatchContext that this service is operating in. + * + * @param ctx The DispatchContext that this service is operating in. * @param context Map containing the input parameters. * @return Map with the result of the service, the output parameters. */ @@ -3049,7 +3128,8 @@ public class ProductionRunServices { } currentStatusId = (String) serviceResult.get("newStatusId"); if (currentStatusId.equals(prevStatusId)) { - return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunUnableToProgressTaskStatus", UtilMisc.toMap("prevStatusId", prevStatusId, "taskId", taskId), locale)); + return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunUnableToProgressTaskStatus", + UtilMisc.toMap("prevStatusId", prevStatusId, "taskId", taskId), locale)); } else { prevStatusId = currentStatusId; } @@ -3068,7 +3148,8 @@ public class ProductionRunServices { /** * Quick runs all the tasks of a ProductionRun to the completed status, * also issuing components if necessary. - * @param ctx The DispatchContext that this service is operating in. + * + * @param ctx The DispatchContext that this service is operating in. * @param context Map containing the input parameters. * @return Map with the result of the service, the output parameters. */ @@ -3152,7 +3233,8 @@ public class ProductionRunServices { /** * Quick moves a ProductionRun to the passed in status, performing all * the needed tasks in the way. - * @param ctx The DispatchContext that this service is operating in. + * + * @param ctx The DispatchContext that this service is operating in. * @param context Map containing the input parameters. * @return Map with the result of the service, the output parameters. */ @@ -3235,7 +3317,8 @@ public class ProductionRunServices { /** * Given a productId and an optional date, returns the total qty * of productId reserved by production runs. - * @param ctx The DispatchContext that this service is operating in. + * + * @param ctx The DispatchContext that this service is operating in. * @param context Map containing the input parameters. * @return Map with the result of the service, the output parameters. */ @@ -3294,18 +3377,21 @@ public class ProductionRunServices { try { GenericValue inventoryItem = EntityQuery.use(delegator).from("InventoryItem").where("inventoryItemId", inventoryItemId).queryOne(); if (inventoryItem == null) { - return ServiceUtil.returnError(UtilProperties.getMessage(RES_PRODUCT, "ProductInventoryItemNotFound", UtilMisc.toMap("inventoryItemId", inventoryItemId), locale)); + return ServiceUtil.returnError(UtilProperties.getMessage(RES_PRODUCT, "ProductInventoryItemNotFound", UtilMisc.toMap( + "inventoryItemId", inventoryItemId), locale)); } if (inventoryItem.get("availableToPromiseTotal") != null && inventoryItem.getBigDecimal("availableToPromiseTotal").compareTo(ZERO) <= 0) { return ServiceUtil.returnSuccess(); } GenericValue product = inventoryItem.getRelatedOne("Product", false); if (product == null) { - return ServiceUtil.returnError(UtilProperties.getMessage(RES_PRODUCT, "ProductProductNotFound", locale) + " " + inventoryItem.get("productId")); + return ServiceUtil.returnError(UtilProperties.getMessage(RES_PRODUCT, "ProductProductNotFound", locale) + " " + inventoryItem.get( + "productId")); } - if (EntityTypeUtil.hasParentType(delegator, "ProductType", "productTypeId", product.getString("productTypeId"), "parentTypeId", "MARKETING_PKG_AUTO")) { + if (EntityTypeUtil.hasParentType(delegator, "ProductType", "productTypeId", product.getString("productTypeId"), "parentTypeId", + "MARKETING_PKG_AUTO")) { Map serviceContext = UtilMisc.toMap("inventoryItemId", inventoryItemId, - "userLogin", userLogin); + "userLogin", userLogin); serviceResult = dispatcher.runSync("decomposeInventoryItem", serviceContext); if (ServiceUtil.isError(serviceResult)) { return ServiceUtil.returnError(ServiceUtil.getErrorMessage(serviceResult)); @@ -3336,13 +3422,16 @@ public class ProductionRunServices { GenericValue inventoryItem = EntityQuery.use(delegator).from("InventoryItem") .where("inventoryItemId", inventoryItemId).queryOne(); if (inventoryItem == null) { - return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunCannotDecomposingInventoryItem", UtilMisc.toMap("inventoryItemId", inventoryItemId), locale)); + return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunCannotDecomposingInventoryItem", + UtilMisc.toMap("inventoryItemId", inventoryItemId), locale)); } // the work effort (disassemble order) is created Map serviceContext = UtilMisc.toMap("workEffortTypeId", "TASK", "workEffortPurposeTypeId", "WEPT_PRODUCTION_RUN", "currentStatusId", "CAL_COMPLETED"); - serviceContext.put("workEffortName", "Decomposing product [" + inventoryItem.getString("productId") + "] inventory item [" + inventoryItem.getString("inventoryItemId") + "]"); + serviceContext.put("workEffortName", + "Decomposing product [" + inventoryItem.getString("productId") + "] inventory item [" + inventoryItem.getString("inventoryItemId") + + "]"); serviceContext.put("facilityId", inventoryItem.getString("facilityId")); serviceContext.put("estimatedStartDate", now); serviceContext.put("userLogin", userLogin); @@ -3364,15 +3453,18 @@ public class ProductionRunServices { } BigDecimal issuedQuantity = (BigDecimal) serviceResult.get("quantityIssued"); if (issuedQuantity.compareTo(ZERO) == 0) { - return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunCannotDecomposingInventoryItemNoMarketingPackagesFound", UtilMisc.toMap("inventoryItemId", inventoryItem.getString("inventoryItemId")), locale)); + return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, + "ManufacturingProductionRunCannotDecomposingInventoryItemNoMarketingPackagesFound", UtilMisc.toMap("inventoryItemId", + inventoryItem.getString("inventoryItemId")), locale)); } - // get the package's unit cost to compute a cost coefficient ratio which is the marketing package's actual unit cost divided by its standard cost + // get the package's unit cost to compute a cost coefficient ratio which is the marketing package's actual unit cost divided by its + // standard cost // this ratio will be used to determine the cost of the marketing package components when they are returned to inventory serviceContext.clear(); serviceContext = UtilMisc.toMap("productId", inventoryItem.getString("productId"), - "currencyUomId", inventoryItem.getString("currencyUomId"), - "costComponentTypePrefix", "EST_STD", - "userLogin", userLogin); + "currencyUomId", inventoryItem.getString("currencyUomId"), + "costComponentTypePrefix", "EST_STD", + "userLogin", userLogin); serviceResult = dispatcher.runSync("getProductCost", serviceContext); if (ServiceUtil.isError(serviceResult)) { return ServiceUtil.returnError(ServiceUtil.getErrorMessage(serviceResult)); @@ -3394,23 +3486,25 @@ public class ProductionRunServices { // the components are retrieved serviceContext.clear(); serviceContext = UtilMisc.toMap("productId", inventoryItem.getString("productId"), - "quantity", issuedQuantity, - "userLogin", userLogin); + "quantity", issuedQuantity, + "userLogin", userLogin); serviceResult = dispatcher.runSync("getManufacturingComponents", serviceContext); if (ServiceUtil.isError(serviceResult)) { return ServiceUtil.returnError(ServiceUtil.getErrorMessage(serviceResult)); } List> components = UtilGenerics.cast(serviceResult.get("componentsMap")); if (UtilValidate.isEmpty(components)) { - return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunCannotDecomposingInventoryItemNoComponentsFound", UtilMisc.toMap("productId", inventoryItem.getString("productId")), locale)); + return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, + "ManufacturingProductionRunCannotDecomposingInventoryItemNoComponentsFound", UtilMisc.toMap("productId", inventoryItem.getString( + "productId")), locale)); } for (Map component : components) { // get the component's standard cost serviceContext.clear(); serviceContext = UtilMisc.toMap("productId", ((GenericValue) component.get("product")).getString("productId"), - "currencyUomId", inventoryItem.getString("currencyUomId"), - "costComponentTypePrefix", "EST_STD", - "userLogin", userLogin); + "currencyUomId", inventoryItem.getString("currencyUomId"), + "costComponentTypePrefix", "EST_STD", + "userLogin", userLogin); serviceResult = dispatcher.runSync("getProductCost", serviceContext); if (ServiceUtil.isError(serviceResult)) { return ServiceUtil.returnError(ServiceUtil.getErrorMessage(serviceResult)); @@ -3421,10 +3515,10 @@ public class ProductionRunServices { BigDecimal componentInventoryItemCost = costCoefficient.multiply(componentCost); serviceContext.clear(); serviceContext = UtilMisc.toMap("productId", ((GenericValue) component.get("product")).getString("productId"), - "quantity", component.get("quantity"), - "facilityId", inventoryItem.getString("facilityId"), - "unitCost", componentInventoryItemCost, - "userLogin", userLogin); + "quantity", component.get("quantity"), + "facilityId", inventoryItem.getString("facilityId"), + "unitCost", componentInventoryItemCost, + "userLogin", userLogin); serviceContext.put("workEffortId", workEffortId); serviceResult = dispatcher.runSync("productionRunTaskProduce", serviceContext); if (ServiceUtil.isError(serviceResult)) { @@ -3456,7 +3550,7 @@ public class ProductionRunServices { .queryList(); for (GenericValue genericResult : resultList) { if ("PRUN_CLOSED".equals(genericResult.getString("currentStatusId")) - || "PRUN_CREATED".equals(genericResult.getString("currentStatusId"))) { + || "PRUN_CREATED".equals(genericResult.getString("currentStatusId"))) { continue; } BigDecimal qtyToProduce = genericResult.getBigDecimal("quantityToProduce"); @@ -3502,12 +3596,14 @@ public class ProductionRunServices { if (!newOrderId.equals(orderId)) { orderDeliverySchedule = null; orderId = newOrderId; - orderDeliverySchedule = EntityQuery.use(delegator).from("OrderDeliverySchedule").where("orderId", orderId, "orderItemSeqId", "_NA_").queryOne(); + orderDeliverySchedule = EntityQuery.use(delegator).from("OrderDeliverySchedule").where("orderId", orderId, "orderItemSeqId", + "_NA_").queryOne(); } String productId = genericResult.getString("productId"); BigDecimal orderQuantity = genericResult.getBigDecimal("quantity"); GenericValue orderItemDeliverySchedule = null; - orderItemDeliverySchedule = EntityQuery.use(delegator).from("OrderDeliverySchedule").where("orderId", orderId, "orderItemSeqId", genericResult.getString("orderItemSeqId")).queryOne(); + orderItemDeliverySchedule = EntityQuery.use(delegator).from("OrderDeliverySchedule").where("orderId", orderId, "orderItemSeqId", + genericResult.getString("orderItemSeqId")).queryOne(); Timestamp estimatedShipDate = null; if (orderItemDeliverySchedule != null && orderItemDeliverySchedule.get("estimatedReadyDate") != null) { estimatedShipDate = orderItemDeliverySchedule.getTimestamp("estimatedReadyDate"); @@ -3590,7 +3686,8 @@ public class ProductionRunServices { } } catch (GenericEntityException e) { Debug.logError(e, "Error", MODULE); - return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunErrorRunningSetEstimatedDeliveryDates", locale)); + return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunErrorRunningSetEstimatedDeliveryDates", + locale)); } return ServiceUtil.returnSuccess(); } diff --git a/applications/manufacturing/src/main/java/org/apache/ofbiz/manufacturing/mrp/InventoryEventPlannedServices.java b/applications/manufacturing/src/main/java/org/apache/ofbiz/manufacturing/mrp/InventoryEventPlannedServices.java index 5cf831fb2c..9c0415e7c3 100644 --- a/applications/manufacturing/src/main/java/org/apache/ofbiz/manufacturing/mrp/InventoryEventPlannedServices.java +++ b/applications/manufacturing/src/main/java/org/apache/ofbiz/manufacturing/mrp/InventoryEventPlannedServices.java @@ -41,7 +41,7 @@ public class InventoryEventPlannedServices { /** * * Create an MrpEvent. - * Make an update if a record exist with same key, (adding the event quantity to the exiting record) + * Make an update if a record exist with same key, (adding the event quantity to the exiting record) * * @param ctx the dispatch context * @param context a map containing the parameters used to create an MrpEvent @@ -58,7 +58,7 @@ public class InventoryEventPlannedServices { try { createOrUpdateMrpEvent(parameters, quantity, (String) context.get("facilityId"), (String) context.get("eventName"), false, delegator); } catch (GenericEntityException e) { - Debug.logError(e, "Error : findOne(\"MrpEvent\", parameters =)"+parameters, MODULE); + Debug.logError(e, "Error : findOne(\"MrpEvent\", parameters =)" + parameters, MODULE); return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingMrpCreateOrUpdateEvent", UtilMisc.toMap("parameters", parameters), locale)); } return ServiceUtil.returnSuccess(); diff --git a/applications/manufacturing/src/main/java/org/apache/ofbiz/manufacturing/mrp/MrpServices.java b/applications/manufacturing/src/main/java/org/apache/ofbiz/manufacturing/mrp/MrpServices.java index 9ebe99f05f..92807a6af4 100644 --- a/applications/manufacturing/src/main/java/org/apache/ofbiz/manufacturing/mrp/MrpServices.java +++ b/applications/manufacturing/src/main/java/org/apache/ofbiz/manufacturing/mrp/MrpServices.java @@ -53,7 +53,6 @@ import com.ibm.icu.util.Calendar; /** * Services for running MRP - * */ public class MrpServices { @@ -83,7 +82,7 @@ public class MrpServices { try { delegator.removeAll(listResult); } catch (GenericEntityException e) { - Debug.logError(e, "Error : removeAll(listResult), listResult ="+listResult, MODULE); + Debug.logError(e, "Error : removeAll(listResult), listResult =" + listResult, MODULE); return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingMrpEventRemoveError", locale)); } } @@ -122,7 +121,7 @@ public class MrpServices { } if (listResult != null) { try { - for (GenericValue tempRequirement: listResult) { + for (GenericValue tempRequirement : listResult) { requirementStatus.addAll(tempRequirement.getRelated("RequirementStatus", null, null, false)); } delegator.removeAll(requirementStatus); @@ -199,9 +198,11 @@ public class MrpServices { } parameters = UtilMisc.toMap("mrpId", mrpId, "productId", productId, "eventDate", requiredByDate, "mrpEventTypeId", "SALES_ORDER_SHIP"); try { - InventoryEventPlannedServices.createOrUpdateMrpEvent(parameters, eventQuantityTmp, null, genericResult.getString("orderId") + "-" + genericResult.getString("orderItemSeqId"), false, delegator); + InventoryEventPlannedServices.createOrUpdateMrpEvent(parameters, eventQuantityTmp, null, + genericResult.getString("orderId") + "-" + genericResult.getString("orderItemSeqId"), false, delegator); } catch (GenericEntityException e) { - return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingMrpEventProblemInitializing", UtilMisc.toMap("mrpEventTypeId", "SALES_ORDER_SHIP"), locale)); + return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingMrpEventProblemInitializing", UtilMisc.toMap( + "mrpEventTypeId", "SALES_ORDER_SHIP"), locale)); } } // ---------------------------------------- @@ -229,9 +230,11 @@ public class MrpServices { parameters = UtilMisc.toMap("mrpId", mrpId, "productId", productId, "eventDate", estimatedShipDate, "mrpEventTypeId", "PROD_REQ_RECP"); try { - InventoryEventPlannedServices.createOrUpdateMrpEvent(parameters, eventQuantityTmp, null, genericResult.getString("requirementId"), false, delegator); + InventoryEventPlannedServices.createOrUpdateMrpEvent(parameters, eventQuantityTmp, null, genericResult.getString("requirementId"), + false, delegator); } catch (GenericEntityException e) { - return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingMrpEventProblemInitializing", UtilMisc.toMap("mrpEventTypeId", "PROD_REQ_RECP"), locale)); + return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingMrpEventProblemInitializing", UtilMisc.toMap( + "mrpEventTypeId", "PROD_REQ_RECP"), locale)); } } @@ -264,7 +267,8 @@ public class MrpServices { if (!newOrderId.equals(orderId)) { orderDeliverySchedule = null; orderId = newOrderId; - orderDeliverySchedule = EntityQuery.use(delegator).from("OrderDeliverySchedule").where("orderId", orderId, "orderItemSeqId", "_NA_").queryOne(); + orderDeliverySchedule = EntityQuery.use(delegator).from("OrderDeliverySchedule").where("orderId", orderId, "orderItemSeqId", + "_NA_").queryOne(); } String productId = genericResult.getString("productId"); BigDecimal shipGroupQuantity = genericResult.getBigDecimal("quantity"); @@ -277,7 +281,9 @@ public class MrpServices { } try { - List shipmentReceipts = EntityQuery.use(delegator).select("quantityAccepted", "quantityRejected").from("ShipmentReceipt").where("orderId", genericResult.getString("orderId"), "orderItemSeqId", genericResult.getString("orderItemSeqId")).queryList(); + List shipmentReceipts = EntityQuery.use(delegator).select("quantityAccepted", "quantityRejected").from( + "ShipmentReceipt").where("orderId", genericResult.getString("orderId"), "orderItemSeqId", genericResult.getString( + "orderItemSeqId")).queryList(); for (GenericValue shipmentReceipt : shipmentReceipts) { shipGroupQuantity = shipGroupQuantity.subtract(shipmentReceipt.getBigDecimal("quantityAccepted")); shipGroupQuantity = shipGroupQuantity.subtract(shipmentReceipt.getBigDecimal("quantityRejected")); @@ -286,7 +292,8 @@ public class MrpServices { Debug.logWarning(e, MODULE); } GenericValue orderItemDeliverySchedule = null; - orderItemDeliverySchedule = EntityQuery.use(delegator).from("OrderDeliverySchedule").where("orderId", orderId, "orderItemSeqId", genericResult.getString("orderItemSeqId")).queryOne(); + orderItemDeliverySchedule = EntityQuery.use(delegator).from("OrderDeliverySchedule").where("orderId", orderId, "orderItemSeqId", + genericResult.getString("orderItemSeqId")).queryOne(); Timestamp estimatedShipDate = null; if (orderItemDeliverySchedule != null && orderItemDeliverySchedule.get("estimatedReadyDate") != null) { estimatedShipDate = orderItemDeliverySchedule.getTimestamp("estimatedReadyDate"); @@ -299,10 +306,13 @@ public class MrpServices { estimatedShipDate = now; } - parameters = UtilMisc.toMap("mrpId", mrpId, "productId", productId, "eventDate", estimatedShipDate, "mrpEventTypeId", "PUR_ORDER_RECP"); - InventoryEventPlannedServices.createOrUpdateMrpEvent(parameters, shipGroupQuantity, null, genericResult.getString("orderId") + "-" + genericResult.getString("orderItemSeqId"), false, delegator); + parameters = UtilMisc.toMap("mrpId", mrpId, "productId", productId, "eventDate", estimatedShipDate, "mrpEventTypeId", + "PUR_ORDER_RECP"); + InventoryEventPlannedServices.createOrUpdateMrpEvent(parameters, shipGroupQuantity, null, + genericResult.getString("orderId") + "-" + genericResult.getString("orderItemSeqId"), false, delegator); } catch (GenericEntityException e) { - return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingMrpEventProblemInitializing", UtilMisc.toMap("mrpEventTypeId", "PUR_ORDER_RECP"), locale)); + return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingMrpEventProblemInitializing", UtilMisc.toMap( + "mrpEventTypeId", "PUR_ORDER_RECP"), locale)); } } @@ -317,8 +327,8 @@ public class MrpServices { .queryList(); for (GenericValue genericResult : resultList) { if ("PRUN_CLOSED".equals(genericResult.getString("currentStatusId")) - || "PRUN_COMPLETED".equals(genericResult.getString("currentStatusId")) - || "PRUN_CANCELLED".equals(genericResult.getString("currentStatusId"))) { + || "PRUN_COMPLETED".equals(genericResult.getString("currentStatusId")) + || "PRUN_CANCELLED".equals(genericResult.getString("currentStatusId"))) { continue; } String productId = genericResult.getString("productId"); @@ -336,12 +346,15 @@ public class MrpServices { estimatedShipDate = now; } - parameters = UtilMisc.toMap("mrpId", mrpId, "productId", productId, "eventDate", estimatedShipDate, "mrpEventTypeId", "MANUF_ORDER_REQ"); - String eventName = (UtilValidate.isEmpty(genericResult.getString("workEffortParentId"))? genericResult.getString("workEffortId"): genericResult.getString("workEffortParentId") + "-" + genericResult.getString("workEffortId")); + parameters = UtilMisc.toMap("mrpId", mrpId, "productId", productId, "eventDate", estimatedShipDate, "mrpEventTypeId", + "MANUF_ORDER_REQ"); + String eventName = (UtilValidate.isEmpty(genericResult.getString("workEffortParentId")) ? genericResult.getString("workEffortId") + : genericResult.getString("workEffortParentId") + "-" + genericResult.getString("workEffortId")); InventoryEventPlannedServices.createOrUpdateMrpEvent(parameters, eventQuantityTmp, null, eventName, false, delegator); } } catch (GenericEntityException e) { - return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingMrpEventProblemInitializing", UtilMisc.toMap("mrpEventTypeId", "MANUF_ORDER_REQ"), locale) + " " + e.getMessage()); + return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingMrpEventProblemInitializing", UtilMisc.toMap( + "mrpEventTypeId", "MANUF_ORDER_REQ"), locale) + " " + e.getMessage()); } // ---------------------------------------- @@ -356,8 +369,8 @@ public class MrpServices { .queryList(); for (GenericValue genericResult : resultList) { if ("PRUN_CLOSED".equals(genericResult.getString("currentStatusId")) - || "PRUN_COMPLETED".equals(genericResult.getString("currentStatusId")) - || "PRUN_CANCELLED".equals(genericResult.getString("currentStatusId"))) { + || "PRUN_COMPLETED".equals(genericResult.getString("currentStatusId")) + || "PRUN_CANCELLED".equals(genericResult.getString("currentStatusId"))) { continue; } BigDecimal qtyToProduce = genericResult.getBigDecimal("quantityToProduce"); @@ -379,11 +392,14 @@ public class MrpServices { estimatedShipDate = now; } - parameters = UtilMisc.toMap("mrpId", mrpId, "productId", productId, "eventDate", estimatedShipDate, "mrpEventTypeId", "MANUF_ORDER_RECP"); - InventoryEventPlannedServices.createOrUpdateMrpEvent(parameters, eventQuantityTmp, null, genericResult.getString("workEffortId"), false, delegator); + parameters = UtilMisc.toMap("mrpId", mrpId, "productId", productId, "eventDate", estimatedShipDate, "mrpEventTypeId", + "MANUF_ORDER_RECP"); + InventoryEventPlannedServices.createOrUpdateMrpEvent(parameters, eventQuantityTmp, null, genericResult.getString("workEffortId"), + false, delegator); } } catch (GenericEntityException e) { - return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingMrpEventProblemInitializing", UtilMisc.toMap("mrpEventTypeId", "MANUF_ORDER_RECP"), locale) + " " + e.getMessage()); + return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingMrpEventProblemInitializing", UtilMisc.toMap( + "mrpEventTypeId", "MANUF_ORDER_RECP"), locale) + " " + e.getMessage()); } // ---------------------------------------- @@ -422,7 +438,8 @@ public class MrpServices { try { InventoryEventPlannedServices.createOrUpdateMrpEvent(parameters, BigDecimal.ZERO, null, null, false, delegator); } catch (GenericEntityException e) { - return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingMrpEventProblemInitializing", UtilMisc.toMap("mrpEventTypeId", "REQUIRED_MRP"), locale)); + return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingMrpEventProblemInitializing", UtilMisc.toMap( + "mrpEventTypeId", "REQUIRED_MRP"), locale)); } } @@ -452,7 +469,8 @@ public class MrpServices { return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingMrpCannotFindCustomTimePeriod", locale)); } if (customTimePeriod != null) { - if (UtilValidate.isNotEmpty(customTimePeriod.getTimestamp("thruDate")) && customTimePeriod.getTimestamp("thruDate").before(UtilDateTime.nowTimestamp())) { + if (UtilValidate.isNotEmpty(customTimePeriod.getTimestamp("thruDate")) + && customTimePeriod.getTimestamp("thruDate").before(UtilDateTime.nowTimestamp())) { continue; } else { List salesForecastDetails = null; @@ -470,11 +488,14 @@ public class MrpServices { continue; } eventQuantityTmp = eventQuantityTmp.negate(); - parameters = UtilMisc.toMap("mrpId", mrpId, "productId", productId, "eventDate", customTimePeriod.getDate("fromDate"), "mrpEventTypeId", "SALES_FORECAST"); + parameters = UtilMisc.toMap("mrpId", mrpId, "productId", productId, "eventDate", customTimePeriod.getDate("fromDate"), + "mrpEventTypeId", "SALES_FORECAST"); try { - InventoryEventPlannedServices.createOrUpdateMrpEvent(parameters, eventQuantityTmp, null, sfd.getString("salesForecastDetailId"), false, delegator); + InventoryEventPlannedServices.createOrUpdateMrpEvent(parameters, eventQuantityTmp, null, sfd.getString( + "salesForecastDetailId"), false, delegator); } catch (GenericEntityException e) { - return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingMrpEventProblemInitializing", UtilMisc.toMap("mrpEventTypeId", "SALES_FORECAST"), locale)); + return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingMrpEventProblemInitializing", + UtilMisc.toMap("mrpEventTypeId", "SALES_FORECAST"), locale)); } } } @@ -494,11 +515,14 @@ public class MrpServices { * * * @param product the product for which the Quantity Available is required - * @return the sum of all the totalAvailableToPromise of the inventoryItem related to the product, if the related facility is Mrp available (not yet implemented!!) + * @return the sum of all the totalAvailableToPromise of the inventoryItem related to the product, if the related facility is Mrp available + * (not yet implemented!!) */ - public static BigDecimal findProductMrpQoh(String mrpId, GenericValue product, String facilityId, LocalDispatcher dispatcher, Delegator delegator) { + public static BigDecimal findProductMrpQoh(String mrpId, GenericValue product, String facilityId, LocalDispatcher dispatcher, + Delegator delegator) { return findProductMrpQoh(mrpId, product.getString("productId"), facilityId, dispatcher, delegator); } + public static BigDecimal findProductMrpQoh(String mrpId, String productId, String facilityId, LocalDispatcher dispatcher, Delegator delegator) { Map resultMap = null; try { @@ -522,14 +546,15 @@ public class MrpServices { public static void logMrpError(String mrpId, String productId, String errorMessage, Delegator delegator) { logMrpError(mrpId, productId, UtilDateTime.nowTimestamp(), errorMessage, delegator); } + public static void logMrpError(String mrpId, String productId, Timestamp eventDate, String errorMessage, Delegator delegator) { try { if (UtilValidate.isNotEmpty(productId) && UtilValidate.isNotEmpty(errorMessage)) { GenericValue inventoryEventError = delegator.makeValue("MrpEvent", UtilMisc.toMap("productId", productId, - "mrpId", mrpId, - "eventDate", eventDate, - "mrpEventTypeId", "ERROR", - "eventName", errorMessage)); + "mrpId", mrpId, + "eventDate", eventDate, + "mrpEventTypeId", "ERROR", + "eventName", errorMessage)); delegator.createOrStore(inventoryEventError); } } catch (GenericEntityException e) { @@ -540,15 +565,17 @@ public class MrpServices { /** * Process the bill of material (bom) of the product to insert components in the MrpEvent table. * Before inserting in the entity, test if there is the record already existing to add quantity rather to create a new one. - * @param mrpId the mrp id - * @param product GenericValue oject of the product - * @param eventQuantity the product quantity needed - * @param startDate the startDate of the productionRun which will used to produce the product + * + * @param mrpId the mrp id + * @param product GenericValue oject of the product + * @param eventQuantity the product quantity needed + * @param startDate the startDate of the productionRun which will used to produce the product * @param routingTaskStartDate Map with all the routingTask as keys and startDate of each of them - * @param listComponent a List with all the components + * @param listComponent a List with all the components */ - public static void processBomComponent(String mrpId, GenericValue product, BigDecimal eventQuantity, Timestamp startDate, Map routingTaskStartDate, List listComponent) { + public static void processBomComponent(String mrpId, GenericValue product, BigDecimal eventQuantity, Timestamp startDate, + Map routingTaskStartDate, List listComponent) { // TODO : change the return type to boolean to be able to test if all is ok or if it have had a exception Delegator delegator = product.getDelegator(); @@ -557,7 +584,8 @@ public class MrpServices { GenericValue productComponent = node.getProductAssoc(); // read the startDate for the component String routingTask = node.getProductAssoc().getString("routingWorkEffortId"); - Timestamp eventDate = (routingTask == null || !routingTaskStartDate.containsKey(routingTask)) ? startDate : (Timestamp) routingTaskStartDate.get(routingTask); + Timestamp eventDate = (routingTask == null || !routingTaskStartDate.containsKey(routingTask)) ? startDate + : (Timestamp) routingTaskStartDate.get(routingTask); // if the components is valid at the event Date create the Mrp requirement in the M entity if (EntityUtil.isValueActive(productComponent, eventDate)) { Map parameters = UtilMisc.toMap("productId", node.getProduct().getString("productId")); @@ -566,7 +594,8 @@ public class MrpServices { parameters.put("mrpEventTypeId", "MRP_REQUIREMENT"); BigDecimal componentEventQuantity = node.getQuantity(); try { - InventoryEventPlannedServices.createOrUpdateMrpEvent(parameters, componentEventQuantity.negate(), null, product.get("productId") + ": " + eventDate, false, delegator); + InventoryEventPlannedServices.createOrUpdateMrpEvent(parameters, componentEventQuantity.negate(), null, product.get( + "productId") + ": " + eventDate, false, delegator); } catch (GenericEntityException e) { Debug.logError("Error : findOne(\"MrpEvent\", parameters) =" + parameters + "--" + e.getMessage(), MODULE); logMrpError(mrpId, node.getProduct().getString("productId"), "Unable to create event (processBomComponent)", delegator); @@ -585,7 +614,7 @@ public class MrpServices { *
  • OUTPUT : Result to put in the map :
    • none
  • * * - * @param ctx The DispatchContext that this service is operating in. + * @param ctx The DispatchContext that this service is operating in. * @param context Map containing the input parameters, productId routingId, quantity, startDate. * @return Map with the result of the service, the output parameters. */ @@ -608,11 +637,13 @@ public class MrpServices { try { GenericValue facilityGroup = EntityQuery.use(delegator).from("FacilityGroup").where("facilityGroupId", facilityGroupId).queryOne(); if (UtilValidate.isEmpty(facilityGroup)) { - return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingMrpFacilityGroupIsNotValid", UtilMisc.toMap("facilityGroupId", facilityGroupId), locale)); + return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingMrpFacilityGroupIsNotValid", UtilMisc.toMap( + "facilityGroupId", facilityGroupId), locale)); } List facilities = facilityGroup.getRelated("FacilityGroupMember", null, UtilMisc.toList("sequenceNum"), false); if (UtilValidate.isEmpty(facilities)) { - return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingMrpFacilityGroupIsNotAssociatedToFacility", UtilMisc.toMap("facilityGroupId", facilityGroupId), locale)); + return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingMrpFacilityGroupIsNotAssociatedToFacility", + UtilMisc.toMap("facilityGroupId", facilityGroupId), locale)); } for (GenericValue facilityMember : facilities) { GenericValue facility = facilityMember.getRelatedOne("Facility", false); @@ -624,14 +655,16 @@ public class MrpServices { } } } catch (GenericEntityException e) { - return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingMrpFacilityGroupCannotBeLoad", UtilMisc.toMap("errorString", e.getMessage()), locale)); + return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingMrpFacilityGroupCannotBeLoad", UtilMisc.toMap( + "errorString", e.getMessage()), locale)); } } else { manufacturingFacilityId = facilityId; } if (UtilValidate.isEmpty(facilityId) || UtilValidate.isEmpty(manufacturingFacilityId)) { - return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingMrpFacilityOrManufacturingFacilityNotAvailable", locale)); + return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingMrpFacilityOrManufacturingFacilityNotAvailable", + locale)); } int bomLevelWithNoEvent = 0; @@ -657,7 +690,8 @@ public class MrpServices { ListIterator iteratorListInventoryEventForMRP = null; // Initialization of the MrpEvent table, This table will contain the products we want to buy or build. - parameters = UtilMisc.toMap("mrpId", mrpId, "reInitialize", Boolean.TRUE, "defaultYearsOffset", defaultYearsOffset, "userLogin", userLogin); + parameters = UtilMisc.toMap("mrpId", mrpId, "reInitialize", Boolean.TRUE, "defaultYearsOffset", defaultYearsOffset, + "userLogin", userLogin); parameters.put("facilityId", facilityId); parameters.put("manufacturingFacilityId", manufacturingFacilityId); try { @@ -666,7 +700,8 @@ public class MrpServices { return ServiceUtil.returnError(ServiceUtil.getErrorMessage(result)); } } catch (GenericServiceException e) { - return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingMrpErrorRunningInitMrpEvents", UtilMisc.toMap("errorString", e.getMessage()), locale)); + return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingMrpErrorRunningInitMrpEvents", UtilMisc.toMap( + "errorString", e.getMessage()), locale)); } long bomLevel = 0; do { @@ -674,8 +709,8 @@ public class MrpServices { EntityCondition filterByConditions = null; if (bomLevel == 0) { filterByConditions = EntityCondition.makeCondition(EntityCondition.makeCondition("billOfMaterialLevel", EntityOperator.EQUALS, null), - EntityOperator.OR, - EntityCondition.makeCondition("billOfMaterialLevel", EntityOperator.EQUALS, bomLevel)); + EntityOperator.OR, + EntityCondition.makeCondition("billOfMaterialLevel", EntityOperator.EQUALS, bomLevel)); } else { filterByConditions = EntityCondition.makeCondition("billOfMaterialLevel", EntityOperator.EQUALS, bomLevel); } @@ -686,7 +721,8 @@ public class MrpServices { .queryList(); } catch (GenericEntityException e) { Long bomLevelToString = bomLevel; - return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingMrpErrorForBomLevel", UtilMisc.toMap("bomLevel", bomLevelToString.toString(), "errorString", e.getMessage()), locale)); + return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingMrpErrorForBomLevel", UtilMisc.toMap("bomLevel", + bomLevelToString.toString(), "errorString", e.getMessage()), locale)); } if (UtilValidate.isNotEmpty(listInventoryEventForMRP)) { @@ -698,15 +734,17 @@ public class MrpServices { eventCount++; productId = inventoryEventForMRP.getString("productId"); - boolean isLastEvent = (eventCount == listInventoryEventForMRP.size() || !productId.equals(listInventoryEventForMRP.get(eventCount).getString("productId"))); + boolean isLastEvent = (eventCount == listInventoryEventForMRP.size() + || !productId.equals(listInventoryEventForMRP.get(eventCount).getString("productId"))); eventQuantity = inventoryEventForMRP.getBigDecimal("quantity"); if (!productId.equals(oldProductId)) { - BigDecimal positiveEventQuantity = eventQuantity.compareTo(BigDecimal.ZERO) > 0 ? eventQuantity: eventQuantity.negate(); + BigDecimal positiveEventQuantity = eventQuantity.compareTo(BigDecimal.ZERO) > 0 ? eventQuantity : eventQuantity.negate(); // It's a new product, so it's necessary to read the MrpQoh try { product = inventoryEventForMRP.getRelatedOne("Product", true); - productFacility = EntityUtil.getFirst(product.getRelated("ProductFacility", UtilMisc.toMap("facilityId", facilityId), null, true)); + productFacility = EntityUtil.getFirst(product.getRelated("ProductFacility", UtilMisc.toMap("facilityId", facilityId), + null, true)); } catch (GenericEntityException e) { return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingMrpCannotFindProductForEvent", locale)); } @@ -717,16 +755,20 @@ public class MrpServices { "mrpEventTypeId", "INITIAL_QOH", "eventDate", now), stockTmp, facilityId, null, false, delegator); } catch (GenericEntityException e) { - return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingMrpCreateOrUpdateEvent", UtilMisc.toMap("parameters", parameters), locale)); + return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingMrpCreateOrUpdateEvent", + UtilMisc.toMap("parameters", parameters), locale)); } - // days to ship is only relevant for sales order to plan for preparatory days to ship. Otherwise MRP will push event dates for manufacturing parts + // days to ship is only relevant for sales order to plan for preparatory days to ship. Otherwise MRP will push event dates + // for manufacturing parts // as well and cause problems daysToShip = 0; if (productFacility != null) { - reorderQuantity = (productFacility.getBigDecimal("reorderQuantity") != null ? productFacility.getBigDecimal("reorderQuantity"): BigDecimal.ONE.negate()); - minimumStock = (productFacility.getBigDecimal("minimumStock") != null ? productFacility.getBigDecimal("minimumStock"): BigDecimal.ZERO); + reorderQuantity = (productFacility.getBigDecimal("reorderQuantity") != null ? productFacility.getBigDecimal( + "reorderQuantity") : BigDecimal.ONE.negate()); + minimumStock = (productFacility.getBigDecimal("minimumStock") != null ? productFacility.getBigDecimal("minimumStock") + : BigDecimal.ZERO); if ("SALES_ORDER_SHIP".equals(inventoryEventForMRP.getString("mrpEventTypeId"))) { - daysToShip = (productFacility.getLong("daysToShip") != null? productFacility.getLong("daysToShip").intValue(): 0); + daysToShip = (productFacility.getLong("daysToShip") != null ? productFacility.getLong("daysToShip").intValue() : 0); } } else { minimumStock = BigDecimal.ZERO; @@ -736,7 +778,9 @@ public class MrpServices { // The components are also loaded thru the configurator Map serviceResponse = null; try { - serviceResponse = dispatcher.runSync("getManufacturingComponents", UtilMisc.toMap("productId", product.getString("productId"), "quantity", positiveEventQuantity, "excludeWIPs", Boolean.FALSE, "userLogin", userLogin)); + serviceResponse = dispatcher.runSync("getManufacturingComponents", UtilMisc.toMap("productId", + product.getString("productId"), "quantity", positiveEventQuantity, "excludeWIPs", Boolean.FALSE, "userLogin", + userLogin)); if (ServiceUtil.isError(serviceResponse)) { return ServiceUtil.returnError(ServiceUtil.getErrorMessage(serviceResponse)); } @@ -757,12 +801,13 @@ public class MrpServices { } stockTmp = stockTmp.add(eventQuantity); - if (stockTmp.compareTo(minimumStock) < 0 && (eventQuantity.compareTo(BigDecimal.ZERO) < 0 || isLastEvent)) { // No need to create a supply event/requirement if the current event is not a demand and there are other events to process + if (stockTmp.compareTo(minimumStock) < 0 && (eventQuantity.compareTo(BigDecimal.ZERO) < 0 || isLastEvent)) { // No need to + // create a supply event/requirement if the current event is not a demand and there are other events to process BigDecimal qtyToStock = minimumStock.subtract(stockTmp); //need to buy or build the product as we have not enough stock eventDate = inventoryEventForMRP.getTimestamp("eventDate"); // to be just before the requirement - eventDate.setTime(eventDate.getTime()-1); + eventDate.setTime(eventDate.getTime() - 1); ProposedOrder proposedOrder = new ProposedOrder(product, facilityId, manufacturingFacilityId, isBuilt, eventDate, qtyToStock); proposedOrder.setMrpName(mrpName); // calculate the ProposedOrder quantity and update the quantity object property. @@ -772,7 +817,9 @@ public class MrpServices { // The components are also loaded thru the configurator Map serviceResponse = null; try { - serviceResponse = dispatcher.runSync("getManufacturingComponents", UtilMisc.toMap("productId", product.getString("productId"), "quantity", proposedOrder.getQuantity(), "excludeWIPs", Boolean.FALSE, "userLogin", userLogin)); + serviceResponse = dispatcher.runSync("getManufacturingComponents", UtilMisc.toMap("productId", + product.getString("productId"), "quantity", proposedOrder.getQuantity(), "excludeWIPs", Boolean.FALSE, + "userLogin", userLogin)); if (ServiceUtil.isError(serviceResponse)) { return ServiceUtil.returnError(ServiceUtil.getErrorMessage(serviceResponse)); } @@ -786,7 +833,8 @@ public class MrpServices { try { routing = EntityQuery.use(delegator).from("WorkEffort").where("workEffortId", routingId).queryOne(); } catch (GenericEntityException e) { - return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingMrpCannotFindProductForEvent", locale)); + return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingMrpCannotFindProductForEvent", + locale)); } } else { routing = null; @@ -800,10 +848,12 @@ public class MrpServices { // ##################################################### // calculate the ProposedOrder requirementStartDate and update the requirementStartDate object property. - Map routingTaskStartDate = proposedOrder.calculateStartDate(daysToShip, routing, delegator, dispatcher, userLogin); + Map routingTaskStartDate = proposedOrder.calculateStartDate(daysToShip, routing, delegator, dispatcher, + userLogin); if (isBuilt) { // process the product components - processBomComponent(mrpId, product, proposedOrder.getQuantity(), proposedOrder.getRequirementStartDate(), routingTaskStartDate, components); + processBomComponent(mrpId, product, proposedOrder.getQuantity(), proposedOrder.getRequirementStartDate(), + routingTaskStartDate, components); } // create the ProposedOrder (only if the product is warehouse managed), and the MrpEvent associated String requirementId = null; @@ -811,20 +861,23 @@ public class MrpServices { requirementId = proposedOrder.create(ctx, userLogin); } if (UtilValidate.isEmpty(productFacility) && !isBuilt) { - logMrpError(mrpId, productId, now, "No ProductFacility record for [" + facilityId + "]; no requirement created.", delegator); + logMrpError(mrpId, productId, now, "No ProductFacility record for [" + facilityId + "]; no requirement created.", + delegator); } String eventName = null; if (UtilValidate.isNotEmpty(requirementId)) { eventName = "*" + requirementId + " (" + proposedOrder.getRequirementStartDate() + ")*"; } Map eventMap = UtilMisc.toMap("productId", product.getString("productId"), - "mrpId", mrpId, - "eventDate", eventDate, - "mrpEventTypeId", (isBuilt? "PROP_MANUF_O_RECP" : "PROP_PUR_O_RECP")); + "mrpId", mrpId, + "eventDate", eventDate, + "mrpEventTypeId", (isBuilt ? "PROP_MANUF_O_RECP" : "PROP_PUR_O_RECP")); try { - InventoryEventPlannedServices.createOrUpdateMrpEvent(eventMap, proposedOrder.getQuantity(), null, eventName, (proposedOrder.getRequirementStartDate().compareTo(now) < 0), delegator); + InventoryEventPlannedServices.createOrUpdateMrpEvent(eventMap, proposedOrder.getQuantity(), null, + eventName, (proposedOrder.getRequirementStartDate().compareTo(now) < 0), delegator); } catch (GenericEntityException e) { - return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingMrpCreateOrUpdateEvent", UtilMisc.toMap("parameters", parameters), locale)); + return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingMrpCreateOrUpdateEvent", + UtilMisc.toMap("parameters", parameters), locale)); } // stockTmp = stockTmp.add(proposedOrder.getQuantity()); diff --git a/applications/manufacturing/src/main/java/org/apache/ofbiz/manufacturing/mrp/ProposedOrder.java b/applications/manufacturing/src/main/java/org/apache/ofbiz/manufacturing/mrp/ProposedOrder.java index 6593056472..7c77cf1787 100644 --- a/applications/manufacturing/src/main/java/org/apache/ofbiz/manufacturing/mrp/ProposedOrder.java +++ b/applications/manufacturing/src/main/java/org/apache/ofbiz/manufacturing/mrp/ProposedOrder.java @@ -176,7 +176,7 @@ public class ProposedOrder { try { routingTask = routingTaskAssoc.getRelatedOne("ToWorkEffort", true); } catch (GenericEntityException e) { - Debug.logError(e.getMessage(), MODULE); + Debug.logError(e.getMessage(), MODULE); } // Calculate the estimatedStartDate long totalTime = ProductionRun.getEstimatedTaskTime(routingTask, quantity, dispatcher); @@ -267,7 +267,7 @@ public class ProposedOrder { } return (String) result.get("requirementId"); } catch (GenericServiceException e) { - Debug.logError(e, "Error : createRequirement with parameters = "+parameters+"--" + e.getMessage(), MODULE); + Debug.logError(e, "Error : createRequirement with parameters = " + parameters + "--" + e.getMessage(), MODULE); return null; } } diff --git a/applications/manufacturing/src/main/java/org/apache/ofbiz/manufacturing/techdata/TechDataServices.java b/applications/manufacturing/src/main/java/org/apache/ofbiz/manufacturing/techdata/TechDataServices.java index 7ae4f2471d..bfbe79a95a 100644 --- a/applications/manufacturing/src/main/java/org/apache/ofbiz/manufacturing/techdata/TechDataServices.java +++ b/applications/manufacturing/src/main/java/org/apache/ofbiz/manufacturing/techdata/TechDataServices.java @@ -137,10 +137,11 @@ public class TechDataServices { if (listRoutingTaskAssoc != null) { for (GenericValue routingTaskAssoc : listRoutingTaskAssoc) { if (!workEffortIdFrom.equals(routingTaskAssoc.getString("workEffortIdFrom")) - || !workEffortIdTo.equals(routingTaskAssoc.getString("workEffortIdTo")) - || !workEffortAssocTypeId.equals(routingTaskAssoc.getString("workEffortAssocTypeId")) - || !sequenceNum.equals(routingTaskAssoc.getLong("sequenceNum"))) { - if (routingTaskAssoc.getTimestamp("thruDate") == null && routingTaskAssoc.getTimestamp("fromDate") == null) sequenceNumNotOk = "Y"; + || !workEffortIdTo.equals(routingTaskAssoc.getString("workEffortIdTo")) + || !workEffortAssocTypeId.equals(routingTaskAssoc.getString("workEffortAssocTypeId")) + || !sequenceNum.equals(routingTaskAssoc.getLong("sequenceNum"))) { + if (routingTaskAssoc.getTimestamp("thruDate") == null && routingTaskAssoc.getTimestamp("fromDate") == null) + sequenceNumNotOk = "Y"; else if (routingTaskAssoc.getTimestamp("thruDate") == null) { if (thruDate == null) sequenceNumNotOk = "Y"; else if (thruDate.after(routingTaskAssoc.getTimestamp("fromDate"))) sequenceNumNotOk = "Y"; @@ -152,7 +153,9 @@ public class TechDataServices { if (fromDate.before(routingTaskAssoc.getTimestamp("thruDate"))) sequenceNumNotOk = "Y"; } else if (fromDate == null) { if (thruDate.after(routingTaskAssoc.getTimestamp("fromDate"))) sequenceNumNotOk = "Y"; - } else if (routingTaskAssoc.getTimestamp("fromDate").before(thruDate) && fromDate.before(routingTaskAssoc.getTimestamp("thruDate"))) sequenceNumNotOk = "Y"; + } else if (routingTaskAssoc.getTimestamp("fromDate").before(thruDate) && fromDate.before(routingTaskAssoc.getTimestamp( + "thruDate"))) + sequenceNumNotOk = "Y"; } else if (createProcess) sequenceNumNotOk = "Y"; } } @@ -436,7 +439,7 @@ public class TechDataServices { Double capacity = (Double) position.get("capacity"); Timestamp startAvailablePeriod = new Timestamp(UtilDateTime.getDayStart(dateFrom).getTime() + startTime.getTime() + cDateTrav.get(Calendar.ZONE_OFFSET) + cDateTrav.get(Calendar.DST_OFFSET)); if (dateFrom.before(startAvailablePeriod)) return 0; - Timestamp endAvailablePeriod = new Timestamp(startAvailablePeriod.getTime()+capacity.longValue()); + Timestamp endAvailablePeriod = new Timestamp(startAvailablePeriod.getTime() + capacity.longValue()); if (dateFrom.after(endAvailablePeriod)) return 0; return dateFrom.getTime() - startAvailablePeriod.getTime(); } diff --git a/applications/marketing/src/main/java/org/apache/ofbiz/marketing/tracking/TrackingCodeEvents.java b/applications/marketing/src/main/java/org/apache/ofbiz/marketing/tracking/TrackingCodeEvents.java index a92d95bd35..e8fbabe3c1 100644 --- a/applications/marketing/src/main/java/org/apache/ofbiz/marketing/tracking/TrackingCodeEvents.java +++ b/applications/marketing/src/main/java/org/apache/ofbiz/marketing/tracking/TrackingCodeEvents.java @@ -277,8 +277,7 @@ public class TrackingCodeEvents { String siteIdEnc; try { siteIdEnc = URLEncoder.encode(siteId, "UTF-8"); - } - catch (UnsupportedEncodingException e) { + } catch (UnsupportedEncodingException e) { Debug.logWarning("There went something wrong while encoding for the cookie creation in TrackingCodeEvents.processTrackingCode", MODULE); return "error"; } diff --git a/applications/order/src/main/java/org/apache/ofbiz/order/finaccount/FinAccountHelper.java b/applications/order/src/main/java/org/apache/ofbiz/order/finaccount/FinAccountHelper.java index 307258d31e..a6757b7e51 100644 --- a/applications/order/src/main/java/org/apache/ofbiz/order/finaccount/FinAccountHelper.java +++ b/applications/order/src/main/java/org/apache/ofbiz/order/finaccount/FinAccountHelper.java @@ -40,22 +40,19 @@ import org.apache.ofbiz.entity.util.EntityQuery; /** * A package of methods for improving efficiency of financial accounts services - * */ public final class FinAccountHelper { private static final String MODULE = FinAccountHelper.class.getName(); /** - * Precision: since we're just adding and subtracting, the interim figures should have one more decimal place of precision than the final numbers - */ + * Precision: since we're just adding and subtracting, the interim figures should have one more decimal place of precision than the final numbers + */ private static final int DECIMALS = UtilNumber.getBigDecimalScale("finaccount.decimals"); private static final RoundingMode ROUNDING = UtilNumber.getRoundingMode("finaccount.rounding"); private static final BigDecimal ZERO = BigDecimal.ZERO.setScale(DECIMALS, ROUNDING); private static final String GC_FIN_ACCOUNT_TYPE = "GIFTCERT_ACCOUNT"; - - protected FinAccountHelper() { } - // pool of available characters for account codes, here numbers plus uppercase characters private static char[] charPool = new char[10 + 26]; + static { int j = 0; for (int i = "0".charAt(0); i <= "9".charAt(0); i++) { @@ -65,118 +62,131 @@ public final class FinAccountHelper { charPool[j++] = (char) i; } } + + protected FinAccountHelper() { + } + public static int getDecimals() { return DECIMALS; } + public static RoundingMode getRounding() { return ROUNDING; } + public static BigDecimal getZero() { return ZERO; } + public static String getGiftCertFinAccountTypeId() { return GC_FIN_ACCOUNT_TYPE; } - /** - * A convenience method which adds transactions.get(0).get(fieldName) to initialValue, all done in BigDecimal to decimals and rounding - * @param initialValue the initial value - * @param transactions a List of GenericValue objects of transactions - * @param fieldName the field name to get the value from the transaction - * @param decimals number of decimals - * @param rounding how to rounding - * @return the new value in a BigDecimal field - * @throws GenericEntityException - */ - public static BigDecimal addFirstEntryAmount(BigDecimal initialValue, List transactions, String fieldName, int decimals, RoundingMode rounding) throws GenericEntityException { - if ((transactions != null) && (transactions.size() == 1)) { - GenericValue firstEntry = transactions.get(0); - if (firstEntry.get(fieldName) != null) { - BigDecimal valueToAdd = firstEntry.getBigDecimal(fieldName); - return initialValue.add(valueToAdd).setScale(decimals, rounding); - } else { - return initialValue; - } - } else { - return initialValue; - } - } - /** - * Returns a unique randomly generated account code for FinAccount.finAccountCode composed of uppercase letters and numbers - * @param codeLength length of code in number of characters - * @param delegator the delegator - * @return returns a unique randomly generated account code for FinAccount.finAccountCode composed of uppercase letters and numbers - * @throws GenericEntityException - */ - public static String getNewFinAccountCode(int codeLength, Delegator delegator) throws GenericEntityException { + /** + * A convenience method which adds transactions.get(0).get(fieldName) to initialValue, all done in BigDecimal to decimals and rounding + * + * @param initialValue the initial value + * @param transactions a List of GenericValue objects of transactions + * @param fieldName the field name to get the value from the transaction + * @param decimals number of decimals + * @param rounding how to rounding + * @return the new value in a BigDecimal field + * @throws GenericEntityException + */ + public static BigDecimal addFirstEntryAmount(BigDecimal initialValue, List transactions, String fieldName, int decimals, + RoundingMode rounding) throws GenericEntityException { + if ((transactions != null) && (transactions.size() == 1)) { + GenericValue firstEntry = transactions.get(0); + if (firstEntry.get(fieldName) != null) { + BigDecimal valueToAdd = firstEntry.getBigDecimal(fieldName); + return initialValue.add(valueToAdd).setScale(decimals, rounding); + } else { + return initialValue; + } + } else { + return initialValue; + } + } - // keep generating new account codes until a unique one is found - Random r = new Random(); - boolean foundUniqueNewCode = false; - StringBuilder newAccountCode = null; - long count = 0; + /** + * Returns a unique randomly generated account code for FinAccount.finAccountCode composed of uppercase letters and numbers + * + * @param codeLength length of code in number of characters + * @param delegator the delegator + * @return returns a unique randomly generated account code for FinAccount.finAccountCode composed of uppercase letters and numbers + * @throws GenericEntityException + */ + public static String getNewFinAccountCode(int codeLength, Delegator delegator) throws GenericEntityException { - while (!foundUniqueNewCode) { - newAccountCode = new StringBuilder(codeLength); - for (int i = 0; i < codeLength; i++) { - newAccountCode.append(charPool[r.nextInt(charPool.length)]); - } + // keep generating new account codes until a unique one is found + Random r = new Random(); + boolean foundUniqueNewCode = false; + StringBuilder newAccountCode = null; + long count = 0; - GenericValue existingAccountWithCode = EntityQuery.use(delegator).from("FinAccount") - .where("finAccountCode", newAccountCode.toString()).queryFirst(); - if (existingAccountWithCode == null) { - foundUniqueNewCode = true; - } + while (!foundUniqueNewCode) { + newAccountCode = new StringBuilder(codeLength); + for (int i = 0; i < codeLength; i++) { + newAccountCode.append(charPool[r.nextInt(charPool.length)]); + } - count++; - if (count > 999999) { - throw new GenericEntityException("Unable to locate unique FinAccountCode! Length [" + codeLength + "]"); - } - } + GenericValue existingAccountWithCode = EntityQuery.use(delegator).from("FinAccount") + .where("finAccountCode", newAccountCode.toString()).queryFirst(); + if (existingAccountWithCode == null) { + foundUniqueNewCode = true; + } - return newAccountCode.toString(); - } + count++; + if (count > 999999) { + throw new GenericEntityException("Unable to locate unique FinAccountCode! Length [" + codeLength + "]"); + } + } - /** - * Gets the first (and should be only) FinAccount based on finAccountCode, which will be cleaned up to be only uppercase and alphanumeric - * @param finAccountCode the financial account code - * @param delegator the delegator - * @return gets the first financial account by code - * @throws GenericEntityException - */ - public static GenericValue getFinAccountFromCode(String finAccountCode, Delegator delegator) throws GenericEntityException { - if (finAccountCode == null) { - return null; - } + return newAccountCode.toString(); + } + + /** + * Gets the first (and should be only) FinAccount based on finAccountCode, which will be cleaned up to be only uppercase and alphanumeric + * + * @param finAccountCode the financial account code + * @param delegator the delegator + * @return gets the first financial account by code + * @throws GenericEntityException + */ + public static GenericValue getFinAccountFromCode(String finAccountCode, Delegator delegator) throws GenericEntityException { + if (finAccountCode == null) { + return null; + } finAccountCode = finAccountCode.toUpperCase(Locale.getDefault()).replaceAll("[^0-9A-Z]", ""); - // now look for the account - List accounts = EntityQuery.use(delegator).from("FinAccount") - .where("finAccountCode", finAccountCode) - .filterByDate().queryList(); - if (UtilValidate.isEmpty(accounts)) { - // OK to display - not a code anyway - Debug.logWarning("No fin account found for account code [" + finAccountCode + "]", MODULE); - return null; - } else if (accounts.size() > 1) { - // This should never happen, but don't display the code if it does -- it is supposed to be encrypted! - Debug.logError("Multiple fin accounts found", MODULE); - return null; - } else { - return accounts.get(0); - } - } + // now look for the account + List accounts = EntityQuery.use(delegator).from("FinAccount") + .where("finAccountCode", finAccountCode) + .filterByDate().queryList(); + if (UtilValidate.isEmpty(accounts)) { + // OK to display - not a code anyway + Debug.logWarning("No fin account found for account code [" + finAccountCode + "]", MODULE); + return null; + } else if (accounts.size() > 1) { + // This should never happen, but don't display the code if it does -- it is supposed to be encrypted! + Debug.logError("Multiple fin accounts found", MODULE); + return null; + } else { + return accounts.get(0); + } + } - /** - * Sum of all DEPOSIT and ADJUSTMENT transactions minus all WITHDRAWAL transactions whose transactionDate is before asOfDateTime - * @param finAccountId the financial account id - * @param asOfDateTime the validity date - * @param delegator the delegator - * @return returns the sum of all DEPOSIT and ADJUSTMENT transactions minus all WITHDRAWAL transactions - * @throws GenericEntityException - */ - public static BigDecimal getBalance(String finAccountId, Timestamp asOfDateTime, Delegator delegator) throws GenericEntityException { + /** + * Sum of all DEPOSIT and ADJUSTMENT transactions minus all WITHDRAWAL transactions whose transactionDate is before asOfDateTime + * + * @param finAccountId the financial account id + * @param asOfDateTime the validity date + * @param delegator the delegator + * @return returns the sum of all DEPOSIT and ADJUSTMENT transactions minus all WITHDRAWAL transactions + * @throws GenericEntityException + */ + public static BigDecimal getBalance(String finAccountId, Timestamp asOfDateTime, Delegator delegator) throws GenericEntityException { if (asOfDateTime == null) asOfDateTime = UtilDateTime.nowTimestamp(); BigDecimal incrementTotal = ZERO; // total amount of transactions which increase balance @@ -191,7 +201,7 @@ public final class FinAccountHelper { EntityCondition.makeCondition(UtilMisc.toList( EntityCondition.makeCondition("finAccountTransTypeId", EntityOperator.EQUALS, "DEPOSIT"), EntityCondition.makeCondition("finAccountTransTypeId", EntityOperator.EQUALS, "ADJUSTMENT")), - EntityOperator.OR)) + EntityOperator.OR)) .queryList(); incrementTotal = addFirstEntryAmount(incrementTotal, transSums, "amount", (DECIMALS + 1), ROUNDING); @@ -209,14 +219,15 @@ public final class FinAccountHelper { return incrementTotal.subtract(decrementTotal).setScale(DECIMALS, ROUNDING); } - /** - * Returns the net balance (see above) minus the sum of all authorization amounts which are not expired and were authorized by the as of date - * @param finAccountId the financial account id - * @param asOfDateTime the validity date - * @param delegator the delegator - * @return returns the net balance (see above) minus the sum of all authorization amounts which are not expired - * @throws GenericEntityException - */ + /** + * Returns the net balance (see above) minus the sum of all authorization amounts which are not expired and were authorized by the as of date + * + * @param finAccountId the financial account id + * @param asOfDateTime the validity date + * @param delegator the delegator + * @return returns the net balance (see above) minus the sum of all authorization amounts which are not expired + * @throws GenericEntityException + */ public static BigDecimal getAvailableBalance(String finAccountId, Timestamp asOfDateTime, Delegator delegator) throws GenericEntityException { if (asOfDateTime == null) asOfDateTime = UtilDateTime.nowTimestamp(); @@ -242,9 +253,10 @@ public final class FinAccountHelper { /** * Validates a FinAccount's PIN number - * @param delegator the delegator + * + * @param delegator the delegator * @param finAccountId the financial account id - * @param pinNumber a pin number + * @param pinNumber a pin number * @return true if the bin is valid */ public static boolean validatePin(Delegator delegator, String finAccountId, String pinNumber) { @@ -269,9 +281,10 @@ public final class FinAccountHelper { /** * Generate a random financial number + * * @param delegator the delegator - * @param length length of the number to generate (up to 19 digits) - * @param isId to be used as an ID (will check the DB to make sure it doesn't already exist) + * @param length length of the number to generate (up to 19 digits) + * @param isId to be used as an ID (will check the DB to make sure it doesn't already exist) * @return Generated number * @throws GenericEntityException */ diff --git a/applications/order/src/main/java/org/apache/ofbiz/order/order/OrderChangeHelper.java b/applications/order/src/main/java/org/apache/ofbiz/order/order/OrderChangeHelper.java index 4e908bb1b4..74846ce5c5 100644 --- a/applications/order/src/main/java/org/apache/ofbiz/order/order/OrderChangeHelper.java +++ b/applications/order/src/main/java/org/apache/ofbiz/order/order/OrderChangeHelper.java @@ -53,24 +53,24 @@ public final class OrderChangeHelper { } // interal status for held orders - String HEADER_STATUS = "ORDER_PROCESSING"; - String ITEM_STATUS = "ITEM_CREATED"; - String DIGITAL_ITEM_STATUS = "ITEM_APPROVED"; + String headerStatus = "ORDER_PROCESSING"; + String itemStatus = "ITEM_CREATED"; + String digitalItemStatus = "ITEM_APPROVED"; if (!holdOrder) { if (productStore.get("headerApprovedStatus") != null) { - HEADER_STATUS = productStore.getString("headerApprovedStatus"); + headerStatus = productStore.getString("headerApprovedStatus"); } if (productStore.get("itemApprovedStatus") != null) { - ITEM_STATUS = productStore.getString("itemApprovedStatus"); + itemStatus = productStore.getString("itemApprovedStatus"); } if (productStore.get("digitalItemApprovedStatus") != null) { - DIGITAL_ITEM_STATUS = productStore.getString("digitalItemApprovedStatus"); + digitalItemStatus = productStore.getString("digitalItemApprovedStatus"); } } try { - OrderChangeHelper.orderStatusChanges(dispatcher, userLogin, orderId, HEADER_STATUS, "ITEM_CREATED", ITEM_STATUS, DIGITAL_ITEM_STATUS); + OrderChangeHelper.orderStatusChanges(dispatcher, userLogin, orderId, headerStatus, "ITEM_CREATED", itemStatus, digitalItemStatus); } catch (GenericServiceException e) { Debug.logError(e, "Service invocation error, status changes were not updated for order #" + orderId, MODULE); return false; @@ -81,17 +81,17 @@ public final class OrderChangeHelper { public static boolean rejectOrder(LocalDispatcher dispatcher, GenericValue userLogin, String orderId) { GenericValue productStore = OrderReadHelper.getProductStoreFromOrder(dispatcher.getDelegator(), orderId); - String HEADER_STATUS = "ORDER_REJECTED"; - String ITEM_STATUS = "ITEM_REJECTED"; + String headerStatus = "ORDER_REJECTED"; + String itemStatus = "ITEM_REJECTED"; if (productStore.get("headerDeclinedStatus") != null) { - HEADER_STATUS = productStore.getString("headerDeclinedStatus"); - } - if (productStore.get("itemDeclinedStatus") != null) { - ITEM_STATUS = productStore.getString("itemDeclinedStatus"); - } + headerStatus = productStore.getString("headerDeclinedStatus"); + } + if (productStore.get("itemDeclinedStatus") != null) { + itemStatus = productStore.getString("itemDeclinedStatus"); + } try { - OrderChangeHelper.orderStatusChanges(dispatcher, userLogin, orderId, HEADER_STATUS, null, ITEM_STATUS, null); + OrderChangeHelper.orderStatusChanges(dispatcher, userLogin, orderId, headerStatus, null, itemStatus, null); OrderChangeHelper.cancelInventoryReservations(dispatcher, userLogin, orderId); OrderChangeHelper.releasePaymentAuthorizations(dispatcher, userLogin, orderId); } catch (GenericServiceException e) { @@ -115,17 +115,17 @@ public final class OrderChangeHelper { public static boolean cancelOrder(LocalDispatcher dispatcher, GenericValue userLogin, String orderId) { GenericValue productStore = OrderReadHelper.getProductStoreFromOrder(dispatcher.getDelegator(), orderId); - String HEADER_STATUS = "ORDER_CANCELLED"; - String ITEM_STATUS = "ITEM_CANCELLED"; + String headerStatus = "ORDER_CANCELLED"; + String itemStatus = "ITEM_CANCELLED"; if (productStore.get("headerCancelStatus") != null) { - HEADER_STATUS = productStore.getString("headerCancelStatus"); - } - if (productStore.get("itemCancelStatus") != null) { - ITEM_STATUS = productStore.getString("itemCancelStatus"); - } + headerStatus = productStore.getString("headerCancelStatus"); + } + if (productStore.get("itemCancelStatus") != null) { + itemStatus = productStore.getString("itemCancelStatus"); + } try { - OrderChangeHelper.orderStatusChanges(dispatcher, userLogin, orderId, HEADER_STATUS, null, ITEM_STATUS, null); + OrderChangeHelper.orderStatusChanges(dispatcher, userLogin, orderId, headerStatus, null, itemStatus, null); OrderChangeHelper.cancelInventoryReservations(dispatcher, userLogin, orderId); OrderChangeHelper.releasePaymentAuthorizations(dispatcher, userLogin, orderId); } catch (GenericServiceException e) { @@ -266,7 +266,7 @@ public final class OrderChangeHelper { // only do this one time; if we have payment already for this pref ignore. Map results = dispatcher.runSync("createPaymentFromPreference", UtilMisc.toMap("userLogin", userLogin, "orderPaymentPreferenceId", opp.getString("orderPaymentPreferenceId"), - "paymentRefNum", UtilDateTime.nowTimestamp().toString(), "paymentFromId", partyId)); + "paymentRefNum", UtilDateTime.nowTimestamp().toString(), "paymentFromId", partyId)); if (ServiceUtil.isError(results)) { String errorMessage = ServiceUtil.getErrorMessage(results); Debug.logError(errorMessage, MODULE); diff --git a/applications/order/src/main/java/org/apache/ofbiz/order/order/OrderEvents.java b/applications/order/src/main/java/org/apache/ofbiz/order/order/OrderEvents.java index 830d944e18..202f293633 100644 --- a/applications/order/src/main/java/org/apache/ofbiz/order/order/OrderEvents.java +++ b/applications/order/src/main/java/org/apache/ofbiz/order/order/OrderEvents.java @@ -107,7 +107,7 @@ public class OrderEvents { String[] orderItemSeqIdAndOrderItemShipGrpId = selectedItem.split(":"); String orderItemSeqId = orderItemSeqIdAndOrderItemShipGrpId[0]; String shipGroupSeqId = orderItemSeqIdAndOrderItemShipGrpId[1]; - BigDecimal cancelQuantity = new BigDecimal(request.getParameter("iqm_"+orderItemSeqId+":"+shipGroupSeqId)); + BigDecimal cancelQuantity = new BigDecimal(request.getParameter("iqm_" + orderItemSeqId + ":" + shipGroupSeqId)); Map contextMap = new HashMap<>(); contextMap.put("orderId", orderId); contextMap.put("orderItemSeqId", orderItemSeqId); diff --git a/applications/order/src/main/java/org/apache/ofbiz/order/order/OrderListState.java b/applications/order/src/main/java/org/apache/ofbiz/order/order/OrderListState.java index 0b7d7f260a..71991e09a1 100644 --- a/applications/order/src/main/java/org/apache/ofbiz/order/order/OrderListState.java +++ b/applications/order/src/main/java/org/apache/ofbiz/order/order/OrderListState.java @@ -254,7 +254,7 @@ public class OrderListState implements Serializable { typeConditions.add(EntityCondition.makeCondition("orderTypeId", EntityOperator.EQUALS, parameterToOrderTypeId.get(type))); } - EntityCondition statusConditionsList = EntityCondition.makeCondition(statusConditions, EntityOperator.OR); + EntityCondition statusConditionsList = EntityCondition.makeCondition(statusConditions, EntityOperator.OR); EntityCondition typeConditionsList = EntityCondition.makeCondition(typeConditions, EntityOperator.OR); if (statusConditions.size() > 0) { allConditions.add(statusConditionsList); diff --git a/applications/order/src/main/java/org/apache/ofbiz/order/order/OrderLookupServices.java b/applications/order/src/main/java/org/apache/ofbiz/order/order/OrderLookupServices.java index a7793b1947..2bec373c5e 100644 --- a/applications/order/src/main/java/org/apache/ofbiz/order/order/OrderLookupServices.java +++ b/applications/order/src/main/java/org/apache/ofbiz/order/order/OrderLookupServices.java @@ -632,7 +632,7 @@ public class OrderLookupServices { result.put("viewSize", viewSize); result.put("showAll", showAll); - result.put("paramList", (paramString != null? paramString: "")); + result.put("paramList", (paramString != null ? paramString : "")); result.put("orderList", orderList); result.put("orderListSize", orderCount); diff --git a/applications/order/src/main/java/org/apache/ofbiz/order/order/OrderReadHelper.java b/applications/order/src/main/java/org/apache/ofbiz/order/order/OrderReadHelper.java index fddaf6090f..3d32603bed 100644 --- a/applications/order/src/main/java/org/apache/ofbiz/order/order/OrderReadHelper.java +++ b/applications/order/src/main/java/org/apache/ofbiz/order/order/OrderReadHelper.java @@ -1220,7 +1220,7 @@ public class OrderReadHelper { itemInfo.put("productId", item.getString("productId")); itemInfo.put("quantity", getOrderItemQuantity(item)); itemInfo.put("weight", this.getItemWeight(item)); - itemInfo.put("size", this.getItemSize(item)); + itemInfo.put("size", this.getItemSize(item)); itemInfo.put("piecesIncluded", this.getItemPiecesIncluded(item)); itemInfo.put("featureSet", this.getItemFeatureSet(item)); return itemInfo; @@ -1540,7 +1540,7 @@ public class OrderReadHelper { return getOrderItemAdjustmentList(orderItem, getAdjustments()); } - public String getCurrentOrderItemWorkEffort(GenericValue orderItem) { + public String getCurrentOrderItemWorkEffort(GenericValue orderItem) { String orderItemSeqId = orderItem.getString("orderItemSeqId"); String orderId = orderItem.getString("orderId"); Delegator delegator = orderItem.getDelegator(); @@ -2422,7 +2422,7 @@ public class OrderReadHelper { Iterator weIter = UtilMisc.toIterator(workEfforts); while (weIter != null && weIter.hasNext()) { GenericValue workEffort = weIter.next(); - if (workEffort.getString("workEffortId").compareTo(orderItem.getString("orderItemSeqId")) == 0) { + if (workEffort.getString("workEffortId").compareTo(orderItem.getString("orderItemSeqId")) == 0) { itemTotal = itemTotal.multiply(getWorkEffortRentalQuantity(workEffort)).setScale(DECIMALS, ROUNDING); break; } @@ -2490,7 +2490,7 @@ public class OrderReadHelper { while (itemIter != null && itemIter.hasNext()) { result = result.add(getOrderItemTotal(itemIter.next(), adjustments)); } - return result.setScale(DECIMALS, ROUNDING); + return result.setScale(DECIMALS, ROUNDING); } public static BigDecimal getOrderItemTotal(GenericValue orderItem, List adjustments) { @@ -2543,7 +2543,7 @@ public class OrderReadHelper { } BigDecimal rentalAdjustment = ZERO; - if (persons.compareTo(BigDecimal.ONE) == 1) { + if (persons.compareTo(BigDecimal.ONE) == 1) { if (persons.compareTo(new BigDecimal(2)) == 1) { persons = persons.subtract(new BigDecimal(2)); if (nthPersonPerc.signum() == 1) { diff --git a/applications/order/src/main/java/org/apache/ofbiz/order/order/OrderReturnServices.java b/applications/order/src/main/java/org/apache/ofbiz/order/order/OrderReturnServices.java index bd6d29380c..714217b647 100644 --- a/applications/order/src/main/java/org/apache/ofbiz/order/order/OrderReturnServices.java +++ b/applications/order/src/main/java/org/apache/ofbiz/order/order/OrderReturnServices.java @@ -836,7 +836,7 @@ public class OrderReturnServices { createAccountCtx.put("finAccountTypeId", "STORE_CREDIT_ACCT"); createAccountCtx.put("productStoreId", productStore.getString("productStoreId")); createAccountCtx.put("currencyUomId", returnHeader.getString("currencyUomId")); - createAccountCtx.put("finAccountName", "Store Credit Account for party ["+fromPartyId+"]"); + createAccountCtx.put("finAccountName", "Store Credit Account for party [" + fromPartyId + "]"); createAccountCtx.put("userLogin", userLogin); Map createAccountResult = null; try { @@ -1751,7 +1751,7 @@ public class OrderReturnServices { orderMap.put("webSiteId", orderHeader.get("webSiteId")); orderMap.put("visitId", orderHeader.get("visitId")); orderMap.put("currencyUom", orderHeader.get("currencyUom")); - orderMap.put("grandTotal", BigDecimal.ZERO); + orderMap.put("grandTotal", BigDecimal.ZERO); // make the contact mechs List contactMechs = new LinkedList<>(); diff --git a/applications/order/src/main/java/org/apache/ofbiz/order/order/OrderServices.java b/applications/order/src/main/java/org/apache/ofbiz/order/order/OrderServices.java index 7c241901c8..21cbe66d9e 100644 --- a/applications/order/src/main/java/org/apache/ofbiz/order/order/OrderServices.java +++ b/applications/order/src/main/java/org/apache/ofbiz/order/order/OrderServices.java @@ -307,14 +307,14 @@ public class OrderServices { try { product = EntityQuery.use(delegator).from("Product").where("productId", currentProductId).cache().queryOne(); } catch (GenericEntityException e) { - String errMsg = UtilProperties.getMessage(RES_ERROR, "product.not_found", new Object[] { currentProductId }, locale); + String errMsg = UtilProperties.getMessage(RES_ERROR, "product.not_found", new Object[] {currentProductId }, locale); Debug.logError(e, errMsg, MODULE); errorMessages.add(errMsg); continue; } if (product == null) { - String errMsg = UtilProperties.getMessage(RES_ERROR, "product.not_found", new Object[] { currentProductId }, locale); + String errMsg = UtilProperties.getMessage(RES_ERROR, "product.not_found", new Object[] {currentProductId }, locale); Debug.logError(errMsg, MODULE); errorMessages.add(errMsg); continue; @@ -359,7 +359,7 @@ public class OrderServices { errorMessages.addAll(errMsgList); } else if (!"Y".equals(invReqResult.get("availableOrNotRequired"))) { String invErrMsg = UtilProperties.getMessage(RES_ERROR, "product.out_of_stock", - new Object[] { getProductName(product, itemName), currentProductId }, locale); + new Object[] {getProductName(product, itemName), currentProductId }, locale); Debug.logWarning(invErrMsg, MODULE); errorMessages.add(invErrMsg); continue; @@ -377,8 +377,8 @@ public class OrderServices { for (GenericValue orderItem : orderItems) { if ("RENTAL_ORDER_ITEM".equals(orderItem.getString("orderItemTypeId"))) { // check to see if workefforts are available for this order type. - if (UtilValidate.isEmpty(workEfforts)) { - String errMsg = "Work Efforts missing for ordertype RENTAL_ORDER_ITEM " + "Product: " + orderItem.getString("productId"); + if (UtilValidate.isEmpty(workEfforts)) { + String errMsg = "Work Efforts missing for ordertype RENTAL_ORDER_ITEM " + "Product: " + orderItem.getString("productId"); Debug.logError(errMsg, MODULE); errorMessages.add(errMsg); return ServiceUtil.returnError(UtilProperties.getMessage(RES_ERROR, @@ -387,7 +387,7 @@ public class OrderServices { for (GenericValue workEffort : workEfforts) { // find the related workEffortItem (workEffortId = orderSeqId) // create the entity maps required. - if (workEffort.getString("workEffortId").equals(orderItem.getString("orderItemSeqId"))) { + if (workEffort.getString("workEffortId").equals(orderItem.getString("orderItemSeqId"))) { List selFixedAssetProduct = null; try { selFixedAssetProduct = EntityQuery.use(delegator).from("FixedAssetProduct").where("productId", orderItem.getString("productId"), "fixedAssetProductTypeId", "FAPT_USE").filterByDate(nowTimestamp, "fromDate", "thruDate").queryList(); @@ -676,8 +676,7 @@ public class OrderServices { Debug.logInfo("find the fixedAsset", MODULE); try { fixedAsset = EntityQuery.use(delegator).from("FixedAsset").where("fixedAssetId", workEffort.get("fixedAssetId")).queryOne(); - } - catch (GenericEntityException e) { + } catch (GenericEntityException e) { return ServiceUtil.returnError(UtilProperties.getMessage(RES_ERROR, "OrderFixedAssetNotFoundFixedAssetId", UtilMisc.toMap("fixedAssetId", workEffort.get("fixedAssetId")), locale)); @@ -690,9 +689,9 @@ public class OrderServices { // see if this fixed asset has a calendar, when no create one and attach to fixed asset Debug.logInfo("find the techdatacalendar", MODULE); GenericValue techDataCalendar = null; - try { techDataCalendar = fixedAsset.getRelatedOne("TechDataCalendar", false); - } - catch (GenericEntityException e) { + try { + techDataCalendar = fixedAsset.getRelatedOne("TechDataCalendar", false); + } catch (GenericEntityException e) { Debug.logInfo("TechData calendar does not exist yet so create for fixedAsset: " + fixedAsset.get("fixedAssetId"), MODULE); } if (techDataCalendar == null) { @@ -736,15 +735,14 @@ public class OrderServices { // please note that calendarId is the same for (TechData)Calendar, CalendarExcDay and CalendarExWeek Timestamp estimatedStartDate = workEffort.getTimestamp("estimatedStartDate"); Timestamp estimatedCompletionDate = workEffort.getTimestamp("estimatedCompletionDate"); - long dayCount = (estimatedCompletionDate.getTime() - estimatedStartDate.getTime())/86400000; - while (--dayCount >= 0) { + long dayCount = (estimatedCompletionDate.getTime() - estimatedStartDate.getTime()) / 86400000; + while (--dayCount >= 0) { GenericValue techDataCalendarExcDay = null; // find an existing Day exception record Timestamp exceptionDateStartTime = UtilDateTime.getDayStart(new Timestamp(estimatedStartDate.getTime()), (int) dayCount); try { techDataCalendarExcDay = EntityQuery.use(delegator).from("TechDataCalendarExcDay").where("calendarId", fixedAsset.get("calendarId"), "exceptionDateStartTime", exceptionDateStartTime).queryOne(); - } - catch (GenericEntityException e) { + } catch (GenericEntityException e) { Debug.logInfo(" techData excday record not found so creating........", MODULE); } if (techDataCalendarExcDay == null) { @@ -756,7 +754,7 @@ public class OrderServices { } } } - if (techDataCalendarExcDay == null) { + if (techDataCalendarExcDay == null) { techDataCalendarExcDay = delegator.makeValue("TechDataCalendarExcDay"); techDataCalendarExcDay.set("calendarId", fixedAsset.get("calendarId")); techDataCalendarExcDay.set("exceptionDateStartTime", exceptionDateStartTime); @@ -766,8 +764,8 @@ public class OrderServices { // add the quantity to the quantity on the date record BigDecimal newUsedCapacity = techDataCalendarExcDay.getBigDecimal("usedCapacity").add(workEffort.getBigDecimal("quantityToProduce")); // check to see if the requested quantity is available on the requested day but only when the maximum capacity is set on the fixed asset - if (fixedAsset.get("productionCapacity") != null) { - if (newUsedCapacity.compareTo(techDataCalendarExcDay.getBigDecimal("exceptionCapacity")) > 0) { + if (fixedAsset.get("productionCapacity") != null) { + if (newUsedCapacity.compareTo(techDataCalendarExcDay.getBigDecimal("exceptionCapacity")) > 0) { String errMsg = UtilProperties.getMessage(RES_ERROR, "OrderFixedAssetSoldOut", UtilMisc.toMap("fixedAssetId", workEffort.get("fixedAssetId"), "exceptionDateStartTime", techDataCalendarExcDay.getString("exceptionDateStartTime")), locale); Debug.logError(errMsg, MODULE); errorMessages.add(errMsg); @@ -1015,25 +1013,25 @@ public class OrderServices { // store the OrderTerm entities - List orderTerms = UtilGenerics.cast(context.get("orderTerms")); - if (UtilValidate.isNotEmpty(orderTerms)) { - for (GenericValue orderTerm : orderTerms) { - orderTerm.set("orderId", orderId); - if (orderTerm.get("orderItemSeqId") == null) { - orderTerm.set("orderItemSeqId", "_NA_"); - } - toBeStored.add(orderTerm); - } - } + List orderTerms = UtilGenerics.cast(context.get("orderTerms")); + if (UtilValidate.isNotEmpty(orderTerms)) { + for (GenericValue orderTerm : orderTerms) { + orderTerm.set("orderId", orderId); + if (orderTerm.get("orderItemSeqId") == null) { + orderTerm.set("orderItemSeqId", "_NA_"); + } + toBeStored.add(orderTerm); + } + } - // if a workEffortId is passed, then prepare a OrderHeaderWorkEffort value - String workEffortId = (String) context.get("workEffortId"); - if (UtilValidate.isNotEmpty(workEffortId)) { - GenericValue orderHeaderWorkEffort = delegator.makeValue("OrderHeaderWorkEffort"); - orderHeaderWorkEffort.set("orderId", orderId); - orderHeaderWorkEffort.set("workEffortId", workEffortId); - toBeStored.add(orderHeaderWorkEffort); - } + // if a workEffortId is passed, then prepare a OrderHeaderWorkEffort value + String workEffortId = (String) context.get("workEffortId"); + if (UtilValidate.isNotEmpty(workEffortId)) { + GenericValue orderHeaderWorkEffort = delegator.makeValue("OrderHeaderWorkEffort"); + orderHeaderWorkEffort.set("orderId", orderId); + orderHeaderWorkEffort.set("workEffortId", workEffortId); + toBeStored.add(orderHeaderWorkEffort); + } try { // store line items, etc so that they will be there for the foreign key checks @@ -1467,7 +1465,7 @@ public class OrderServices { Debug.logError(e, errorMessage, MODULE); return ServiceUtil.returnError(errorMessage + e.getMessage() + ")."); } - showPricesWithVatTax = productStore.getString("showPricesWithVatTax"); + showPricesWithVatTax = productStore.getString("showPricesWithVatTax"); } BigDecimal remainingSubTotal = ZERO; if (UtilValidate.isNotEmpty(productStoreId) && "Y".equalsIgnoreCase(showPricesWithVatTax)) { @@ -1958,7 +1956,7 @@ public class OrderServices { } } } catch (GenericEntityException e) { - String errMsg = UtilProperties.getMessage(RES_ERROR, "OrderDatabaseErrorCheckingIfWeShouldChangeOrderHeaderStatusToApproved", UtilMisc.toMap("errorString", e.toString()), locale); + String errMsg = UtilProperties.getMessage(RES_ERROR, "OrderDatabaseErrorCheckingIfWeShouldChangeOrderHeaderStatusToApproved", UtilMisc.toMap("errorString", e.toString()), locale); Debug.logError(e, errMsg, MODULE); return ServiceUtil.returnError(errMsg); } @@ -2021,7 +2019,7 @@ public class OrderServices { Map itemCommentMap = UtilGenerics.cast(context.get("itemCommentMap")); Map itemQuantityMap = UtilGenerics.cast(context.get("itemQtyMap")); if ((cancelQuantity == null) && UtilValidate.isNotEmpty(itemQuantityMap)) { - String key = orderItemSeqId+":"+shipGroupSeqId; + String key = orderItemSeqId + ":" + shipGroupSeqId; if (UtilValidate.isNotEmpty(itemQuantityMap.get(key))) { cancelQuantity = new BigDecimal(itemQuantityMap.get(key)); } @@ -2098,7 +2096,7 @@ public class OrderServices { itemQuantity = itemQuantity.subtract(receivedQty); } else { BigDecimal shippedQty = orh.getItemShippedQuantity(orderItem); - if (shippedQty.compareTo(BigDecimal.ZERO) > 0 ) { + if (shippedQty.compareTo(BigDecimal.ZERO) > 0) { itemStatus = "ITEM_COMPLETED"; } itemQuantity = itemQuantity.subtract(shippedQty); @@ -2178,8 +2176,8 @@ public class OrderServices { try { BigDecimal quantity = thisCancelQty.setScale(1, ROUNDING); String cancelledItemToOrder = UtilProperties.getMessage(RESOURCE, "OrderCancelledItemToOrder", locale); - resp = dispatcher.runSync("createOrderNote", UtilMisc.toMap("orderId", orderId, "note", cancelledItemToOrder + - orderItem.getString("productId") + " (" + quantity + ")", "internalNote", "Y", "userLogin", userLogin)); + resp = dispatcher.runSync("createOrderNote", UtilMisc.toMap("orderId", orderId, "note", cancelledItemToOrder + + orderItem.getString("productId") + " (" + quantity + ")", "internalNote", "Y", "userLogin", userLogin)); if (ServiceUtil.isError(resp)) { return ServiceUtil.returnError(ServiceUtil.getErrorMessage(resp)); } @@ -3620,7 +3618,7 @@ public class OrderServices { if (itemAttributesMap != null) { // go through the item attributes map once to get a list of key names Set attributeNames = new HashSet<>(); - Set keys = itemAttributesMap.keySet(); + Set keys = itemAttributesMap.keySet(); for (String key : keys) { attributeNames.add(key); } @@ -3650,8 +3648,8 @@ public class OrderServices { // log an order note try { String addedItemToOrder = UtilProperties.getMessage(RESOURCE, "OrderAddedItemToOrder", locale); - Map result = dispatcher.runSync("createOrderNote", UtilMisc.toMap("orderId", orderId, "note", addedItemToOrder + - productId + " (" + quantity + ")", "internalNote", "Y", "userLogin", userLogin)); + Map result = dispatcher.runSync("createOrderNote", UtilMisc.toMap("orderId", orderId, "note", addedItemToOrder + + productId + " (" + quantity + ")", "internalNote", "Y", "userLogin", userLogin)); if (ServiceUtil.isError(result)) { return ServiceUtil.returnError(ServiceUtil.getErrorMessage(result)); } @@ -3801,7 +3799,7 @@ public class OrderServices { if (itemAttributesMap != null) { // go through the item attributes map once to get a list of key names Set attributeNames = new HashSet<>(); - Set keys = itemAttributesMap.keySet(); + Set keys = itemAttributesMap.keySet(); for (String key : keys) { String[] attributeInfo = key.split(":"); attributeNames.add(attributeInfo[0]); @@ -4665,15 +4663,15 @@ public class OrderServices { // create the payment Map paymentParams = new HashMap<>(); BigDecimal maxAmount = orderPaymentPreference.getBigDecimal("maxAmount"); - paymentParams.put("paymentTypeId", "CUSTOMER_PAYMENT"); - paymentParams.put("paymentMethodTypeId", orderPaymentPreference.getString("paymentMethodTypeId")); - paymentParams.put("paymentPreferenceId", orderPaymentPreference.getString("orderPaymentPreferenceId")); - paymentParams.put("amount", maxAmount); - paymentParams.put("statusId", "PMNT_RECEIVED"); - paymentParams.put("effectiveDate", eventDate); - paymentParams.put("partyIdFrom", paymentFromId); - paymentParams.put("currencyUomId", productStore.getString("defaultCurrencyUomId")); - paymentParams.put("partyIdTo", payToPartyId); + paymentParams.put("paymentTypeId", "CUSTOMER_PAYMENT"); + paymentParams.put("paymentMethodTypeId", orderPaymentPreference.getString("paymentMethodTypeId")); + paymentParams.put("paymentPreferenceId", orderPaymentPreference.getString("orderPaymentPreferenceId")); + paymentParams.put("amount", maxAmount); + paymentParams.put("statusId", "PMNT_RECEIVED"); + paymentParams.put("effectiveDate", eventDate); + paymentParams.put("partyIdFrom", paymentFromId); + paymentParams.put("currencyUomId", productStore.getString("defaultCurrencyUomId")); + paymentParams.put("partyIdTo", payToPartyId); if (paymentRefNum != null) { paymentParams.put("paymentRefNum", paymentRefNum); } @@ -6036,8 +6034,7 @@ public class OrderServices { if (rowCountInt == rowNumberInt - 1) { try { message = validateOrderItemShipGroupAssoc(delegator, dispatcher, orderItem, totalQuantity, oisga, userLogin, locale); - } - catch (GeneralException e) { + } catch (GeneralException e) { String errMsg = mainErrorMessage + UtilProperties.getMessage(RES_ERROR, "OrderQuantityAssociatedIsLessThanOrderItemQuantity", locale); Debug.logError(errMsg, MODULE); return ServiceUtil.returnError(errMsg); @@ -6049,20 +6046,21 @@ public class OrderServices { result.put(ModelService.SUCCESS_MESSAGE, message); } return result; - } + } - BigDecimal actualQuantity = totalQuantity.add(quantity); - BigDecimal qty = (BigDecimal) orderItem.get("quantity"); - if (UtilValidate.isEmpty(qty)) { - qty = BigDecimal.ZERO; - } - BigDecimal cancelQty = (BigDecimal) orderItem.get("cancelQuantity"); - if (UtilValidate.isEmpty(cancelQty)) { - cancelQty = BigDecimal.ZERO; - } - BigDecimal orderItemQuantity = qty.subtract(cancelQty); + BigDecimal actualQuantity = totalQuantity.add(quantity); + BigDecimal qty = (BigDecimal) orderItem.get("quantity"); + if (UtilValidate.isEmpty(qty)) { + qty = BigDecimal.ZERO; + } + BigDecimal cancelQty = (BigDecimal) orderItem.get("cancelQuantity"); + if (UtilValidate.isEmpty(cancelQty)) { + cancelQty = BigDecimal.ZERO; + } + BigDecimal orderItemQuantity = qty.subtract(cancelQty); if (actualQuantity.compareTo(orderItemQuantity) > 0) { - String errMsg = mainErrorMessage + UtilProperties.getMessage(RES_ERROR, "OrderQuantityAssociatedIsBiggerThanOrderItemQuantity", locale); + String errMsg = mainErrorMessage + UtilProperties.getMessage(RES_ERROR, "OrderQuantityAssociatedIsBiggerThanOrderItemQuantity", + locale); Debug.logError(errMsg, MODULE); return ServiceUtil.returnError(errMsg); } @@ -6102,9 +6100,8 @@ public class OrderServices { int rowNumberInt = rowNumber; if (rowCountInt == rowNumberInt - 1) { try { - message = validateOrderItemShipGroupAssoc(delegator, dispatcher, orderItem, totalQuantity, oisga, userLogin, locale); - } - catch (GeneralException e) { + message = validateOrderItemShipGroupAssoc(delegator, dispatcher, orderItem, totalQuantity, oisga, userLogin, locale); + } catch (GeneralException e) { String errMsg = mainErrorMessage + UtilProperties.getMessage(RES_ERROR, "OrderQuantityAssociatedIsLessThanOrderItemQuantity", locale); Debug.logError(errMsg, MODULE); return ServiceUtil.returnError(errMsg); @@ -6380,7 +6377,7 @@ public class OrderServices { LocalDispatcher dispatcher = dctx.getDispatcher(); Delegator delegator = dctx.getDelegator(); Locale locale = (Locale) context.get("locale"); - GenericValue userLogin = (GenericValue) context.get("userLogin"); + GenericValue userLogin = (GenericValue) context.get("userLogin"); String orderId = (String) context.get("orderId"); String shipGroupSeqId = (String) context.get("shipGroupSeqId"); String contactMechId = (String) context.get("contactMechId"); @@ -6446,8 +6443,8 @@ public class OrderServices { shoppingCart.setShipmentMethodTypeId(groupIdx - 1, shippingMethods.get(0).getString("shipmentMethodTypeId")); shoppingCart.setCarrierPartyId(groupIdx - 1, shippingMethods.get(0).getString("carrierPartyId")); - String newShipMethTypeDesc =null; - String shipMethTypeDesc=null; + String newShipMethTypeDesc = null; + String shipMethTypeDesc = null; try { shipMethTypeDesc = EntityQuery.use(delegator).from("ShipmentMethodType").where("shipmentMethodTypeId", shipmentMethodTypeId).queryOne().getString("description"); newShipMethTypeDesc = EntityQuery.use(delegator).from("ShipmentMethodType").where("shipmentMethodTypeId", shippingMethods.get(0).getString("shipmentMethodTypeId")).queryOne().getString("description"); @@ -6455,7 +6452,7 @@ public class OrderServices { Debug.logError(e, MODULE); } // message to notify user for not applicability of shipping method - message= "Shipping Method "+carrierPartyId+" "+shipMethTypeDesc+" is not applicable to shipping address. "+shippingMethods.get(0).getString("carrierPartyId")+" "+newShipMethTypeDesc+" has been set for shipping address."; + message = "Shipping Method " + carrierPartyId + " " + shipMethTypeDesc + " is not applicable to shipping address. " + shippingMethods.get(0).getString("carrierPartyId") + " " + newShipMethTypeDesc + " has been set for shipping address."; } shoppingCart.setShippingContactMechId(groupIdx-1, contactMechId); } @@ -6478,7 +6475,7 @@ public class OrderServices { public static Map associateOrderWithAllocationPlans(DispatchContext dctx, Map context) { Delegator delegator = dctx.getDelegator(); LocalDispatcher dispatcher = dctx.getDispatcher(); - GenericValue userLogin = (GenericValue) context.get("userLogin"); + GenericValue userLogin = (GenericValue) context.get("userLogin"); String orderId = (String) context.get("orderId"); Map productPlanMap = new HashMap<>(); Map serviceResult = new HashMap<>(); @@ -6513,7 +6510,7 @@ public class OrderServices { serviceCtx.put("planId", planId); serviceCtx.put("productId", productId); serviceCtx.put("planTypeId", "SALES_ORD_ALLOCATION"); - serviceCtx.put("planName", "Allocation Plan For Product #"+productId); + serviceCtx.put("planName", "Allocation Plan For Product #" + productId); serviceCtx.put("statusId", "ALLOC_PLAN_CREATED"); serviceCtx.put("createdByUserLogin", userLoginId); serviceCtx.put("userLogin", userLogin); @@ -6597,7 +6594,7 @@ public class OrderServices { public static Map approveAllocationPlanItems(DispatchContext dctx, Map context) { Delegator delegator = dctx.getDelegator(); LocalDispatcher dispatcher = dctx.getDispatcher(); - GenericValue userLogin = (GenericValue) context.get("userLogin"); + GenericValue userLogin = (GenericValue) context.get("userLogin"); String planId = (String) context.get("planId"); Map serviceCtx = new HashMap<>(); Map serviceResult = new HashMap<>(); @@ -6661,7 +6658,7 @@ public class OrderServices { public static Map cancelAllocationPlanItems(DispatchContext dctx, Map context) { Delegator delegator = dctx.getDelegator(); LocalDispatcher dispatcher = dctx.getDispatcher(); - GenericValue userLogin = (GenericValue) context.get("userLogin"); + GenericValue userLogin = (GenericValue) context.get("userLogin"); String planId = (String) context.get("planId"); Map serviceCtx = new HashMap<>(); Map serviceResult = new HashMap<>(); @@ -6698,7 +6695,7 @@ public class OrderServices { public static Map changeAllocationPlanStatus(DispatchContext dctx, Map context) { Delegator delegator = dctx.getDelegator(); LocalDispatcher dispatcher = dctx.getDispatcher(); - GenericValue userLogin = (GenericValue) context.get("userLogin"); + GenericValue userLogin = (GenericValue) context.get("userLogin"); Locale locale = (Locale) context.get("locale"); String planId = (String) context.get("planId"); String statusId = (String) context.get("statusId"); @@ -6749,7 +6746,7 @@ public class OrderServices { public static Map changeAllocationPlanItemStatus(DispatchContext dctx, Map context) { Delegator delegator = dctx.getDelegator(); LocalDispatcher dispatcher = dctx.getDispatcher(); - GenericValue userLogin = (GenericValue) context.get("userLogin"); + GenericValue userLogin = (GenericValue) context.get("userLogin"); Locale locale = (Locale) context.get("locale"); String planId = (String) context.get("planId"); String planItemSeqId = (String) context.get("planItemSeqId"); @@ -6799,7 +6796,7 @@ public class OrderServices { public static Map completeAllocationPlanItemByOrderItem(DispatchContext dctx, Map context) { Delegator delegator = dctx.getDelegator(); LocalDispatcher dispatcher = dctx.getDispatcher(); - GenericValue userLogin = (GenericValue) context.get("userLogin"); + GenericValue userLogin = (GenericValue) context.get("userLogin"); String orderId = (String) context.get("orderId"); String orderItemSeqId = (String) context.get("orderItemSeqId"); try { @@ -6865,7 +6862,7 @@ public class OrderServices { public static Map cancelAllocationPlanItemByOrderItem(DispatchContext dctx, Map context) { Delegator delegator = dctx.getDelegator(); LocalDispatcher dispatcher = dctx.getDispatcher(); - GenericValue userLogin = (GenericValue) context.get("userLogin"); + GenericValue userLogin = (GenericValue) context.get("userLogin"); String orderId = (String) context.get("orderId"); String orderItemSeqId = (String) context.get("orderItemSeqId"); try { @@ -6930,7 +6927,7 @@ public class OrderServices { public static Map updateAllocatedQuantityOnOrderItemChange(DispatchContext dctx, Map context) { Delegator delegator = dctx.getDelegator(); LocalDispatcher dispatcher = dctx.getDispatcher(); - GenericValue userLogin = (GenericValue) context.get("userLogin"); + GenericValue userLogin = (GenericValue) context.get("userLogin"); String orderId = (String) context.get("orderId"); try { OrderReadHelper orderReadHelper = new OrderReadHelper(delegator, orderId); @@ -6977,7 +6974,7 @@ public class OrderServices { public static Map createAllocationPlanAndItems(DispatchContext dctx, Map context) { Delegator delegator = dctx.getDelegator(); LocalDispatcher dispatcher = dctx.getDispatcher(); - GenericValue userLogin = (GenericValue) context.get("userLogin"); + GenericValue userLogin = (GenericValue) context.get("userLogin"); Locale locale = (Locale) context.get("locale"); String productId = (String) context.get("productId"); Integer itemListSize = (Integer) context.get("itemListSize"); diff --git a/applications/order/src/main/java/org/apache/ofbiz/order/shoppingcart/CheckOutEvents.java b/applications/order/src/main/java/org/apache/ofbiz/order/shoppingcart/CheckOutEvents.java index d5184b0761..47fba12828 100644 --- a/applications/order/src/main/java/org/apache/ofbiz/order/shoppingcart/CheckOutEvents.java +++ b/applications/order/src/main/java/org/apache/ofbiz/order/shoppingcart/CheckOutEvents.java @@ -891,7 +891,7 @@ public class CheckOutEvents { //See whether we need to return an error or not callResult = ServiceUtil.returnSuccess(); if (errorMessages.size() > 0) { - callResult.put(ModelService.ERROR_MESSAGE_LIST, errorMessages); + callResult.put(ModelService.ERROR_MESSAGE_LIST, errorMessages); callResult.put(ModelService.RESPONSE_MESSAGE, ModelService.RESPOND_ERROR); } if (errorMaps.size() > 0) { diff --git a/applications/order/src/main/java/org/apache/ofbiz/order/shoppingcart/CheckOutHelper.java b/applications/order/src/main/java/org/apache/ofbiz/order/shoppingcart/CheckOutHelper.java index e03a6f75ce..2811553586 100644 --- a/applications/order/src/main/java/org/apache/ofbiz/order/shoppingcart/CheckOutHelper.java +++ b/applications/order/src/main/java/org/apache/ofbiz/order/shoppingcart/CheckOutHelper.java @@ -366,27 +366,27 @@ public class CheckOutHelper { } public Map setCheckOutDates(Timestamp shipBefore, Timestamp shipAfter) { - List errorMessages = new ArrayList<>(); - Map result = null; - String errMsg = null; + List errorMessages = new ArrayList<>(); + Map result = null; + String errMsg = null; - if (UtilValidate.isNotEmpty(this.cart)) { - this.cart.setShipBeforeDate(shipBefore); - this.cart.setShipAfterDate(shipAfter); - } else { - errMsg = UtilProperties.getMessage(RES_ERROR, "checkhelper.no_items_in_cart", - (cart != null ? cart.getLocale() : Locale.getDefault())); - errorMessages.add(errMsg); - } + if (UtilValidate.isNotEmpty(this.cart)) { + this.cart.setShipBeforeDate(shipBefore); + this.cart.setShipAfterDate(shipAfter); + } else { + errMsg = UtilProperties.getMessage(RES_ERROR, "checkhelper.no_items_in_cart", + (cart != null ? cart.getLocale() : Locale.getDefault())); + errorMessages.add(errMsg); + } - if (errorMessages.size() == 1) { - result = ServiceUtil.returnError(errorMessages.get(0)); - } else if (errorMessages.size() > 0) { - result = ServiceUtil.returnError(errorMessages); - } else { - result = ServiceUtil.returnSuccess(); - } - return result; + if (errorMessages.size() == 1) { + result = ServiceUtil.returnError(errorMessages.get(0)); + } else if (errorMessages.size() > 0) { + result = ServiceUtil.returnError(errorMessages); + } else { + result = ServiceUtil.returnSuccess(); + } + return result; } @@ -950,11 +950,11 @@ public class CheckOutHelper { public static Map processPayment(String orderId, BigDecimal orderTotal, String currencyUomId, GenericValue productStore, GenericValue userLogin, boolean faceToFace, boolean manualHold, LocalDispatcher dispatcher, Delegator delegator) throws GeneralException { // Get some payment related strings - String DECLINE_MESSAGE = productStore.getString("authDeclinedMessage"); - String ERROR_MESSAGE = productStore.getString("authErrorMessage"); - String RETRY_ON_ERROR = productStore.getString("retryFailedAuths"); - if (RETRY_ON_ERROR == null) { - RETRY_ON_ERROR = "Y"; + String declineMessage = productStore.getString("authDeclinedMessage"); + String errMessage = productStore.getString("authErrorMessage"); + String retryOnError = productStore.getString("retryFailedAuths"); + if (retryOnError == null) { + retryOnError = "Y"; } List allPaymentPreferences = null; @@ -1033,6 +1033,8 @@ public class CheckOutHelper { // Check the payment preferences; if we have ANY w/ status PAYMENT_NOT_AUTH invoke payment service. // Invoke payment processing. + Debug.log("==========allPaymentPreferences=======" + allPaymentPreferences); + Debug.log("==========onlinePaymentPrefs=======" + onlinePaymentPrefs); if (UtilValidate.isNotEmpty(onlinePaymentPrefs)) { boolean autoApproveOrder = UtilValidate.isEmpty(productStore.get("autoApproveOrder")) || "Y".equalsIgnoreCase(productStore.getString("autoApproveOrder")); if (orderTotal.compareTo(BigDecimal.ZERO) == 0 && autoApproveOrder) { @@ -1078,7 +1080,7 @@ public class CheckOutHelper { throw new GeneralException("Problem with order change; see above error"); } if (UtilValidate.isEmpty(messages)) { - return ServiceUtil.returnError(DECLINE_MESSAGE); + return ServiceUtil.returnError(declineMessage); } return ServiceUtil.returnError(messages); } else if ("APPROVED".equals(authResp)) { @@ -1119,16 +1121,16 @@ public class CheckOutHelper { if (Debug.verboseOn()) { Debug.logVerbose("Payment auth failed due to processor trouble.", MODULE); } - if (!faceToFace && "Y".equalsIgnoreCase(RETRY_ON_ERROR)) { + if (!faceToFace && "Y".equalsIgnoreCase(retryOnError)) { // never do this for a face to face purchase regardless of store setting - return ServiceUtil.returnSuccess(ERROR_MESSAGE); + return ServiceUtil.returnSuccess(errMessage); } boolean ok = OrderChangeHelper.cancelOrder(dispatcher, userLogin, orderId); if (!ok) { throw new GeneralException("Problem with order change; see above error"); } if (UtilValidate.isEmpty(messages)) { - return ServiceUtil.returnError(ERROR_MESSAGE); + return ServiceUtil.returnError(errMessage); } return ServiceUtil.returnError(messages); } else { @@ -1140,15 +1142,15 @@ public class CheckOutHelper { if (Debug.verboseOn()) { Debug.logVerbose("Payment auth failed due to processor trouble.", MODULE); } - if (!faceToFace && "Y".equalsIgnoreCase(RETRY_ON_ERROR)) { + if (!faceToFace && "Y".equalsIgnoreCase(retryOnError)) { // never do this for a face to face purchase regardless of store setting - return ServiceUtil.returnSuccess(ERROR_MESSAGE); + return ServiceUtil.returnSuccess(errMessage); } boolean ok = OrderChangeHelper.cancelOrder(dispatcher, userLogin, orderId); if (!ok) { throw new GeneralException("Problem with order change; see above error"); } - return ServiceUtil.returnError(ERROR_MESSAGE); + return ServiceUtil.returnError(errMessage); } } else { // Get the paymentMethodTypeIds - this will need to change when ecom supports multiple payments @@ -1158,6 +1160,7 @@ public class CheckOutHelper { EntityCondition.makeCondition("paymentMethodTypeId", EntityOperator.EQUALS, "EXT_BILLACT")); List cashCodPcBaPaymentPreferences = EntityUtil.filterByOr(allPaymentPreferences, cashCodPcBaExpr); + Debug.log("==========cashCodPcBaPaymentPreferences=======" + cashCodPcBaPaymentPreferences); if (UtilValidate.isNotEmpty(cashCodPcBaPaymentPreferences) && UtilValidate.isNotEmpty(allPaymentPreferences) && cashCodPcBaPaymentPreferences.size() == allPaymentPreferences.size()) { @@ -1472,31 +1475,32 @@ public class CheckOutHelper { // set ship before date if ((shipBeforeDate != null) && (shipBeforeDate.length() > 8)) { - shipBeforeDate = shipBeforeDate.trim(); - if (shipBeforeDate.length() < 14) { - shipBeforeDate = shipBeforeDate + " " + "00:00:00.000"; - } + shipBeforeDate = shipBeforeDate.trim(); + if (shipBeforeDate.length() < 14) { + shipBeforeDate = shipBeforeDate + " " + "00:00:00.000"; + } - try { - this.cart.setShipBeforeDate(shipGroupIndex, (Timestamp) ObjectType.simpleTypeOrObjectConvert(shipBeforeDate, "Timestamp", null, null)); - } catch (Exception e) { - errMsg = "Ship Before Date must be a valid date formed "; - result = ServiceUtil.returnError(errMsg); - } + try { + this.cart.setShipBeforeDate(shipGroupIndex, (Timestamp) ObjectType.simpleTypeOrObjectConvert(shipBeforeDate, "Timestamp", null, + null)); + } catch (Exception e) { + errMsg = "Ship Before Date must be a valid date formed "; + result = ServiceUtil.returnError(errMsg); + } } // set ship after date if ((shipAfterDate != null) && (shipAfterDate.length() > 8)) { - shipAfterDate = shipAfterDate.trim(); - if (shipAfterDate.length() < 14) { - shipAfterDate = shipAfterDate + " " + "00:00:00.000"; - } + shipAfterDate = shipAfterDate.trim(); + if (shipAfterDate.length() < 14) { + shipAfterDate = shipAfterDate + " " + "00:00:00.000"; + } - try { - this.cart.setShipAfterDate(shipGroupIndex, (Timestamp) ObjectType.simpleTypeOrObjectConvert(shipAfterDate, "Timestamp", null, null)); + try { + this.cart.setShipAfterDate(shipGroupIndex, (Timestamp) ObjectType.simpleTypeOrObjectConvert(shipAfterDate, "Timestamp", null, null)); } catch (Exception e) { - errMsg = "Ship After Date must be a valid date formed "; - result = ServiceUtil.returnError(errMsg); + errMsg = "Ship After Date must be a valid date formed "; + result = ServiceUtil.returnError(errMsg); } } diff --git a/applications/order/src/main/java/org/apache/ofbiz/order/shoppingcart/ShoppingCart.java b/applications/order/src/main/java/org/apache/ofbiz/order/shoppingcart/ShoppingCart.java index f03cdbaf5a..5ad2ca2ccb 100644 --- a/applications/order/src/main/java/org/apache/ofbiz/order/shoppingcart/ShoppingCart.java +++ b/applications/order/src/main/java/org/apache/ofbiz/order/shoppingcart/ShoppingCart.java @@ -587,11 +587,12 @@ public class ShoppingCart implements Iterable, Serializable { if (supplierProduct != null && supplierProduct.getBigDecimal("lastPrice") != null) { sci.setSupplierProductId(supplierProduct.getString("supplierProductId")); sci.setBasePrice(supplierProduct.getBigDecimal("lastPrice")); - sci.setName(ShoppingCartItem.getPurchaseOrderItemDescription(sci.getProduct(), supplierProduct, this.getLocale(), dispatcher)); + sci.setName(ShoppingCartItem.getPurchaseOrderItemDescription(sci.getProduct(), supplierProduct, this.getLocale(), + dispatcher)); } else { - throw new CartItemModifyException("SupplierProduct not found"); + throw new CartItemModifyException("SupplierProduct not found"); } - } + } return i; } } @@ -600,7 +601,8 @@ public class ShoppingCart implements Iterable, Serializable { if ("PURCHASE_ORDER".equals(getOrderType())) { supplierProduct = getSupplierProduct(productId, quantity, dispatcher); if (supplierProduct != null || "_NA_".equals(this.getPartyId())) { - item = ShoppingCartItem.makePurchaseOrderItem(0, productId, selectedAmount, quantity, features, attributes, prodCatalogId, configWrapper, itemType, itemGroup, dispatcher, this, supplierProduct, shipBeforeDate, shipAfterDate, cancelBackOrderDate); + item = ShoppingCartItem.makePurchaseOrderItem(0, productId, selectedAmount, quantity, features, attributes, prodCatalogId, + configWrapper, itemType, itemGroup, dispatcher, this, supplierProduct, shipBeforeDate, shipAfterDate, cancelBackOrderDate); } else { throw new CartItemModifyException("SupplierProduct not found"); } @@ -664,55 +666,105 @@ public class ShoppingCart implements Iterable, Serializable { /** Add an item to the shopping cart. */ public int addItemToEnd(String productId, BigDecimal amount, BigDecimal quantity, BigDecimal unitPrice, HashMap features, - HashMap attributes, String prodCatalogId, String itemType, ProductConfigWrapper configWrapper, LocalDispatcher dispatcher, - Boolean triggerExternalOps, Boolean triggerPriceRules) throws CartItemModifyException, ItemNotFoundException { + HashMap attributes, String prodCatalogId, String itemType, ProductConfigWrapper configWrapper, LocalDispatcher dispatcher, + Boolean triggerExternalOps, Boolean triggerPriceRules) throws CartItemModifyException, ItemNotFoundException { return addItemToEnd(ShoppingCartItem.makeItem(null, productId, amount, quantity, unitPrice, null, null, null, null, null, features, attributes, prodCatalogId, configWrapper, itemType, null, dispatcher, this, triggerExternalOps, triggerPriceRules, null, Boolean.FALSE, Boolean.FALSE)); } - /** Add an item to the shopping cart. */ + /** + * Add an item to the shopping cart. + */ public int addItemToEnd(String productId, BigDecimal amount, BigDecimal quantity, BigDecimal unitPrice, HashMap features, - HashMap attributes, String prodCatalogId, String itemType, LocalDispatcher dispatcher, Boolean triggerExternalOps, - Boolean triggerPriceRules) throws CartItemModifyException, ItemNotFoundException { - return addItemToEnd(productId, amount, quantity, unitPrice, features, attributes, prodCatalogId, itemType, dispatcher, triggerExternalOps, triggerPriceRules, Boolean.FALSE, Boolean.FALSE); + HashMap attributes, String prodCatalogId, String itemType, LocalDispatcher dispatcher, + Boolean triggerExternalOps, + Boolean triggerPriceRules) throws CartItemModifyException, ItemNotFoundException { + return addItemToEnd(productId, amount, quantity, unitPrice, features, attributes, prodCatalogId, itemType, dispatcher, triggerExternalOps, + triggerPriceRules, Boolean.FALSE, Boolean.FALSE); } - /** Add an (rental)item to the shopping cart. */ - public int addItemToEnd(String productId, BigDecimal amount, BigDecimal quantity, BigDecimal unitPrice, Timestamp reservStart, BigDecimal reservLength, BigDecimal reservPersons, HashMap features, HashMap attributes, String prodCatalogId, String itemType, LocalDispatcher dispatcher, Boolean triggerExternalOps, Boolean triggerPriceRules) throws CartItemModifyException, ItemNotFoundException { - return addItemToEnd(ShoppingCartItem.makeItem(null, productId, amount, quantity, unitPrice, reservStart, reservLength, reservPersons, null, null, features, attributes, prodCatalogId, null, itemType, null, dispatcher, this, triggerExternalOps, triggerPriceRules, null, Boolean.FALSE, Boolean.FALSE)); - } - - /** Add an (rental)item to the shopping cart. */ - public int addItemToEnd(String productId, BigDecimal amount, BigDecimal quantity, BigDecimal unitPrice, Timestamp reservStart, BigDecimal reservLength, BigDecimal reservPersons, HashMap features, HashMap attributes, String prodCatalogId, String itemType, LocalDispatcher dispatcher, Boolean triggerExternalOps, Boolean triggerPriceRules, Boolean skipInventoryChecks, Boolean skipProductChecks) throws CartItemModifyException, ItemNotFoundException { - return addItemToEnd(ShoppingCartItem.makeItem(null, productId, amount, quantity, unitPrice, reservStart, reservLength, reservPersons, null, null, features, attributes, prodCatalogId, null, itemType, null, dispatcher, this, triggerExternalOps, triggerPriceRules, null, skipInventoryChecks, skipProductChecks)); - } - - /** Add an (rental/aggregated)item to the shopping cart. */ - public int addItemToEnd(String productId, BigDecimal amount, BigDecimal quantity, BigDecimal unitPrice, Timestamp reservStart, BigDecimal reservLength, BigDecimal reservPersons, HashMap features, HashMap attributes, String prodCatalogId, ProductConfigWrapper configWrapper, String itemType, LocalDispatcher dispatcher, Boolean triggerExternalOps, Boolean triggerPriceRules, Boolean skipInventoryChecks, Boolean skipProductChecks) throws CartItemModifyException, ItemNotFoundException { - return addItemToEnd(ShoppingCartItem.makeItem(null, productId, amount, quantity, unitPrice, reservStart, reservLength, reservPersons, null, null, features, attributes, prodCatalogId, configWrapper, itemType, null, dispatcher, this, triggerExternalOps, triggerPriceRules, null, skipInventoryChecks, skipProductChecks)); - } - - /** Add an accommodation(rental)item to the shopping cart. */ - public int addItemToEnd(String productId, BigDecimal amount, BigDecimal quantity, BigDecimal unitPrice, Timestamp reservStart, BigDecimal reservLength, BigDecimal reservPersons, String accommodationMapId, String accommodationSpotId, HashMap features, HashMap attributes, String prodCatalogId, String itemType, LocalDispatcher dispatcher, Boolean triggerExternalOps, Boolean triggerPriceRules) throws CartItemModifyException, ItemNotFoundException { - return addItemToEnd(ShoppingCartItem.makeItem(null, productId, amount, quantity, unitPrice, reservStart, reservLength, reservPersons, accommodationMapId, accommodationSpotId, null, null, features, attributes, prodCatalogId, null, itemType, null, dispatcher, this, triggerExternalOps, triggerPriceRules, null, Boolean.FALSE, Boolean.FALSE)); - } - - /** Add an accommodation(rental)item to the shopping cart. */ - public int addItemToEnd(String productId, BigDecimal amount, BigDecimal quantity, BigDecimal unitPrice, Timestamp reservStart, BigDecimal reservLength, BigDecimal reservPersons, String accommodationMapId, String accommodationSpotId, HashMap features, HashMap attributes, String prodCatalogId, String itemType, LocalDispatcher dispatcher, Boolean triggerExternalOps, Boolean triggerPriceRules, Boolean skipInventoryChecks, Boolean skipProductChecks) throws CartItemModifyException, ItemNotFoundException { - return addItemToEnd(ShoppingCartItem.makeItem(null, productId, amount, quantity, unitPrice, reservStart, reservLength, reservPersons, accommodationMapId, accommodationSpotId, null, null, features, attributes, prodCatalogId, null, itemType, null, dispatcher, this, triggerExternalOps, triggerPriceRules, null, skipInventoryChecks, skipProductChecks)); - } - - /** Add an accommodation(rental/aggregated)item to the shopping cart. */ + /** + * Add an (rental)item to the shopping cart. + */ public int addItemToEnd(String productId, BigDecimal amount, BigDecimal quantity, BigDecimal unitPrice, Timestamp reservStart, - BigDecimal reservLength, BigDecimal reservPersonsDbl, String accommodationMapId, String accommodationSpotId, HashMap features, HashMap attributes, String prodCatalogId, ProductConfigWrapper configWrapper, String itemType, LocalDispatcher dispatcher, Boolean triggerExternalOps, - Boolean triggerPriceRules, Boolean skipInventoryChecks, Boolean skipProductChecks) throws CartItemModifyException, ItemNotFoundException { - return addItemToEnd(ShoppingCartItem.makeItem(null, productId, amount, quantity, unitPrice, reservStart, reservLength, reservPersonsDbl, accommodationMapId, accommodationSpotId, null, null, features, attributes, prodCatalogId, configWrapper, itemType, null, dispatcher, this, triggerExternalOps, triggerPriceRules, null, skipInventoryChecks, skipProductChecks)); + BigDecimal reservLength, BigDecimal reservPersons, HashMap features, HashMap attributes, + String prodCatalogId, String itemType, LocalDispatcher dispatcher, Boolean triggerExternalOps, Boolean triggerPriceRules) throws CartItemModifyException, ItemNotFoundException { + return addItemToEnd(ShoppingCartItem.makeItem(null, productId, amount, quantity, unitPrice, reservStart, reservLength, reservPersons, null, + null, features, attributes, prodCatalogId, null, itemType, null, dispatcher, this, triggerExternalOps, triggerPriceRules, null, + Boolean.FALSE, Boolean.FALSE)); } - /** Add an item to the shopping cart. */ - public int addItemToEnd(String productId, BigDecimal amount, BigDecimal quantity, BigDecimal unitPrice, HashMap features, HashMap attributes, String prodCatalogId, String itemType, LocalDispatcher dispatcher, Boolean triggerExternalOps, Boolean triggerPriceRules, Boolean skipInventoryChecks, Boolean skipProductChecks) throws CartItemModifyException, ItemNotFoundException { - return addItemToEnd(ShoppingCartItem.makeItem(null, productId, amount, quantity, unitPrice, null, null, null, null, null, features, attributes, prodCatalogId, null, itemType, null, dispatcher, this, triggerExternalOps, triggerPriceRules, null, skipInventoryChecks, skipProductChecks)); + /** + * Add an (rental)item to the shopping cart. + */ + public int addItemToEnd(String productId, BigDecimal amount, BigDecimal quantity, BigDecimal unitPrice, Timestamp reservStart, + BigDecimal reservLength, BigDecimal reservPersons, HashMap features, HashMap attributes, + String prodCatalogId, String itemType, LocalDispatcher dispatcher, Boolean triggerExternalOps, Boolean triggerPriceRules, + Boolean skipInventoryChecks, Boolean skipProductChecks) throws CartItemModifyException, ItemNotFoundException { + return addItemToEnd(ShoppingCartItem.makeItem(null, productId, amount, quantity, unitPrice, reservStart, reservLength, reservPersons, null, + null, features, attributes, prodCatalogId, null, itemType, null, dispatcher, this, triggerExternalOps, triggerPriceRules, null, + skipInventoryChecks, skipProductChecks)); + } + + /** + * Add an (rental/aggregated)item to the shopping cart. + */ + public int addItemToEnd(String productId, BigDecimal amount, BigDecimal quantity, BigDecimal unitPrice, Timestamp reservStart, + BigDecimal reservLength, BigDecimal reservPersons, HashMap features, HashMap attributes, + String prodCatalogId, ProductConfigWrapper configWrapper, String itemType, LocalDispatcher dispatcher, Boolean triggerExternalOps, + Boolean triggerPriceRules, Boolean skipInventoryChecks, Boolean skipProductChecks) throws CartItemModifyException, ItemNotFoundException { + return addItemToEnd(ShoppingCartItem.makeItem(null, productId, amount, quantity, unitPrice, reservStart, reservLength, reservPersons, null, + null, features, attributes, prodCatalogId, configWrapper, itemType, null, dispatcher, this, triggerExternalOps, triggerPriceRules, null, + skipInventoryChecks, skipProductChecks)); + } + + /** + * Add an accommodation(rental)item to the shopping cart. + */ + public int addItemToEnd(String productId, BigDecimal amount, BigDecimal quantity, BigDecimal unitPrice, Timestamp reservStart, + BigDecimal reservLength, BigDecimal reservPersons, String accommodationMapId, String accommodationSpotId, + HashMap features, HashMap attributes, String prodCatalogId, String itemType, LocalDispatcher dispatcher + , Boolean triggerExternalOps, Boolean triggerPriceRules) throws CartItemModifyException, ItemNotFoundException { + return addItemToEnd(ShoppingCartItem.makeItem(null, productId, amount, quantity, unitPrice, reservStart, reservLength, reservPersons, + accommodationMapId, accommodationSpotId, null, null, features, attributes, prodCatalogId, null, itemType, null, dispatcher, this, + triggerExternalOps, triggerPriceRules, null, Boolean.FALSE, Boolean.FALSE)); + } + + /** + * Add an accommodation(rental)item to the shopping cart. + */ + public int addItemToEnd(String productId, BigDecimal amount, BigDecimal quantity, BigDecimal unitPrice, Timestamp reservStart, + BigDecimal reservLength, BigDecimal reservPersons, String accommodationMapId, String accommodationSpotId, + HashMap features, HashMap attributes, String prodCatalogId, String itemType, LocalDispatcher dispatcher + , Boolean triggerExternalOps, Boolean triggerPriceRules, Boolean skipInventoryChecks, Boolean skipProductChecks) throws CartItemModifyException, ItemNotFoundException { + return addItemToEnd(ShoppingCartItem.makeItem(null, productId, amount, quantity, unitPrice, reservStart, reservLength, reservPersons, + accommodationMapId, accommodationSpotId, null, null, features, attributes, prodCatalogId, null, itemType, null, dispatcher, this, + triggerExternalOps, triggerPriceRules, null, skipInventoryChecks, skipProductChecks)); + } + + /** + * Add an accommodation(rental/aggregated)item to the shopping cart. + */ + public int addItemToEnd(String productId, BigDecimal amount, BigDecimal quantity, BigDecimal unitPrice, Timestamp reservStart, + BigDecimal reservLength, BigDecimal reservPersonsDbl, String accommodationMapId, String accommodationSpotId, + HashMap features, HashMap attributes, String prodCatalogId, + ProductConfigWrapper configWrapper, String itemType, LocalDispatcher dispatcher, Boolean triggerExternalOps, + Boolean triggerPriceRules, Boolean skipInventoryChecks, Boolean skipProductChecks) throws CartItemModifyException, + ItemNotFoundException { + return addItemToEnd(ShoppingCartItem.makeItem(null, productId, amount, quantity, unitPrice, reservStart, reservLength, reservPersonsDbl, + accommodationMapId, accommodationSpotId, null, null, features, attributes, prodCatalogId, configWrapper, itemType, null, dispatcher, this, + triggerExternalOps, triggerPriceRules, null, skipInventoryChecks, skipProductChecks)); + } + + /** + * Add an item to the shopping cart. + */ + public int addItemToEnd(String productId, BigDecimal amount, BigDecimal quantity, BigDecimal unitPrice, HashMap features, + HashMap attributes, String prodCatalogId, String itemType, LocalDispatcher dispatcher, Boolean triggerExternalOps, + Boolean triggerPriceRules, Boolean skipInventoryChecks, Boolean skipProductChecks) throws CartItemModifyException, ItemNotFoundException { + return addItemToEnd(ShoppingCartItem.makeItem(null, productId, amount, quantity, unitPrice, null, null, null, null, null, features, + attributes, prodCatalogId, null, itemType, null, dispatcher, this, triggerExternalOps, triggerPriceRules, null, skipInventoryChecks, skipProductChecks)); } /** Add an item to the shopping cart. */ @@ -1183,69 +1235,74 @@ public class ShoppingCart implements Iterable, Serializable { */ public void setShipBeforeDate(int idx, Timestamp shipBeforeDate) { CartShipInfo csi = this.getShipInfo(idx); - csi.shipBeforeDate = shipBeforeDate; + csi.shipBeforeDate = shipBeforeDate; } /** * Set ship before date for ship group 0 * @param shipBeforeDate - */ + */ public void setShipBeforeDate(Timestamp shipBeforeDate) { - this.setShipBeforeDate(0, shipBeforeDate); + this.setShipBeforeDate(0, shipBeforeDate); } + /** * Get ship before date for a particular ship group * @param idx the ship group number * @return ship before date for a given ship group */ public Timestamp getShipBeforeDate(int idx) { - CartShipInfo csi = this.getShipInfo(idx); - return csi.shipBeforeDate; + CartShipInfo csi = this.getShipInfo(idx); + return csi.shipBeforeDate; } /** - * Get ship before date for ship group 0 - * @return ship before date for the first ship group - */ + * Get ship before date for ship group 0 + * + * @return ship before date for the first ship group + */ public Timestamp getShipBeforeDate() { - return this.getShipBeforeDate(0); - } + return this.getShipBeforeDate(0); + } - /** - * Set ship after date for a particular ship group - * @param idx the ship group number - * @param shipAfterDate the ship after date to be set for the given ship group - */ + /** + * Set ship after date for a particular ship group + * + * @param idx the ship group number + * @param shipAfterDate the ship after date to be set for the given ship group + */ public void setShipAfterDate(int idx, Timestamp shipAfterDate) { CartShipInfo csi = this.getShipInfo(idx); csi.shipAfterDate = shipAfterDate; } - /** - * Set ship after date for a particular ship group - * @param shipAfterDate the ship after date to be set for the first ship group - */ - public void setShipAfterDate(Timestamp shipAfterDate) { - this.setShipAfterDate(0, shipAfterDate); - } - - /** - * Get ship after date for a particular ship group - * @param idx the ship group number - * @return return the ship after date for the given ship group - */ + /** + * Get ship after date for a particular ship group + * + * @param idx the ship group number + * @return return the ship after date for the given ship group + */ public Timestamp getShipAfterDate(int idx) { CartShipInfo csi = this.getShipInfo(idx); return csi.shipAfterDate; } - /** + /** * Get ship after date for ship group 0 * @return return the ship after date for the first ship group */ public Timestamp getShipAfterDate() { - return this.getShipAfterDate(0); - } + return this.getShipAfterDate(0); + } + + /** + * Set ship after date for a particular ship group + * + * @param shipAfterDate the ship after date to be set for the first ship group + */ + public void setShipAfterDate(Timestamp shipAfterDate) { + this.setShipAfterDate(0, shipAfterDate); + } public void setDefaultShipBeforeDate(Timestamp defaultShipBeforeDate) { this.defaultShipBeforeDate = defaultShipBeforeDate != null ? (Timestamp) defaultShipBeforeDate.clone() : null; @@ -2264,20 +2321,20 @@ public class ShoppingCart implements Iterable, Serializable { * @return */ public int getItemShipGroupIndex(int itemId) { - int shipGroupIndex = this.getShipGroupSize() - 1; - ShoppingCartItem item = this.findCartItem(itemId); - int result = 0; - for (int i = 0; i < (shipGroupIndex + 1); i++) { - CartShipInfo csi = this.getShipInfo(i); - Iterator it = csi.shipItemInfo.keySet().iterator(); - while (it.hasNext()) { - ShoppingCartItem item2 = it.next(); - if (item.equals(item2)) { - result = i; + int shipGroupIndex = this.getShipGroupSize() - 1; + ShoppingCartItem item = this.findCartItem(itemId); + int result = 0; + for (int i = 0; i < (shipGroupIndex + 1); i++) { + CartShipInfo csi = this.getShipInfo(i); + Iterator it = csi.shipItemInfo.keySet().iterator(); + while (it.hasNext()) { + ShoppingCartItem item2 = it.next(); + if (item.equals(item2)) { + result = i; + } } } - } - return result; + return result; } /** Sets the shipping contact mech id. */ @@ -2776,7 +2833,7 @@ public class ShoppingCart implements Iterable, Serializable { return OrderReadHelper.calcOrderAdjustments(tempAdjustmentsList, this.getSubTotal(), false, true, true); } public BigDecimal getDisplayTaxIncluded() { - BigDecimal taxIncluded = getDisplaySubTotal().subtract(getSubTotal()); + BigDecimal taxIncluded = getDisplaySubTotal().subtract(getSubTotal()); return taxIncluded.setScale(TAX_FINAL_SCALE, TAX_ROUNDING); } @@ -4203,8 +4260,8 @@ public class ShoppingCart implements Iterable, Serializable { for (int i = 0; i < this.shipInfo.size(); i++) { CartShipInfo csi = shipInfo.get(i); if ((csi.supplierPartyId == null && supplierPartyId == null) - || (UtilValidate.isNotEmpty(csi.supplierPartyId) && csi.supplierPartyId.equals(supplierPartyId))) { - shipGroups.put(i, csi); + || (UtilValidate.isNotEmpty(csi.supplierPartyId) && csi.supplierPartyId.equals(supplierPartyId))) { + shipGroups.put(i, csi); } } return shipGroups; @@ -4786,7 +4843,7 @@ public class ShoppingCart implements Iterable, Serializable { Timestamp estimatedShipDate = null; if (estimatedShipDates.size() > 0) { estimatedShipDates.sort(null); - estimatedShipDate = estimatedShipDates.getLast(); + estimatedShipDate = estimatedShipDates.getLast(); shipGroup.set("estimatedShipDate", estimatedShipDate); } diff --git a/applications/order/src/main/java/org/apache/ofbiz/order/shoppingcart/ShoppingCartHelper.java b/applications/order/src/main/java/org/apache/ofbiz/order/shoppingcart/ShoppingCartHelper.java index 0ce20854cf..634870ffe9 100644 --- a/applications/order/src/main/java/org/apache/ofbiz/order/shoppingcart/ShoppingCartHelper.java +++ b/applications/order/src/main/java/org/apache/ofbiz/order/shoppingcart/ShoppingCartHelper.java @@ -890,13 +890,13 @@ public class ShoppingCartHelper { } if (parameterName.toUpperCase(Locale.getDefault()).startsWith("COMMENT")) { - if (!oldItemComment.equals(itemComment)) { - if (security.hasEntityPermission("ORDERMGR", "_CREATE", userLogin)) { - if (item != null) { - item.setItemComment(itemComment); - } - } - } + if (!oldItemComment.equals(itemComment)) { + if (security.hasEntityPermission("ORDERMGR", "_CREATE", userLogin)) { + if (item != null) { + item.setItemComment(itemComment); + } + } + } } if (parameterName.toUpperCase(Locale.getDefault()).startsWith("PRICE")) { @@ -1091,24 +1091,26 @@ public class ShoppingCartHelper { } try { - // clear the existing order terms - cart.removeOrderTerms(); - // set order terms based on agreement terms - List agreementTerms = EntityUtil.filterByDate(agreement.getRelated("AgreementTerm", null, null, false)); - if (agreementTerms.size() > 0) { - for (int i = 0; agreementTerms.size() > i;i++) { - GenericValue agreementTerm = agreementTerms.get(i); - String termTypeId = (String) agreementTerm.get("termTypeId"); - BigDecimal termValue = agreementTerm.getBigDecimal("termValue"); - Long termDays = (Long) agreementTerm.get("termDays"); - String textValue = agreementTerm.getString("textValue"); - cart.addOrderTerm(termTypeId, termValue, termDays, textValue); - } - } + // clear the existing order terms + cart.removeOrderTerms(); + // set order terms based on agreement terms + List agreementTerms = EntityUtil.filterByDate(agreement.getRelated("AgreementTerm", null, null, false)); + if (agreementTerms.size() > 0) { + for (int i = 0; agreementTerms.size() > i; i++) { + GenericValue agreementTerm = agreementTerms.get(i); + String termTypeId = (String) agreementTerm.get("termTypeId"); + BigDecimal termValue = agreementTerm.getBigDecimal("termValue"); + Long termDays = (Long) agreementTerm.get("termDays"); + String textValue = agreementTerm.getString("textValue"); + cart.addOrderTerm(termTypeId, termValue, termDays, textValue); + } + } } catch (GenericEntityException e) { - Debug.logWarning(e.toString(), MODULE); - result = ServiceUtil.returnError(UtilProperties.getMessage(RES_ERROR, "OrderCouldNotGetAgreementTermsThrough", UtilMisc.toMap("agreementId", agreementId), this.cart.getLocale()) + UtilProperties.getMessage(RES_ERROR, "OrderError", this.cart.getLocale()) + e.getMessage()); - return result; + Debug.logWarning(e.toString(), MODULE); + result = ServiceUtil.returnError(UtilProperties.getMessage(RES_ERROR, "OrderCouldNotGetAgreementTermsThrough", UtilMisc.toMap( + "agreementId", agreementId), this.cart.getLocale()) + UtilProperties.getMessage(RES_ERROR, "OrderError", + this.cart.getLocale()) + e.getMessage()); + return result; } } return result; @@ -1120,10 +1122,10 @@ public class ShoppingCartHelper { try { this.cart.setCurrency(this.dispatcher, currencyUomId); result = ServiceUtil.returnSuccess(); - } catch (CartItemModifyException ex) { - result = ServiceUtil.returnError(UtilProperties.getMessage(RES_ERROR, "OrderSetCurrencyError", this.cart.getLocale()) + ex.getMessage()); - return result; - } + } catch (CartItemModifyException ex) { + result = ServiceUtil.returnError(UtilProperties.getMessage(RES_ERROR, "OrderSetCurrencyError", this.cart.getLocale()) + ex.getMessage()); + return result; + } return result; } @@ -1144,5 +1146,4 @@ public class ShoppingCartHelper { result = ServiceUtil.returnSuccess(); return result; } - } diff --git a/applications/order/src/main/java/org/apache/ofbiz/order/shoppingcart/ShoppingCartItem.java b/applications/order/src/main/java/org/apache/ofbiz/order/shoppingcart/ShoppingCartItem.java index 26c16ade42..dc63e7d87a 100644 --- a/applications/order/src/main/java/org/apache/ofbiz/order/shoppingcart/ShoppingCartItem.java +++ b/applications/order/src/main/java/org/apache/ofbiz/order/shoppingcart/ShoppingCartItem.java @@ -429,18 +429,18 @@ public class ShoppingCartItem implements java.io.Serializable { // check to see if the product is a rental item if ("ASSET_USAGE".equals(product.getString("productTypeId")) || "ASSET_USAGE_OUT_IN".equals(product.getString("productTypeId"))) { - if (reservStart == null) { + if (reservStart == null) { String excMsg = UtilProperties.getMessage(RES_ERROR, "item.missing_reservation_starting_date", cart.getLocale()); throw new CartItemModifyException(excMsg); } - if (reservStart.before(UtilDateTime.nowTimestamp())) { + if (reservStart.before(UtilDateTime.nowTimestamp())) { String excMsg = UtilProperties.getMessage(RES_ERROR, "item.reservation_from_tomorrow", cart.getLocale()); throw new CartItemModifyException(excMsg); } newItem.setReservStart(reservStart); - if (reservLength.compareTo(BigDecimal.ONE) < 0) { + if (reservLength.compareTo(BigDecimal.ONE) < 0) { String excMsg = UtilProperties.getMessage(RES_ERROR, "item.number_of_days", cart.getLocale()); throw new CartItemModifyException(excMsg); } @@ -448,32 +448,34 @@ public class ShoppingCartItem implements java.io.Serializable { if (product.get("reservMaxPersons") != null) { BigDecimal reservMaxPersons = product.getBigDecimal("reservMaxPersons"); - if (reservMaxPersons.compareTo(reservPersons) < 0) { - Map messageMap = UtilMisc.toMap("reservMaxPersons", product.getString("reservMaxPersons"), "reservPersons", reservPersons); - String excMsg = UtilProperties.getMessage(RES_ERROR, "item.maximum_number_of_person_renting", messageMap, cart.getLocale()); + if (reservMaxPersons.compareTo(reservPersons) < 0) { + Map messageMap = UtilMisc.toMap("reservMaxPersons", product.getString("reservMaxPersons"), + "reservPersons", reservPersons); + String excMsg = UtilProperties.getMessage(RES_ERROR, "item.maximum_number_of_person_renting", messageMap, cart.getLocale()); - Debug.logInfo(excMsg, MODULE); - throw new CartItemModifyException(excMsg); - } - } - newItem.setReservPersons(reservPersons); + Debug.logInfo(excMsg, MODULE); + throw new CartItemModifyException(excMsg); + } + } + newItem.setReservPersons(reservPersons); - if (product.get("reserv2ndPPPerc") != null) { + if (product.get("reserv2ndPPPerc") != null) { newItem.setReserv2ndPPPerc(product.getBigDecimal("reserv2ndPPPerc")); } - if (product.get("reservNthPPPerc") != null) { + if (product.get("reservNthPPPerc") != null) { newItem.setReservNthPPPerc(product.getBigDecimal("reservNthPPPerc")); } - if ((accommodationMapId != null) && (accommodationSpotId != null)) { + if ((accommodationMapId != null) && (accommodationSpotId != null)) { newItem.setAccommodationId(accommodationMapId, accommodationSpotId); - } + } // check to see if the related fixed asset is available for rent String isAvailable = checkAvailability(product.getString("productId"), quantity, reservStart, reservLength, cart); if (isAvailable.compareTo("OK") != 0) { - Map messageMap = UtilMisc.toMap("productId", product.getString("productId"), "availableMessage", isAvailable); + Map messageMap = UtilMisc.toMap("productId", product.getString("productId"), "availableMessage", + isAvailable); String excMsg = UtilProperties.getMessage(RES_ERROR, "item.product_not_available", messageMap, cart.getLocale()); Debug.logInfo(excMsg, MODULE); throw new CartItemModifyException(isAvailable); @@ -548,41 +550,41 @@ public class ShoppingCartItem implements java.io.Serializable { } public static void isValidCartProduct(ProductConfigWrapper configWrapper, GenericValue product, Timestamp nowTimestamp, Locale locale) throws CartItemModifyException { - // check to see if introductionDate hasn't passed yet - if (product.get("introductionDate") != null && nowTimestamp.before(product.getTimestamp("introductionDate"))) { + // check to see if introductionDate hasn't passed yet + if (product.get("introductionDate") != null && nowTimestamp.before(product.getTimestamp("introductionDate"))) { + Map messageMap = UtilMisc.toMap("productName", product.getString("productName"), + "productId", product.getString("productId")); + + String excMsg = UtilProperties.getMessage(RES_ERROR, "item.cannot_add_product_not_yet_available", + messageMap, locale); + + Debug.logWarning(excMsg, MODULE); + throw new CartItemModifyException(excMsg); + } + + // check to see if salesDiscontinuationDate has passed + if (product.get("salesDiscontinuationDate") != null && nowTimestamp.after(product.getTimestamp("salesDiscontinuationDate"))) { + Map messageMap = UtilMisc.toMap("productName", product.getString("productName"), + "productId", product.getString("productId")); + + String excMsg = UtilProperties.getMessage(RES_ERROR, "item.cannot_add_product_no_longer_available", + messageMap, locale); + + Debug.logWarning(excMsg, MODULE); + throw new CartItemModifyException(excMsg); + } + + // check to see if the product is fully configured + if ("AGGREGATED".equals(product.getString("productTypeId")) || "AGGREGATED_SERVICE".equals(product.getString("productTypeId"))) { + if (configWrapper == null || !configWrapper.isCompleted()) { Map messageMap = UtilMisc.toMap("productName", product.getString("productName"), - "productId", product.getString("productId")); - - String excMsg = UtilProperties.getMessage(RES_ERROR, "item.cannot_add_product_not_yet_available", - messageMap, locale); - + "productId", product.getString("productId")); + String excMsg = UtilProperties.getMessage(RES_ERROR, "item.cannot_add_product_not_configured_correctly", + messageMap, locale); Debug.logWarning(excMsg, MODULE); throw new CartItemModifyException(excMsg); } - - // check to see if salesDiscontinuationDate has passed - if (product.get("salesDiscontinuationDate") != null && nowTimestamp.after(product.getTimestamp("salesDiscontinuationDate"))) { - Map messageMap = UtilMisc.toMap("productName", product.getString("productName"), - "productId", product.getString("productId")); - - String excMsg = UtilProperties.getMessage(RES_ERROR, "item.cannot_add_product_no_longer_available", - messageMap, locale); - - Debug.logWarning(excMsg, MODULE); - throw new CartItemModifyException(excMsg); - } - - // check to see if the product is fully configured - if ("AGGREGATED".equals(product.getString("productTypeId")) || "AGGREGATED_SERVICE".equals(product.getString("productTypeId"))) { - if (configWrapper == null || !configWrapper.isCompleted()) { - Map messageMap = UtilMisc.toMap("productName", product.getString("productName"), - "productId", product.getString("productId")); - String excMsg = UtilProperties.getMessage(RES_ERROR, "item.cannot_add_product_not_configured_correctly", - messageMap, locale); - Debug.logWarning(excMsg, MODULE); - throw new CartItemModifyException(excMsg); - } - } + } } /** @@ -850,19 +852,19 @@ public class ShoppingCartItem implements java.io.Serializable { this.reservNthPPPerc = reservNthPPPerc; } /** Sets the reservation start date */ - public void setReservStart(Timestamp reservStart) { + public void setReservStart(Timestamp reservStart) { this.reservStart = reservStart != null ? (Timestamp) reservStart.clone() : null; } /** Sets the reservation length */ - public void setReservLength(BigDecimal reservLength) { + public void setReservLength(BigDecimal reservLength) { this.reservLength = reservLength; } /** Sets number of persons using the reservation */ - public void setReservPersons(BigDecimal reservPersons) { + public void setReservPersons(BigDecimal reservPersons) { this.reservPersons = reservPersons; } /** Sets accommodationId using the reservation */ - public void setAccommodationId(String accommodationMapId, String accommodationSpotId) { + public void setAccommodationId(String accommodationMapId, String accommodationSpotId) { this.accommodationMapId = accommodationMapId; this.accommodationSpotId = accommodationSpotId; } @@ -1321,11 +1323,11 @@ public class ShoppingCartItem implements java.io.Serializable { } /** Returns accommodationMapId */ - public String getAccommodationMapId() { + public String getAccommodationMapId() { return this.accommodationMapId; } /** Returns accommodationSpotId */ - public String getAccommodationSpotId() { + public String getAccommodationSpotId() { return this.accommodationSpotId; } @@ -2070,7 +2072,7 @@ public class ShoppingCartItem implements java.io.Serializable { } BigDecimal persons = this.getReservPersons(); BigDecimal rentalValue = BigDecimal.ZERO; - if (persons.compareTo(BigDecimal.ONE) > 0) { + if (persons.compareTo(BigDecimal.ONE) > 0) { if (persons.compareTo(new BigDecimal("2")) > 0) { persons = persons.subtract(new BigDecimal("2")); if (getReservNthPPPerc().compareTo(BigDecimal.ZERO) > 0) { diff --git a/applications/order/src/main/java/org/apache/ofbiz/order/shoppingcart/product/ProductDisplayWorker.java b/applications/order/src/main/java/org/apache/ofbiz/order/shoppingcart/product/ProductDisplayWorker.java index d34f421dc5..e1c7a3d937 100644 --- a/applications/order/src/main/java/org/apache/ofbiz/order/shoppingcart/product/ProductDisplayWorker.java +++ b/applications/order/src/main/java/org/apache/ofbiz/order/shoppingcart/product/ProductDisplayWorker.java @@ -246,18 +246,18 @@ public final class ProductDisplayWorker { } // if desired check view allow category - String currentCatalogId = CatalogWorker.getCurrentCatalogId(request); - String viewProductCategoryId = CatalogWorker.getCatalogViewAllowCategoryId(delegator, currentCatalogId); - if (viewProductCategoryId != null) { - for (Map.Entry entry : products.entrySet()) { - String productId = entry.getKey(); - if (!CategoryWorker.isProductInCategory(delegator, productId, viewProductCategoryId)) { - products.remove(productId); - productQuantities.remove(productId); - productOccurances.remove(productId); - } + String currentCatalogId = CatalogWorker.getCurrentCatalogId(request); + String viewProductCategoryId = CatalogWorker.getCatalogViewAllowCategoryId(delegator, currentCatalogId); + if (viewProductCategoryId != null) { + for (Map.Entry entry : products.entrySet()) { + String productId = entry.getKey(); + if (!CategoryWorker.isProductInCategory(delegator, productId, viewProductCategoryId)) { + products.remove(productId); + productQuantities.remove(productId); + productOccurances.remove(productId); } } + } List reorderProds = new LinkedList<>(); reorderProds.addAll(products.values()); diff --git a/applications/party/src/main/java/org/apache/ofbiz/party/communication/CommunicationEventServices.java b/applications/party/src/main/java/org/apache/ofbiz/party/communication/CommunicationEventServices.java index 4ce9478b27..f43741ba43 100644 --- a/applications/party/src/main/java/org/apache/ofbiz/party/communication/CommunicationEventServices.java +++ b/applications/party/src/main/java/org/apache/ofbiz/party/communication/CommunicationEventServices.java @@ -1187,10 +1187,10 @@ public class CommunicationEventServices { private static List getCommEventAttachmentNames(final Delegator delegator, final String communicationEventId) throws GenericEntityException { List commEventContentAssocList = EntityQuery.use(delegator) - .from("CommEventContentDataResource") - .where(EntityCondition.makeCondition("communicationEventId", communicationEventId)) - .filterByDate() - .queryList(); + .from("CommEventContentDataResource") + .where(EntityCondition.makeCondition("communicationEventId", communicationEventId)) + .filterByDate() + .queryList(); List attachmentNames = new ArrayList<>(); for (GenericValue commEventContentAssoc : commEventContentAssocList) { @@ -1431,7 +1431,7 @@ public class CommunicationEventServices { part2Text = ""; } if (Debug.verboseOn()) { - Debug.logVerbose("Part 2 Text :\n\n" + part2Text, MODULE); + Debug.logVerbose("Part 2 Text :\n\n" + part2Text, MODULE); } // find the "Action" element and obtain its value (looking for "failed") @@ -1449,7 +1449,7 @@ public class CommunicationEventServices { part3Text = ""; } if (Debug.verboseOn()) { - Debug.logVerbose("Part 3 Text :\n\n" + part3Text, MODULE); + Debug.logVerbose("Part 3 Text :\n\n" + part3Text, MODULE); } // find the "Message-Id" element and obtain its value (looking for "failed") @@ -1609,7 +1609,7 @@ public class CommunicationEventServices { try { imageUrl = FlexibleLocation.resolveLocation("component://common-theme/webapp/images/spacer.gif"); try (InputStream imageStream = imageUrl.openStream()) { - UtilHttp.streamContentToBrowser(response, imageStream, 43, "image/gif", null); + UtilHttp.streamContentToBrowser(response, imageStream, 43, "image/gif", null); } } catch (IOException e) { Debug.logError(e, MODULE); diff --git a/applications/party/src/main/java/org/apache/ofbiz/party/content/PartyContentWrapper.java b/applications/party/src/main/java/org/apache/ofbiz/party/content/PartyContentWrapper.java index 58eb9a518d..04c4026f8f 100644 --- a/applications/party/src/main/java/org/apache/ofbiz/party/content/PartyContentWrapper.java +++ b/applications/party/src/main/java/org/apache/ofbiz/party/content/PartyContentWrapper.java @@ -161,7 +161,7 @@ public class PartyContentWrapper implements ContentWrapper { String outString = outWriter.toString(); if (UtilValidate.isEmpty(outString)) { outString = party.getModelEntity().isField(candidateFieldName) ? party.getString(candidateFieldName): ""; - outString = outString == null? "" : outString; + outString = outString == null ? "" : outString; } outString = encoder.sanitize(outString, null); if (partyContentCache != null) { @@ -171,7 +171,7 @@ public class PartyContentWrapper implements ContentWrapper { } catch (GeneralException | IOException e) { Debug.logError(e, "Error rendering PartyContent, inserting empty String", MODULE); String candidateOut = party.getModelEntity().isField(candidateFieldName) ? party.getString(candidateFieldName): ""; - return candidateOut == null? "" : encoder.sanitize(candidateOut, null); + return candidateOut == null ? "" : encoder.sanitize(candidateOut, null); } } diff --git a/applications/party/src/main/java/org/apache/ofbiz/party/party/PartyServices.java b/applications/party/src/main/java/org/apache/ofbiz/party/party/PartyServices.java index 2ce8d70801..a1ffe1a3d4 100644 --- a/applications/party/src/main/java/org/apache/ofbiz/party/party/PartyServices.java +++ b/applications/party/src/main/java/org/apache/ofbiz/party/party/PartyServices.java @@ -1810,7 +1810,7 @@ public class PartyServices { // filter on infoString String infoString = (String) context.get("infoString"); if (UtilValidate.isNotEmpty(infoString)) { - andExprs.add(EntityCondition.makeCondition(EntityFunction.UPPER_FIELD("infoString"), EntityOperator.LIKE, EntityFunction.UPPER("%"+infoString+"%"))); + andExprs.add(EntityCondition.makeCondition(EntityFunction.UPPER_FIELD("infoString"), EntityOperator.LIKE, EntityFunction.UPPER("%"+ infoString +"%"))); fieldsToSelect.add("infoString"); } } diff --git a/applications/party/src/main/java/org/apache/ofbiz/party/party/PartyWorker.java b/applications/party/src/main/java/org/apache/ofbiz/party/party/PartyWorker.java index 13c86e6018..cbaab5a622 100644 --- a/applications/party/src/main/java/org/apache/ofbiz/party/party/PartyWorker.java +++ b/applications/party/src/main/java/org/apache/ofbiz/party/party/PartyWorker.java @@ -219,7 +219,7 @@ public class PartyWorker { String firstName, String middleName, String lastName) throws GeneralException { List matching = findMatchingPersonPostalAddresses(delegator, address1, address2, city, stateProvinceGeoId, postalCode, - postalCodeExt, countryGeoId, firstName, middleName, lastName); + postalCodeExt, countryGeoId, firstName, middleName, lastName); GenericValue v = EntityUtil.getFirst(matching); if (v != null) { return new String[] {v.getString("partyId"), v.getString("contactMechId") }; @@ -462,7 +462,7 @@ public class PartyWorker { } partyList.add(associatedParty); } - associatedParties = currentAssociatedParties; + associatedParties = currentAssociatedParties; } partyIds = EntityUtil.getFieldListFromEntityList(partyList, "partyIdTo", true); } catch (GenericEntityException e) { diff --git a/applications/product/src/main/java/org/apache/ofbiz/product/category/CatalogUrlServlet.java b/applications/product/src/main/java/org/apache/ofbiz/product/category/CatalogUrlServlet.java index 865728927f..2ac3b82cd4 100644 --- a/applications/product/src/main/java/org/apache/ofbiz/product/category/CatalogUrlServlet.java +++ b/applications/product/src/main/java/org/apache/ofbiz/product/category/CatalogUrlServlet.java @@ -79,70 +79,72 @@ public class CatalogUrlServlet extends HttpServlet { RequestDispatcher rd = request.getRequestDispatcher("/" + WebAppUtil.CONTROL_MOUNT_POINT + "/main"); rd.forward(request, response); } else { - try { - String lastPathElement = pathElements.get(pathElements.size() - 1); - if (lastPathElement.startsWith("p_")) { - productId = lastPathElement.substring(2); - } else { - GenericValue productCategory = EntityQuery.use(delegator).from("ProductCategory").where("productCategoryId", lastPathElement).cache(true).queryOne(); - if (productCategory != null) { - categoryId = lastPathElement; + try { + String lastPathElement = pathElements.get(pathElements.size() - 1); + if (lastPathElement.startsWith("p_")) { + productId = lastPathElement.substring(2); } else { - productId = lastPathElement; + GenericValue productCategory = + EntityQuery.use(delegator).from("ProductCategory").where("productCategoryId", lastPathElement).cache(true).queryOne(); + if (productCategory != null) { + categoryId = lastPathElement; + } else { + productId = lastPathElement; + } } - } - pathElements.remove(pathElements.size() - 1); - } catch (GenericEntityException e) { - Debug.logError(e, "Error in looking up ProductUrl or CategoryUrl with path info [" + pathInfo + "]: " + e.toString(), MODULE); - } - - // get category info going with the IDs that remain - if (pathElements.size() == 1) { - CategoryWorker.setTrail(request, pathElements.get(0), null); - categoryId = pathElements.get(0); - } else if (pathElements.size() == 2) { - CategoryWorker.setTrail(request, pathElements.get(1), pathElements.get(0)); - categoryId = pathElements.get(1); - } else if (pathElements.size() > 2) { - List trail = CategoryWorker.getTrail(request); - if (trail == null) { - trail = new LinkedList<>(); + pathElements.remove(pathElements.size() - 1); + } catch (GenericEntityException e) { + Debug.logError(e, "Error in looking up ProductUrl or CategoryUrl with path info [" + pathInfo + "]: " + e.toString(), MODULE); } - if (trail.contains(pathElements.get(0))) { - // first category is in the trail, so remove it everything after that and fill it in with the list from the pathInfo - int firstElementIndex = trail.indexOf(pathElements.get(0)); - while (trail.size() > firstElementIndex) { - trail.remove(firstElementIndex); + // get category info going with the IDs that remain + if (pathElements.size() == 1) { + CategoryWorker.setTrail(request, pathElements.get(0), null); + categoryId = pathElements.get(0); + } else if (pathElements.size() == 2) { + CategoryWorker.setTrail(request, pathElements.get(1), pathElements.get(0)); + categoryId = pathElements.get(1); + } else if (pathElements.size() > 2) { + List trail = CategoryWorker.getTrail(request); + if (trail == null) { + trail = new LinkedList<>(); } - trail.addAll(pathElements); - } else { - // first category is NOT in the trail, so clear out the trail and use the pathElements list - trail.clear(); - trail.addAll(pathElements); + + if (trail.contains(pathElements.get(0))) { + // first category is in the trail, so remove it everything after that and fill it in with the list from the pathInfo + int firstElementIndex = trail.indexOf(pathElements.get(0)); + while (trail.size() > firstElementIndex) { + trail.remove(firstElementIndex); + } + trail.addAll(pathElements); + } else { + // first category is NOT in the trail, so clear out the trail and use the pathElements list + trail.clear(); + trail.addAll(pathElements); + } + CategoryWorker.setTrail(request, trail); + categoryId = pathElements.get(pathElements.size() - 1); + } + if (categoryId != null) { + request.setAttribute("productCategoryId", categoryId); } - CategoryWorker.setTrail(request, trail); - categoryId = pathElements.get(pathElements.size() - 1); - } - if (categoryId != null) { - request.setAttribute("productCategoryId", categoryId); - } - String rootCategoryId = null; - if (pathElements.size() >= 1) { - rootCategoryId = pathElements.get(0); - } - if (rootCategoryId != null) { - request.setAttribute("rootCategoryId", rootCategoryId); - } + String rootCategoryId = null; + if (pathElements.size() >= 1) { + rootCategoryId = pathElements.get(0); + } + if (rootCategoryId != null) { + request.setAttribute("rootCategoryId", rootCategoryId); + } - if (productId != null) { - request.setAttribute("product_id", productId); - request.setAttribute("productId", productId); - } + if (productId != null) { + request.setAttribute("product_id", productId); + request.setAttribute("productId", productId); + } - RequestDispatcher rd = request.getRequestDispatcher("/" + WebAppUtil.CONTROL_MOUNT_POINT + "/" + (productId != null ? PRODUCT_REQUEST : CATEGORY_REQUEST)); - rd.forward(request, response); + RequestDispatcher rd = request.getRequestDispatcher("/" + WebAppUtil.CONTROL_MOUNT_POINT + "/" + (productId != null ? PRODUCT_REQUEST + : CATEGORY_REQUEST)); + rd.forward(request, response); } } diff --git a/applications/product/src/main/java/org/apache/ofbiz/product/category/CategoryContentWrapper.java b/applications/product/src/main/java/org/apache/ofbiz/product/category/CategoryContentWrapper.java index 7b3dcb627a..5fd01af39d 100644 --- a/applications/product/src/main/java/org/apache/ofbiz/product/category/CategoryContentWrapper.java +++ b/applications/product/src/main/java/org/apache/ofbiz/product/category/CategoryContentWrapper.java @@ -108,7 +108,7 @@ public class CategoryContentWrapper implements ContentWrapper { String outString = outWriter.toString(); if (UtilValidate.isEmpty(outString)) { outString = productCategory.getModelEntity().isField(candidateFieldName) ? productCategory.getString(candidateFieldName): ""; - outString = outString == null? "" : outString; + outString = outString == null ? "" : outString; } outString = encoder.sanitize(outString, null); categoryContentCache.put(cacheKey, outString); diff --git a/applications/product/src/main/java/org/apache/ofbiz/product/category/CategoryWorker.java b/applications/product/src/main/java/org/apache/ofbiz/product/category/CategoryWorker.java index 984f35644e..c864e6668f 100644 --- a/applications/product/src/main/java/org/apache/ofbiz/product/category/CategoryWorker.java +++ b/applications/product/src/main/java/org/apache/ofbiz/product/category/CategoryWorker.java @@ -398,7 +398,7 @@ public final class CategoryWorker { } /** * Returns a complete category trail - can be used for exporting proper category trees. - * This is mostly useful when used in combination with bread-crumbs, for building a + * This is mostly useful when used in combination with bread-crumbs, for building a * faceted index tree, or to export a category tree for migration to another system. * Will create the tree from root point to categoryId. * This method is not meant to be run on every request. diff --git a/applications/product/src/main/java/org/apache/ofbiz/product/config/ProductConfigItemContentWrapper.java b/applications/product/src/main/java/org/apache/ofbiz/product/config/ProductConfigItemContentWrapper.java index 4c4067900d..de30f57116 100644 --- a/applications/product/src/main/java/org/apache/ofbiz/product/config/ProductConfigItemContentWrapper.java +++ b/applications/product/src/main/java/org/apache/ofbiz/product/config/ProductConfigItemContentWrapper.java @@ -132,7 +132,7 @@ public class ProductConfigItemContentWrapper implements ContentWrapper { String outString = outWriter.toString(); if (UtilValidate.isEmpty(outString)) { outString = productConfigItem.getModelEntity().isField(candidateFieldName) ? productConfigItem.getString(candidateFieldName): ""; - outString = outString == null? "" : outString; + outString = outString == null ? "" : outString; } outString = encoder.sanitize(outString, null); configItemContentCache.put(cacheKey, outString); @@ -140,7 +140,7 @@ public class ProductConfigItemContentWrapper implements ContentWrapper { } catch (GeneralException | IOException e) { Debug.logError(e, "Error rendering ProdConfItemContent, inserting empty String", MODULE); String candidateOut = productConfigItem.getModelEntity().isField(candidateFieldName) ? productConfigItem.getString(candidateFieldName): ""; - return candidateOut == null? "" : encoder.sanitize(candidateOut, null); + return candidateOut == null ? "" : encoder.sanitize(candidateOut, null); } } diff --git a/applications/product/src/main/java/org/apache/ofbiz/product/config/ProductConfigWorker.java b/applications/product/src/main/java/org/apache/ofbiz/product/config/ProductConfigWorker.java index cdce5d9194..2dba196a26 100644 --- a/applications/product/src/main/java/org/apache/ofbiz/product/config/ProductConfigWorker.java +++ b/applications/product/src/main/java/org/apache/ofbiz/product/config/ProductConfigWorker.java @@ -296,14 +296,14 @@ public final class ProductConfigWorker { if (match && (UtilValidate.isEmpty(configOptionProductOptions))) { configWrapper.configId = tempConfigId; - Debug.logInfo("Existing configuration found with configId:"+ tempConfigId, MODULE); + Debug.logInfo("Existing configuration found with configId:"+ tempConfigId, MODULE); return; } } } else { configWrapper.configId = tempConfigId; - Debug.logInfo("Existing configuration found with configId:"+ tempConfigId, MODULE); + Debug.logInfo("Existing configuration found with configId:"+ tempConfigId, MODULE); return; } } @@ -380,7 +380,7 @@ public final class ProductConfigWorker { //save configId to configWrapper, so we can use it in shopping cart operations configWrapper.configId = configId; - Debug.logInfo("New configId created:"+ configId, MODULE); + Debug.logInfo("New configId created:"+ configId, MODULE); return; } diff --git a/applications/product/src/main/java/org/apache/ofbiz/product/config/ProductConfigWrapper.java b/applications/product/src/main/java/org/apache/ofbiz/product/config/ProductConfigWrapper.java index 05fc4dc75e..8b3e353a1d 100644 --- a/applications/product/src/main/java/org/apache/ofbiz/product/config/ProductConfigWrapper.java +++ b/applications/product/src/main/java/org/apache/ofbiz/product/config/ProductConfigWrapper.java @@ -476,7 +476,7 @@ public class ProductConfigWrapper implements Serializable { if (content != null) { question = content.get("DESCRIPTION", "html").toString(); } else { - question = (configItem.getString("description") != null? configItem.getString("description"): ""); + question = (configItem.getString("description") != null ? configItem.getString("description") : ""); } } return question; @@ -490,7 +490,7 @@ public class ProductConfigWrapper implements Serializable { if (content != null) { description = content.get("LONG_DESCRIPTION", "html").toString(); } else { - description = (configItem.getString("longDescription") != null? configItem.getString("longDescription"): ""); + description = (configItem.getString("longDescription") != null ? configItem.getString("longDescription") : ""); } } return description; @@ -692,20 +692,20 @@ public class ProductConfigWrapper implements Serializable { } public String getOptionName() { - return (configOption.getString("configOptionName") != null? configOption.getString("configOptionName"): "no option name"); + return (configOption.getString("configOptionName") != null ? configOption.getString("configOptionName") : "no option name"); } public String getOptionName(Locale locale) { - return (configOption.getString("configOptionName") != null? (String) configOption.get("configOptionName", locale): "no option name"); + return (configOption.getString("configOptionName") != null ? (String) configOption.get("configOptionName", locale) : "no option name"); } public String getDescription() { - return (configOption.getString("description") != null? configOption.getString("description"): "no description"); + return (configOption.getString("description") != null ? configOption.getString("description") : "no description"); } public String getDescription(Locale locale) { - return (configOption.getString("description") != null? (String) configOption.get("description", locale): "no description"); + return (configOption.getString("description") != null ? (String) configOption.get("description", locale) : "no description"); } public String getId() { @@ -751,20 +751,20 @@ public class ProductConfigWrapper implements Serializable { return this.equals(defaultConfigOption); } - public boolean hasVirtualComponent () { - List components = getComponents(); - if (UtilValidate.isNotEmpty(components)) { - for (GenericValue component : components) { - if (isVirtualComponent(component)) { - return true; - } - } - } + public boolean hasVirtualComponent() { + List components = getComponents(); + if (UtilValidate.isNotEmpty(components)) { + for (GenericValue component : components) { + if (isVirtualComponent(component)) { + return true; + } + } + } - return false; - } + return false; + } - public boolean isVirtualComponent (GenericValue component) { + public boolean isVirtualComponent(GenericValue component) { int index = getComponents().indexOf(component); if (index != -1) { try { @@ -806,10 +806,10 @@ public class ProductConfigWrapper implements Serializable { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ConfigOption that = (ConfigOption) o; - return Objects.equals(availabilityDate, that.availabilityDate) && - Objects.equals(componentList, that.componentList) && - Objects.equals(getComponentOptions(), that.getComponentOptions()) && - Objects.equals(configOption, that.configOption); + return Objects.equals(availabilityDate, that.availabilityDate) + && Objects.equals(componentList, that.componentList) + && Objects.equals(getComponentOptions(), that.getComponentOptions()) + && Objects.equals(configOption, that.configOption); } @Override diff --git a/applications/product/src/main/java/org/apache/ofbiz/product/imagemanagement/FrameImage.java b/applications/product/src/main/java/org/apache/ofbiz/product/imagemanagement/FrameImage.java index 5d21ac3765..ecc47539d1 100644 --- a/applications/product/src/main/java/org/apache/ofbiz/product/imagemanagement/FrameImage.java +++ b/applications/product/src/main/java/org/apache/ofbiz/product/imagemanagement/FrameImage.java @@ -110,7 +110,7 @@ public class FrameImage { // Image Frame BufferedImage bufImg1 = ImageIO.read(new File(imageServerPath + "/" + productId + "/" + imageName)); - BufferedImage bufImg2 = ImageIO.read(new File(imageServerPath + "/frame/"+frameImageName)); + BufferedImage bufImg2 = ImageIO.read(new File(imageServerPath + "/frame/" + frameImageName)); int bufImgType; if (BufferedImage.TYPE_CUSTOM == bufImg1.getType()) { @@ -224,10 +224,10 @@ public class FrameImage { result.putAll(context); } } else { - String errMsg = UtilProperties.getMessage(RES_ERROR, "ProductPleaseSelectImage", locale); - Debug.logFatal(errMsg, MODULE); - result = ServiceUtil.returnError(errMsg); - result.putAll(context); + String errMsg = UtilProperties.getMessage(RES_ERROR, "ProductPleaseSelectImage", locale); + Debug.logFatal(errMsg, MODULE); + result = ServiceUtil.returnError(errMsg); + result.putAll(context); } String successMsg = UtilProperties.getMessage(RESOURCE, "ProductFrameImageSuccessfully", locale); result = ServiceUtil.returnSuccess(successMsg); @@ -409,7 +409,7 @@ public class FrameImage { } int width = Integer.parseInt(request.getParameter("imageWidth")); - int height= Integer.parseInt(request.getParameter("imageHeight")); + int height = Integer.parseInt(request.getParameter("imageHeight")); Image newImg1 = bufImg1.getScaledInstance(width, height, Image.SCALE_SMOOTH); Image newImg2 = bufImg2.getScaledInstance(width, height, Image.SCALE_SMOOTH); @@ -418,8 +418,8 @@ public class FrameImage { ImageIO.write(bufNewImg, mimeType, new File(imageServerPath + "/preview/" + "/previewImage.jpg")); } else { - String errMsg = "Please select Image."; - request.setAttribute("_EVENT_MESSAGE_", errMsg); + String errMsg = "Please select Image."; + request.setAttribute("_EVENT_MESSAGE_", errMsg); return "error"; } return "success"; diff --git a/applications/product/src/main/java/org/apache/ofbiz/product/imagemanagement/ImageManagementServices.java b/applications/product/src/main/java/org/apache/ofbiz/product/imagemanagement/ImageManagementServices.java index c1762ae86c..b8d4194b87 100644 --- a/applications/product/src/main/java/org/apache/ofbiz/product/imagemanagement/ImageManagementServices.java +++ b/applications/product/src/main/java/org/apache/ofbiz/product/imagemanagement/ImageManagementServices.java @@ -303,7 +303,7 @@ public class ImageManagementServices { Locale locale = (Locale) context.get("locale"); List sizeTypeList = null; if (UtilValidate.isNotEmpty(resizeType)) { - sizeTypeList = UtilMisc.toList(resizeType); + sizeTypeList = UtilMisc.toList(resizeType); } else { sizeTypeList = UtilMisc.toList("small","100x75", "150x112", "320x240", "640x480", "800x600", "1024x768", "1280x1024", "1600x1200"); } diff --git a/applications/product/src/main/java/org/apache/ofbiz/product/inventory/InventoryServices.java b/applications/product/src/main/java/org/apache/ofbiz/product/inventory/InventoryServices.java index eda645975e..45be1964bb 100644 --- a/applications/product/src/main/java/org/apache/ofbiz/product/inventory/InventoryServices.java +++ b/applications/product/src/main/java/org/apache/ofbiz/product/inventory/InventoryServices.java @@ -689,56 +689,56 @@ public class InventoryServices { BigDecimal minQuantityOnHandTotal = null; BigDecimal minAvailableToPromiseTotal = null; - // loop through each associated product. - for (GenericValue productAssoc: productAssocList) { - String productIdTo = productAssoc.getString("productIdTo"); - BigDecimal assocQuantity = productAssoc.getBigDecimal("quantity"); + // loop through each associated product. + for (GenericValue productAssoc : productAssocList) { + String productIdTo = productAssoc.getString("productIdTo"); + BigDecimal assocQuantity = productAssoc.getBigDecimal("quantity"); - // if there is no quantity for the associated product in ProductAssoc entity, default it to 1.0 - if (assocQuantity == null) { - Debug.logWarning("ProductAssoc from [" + productAssoc.getString("productId") + "] to [" + productAssoc.getString("productIdTo") - + "] has no quantity, assuming 1.0", MODULE); - assocQuantity = BigDecimal.ONE; - } + // if there is no quantity for the associated product in ProductAssoc entity, default it to 1.0 + if (assocQuantity == null) { + Debug.logWarning("ProductAssoc from [" + productAssoc.getString("productId") + "] to [" + productAssoc.getString("productIdTo") + + "] has no quantity, assuming 1.0", MODULE); + assocQuantity = BigDecimal.ONE; + } - // figure out the inventory available for this associated product - Map resultOutput = null; - try { - Map inputMap = UtilMisc.toMap("productId", productIdTo, "statusId", statusId); - if (facilityId != null) { - inputMap.put("facilityId", facilityId); - resultOutput = dispatcher.runSync("getInventoryAvailableByFacility", inputMap); - } else { - resultOutput = dispatcher.runSync("getProductInventoryAvailable", inputMap); - } - } catch (GenericServiceException e) { - Debug.logError(e, "Problems getting inventory available by facility", MODULE); - return ServiceUtil.returnError(e.getMessage()); - } + // figure out the inventory available for this associated product + Map resultOutput = null; + try { + Map inputMap = UtilMisc.toMap("productId", productIdTo, "statusId", statusId); + if (facilityId != null) { + inputMap.put("facilityId", facilityId); + resultOutput = dispatcher.runSync("getInventoryAvailableByFacility", inputMap); + } else { + resultOutput = dispatcher.runSync("getProductInventoryAvailable", inputMap); + } + } catch (GenericServiceException e) { + Debug.logError(e, "Problems getting inventory available by facility", MODULE); + return ServiceUtil.returnError(e.getMessage()); + } - // Figure out what the QOH and ATP inventory would be with this associated product - BigDecimal currentQuantityOnHandTotal = (BigDecimal) resultOutput.get("quantityOnHandTotal"); - BigDecimal currentAvailableToPromiseTotal = (BigDecimal) resultOutput.get("availableToPromiseTotal"); - BigDecimal tmpQuantityOnHandTotal = currentQuantityOnHandTotal.divideToIntegralValue(assocQuantity, GEN_ROUNDING); - BigDecimal tmpAvailableToPromiseTotal = currentAvailableToPromiseTotal.divideToIntegralValue(assocQuantity, GEN_ROUNDING); + // Figure out what the QOH and ATP inventory would be with this associated product + BigDecimal currentQuantityOnHandTotal = (BigDecimal) resultOutput.get("quantityOnHandTotal"); + BigDecimal currentAvailableToPromiseTotal = (BigDecimal) resultOutput.get("availableToPromiseTotal"); + BigDecimal tmpQuantityOnHandTotal = currentQuantityOnHandTotal.divideToIntegralValue(assocQuantity, GEN_ROUNDING); + BigDecimal tmpAvailableToPromiseTotal = currentAvailableToPromiseTotal.divideToIntegralValue(assocQuantity, GEN_ROUNDING); - // reset the minimum QOH and ATP quantities if those quantities for this product are less - if (minQuantityOnHandTotal == null || tmpQuantityOnHandTotal.compareTo(minQuantityOnHandTotal) < 0) { - minQuantityOnHandTotal = tmpQuantityOnHandTotal; - } - if (minAvailableToPromiseTotal == null || tmpAvailableToPromiseTotal.compareTo(minAvailableToPromiseTotal) < 0) { - minAvailableToPromiseTotal = tmpAvailableToPromiseTotal; - } + // reset the minimum QOH and ATP quantities if those quantities for this product are less + if (minQuantityOnHandTotal == null || tmpQuantityOnHandTotal.compareTo(minQuantityOnHandTotal) < 0) { + minQuantityOnHandTotal = tmpQuantityOnHandTotal; + } + if (minAvailableToPromiseTotal == null || tmpAvailableToPromiseTotal.compareTo(minAvailableToPromiseTotal) < 0) { + minAvailableToPromiseTotal = tmpAvailableToPromiseTotal; + } - if (Debug.verboseOn()) { - Debug.logVerbose("productIdTo = " + productIdTo + " assocQuantity = " + assocQuantity + "current QOH " + currentQuantityOnHandTotal - + "currentATP = " + currentAvailableToPromiseTotal + " minQOH = " + minQuantityOnHandTotal + " minATP = " - + minAvailableToPromiseTotal, MODULE); - } - } - // the final QOH and ATP quantities are the minimum of all the products - quantityOnHandTotal = minQuantityOnHandTotal; - availableToPromiseTotal = minAvailableToPromiseTotal; + if (Debug.verboseOn()) { + Debug.logVerbose("productIdTo = " + productIdTo + " assocQuantity = " + assocQuantity + "current QOH " + currentQuantityOnHandTotal + + "currentATP = " + currentAvailableToPromiseTotal + " minQOH = " + minQuantityOnHandTotal + " minATP = " + + minAvailableToPromiseTotal, MODULE); + } + } + // the final QOH and ATP quantities are the minimum of all the products + quantityOnHandTotal = minQuantityOnHandTotal; + availableToPromiseTotal = minAvailableToPromiseTotal; } Map result = ServiceUtil.returnSuccess(); @@ -802,10 +802,13 @@ public class InventoryServices { // get both the real ATP/QOH available and the quantities available from marketing packages try { - if (EntityTypeUtil.hasParentType(delegator, "ProductType", "productTypeId", product.getString("productTypeId"), "parentTypeId", "MARKETING_PKG")) { - mktgPkgInvResult = dispatcher.runSync("getMktgPackagesAvailable", UtilMisc.toMap("productId", productId, "facilityId", facility.getString("facilityId"))); + if (EntityTypeUtil.hasParentType(delegator, "ProductType", "productTypeId", product.getString("productTypeId"), "parentTypeId", + "MARKETING_PKG")) { + mktgPkgInvResult = dispatcher.runSync("getMktgPackagesAvailable", UtilMisc.toMap("productId", productId, "facilityId", + facility.getString("facilityId"))); } - invResult = dispatcher.runSync("getInventoryAvailableByFacility", UtilMisc.toMap("productId", productId, "facilityId", facility.getString("facilityId"))); + invResult = dispatcher.runSync("getInventoryAvailableByFacility", UtilMisc.toMap("productId", productId, "facilityId", + facility.getString("facilityId"))); } catch (GenericServiceException e) { Debug.logError(e, "Could not find inventory for facility " + facility.getString("facilityId"), MODULE); return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, @@ -824,7 +827,8 @@ public class InventoryServices { qoh = qoh.add(fqoh); } } - if (EntityTypeUtil.hasParentType(delegator, "ProductType", "productTypeId", product.getString("productTypeId"), "parentTypeId", "MARKETING_PKG") && ServiceUtil.isSuccess(mktgPkgInvResult)) { + if (EntityTypeUtil.hasParentType(delegator, "ProductType", "productTypeId", product.getString("productTypeId"), "parentTypeId", + "MARKETING_PKG") && ServiceUtil.isSuccess(mktgPkgInvResult)) { BigDecimal fatp = (BigDecimal) mktgPkgInvResult.get("availableToPromiseTotal"); BigDecimal fqoh = (BigDecimal) mktgPkgInvResult.get("quantityOnHandTotal"); if (fatp != null) { diff --git a/applications/product/src/main/java/org/apache/ofbiz/product/price/PriceServices.java b/applications/product/src/main/java/org/apache/ofbiz/product/price/PriceServices.java index f1b76ec458..068144b972 100644 --- a/applications/product/src/main/java/org/apache/ofbiz/product/price/PriceServices.java +++ b/applications/product/src/main/java/org/apache/ofbiz/product/price/PriceServices.java @@ -461,11 +461,12 @@ public class PriceServices { ruleListToUse.addAll(nonQuantityProductPriceRules); Map quantCalcResults = calcPriceResultFromRules(ruleListToUse, listPrice, defaultPrice, promoPrice, - wholesalePrice, maximumPriceValue, minimumPriceValue, validPriceFound, - averageCostValue, productId, virtualProductId, prodCatalogId, productStoreGroupId, - webSiteId, partyId, null, currencyDefaultUomId, delegator, nowTimestamp, locale); - Map quantErrorResult = addGeneralResults(quantCalcResults, competitivePriceValue, specialPromoPriceValue, productStore, - checkIncludeVat, currencyDefaultUomId, productId, quantity, partyId, dispatcher, locale); + wholesalePrice, maximumPriceValue, minimumPriceValue, validPriceFound, + averageCostValue, productId, virtualProductId, prodCatalogId, productStoreGroupId, + webSiteId, partyId, null, currencyDefaultUomId, delegator, nowTimestamp, locale); + Map quantErrorResult = addGeneralResults(quantCalcResults, competitivePriceValue, specialPromoPriceValue, + productStore, + checkIncludeVat, currencyDefaultUomId, productId, quantity, partyId, dispatcher, locale); if (quantErrorResult != null) return quantErrorResult; // also add the quantityProductPriceRule to the Map so it can be used for quantity break information @@ -477,9 +478,9 @@ public class PriceServices { // use a quantity 1 to get the main price, then fill in the quantity break prices Map calcResults = calcPriceResultFromRules(allProductPriceRules, listPrice, defaultPrice, promoPrice, - wholesalePrice, maximumPriceValue, minimumPriceValue, validPriceFound, - averageCostValue, productId, virtualProductId, prodCatalogId, productStoreGroupId, - webSiteId, partyId, BigDecimal.ONE, currencyDefaultUomId, delegator, nowTimestamp, locale); + wholesalePrice, maximumPriceValue, minimumPriceValue, validPriceFound, + averageCostValue, productId, virtualProductId, prodCatalogId, productStoreGroupId, + webSiteId, partyId, BigDecimal.ONE, currencyDefaultUomId, delegator, nowTimestamp, locale); result.putAll(calcResults); // The orderItemPriceInfos out parameter requires a special treatment: // the list of OrderItemPriceInfos generated by the price rule is appended to @@ -495,9 +496,9 @@ public class PriceServices { if (errorResult != null) return errorResult; } else { Map calcResults = calcPriceResultFromRules(allProductPriceRules, listPrice, defaultPrice, promoPrice, - wholesalePrice, maximumPriceValue, minimumPriceValue, validPriceFound, - averageCostValue, productId, virtualProductId, prodCatalogId, productStoreGroupId, - webSiteId, partyId, quantity, currencyDefaultUomId, delegator, nowTimestamp, locale); + wholesalePrice, maximumPriceValue, minimumPriceValue, validPriceFound, + averageCostValue, productId, virtualProductId, prodCatalogId, productStoreGroupId, + webSiteId, partyId, quantity, currencyDefaultUomId, delegator, nowTimestamp, locale); result.putAll(calcResults); // The orderItemPriceInfos out parameter requires a special treatment: // the list of OrderItemPriceInfos generated by the price rule is appended to @@ -509,7 +510,7 @@ public class PriceServices { result.put("orderItemPriceInfos", orderItemPriceInfos); Map errorResult = addGeneralResults(result, competitivePriceValue, specialPromoPriceValue, productStore, - checkIncludeVat, currencyDefaultUomId, productId, quantity, partyId, dispatcher, locale); + checkIncludeVat, currencyDefaultUomId, productId, quantity, partyId, dispatcher, locale); if (errorResult != null) return errorResult; } } catch (GenericEntityException e) { @@ -544,7 +545,8 @@ public class PriceServices { if (tempPrice != null && tempPrice != BigDecimal.ZERO) { Map priceResults = new HashMap<>(); try { - priceResults = dispatcher.runSync("convertUom", UtilMisc. toMap("uomId", currencyDefaultUomId, "uomIdTo", currencyUomIdTo, + priceResults = dispatcher.runSync("convertUom", UtilMisc.toMap("uomId", currencyDefaultUomId, + "uomIdTo", currencyUomIdTo, "originalValue", tempPrice, "defaultDecimalScale", 2L, "defaultRoundingMode", "HalfUp")); if (ServiceUtil.isError(priceResults) || (priceResults.get("convertedValue") == null)) { Debug.logWarning("Unable to convert " + entry.getKey() + " for product " + productId, MODULE); @@ -573,8 +575,8 @@ public class PriceServices { if (filteredPrices != null && filteredPrices.size() > 1) { if (Debug.infoOn()) { Debug.logInfo("There is more than one " + productPriceTypeId + " with the currencyUomId " + priceValue.getString("currencyUomId") - + " and productId " + priceValue.getString("productId") + ", using the latest found with price: " - + priceValue.getBigDecimal("price"), MODULE); + + " and productId " + priceValue.getString("productId") + ", using the latest found with price: " + + priceValue.getBigDecimal("price"), MODULE); } } if (priceValue == null && secondaryPriceList != null) { @@ -584,8 +586,9 @@ public class PriceServices { } public static Map addGeneralResults(Map result, GenericValue competitivePriceValue, - GenericValue specialPromoPriceValue, GenericValue productStore, String checkIncludeVat, String currencyUomId, String productId, - BigDecimal quantity, String partyId, LocalDispatcher dispatcher, Locale locale) { + GenericValue specialPromoPriceValue, GenericValue productStore, String checkIncludeVat, + String currencyUomId, String productId, + BigDecimal quantity, String partyId, LocalDispatcher dispatcher, Locale locale) { result.put("competitivePrice", competitivePriceValue != null ? competitivePriceValue.getBigDecimal("price") : null); result.put("specialPromoPrice", specialPromoPriceValue != null ? specialPromoPriceValue.getBigDecimal("price") : null); result.put("currencyUsed", currencyUomId); @@ -790,11 +793,15 @@ public class PriceServices { return productPriceRules; } - public static Map calcPriceResultFromRules(List productPriceRules, BigDecimal listPrice, BigDecimal defaultPrice, BigDecimal promoPrice, - BigDecimal wholesalePrice, GenericValue maximumPriceValue, GenericValue minimumPriceValue, boolean validPriceFound, - GenericValue averageCostValue, String productId, String virtualProductId, String prodCatalogId, String productStoreGroupId, - String webSiteId, String partyId, BigDecimal quantity, String currencyUomId, Delegator delegator, Timestamp nowTimestamp, - Locale locale) throws GenericEntityException { + public static Map calcPriceResultFromRules(List productPriceRules, BigDecimal listPrice, BigDecimal defaultPrice, + BigDecimal promoPrice, + BigDecimal wholesalePrice, GenericValue maximumPriceValue, + GenericValue minimumPriceValue, boolean validPriceFound, + GenericValue averageCostValue, String productId, String virtualProductId, + String prodCatalogId, String productStoreGroupId, + String webSiteId, String partyId, BigDecimal quantity, String currencyUomId, + Delegator delegator, Timestamp nowTimestamp, + Locale locale) throws GenericEntityException { Map calcResults = new HashMap<>(); @@ -1057,7 +1064,7 @@ public class PriceServices { int compare = 0; if ("PRIP_PRODUCT_ID".equals(productPriceCond.getString("inputParamEnumId"))) { - compare = UtilMisc.toList(productId, virtualProductId).contains(productPriceCond.getString("condValue"))? 0: 1; + compare = UtilMisc.toList(productId, virtualProductId).contains(productPriceCond.getString("condValue")) ? 0 : 1; } else if ("PRIP_PROD_CAT_ID".equals(productPriceCond.getString("inputParamEnumId"))) { // if a ProductCategoryMember exists for this productId and the specified productCategoryId String productCategoryId = productPriceCond.getString("condValue"); diff --git a/applications/product/src/main/java/org/apache/ofbiz/product/product/ProductContentWrapper.java b/applications/product/src/main/java/org/apache/ofbiz/product/product/ProductContentWrapper.java index 1e72b0f0a8..b05727042d 100644 --- a/applications/product/src/main/java/org/apache/ofbiz/product/product/ProductContentWrapper.java +++ b/applications/product/src/main/java/org/apache/ofbiz/product/product/ProductContentWrapper.java @@ -121,16 +121,16 @@ public class ProductContentWrapper implements ContentWrapper { getProductContentAsText(null, product, productContentTypeId, locale, mimeTypeId, partyId, roleTypeId, delegator, dispatcher, outWriter, false); String outString = outWriter.toString(); if (UtilValidate.isEmpty(outString)) { - outString = product.getModelEntity().isField(candidateFieldName) ? product.getString(candidateFieldName): ""; - outString = outString == null? "" : outString; + outString = product.getModelEntity().isField(candidateFieldName) ? product.getString(candidateFieldName) : ""; + outString = outString == null ? "" : outString; } outString = encoder.sanitize(outString, null); productContentCache.put(cacheKey, outString); return outString; } catch (GeneralException | IOException e) { Debug.logError(e, "Error rendering ProductContent, inserting empty String", MODULE); - String candidateOut = product.getModelEntity().isField(candidateFieldName) ? product.getString(candidateFieldName): ""; - return candidateOut == null? "" : encoder.sanitize(candidateOut, null); + String candidateOut = product.getModelEntity().isField(candidateFieldName) ? product.getString(candidateFieldName) : ""; + return candidateOut == null ? "" : encoder.sanitize(candidateOut, null); } } @@ -183,22 +183,21 @@ public class ProductContentWrapper implements ContentWrapper { } if (productModel.isField(candidateFieldName)) { - String candidateValue = product.getString(candidateFieldName); - if (UtilValidate.isNotEmpty(candidateValue)) { - outWriter.write(candidateValue); - return; - } else if ("Y".equals(product.getString("isVariant"))) { - // look up the virtual product - GenericValue parent = ProductWorker.getParentProduct(productId, delegator); - if (parent != null) { - candidateValue = parent.getString(candidateFieldName); - if (UtilValidate.isNotEmpty(candidateValue)) { - outWriter.write(candidateValue); - return; - } + String candidateValue = product.getString(candidateFieldName); + if (UtilValidate.isNotEmpty(candidateValue)) { + outWriter.write(candidateValue); + return; + } else if ("Y".equals(product.getString("isVariant"))) { + // look up the virtual product + GenericValue parent = ProductWorker.getParentProduct(productId, delegator); + if (parent != null) { + candidateValue = parent.getString(candidateFieldName); + if (UtilValidate.isNotEmpty(candidateValue)) { + outWriter.write(candidateValue); + return; } } + } } - } } diff --git a/applications/product/src/main/java/org/apache/ofbiz/product/product/ProductPromoContentWrapper.java b/applications/product/src/main/java/org/apache/ofbiz/product/product/ProductPromoContentWrapper.java index d2fd50bb41..9ebaa07ce7 100644 --- a/applications/product/src/main/java/org/apache/ofbiz/product/product/ProductPromoContentWrapper.java +++ b/applications/product/src/main/java/org/apache/ofbiz/product/product/ProductPromoContentWrapper.java @@ -127,7 +127,7 @@ public class ProductPromoContentWrapper implements ContentWrapper { String outString = outWriter.toString(); if (UtilValidate.isEmpty(outString)) { outString = productPromo.getModelEntity().isField(candidateFieldName) ? productPromo.getString(candidateFieldName): ""; - outString = outString == null? "" : outString; + outString = outString == null ? "" : outString; } outString = encoder.sanitize(outString, null); productPromoContentCache.put(cacheKey, outString); @@ -135,7 +135,7 @@ public class ProductPromoContentWrapper implements ContentWrapper { } catch (GeneralException | IOException e) { Debug.logError(e, "Error rendering ProductPromoContent, inserting empty String", MODULE); String candidateOut = productPromo.getModelEntity().isField(candidateFieldName) ? productPromo.getString(candidateFieldName): ""; - return candidateOut == null? "" : encoder.sanitize(candidateOut, null); + return candidateOut == null ? "" : encoder.sanitize(candidateOut, null); } } diff --git a/applications/product/src/main/java/org/apache/ofbiz/product/product/ProductSearch.java b/applications/product/src/main/java/org/apache/ofbiz/product/product/ProductSearch.java index 16bb96061f..48f7dfdf86 100644 --- a/applications/product/src/main/java/org/apache/ofbiz/product/product/ProductSearch.java +++ b/applications/product/src/main/java/org/apache/ofbiz/product/product/ProductSearch.java @@ -357,11 +357,11 @@ public class ProductSearch { public void finishCategoryAndFeatureConstraints() { if (includeCategoryIds.size() == 0 && excludeCategoryIds.size() == 0 && alwaysIncludeCategoryIds.size() == 0 - && includeCategoryIdOrSetAndList.size() == 0 && alwaysIncludeCategoryIdOrSetAndList.size() == 0 - && includeFeatureIds.size() == 0 && excludeFeatureIds.size() == 0 && alwaysIncludeFeatureIds.size() == 0 - && includeFeatureIdOrSetAndList.size() == 0 && alwaysIncludeFeatureIdOrSetAndList.size() == 0 - && includeFeatureCategoryIds.size() == 0 && excludeFeatureCategoryIds.size() == 0 && alwaysIncludeFeatureCategoryIds.size() == 0 - && includeFeatureGroupIds.size() == 0 && excludeFeatureGroupIds.size() == 0 && alwaysIncludeFeatureGroupIds.size() == 0) { + && includeCategoryIdOrSetAndList.size() == 0 && alwaysIncludeCategoryIdOrSetAndList.size() == 0 + && includeFeatureIds.size() == 0 && excludeFeatureIds.size() == 0 && alwaysIncludeFeatureIds.size() == 0 + && includeFeatureIdOrSetAndList.size() == 0 && alwaysIncludeFeatureIdOrSetAndList.size() == 0 + && includeFeatureCategoryIds.size() == 0 && excludeFeatureCategoryIds.size() == 0 && alwaysIncludeFeatureCategoryIds.size() == 0 + && includeFeatureGroupIds.size() == 0 && excludeFeatureGroupIds.size() == 0 && alwaysIncludeFeatureGroupIds.size() == 0) { return; } diff --git a/applications/product/src/main/java/org/apache/ofbiz/product/product/ProductSearchEvents.java b/applications/product/src/main/java/org/apache/ofbiz/product/product/ProductSearchEvents.java index 02aa096334..94ab324c75 100644 --- a/applications/product/src/main/java/org/apache/ofbiz/product/product/ProductSearchEvents.java +++ b/applications/product/src/main/java/org/apache/ofbiz/product/product/ProductSearchEvents.java @@ -51,25 +51,28 @@ import org.apache.ofbiz.webapp.stats.VisitHandler; */ public class ProductSearchEvents { + public static final int DEFAULT_TX_TIMEOUT = 600; private static final String MODULE = ProductSearchEvents.class.getName(); private static final String RESOURCE = "ProductErrorUiLabels"; - public static final int DEFAULT_TX_TIMEOUT = 600; - /** Removes the results of a search from the specified category - *@param request The HTTPRequest object for the current request - *@param response The HTTPResponse object for the current request - *@return String specifying the exit status of this event + /** + * Removes the results of a search from the specified category + * + * @param request The HTTPRequest object for the current request + * @param response The HTTPResponse object for the current request + * @return String specifying the exit status of this event */ public static String searchRemoveFromCategory(HttpServletRequest request, HttpServletResponse response) { Delegator delegator = (Delegator) request.getAttribute("delegator"); String productCategoryId = request.getParameter("SE_SEARCH_CATEGORY_ID"); - String errMsg=null; + String errMsg = null; try { boolean beganTransaction = TransactionUtil.begin(DEFAULT_TX_TIMEOUT); try (EntityListIterator eli = getProductSearchResults(request)) { if (eli == null) { - errMsg = UtilProperties.getMessage(RESOURCE, "productsearchevents.no_results_found_probably_error_constraints", UtilHttp.getLocale(request)); + errMsg = UtilProperties.getMessage(RESOURCE, "productsearchevents.no_results_found_probably_error_constraints", + UtilHttp.getLocale(request)); request.setAttribute("_ERROR_MESSAGE_", errMsg); return "error"; } @@ -78,14 +81,16 @@ public class ProductSearchEvents { GenericValue searchResultView = null; while ((searchResultView = eli.next()) != null) { String productId = searchResultView.getString("mainProductId"); - numRemoved += delegator.removeByAnd("ProductCategoryMember", UtilMisc.toMap("productCategoryId", productCategoryId, "productId", productId)); + numRemoved += delegator.removeByAnd("ProductCategoryMember", UtilMisc.toMap("productCategoryId", productCategoryId, + "productId", productId)); } Map messageMap = UtilMisc.toMap("numRemoved", Integer.toString(numRemoved)); errMsg = UtilProperties.getMessage(RESOURCE, "productsearchevents.removed_x_items", messageMap, UtilHttp.getLocale(request)); request.setAttribute("_EVENT_MESSAGE_", errMsg); } catch (GenericEntityException e) { Map messageMap = UtilMisc.toMap("errSearchResult", e.toString()); - errMsg = UtilProperties.getMessage(RESOURCE, "productsearchevents.error_getting_search_results", messageMap, UtilHttp.getLocale(request)); + errMsg = UtilProperties.getMessage(RESOURCE, "productsearchevents.error_getting_search_results", messageMap, + UtilHttp.getLocale(request)); Debug.logError(e, errMsg, MODULE); request.setAttribute("_ERROR_MESSAGE_", errMsg); TransactionUtil.rollback(beganTransaction, errMsg, e); @@ -103,148 +108,161 @@ public class ProductSearchEvents { return "success"; } - /** Sets the thru date of the results of a search to the specified date for the specified catogory - *@param request The HTTPRequest object for the current request - *@param response The HTTPResponse object for the current request - *@return String specifying the exit status of this event - */ - public static String searchExpireFromCategory(HttpServletRequest request, HttpServletResponse response) { - Delegator delegator = (Delegator) request.getAttribute("delegator"); - String productCategoryId = request.getParameter("SE_SEARCH_CATEGORY_ID"); - String thruDateStr = request.getParameter("thruDate"); - String errMsg=null; + /** + * Sets the thru date of the results of a search to the specified date for the specified catogory + * + * @param request The HTTPRequest object for the current request + * @param response The HTTPResponse object for the current request + * @return String specifying the exit status of this event + */ + public static String searchExpireFromCategory(HttpServletRequest request, HttpServletResponse response) { + Delegator delegator = (Delegator) request.getAttribute("delegator"); + String productCategoryId = request.getParameter("SE_SEARCH_CATEGORY_ID"); + String thruDateStr = request.getParameter("thruDate"); + String errMsg = null; - Timestamp thruDate; - try { - thruDate = Timestamp.valueOf(thruDateStr); - } catch (RuntimeException e) { - Map messageMap = UtilMisc.toMap("errDateFormat", e.toString()); - errMsg = UtilProperties.getMessage(RESOURCE, "productsearchevents.thruDate_not_formatted_properly", messageMap, UtilHttp.getLocale(request)); - Debug.logError(e, errMsg, MODULE); - request.setAttribute("_ERROR_MESSAGE_", errMsg); - return "error"; - } - - try { - boolean beganTransaction = TransactionUtil.begin(DEFAULT_TX_TIMEOUT); - try (EntityListIterator eli = getProductSearchResults(request)) { - if (eli == null) { - errMsg = UtilProperties.getMessage(RESOURCE, "productsearchevents.no_results_found_probably_error_constraints", UtilHttp.getLocale(request)); - request.setAttribute("_ERROR_MESSAGE_", errMsg); - return "error"; - } - - GenericValue searchResultView = null; - int numExpired = 0; - while ((searchResultView = eli.next()) != null) { - String productId = searchResultView.getString("mainProductId"); - //get all tuples that match product and category - List pcmList = EntityQuery.use(delegator).from("ProductCategoryMember").where("productCategoryId", productCategoryId, "productId", productId).queryList(); - - //set those thrudate to that specificed maybe remove then add new one - for (GenericValue pcm: pcmList) { - if (pcm.get("thruDate") == null) { - pcm.set("thruDate", thruDate); - pcm.store(); - numExpired++; - } - } - } - Map messageMap = UtilMisc.toMap("numExpired", Integer.toString(numExpired)); - errMsg = UtilProperties.getMessage(RESOURCE, "productsearchevents.expired_x_items", messageMap, UtilHttp.getLocale(request)); - request.setAttribute("_EVENT_MESSAGE_", errMsg); - } catch (GenericEntityException e) { - Map messageMap = UtilMisc.toMap("errSearchResult", e.toString()); - errMsg = UtilProperties.getMessage(RESOURCE, "productsearchevents.error_getting_search_results", messageMap, UtilHttp.getLocale(request)); - Debug.logError(e, errMsg, MODULE); - request.setAttribute("_ERROR_MESSAGE_", errMsg); - TransactionUtil.rollback(beganTransaction, errMsg, e); - return "error"; - } finally { - TransactionUtil.commit(beganTransaction); - } - } catch (GenericTransactionException e) { - Map messageMap = UtilMisc.toMap("errSearchResult", e.toString()); - errMsg = UtilProperties.getMessage(RESOURCE, "productsearchevents.error_getting_search_results", messageMap, UtilHttp.getLocale(request)); - Debug.logError(e, errMsg, MODULE); - request.setAttribute("_ERROR_MESSAGE_", errMsg); - return "error"; - } - - return "success"; - } - - /** Adds the results of a search to the specified catogory - *@param request The HTTPRequest object for the current request - *@param response The HTTPResponse object for the current request - *@return String specifying the exit status of this event - */ - public static String searchAddToCategory(HttpServletRequest request, HttpServletResponse response) { - Delegator delegator = (Delegator) request.getAttribute("delegator"); - String productCategoryId = request.getParameter("SE_SEARCH_CATEGORY_ID"); - String fromDateStr = request.getParameter("fromDate"); - Timestamp fromDate = null; - String errMsg = null; - - try { - fromDate = Timestamp.valueOf(fromDateStr); + Timestamp thruDate; + try { + thruDate = Timestamp.valueOf(thruDateStr); } catch (RuntimeException e) { - Map messageMap = UtilMisc.toMap("errDateFormat", e.toString()); - errMsg = UtilProperties.getMessage(RESOURCE, "productsearchevents.fromDate_not_formatted_properly", messageMap, UtilHttp.getLocale(request)); - request.setAttribute("_ERROR_MESSAGE_", errMsg); + Map messageMap = UtilMisc.toMap("errDateFormat", e.toString()); + errMsg = UtilProperties.getMessage(RESOURCE, "productsearchevents.thruDate_not_formatted_properly", messageMap, + UtilHttp.getLocale(request)); + Debug.logError(e, errMsg, MODULE); + request.setAttribute("_ERROR_MESSAGE_", errMsg); return "error"; } - try { - boolean beganTransaction = TransactionUtil.begin(DEFAULT_TX_TIMEOUT); - try (EntityListIterator eli = getProductSearchResults(request)) { - if (eli == null) { - errMsg = UtilProperties.getMessage(RESOURCE, "productsearchevents.no_results_found_probably_error_constraints", UtilHttp.getLocale(request)); - request.setAttribute("_ERROR_MESSAGE_", errMsg); - return "error"; - } + try { + boolean beganTransaction = TransactionUtil.begin(DEFAULT_TX_TIMEOUT); + try (EntityListIterator eli = getProductSearchResults(request)) { + if (eli == null) { + errMsg = UtilProperties.getMessage(RESOURCE, "productsearchevents.no_results_found_probably_error_constraints", + UtilHttp.getLocale(request)); + request.setAttribute("_ERROR_MESSAGE_", errMsg); + return "error"; + } - GenericValue searchResultView = null; - int numAdded = 0; - while ((searchResultView = eli.next()) != null) { - String productId = searchResultView.getString("mainProductId"); + GenericValue searchResultView = null; + int numExpired = 0; + while ((searchResultView = eli.next()) != null) { + String productId = searchResultView.getString("mainProductId"); + //get all tuples that match product and category + List pcmList = EntityQuery.use(delegator).from("ProductCategoryMember").where("productCategoryId", + productCategoryId, "productId", productId).queryList(); - GenericValue pcm=delegator.makeValue("ProductCategoryMember"); - pcm.set("productCategoryId", productCategoryId); - pcm.set("productId", productId); - pcm.set("fromDate", fromDate); - pcm.create(); + //set those thrudate to that specificed maybe remove then add new one + for (GenericValue pcm : pcmList) { + if (pcm.get("thruDate") == null) { + pcm.set("thruDate", thruDate); + pcm.store(); + numExpired++; + } + } + } + Map messageMap = UtilMisc.toMap("numExpired", Integer.toString(numExpired)); + errMsg = UtilProperties.getMessage(RESOURCE, "productsearchevents.expired_x_items", messageMap, UtilHttp.getLocale(request)); + request.setAttribute("_EVENT_MESSAGE_", errMsg); + } catch (GenericEntityException e) { + Map messageMap = UtilMisc.toMap("errSearchResult", e.toString()); + errMsg = UtilProperties.getMessage(RESOURCE, "productsearchevents.error_getting_search_results", messageMap, + UtilHttp.getLocale(request)); + Debug.logError(e, errMsg, MODULE); + request.setAttribute("_ERROR_MESSAGE_", errMsg); + TransactionUtil.rollback(beganTransaction, errMsg, e); + return "error"; + } finally { + TransactionUtil.commit(beganTransaction); + } + } catch (GenericTransactionException e) { + Map messageMap = UtilMisc.toMap("errSearchResult", e.toString()); + errMsg = UtilProperties.getMessage(RESOURCE, "productsearchevents.error_getting_search_results", messageMap, UtilHttp.getLocale(request)); + Debug.logError(e, errMsg, MODULE); + request.setAttribute("_ERROR_MESSAGE_", errMsg); + return "error"; + } + return "success"; + } - numAdded++; - } - Map messageMap = UtilMisc.toMap("numAdded", Integer.toString(numAdded)); - errMsg = UtilProperties.getMessage(RESOURCE, "productsearchevents.added_x_product_category_members", messageMap, UtilHttp.getLocale(request)); - request.setAttribute("_EVENT_MESSAGE_", errMsg); - } catch (GenericEntityException e) { - Map messageMap = UtilMisc.toMap("errSearchResult", e.toString()); - errMsg = UtilProperties.getMessage(RESOURCE, "productsearchevents.error_getting_search_results", messageMap, UtilHttp.getLocale(request)); - Debug.logError(e, errMsg, MODULE); - request.setAttribute("_ERROR_MESSAGE_", errMsg); - TransactionUtil.rollback(beganTransaction, errMsg, e); - return "error"; - } finally { - TransactionUtil.commit(beganTransaction); - } - } catch (GenericTransactionException e) { - Map messageMap = UtilMisc.toMap("errSearchResult", e.toString()); - errMsg = UtilProperties.getMessage(RESOURCE, "productsearchevents.error_getting_search_results", messageMap, UtilHttp.getLocale(request)); - Debug.logError(e, errMsg, MODULE); - request.setAttribute("_ERROR_MESSAGE_", errMsg); - return "error"; - } + /** + * Adds the results of a search to the specified catogory + * + * @param request The HTTPRequest object for the current request + * @param response The HTTPResponse object for the current request + * @return String specifying the exit status of this event + */ + public static String searchAddToCategory(HttpServletRequest request, HttpServletResponse response) { + Delegator delegator = (Delegator) request.getAttribute("delegator"); + String productCategoryId = request.getParameter("SE_SEARCH_CATEGORY_ID"); + String fromDateStr = request.getParameter("fromDate"); + Timestamp fromDate = null; + String errMsg = null; - return "success"; - } + try { + fromDate = Timestamp.valueOf(fromDateStr); + } catch (RuntimeException e) { + Map messageMap = UtilMisc.toMap("errDateFormat", e.toString()); + errMsg = UtilProperties.getMessage(RESOURCE, "productsearchevents.fromDate_not_formatted_properly", messageMap, + UtilHttp.getLocale(request)); + request.setAttribute("_ERROR_MESSAGE_", errMsg); + return "error"; + } - /** Adds a feature to search results - *@param request The HTTPRequest object for the current request - *@param response The HTTPResponse object for the current request - *@return String specifying the exit status of this event + try { + boolean beganTransaction = TransactionUtil.begin(DEFAULT_TX_TIMEOUT); + try (EntityListIterator eli = getProductSearchResults(request)) { + if (eli == null) { + errMsg = UtilProperties.getMessage(RESOURCE, "productsearchevents.no_results_found_probably_error_constraints", + UtilHttp.getLocale(request)); + request.setAttribute("_ERROR_MESSAGE_", errMsg); + return "error"; + } + + GenericValue searchResultView = null; + int numAdded = 0; + while ((searchResultView = eli.next()) != null) { + String productId = searchResultView.getString("mainProductId"); + + GenericValue pcm = delegator.makeValue("ProductCategoryMember"); + pcm.set("productCategoryId", productCategoryId); + pcm.set("productId", productId); + pcm.set("fromDate", fromDate); + pcm.create(); + + numAdded++; + } + Map messageMap = UtilMisc.toMap("numAdded", Integer.toString(numAdded)); + errMsg = UtilProperties.getMessage(RESOURCE, "productsearchevents.added_x_product_category_members", messageMap, + UtilHttp.getLocale(request)); + request.setAttribute("_EVENT_MESSAGE_", errMsg); + } catch (GenericEntityException e) { + Map messageMap = UtilMisc.toMap("errSearchResult", e.toString()); + errMsg = UtilProperties.getMessage(RESOURCE, "productsearchevents.error_getting_search_results", messageMap, + UtilHttp.getLocale(request)); + Debug.logError(e, errMsg, MODULE); + request.setAttribute("_ERROR_MESSAGE_", errMsg); + TransactionUtil.rollback(beganTransaction, errMsg, e); + return "error"; + } finally { + TransactionUtil.commit(beganTransaction); + } + } catch (GenericTransactionException e) { + Map messageMap = UtilMisc.toMap("errSearchResult", e.toString()); + errMsg = UtilProperties.getMessage(RESOURCE, "productsearchevents.error_getting_search_results", messageMap, UtilHttp.getLocale(request)); + Debug.logError(e, errMsg, MODULE); + request.setAttribute("_ERROR_MESSAGE_", errMsg); + return "error"; + } + + return "success"; + } + + /** + * Adds a feature to search results + * + * @param request The HTTPRequest object for the current request + * @param response The HTTPResponse object for the current request + * @return String specifying the exit status of this event */ public static String searchAddFeature(HttpServletRequest request, HttpServletResponse response) { Delegator delegator = (Delegator) request.getAttribute("delegator"); @@ -273,7 +291,7 @@ public class ProductSearchEvents { amount = new BigDecimal(amountStr); } if (UtilValidate.isNotEmpty(sequenceNumStr)) { - sequenceNum= Long.valueOf(sequenceNumStr); + sequenceNum = Long.valueOf(sequenceNumStr); } } catch (RuntimeException e) { String errorMsg = UtilProperties.getMessage(RESOURCE, "productSearchEvents.error_casting_types", locale) + " : " + e.toString(); @@ -286,7 +304,8 @@ public class ProductSearchEvents { boolean beganTransaction = TransactionUtil.begin(DEFAULT_TX_TIMEOUT); try (EntityListIterator eli = getProductSearchResults(request)) { if (eli == null) { - String errMsg = UtilProperties.getMessage(RESOURCE, "productsearchevents.no_results_found_probably_error_constraints", UtilHttp.getLocale(request)); + String errMsg = UtilProperties.getMessage(RESOURCE, "productsearchevents.no_results_found_probably_error_constraints", + UtilHttp.getLocale(request)); request.setAttribute("_ERROR_MESSAGE_", errMsg); return "error"; } @@ -295,7 +314,7 @@ public class ProductSearchEvents { int numAdded = 0; while ((searchResultView = eli.next()) != null) { String productId = searchResultView.getString("mainProductId"); - GenericValue pfa=delegator.makeValue("ProductFeatureAppl"); + GenericValue pfa = delegator.makeValue("ProductFeatureAppl"); pfa.set("productId", productId); pfa.set("productFeatureId", productFeatureId); pfa.set("fromDate", fromDate); @@ -328,10 +347,12 @@ public class ProductSearchEvents { return "success"; } - /** Removes a feature from search results - *@param request The HTTPRequest object for the current request - *@param response The HTTPResponse object for the current request - *@return String specifying the exit status of this event + /** + * Removes a feature from search results + * + * @param request The HTTPRequest object for the current request + * @param response The HTTPResponse object for the current request + * @return String specifying the exit status of this event */ public static String searchRemoveFeature(HttpServletRequest request, HttpServletResponse response) { Delegator delegator = (Delegator) request.getAttribute("delegator"); @@ -343,7 +364,8 @@ public class ProductSearchEvents { boolean beganTransaction = TransactionUtil.begin(DEFAULT_TX_TIMEOUT); try (EntityListIterator eli = getProductSearchResults(request)) { if (eli == null) { - String errMsg = UtilProperties.getMessage(RESOURCE, "productsearchevents.no_results_found_probably_error_constraints", UtilHttp.getLocale(request)); + String errMsg = UtilProperties.getMessage(RESOURCE, "productsearchevents.no_results_found_probably_error_constraints", + UtilHttp.getLocale(request)); request.setAttribute("_ERROR_MESSAGE_", errMsg); return "error"; } @@ -352,7 +374,8 @@ public class ProductSearchEvents { int numRemoved = 0; while ((searchResultView = eli.next()) != null) { String productId = searchResultView.getString("mainProductId"); - numRemoved += delegator.removeByAnd("ProductFeatureAppl", UtilMisc.toMap("productId", productId, "productFeatureId", productFeatureId)); + numRemoved += delegator.removeByAnd("ProductFeatureAppl", UtilMisc.toMap("productId", productId, "productFeatureId", + productFeatureId)); } Map messageMap = UtilMisc.toMap("numRemoved", numRemoved, "productFeatureId", productFeatureId); String eventMsg = UtilProperties.getMessage(RESOURCE, "productSearchEvents.removed_param_features", messageMap, locale) + "."; @@ -376,10 +399,12 @@ public class ProductSearchEvents { return "success"; } - /** Formats the results of a search to the screen as a tab-delimited output - *@param request The HTTPRequest object for the current request - *@param response The HTTPResponse object for the current request - *@return String specifying the exit status of this event + /** + * Formats the results of a search to the screen as a tab-delimited output + * + * @param request The HTTPRequest object for the current request + * @param response The HTTPResponse object for the current request + * @return String specifying the exit status of this event */ public static String searchExportProductList(HttpServletRequest request, HttpServletResponse response) { Delegator delegator = (Delegator) request.getAttribute("delegator"); @@ -390,7 +415,8 @@ public class ProductSearchEvents { boolean beganTransaction = TransactionUtil.begin(DEFAULT_TX_TIMEOUT); try (EntityListIterator eli = getProductSearchResults(request)) { if (eli == null) { - errMsg = UtilProperties.getMessage(RESOURCE, "productsearchevents.no_results_found_probably_error_constraints", UtilHttp.getLocale(request)); + errMsg = UtilProperties.getMessage(RESOURCE, "productsearchevents.no_results_found_probably_error_constraints", + UtilHttp.getLocale(request)); request.setAttribute("_ERROR_MESSAGE_", errMsg); return "error"; } @@ -401,17 +427,21 @@ public class ProductSearchEvents { String productId = searchResultView.getString("mainProductId"); productMap.put("productId", productId); - productMap.put("productFeatureCustom", EntityQuery.use(delegator).from("ProductFeatureAndAppl").where("productId", productId, "productFeatureTypeId", "HAZMAT").filterByDate().queryFirst()); + productMap.put("productFeatureCustom", EntityQuery.use(delegator).from("ProductFeatureAndAppl").where("productId", productId, + "productFeatureTypeId", "HAZMAT").filterByDate().queryFirst()); - List productCategories = EntityQuery.use(delegator).from("ProductCategoryAndMember").where("productId", productId).filterByDate().queryList(); + List productCategories = EntityQuery.use(delegator).from("ProductCategoryAndMember").where("productId", + productId).filterByDate().queryList(); productMap.put("productCategories", productCategories); - List productFeatures = EntityQuery.use(delegator).from("ProductFeatureAndAppl").where("productId", productId).filterByDate().queryList(); + List productFeatures = + EntityQuery.use(delegator).from("ProductFeatureAndAppl").where("productId", productId).filterByDate().queryList(); productMap.put("productFeatures", productFeatures); productExportList.add(productMap); } } catch (GenericEntityException e) { Map messageMap = UtilMisc.toMap("errSearchResult", e.toString()); - errMsg = UtilProperties.getMessage(RESOURCE, "productsearchevents.error_getting_search_results", messageMap, UtilHttp.getLocale(request)); + errMsg = UtilProperties.getMessage(RESOURCE, "productsearchevents.error_getting_search_results", messageMap, + UtilHttp.getLocale(request)); Debug.logError(e, errMsg, MODULE); request.setAttribute("_ERROR_MESSAGE_", errMsg); TransactionUtil.rollback(beganTransaction, errMsg, e); @@ -436,7 +466,8 @@ public class ProductSearchEvents { Delegator delegator = (Delegator) request.getAttribute("delegator"); String visitId = VisitHandler.getVisitId(session); - List productSearchConstraintList = ProductSearchSession.ProductSearchOptions.getConstraintList(session); + List productSearchConstraintList = + ProductSearchSession.ProductSearchOptions.getConstraintList(session); // if no constraints, don't do a search... if (UtilValidate.isNotEmpty(productSearchConstraintList)) { ResultSortOrder resultSortOrder = ProductSearchSession.ProductSearchOptions.getResultSortOrder(request); diff --git a/applications/product/src/main/java/org/apache/ofbiz/product/product/ProductServices.java b/applications/product/src/main/java/org/apache/ofbiz/product/product/ProductServices.java index ca3ee88a93..84321e73a5 100644 --- a/applications/product/src/main/java/org/apache/ofbiz/product/product/ProductServices.java +++ b/applications/product/src/main/java/org/apache/ofbiz/product/product/ProductServices.java @@ -1336,7 +1336,7 @@ public class ProductServices { filenameToUse += "." + extension.getString("fileExtensionId"); } - File makeResourceDirectory = new File(imageServerPath + "/" + filePathPrefix); + File makeResourceDirectory = new File(imageServerPath + "/" + filePathPrefix); if (!makeResourceDirectory.exists()) { if (!makeResourceDirectory.mkdirs()) { Debug.logError("Directory :" + makeResourceDirectory.getPath() + ", couldn't be created", MODULE); diff --git a/applications/product/src/main/java/org/apache/ofbiz/product/product/ProductWorker.java b/applications/product/src/main/java/org/apache/ofbiz/product/product/ProductWorker.java index 7b47f47480..ba44d38732 100644 --- a/applications/product/src/main/java/org/apache/ofbiz/product/product/ProductWorker.java +++ b/applications/product/src/main/java/org/apache/ofbiz/product/product/ProductWorker.java @@ -100,11 +100,11 @@ public final class ProductWorker { return true; } // exclusion - for (GenericValue productGeo: excludeGeos) { + for (GenericValue productGeo : excludeGeos) { List excludeGeoGroup = GeoWorker.expandGeoGroup(productGeo.getString("geoId"), delegator); if (GeoWorker.containsGeo(excludeGeoGroup, postalAddress.getString("countryGeoId"), delegator) - || GeoWorker.containsGeo(excludeGeoGroup, postalAddress.getString("stateProvinceGeoId"), delegator) - || GeoWorker.containsGeo(excludeGeoGroup, postalAddress.getString("postalCodeGeoId"), delegator)) { + || GeoWorker.containsGeo(excludeGeoGroup, postalAddress.getString("stateProvinceGeoId"), delegator) + || GeoWorker.containsGeo(excludeGeoGroup, postalAddress.getString("postalCodeGeoId"), delegator)) { return false; } } @@ -750,7 +750,7 @@ public final class ProductWorker { } catch (GenericEntityException e) { Debug.logWarning(e.getMessage(), MODULE); } - String isDigitalValue = (productType != null? productType.getString("isDigital"): null); + String isDigitalValue = (productType != null ? productType.getString("isDigital") : null); isDigital = isDigitalValue != null && "Y".equalsIgnoreCase(isDigitalValue); } return isDigital; @@ -765,7 +765,7 @@ public final class ProductWorker { } catch (GenericEntityException e) { Debug.logWarning(e.getMessage(), MODULE); } - String isPhysicalValue = (productType != null? productType.getString("isPhysical"): null); + String isPhysicalValue = (productType != null ? productType.getString("isPhysical") : null); isPhysical = isPhysicalValue != null && "Y".equalsIgnoreCase(isPhysicalValue); } return isPhysical; @@ -909,7 +909,7 @@ public final class ProductWorker { } public static List findProductsById(Delegator delegator, String idToFind, String goodIdentificationTypeId) - throws GenericEntityException { + throws GenericEntityException { return findProductsById(delegator, idToFind, goodIdentificationTypeId, true, false); } @@ -1051,7 +1051,7 @@ public final class ProductWorker { // find variant List productAssocs = EntityQuery.use(delegator).from("ProductAssoc").where("productId", productId, "productAssocTypeId", "PRODUCT_VARIANT").filterByDate().queryList(); boolean productFound = false; -nextProd: + nextProd: for (GenericValue productAssoc: productAssocs) { for (String featureId: selectedFeatures) { List pAppls = EntityQuery.use(delegator).from("ProductFeatureAppl").where("productId", productAssoc.getString("productIdTo"), "productFeatureId", featureId, "productFeatureApplTypeId", "STANDARD_FEATURE").cache(true).queryList(); @@ -1070,7 +1070,7 @@ nextProd: */ if (!productFound) { // copy product to be variant - GenericValue product = EntityQuery.use(delegator).from("Product").where("productId", productId).queryOne(); + GenericValue product = EntityQuery.use(delegator).from("Product").where("productId", productId).queryOne(); product.put("isVariant", "Y"); product.put("isVirtual", "N"); product.put("productId", delegator.getNextSeqId("Product")); @@ -1081,13 +1081,13 @@ nextProd: UtilMisc.toMap("productId", product.getString("productId"), "productFeatureApplTypeId", "STANDARD_FEATURE")); productFeatureAppl.put("fromDate", UtilDateTime.nowTimestamp()); for (String productFeatureId: selectedFeatures) { - productFeatureAppl.put("productFeatureId", productFeatureId); + productFeatureAppl.put("productFeatureId", productFeatureId); productFeatureAppl.create(); } //add standard features too List stdFeaturesAppls = EntityQuery.use(delegator).from("ProductFeatureAppl").where("productId", productId, "productFeatureApplTypeId", "STANDARD_FEATURE").filterByDate().queryList(); for (GenericValue stdFeaturesAppl: stdFeaturesAppls) { - stdFeaturesAppl.put("productId", product.getString("productId")); + stdFeaturesAppl.put("productId", product.getString("productId")); stdFeaturesAppl.create(); } /* 3. use the price of the virtual product(Entity:ProductPrice) as a basis and adjust according the prices in the feature price table. @@ -1110,7 +1110,7 @@ nextProd: if (productPrice.get("price") == null) { productPrice.put("price", productPrice.getBigDecimal("price")); } - productPrice.put("productId", product.getString("productId")); + productPrice.put("productId", product.getString("productId")); productPrice.create(); } // add the product association @@ -1123,7 +1123,7 @@ nextProd: List supplierProducts = EntityQuery.use(delegator).from("SupplierProduct").where("productId", productId).cache(true).queryList(); for (GenericValue supplierProduct: supplierProducts) { supplierProduct = (GenericValue) supplierProduct.clone(); - supplierProduct.set("productId", product.getString("productId")); + supplierProduct.set("productId", product.getString("productId")); supplierProduct.create(); } @@ -1131,7 +1131,7 @@ nextProd: List productContents = EntityQuery.use(delegator).from("ProductContent").where("productId", productId).cache(true).queryList(); for (GenericValue productContent: productContents) { productContent = (GenericValue) productContent.clone(); - productContent.set("productId", product.getString("productId")); + productContent.set("productId", product.getString("productId")); productContent.create(); } diff --git a/applications/product/src/main/java/org/apache/ofbiz/product/promo/PromoServices.java b/applications/product/src/main/java/org/apache/ofbiz/product/promo/PromoServices.java index 4e37388432..16a5c8b602 100644 --- a/applications/product/src/main/java/org/apache/ofbiz/product/promo/PromoServices.java +++ b/applications/product/src/main/java/org/apache/ofbiz/product/promo/PromoServices.java @@ -94,8 +94,7 @@ public class PromoServices { GenericValue existingPromoCode = null; try { existingPromoCode = EntityQuery.use(delegator).from("ProductPromoCode").where("productPromoCodeId", newPromoCodeId).cache().queryOne(); - } - catch (GenericEntityException e) { + } catch (GenericEntityException e) { Debug.logWarning("Could not find ProductPromoCode for just generated ID: " + newPromoCodeId, MODULE); } if (existingPromoCode == null) { diff --git a/applications/product/src/main/java/org/apache/ofbiz/product/subscription/SubscriptionServices.java b/applications/product/src/main/java/org/apache/ofbiz/product/subscription/SubscriptionServices.java index 55a4eedf7d..04d8afb8f7 100644 --- a/applications/product/src/main/java/org/apache/ofbiz/product/subscription/SubscriptionServices.java +++ b/applications/product/src/main/java/org/apache/ofbiz/product/subscription/SubscriptionServices.java @@ -326,9 +326,9 @@ public class SubscriptionServices { if (subscriptionList != null) { for (GenericValue subscription : subscriptionList) { - expirationCompletedDate = subscription.getTimestamp("expirationCompletedDate"); - if (expirationCompletedDate == null) { - Calendar currentDate = Calendar.getInstance(); + expirationCompletedDate = subscription.getTimestamp("expirationCompletedDate"); + if (expirationCompletedDate == null) { + Calendar currentDate = Calendar.getInstance(); currentDate.setTime(UtilDateTime.nowTimestamp()); // check if the thruDate + grace period (if provided) is earlier than today's date Calendar endDateSubscription = Calendar.getInstance(); @@ -377,10 +377,11 @@ public class SubscriptionServices { Debug.logInfo("Service mentioned in serviceNameOnExpiry called with result: " + ServiceUtil.makeSuccessMessage(result, "", "", "", ""), MODULE); } else if (result == null && subscriptionId != null) { Debug.logError("Subscription couldn't be expired for subscriptionId: " + subscriptionId, MODULE); - return ServiceUtil.returnError(UtilProperties.getMessage(RES_ERROR, "ProductSubscriptionCouldntBeExpired", UtilMisc.toMap("subscriptionId", subscriptionId), locale)); + return ServiceUtil.returnError(UtilProperties.getMessage(RES_ERROR, "ProductSubscriptionCouldntBeExpired", + UtilMisc.toMap("subscriptionId", subscriptionId), locale)); } } - } + } } } } catch (GenericServiceException e) { diff --git a/applications/product/src/main/java/org/apache/ofbiz/shipment/packing/PackingEvent.java b/applications/product/src/main/java/org/apache/ofbiz/shipment/packing/PackingEvent.java index a9e1003a60..9f2b2ccf61 100644 --- a/applications/product/src/main/java/org/apache/ofbiz/shipment/packing/PackingEvent.java +++ b/applications/product/src/main/java/org/apache/ofbiz/shipment/packing/PackingEvent.java @@ -20,16 +20,16 @@ package org.apache.ofbiz.shipment.packing; public interface PackingEvent extends java.io.Serializable { - public static final int EVENT_CODE_ADD = 1; - public static final int EVENT_CODE_EREG = 5; - public static final int EVENT_CODE_CLEAR = 20; - public static final int EVENT_CODE_COMPLETE = 100; + int EVENT_CODE_ADD = 1; + int EVENT_CODE_EREG = 5; + int EVENT_CODE_CLEAR = 20; + int EVENT_CODE_COMPLETE = 100; - public void runEvent(PackingSession session, int eventCode); + void runEvent(PackingSession session, int eventCode); - public String receiveMessage(); + String receiveMessage(); - public int getEventStatus(); + int getEventStatus(); - public int getEventCode(); + int getEventCode(); } diff --git a/applications/product/src/main/java/org/apache/ofbiz/shipment/packing/PackingServices.java b/applications/product/src/main/java/org/apache/ofbiz/shipment/packing/PackingServices.java index f6c2c7d1f0..5b31a1bdde 100644 --- a/applications/product/src/main/java/org/apache/ofbiz/shipment/packing/PackingServices.java +++ b/applications/product/src/main/java/org/apache/ofbiz/shipment/packing/PackingServices.java @@ -194,7 +194,7 @@ public class PackingServices { } } for (int numPackage = 0; numPackage < numPackages; numPackage++) { - session.addOrIncreaseLine(orderId, orderItemSeqId, shipGroupSeqId, prdStr, quantity, packageSeq+numPackage, weightSeq, updateQuantity); + session.addOrIncreaseLine(orderId, orderItemSeqId, shipGroupSeqId, prdStr, quantity, packageSeq + numPackage, weightSeq, updateQuantity); } } catch (GeneralException e) { Debug.logError(e, MODULE); diff --git a/applications/product/src/main/java/org/apache/ofbiz/shipment/packing/PackingSession.java b/applications/product/src/main/java/org/apache/ofbiz/shipment/packing/PackingSession.java index 641f0ffe7f..8c66eade58 100644 --- a/applications/product/src/main/java/org/apache/ofbiz/shipment/packing/PackingSession.java +++ b/applications/product/src/main/java/org/apache/ofbiz/shipment/packing/PackingSession.java @@ -238,11 +238,11 @@ public class PackingSession implements java.io.Serializable { public PackingSessionLine findLine(String orderId, String orderItemSeqId, String shipGroupSeqId, String productId, String inventoryItemId, int packageSeq) { for (PackingSessionLine line: this.getLines()) { if (orderId.equals(line.getOrderId()) - && orderItemSeqId.equals(line.getOrderItemSeqId()) - && shipGroupSeqId.equals(line.getShipGroupSeqId()) - && productId.equals(line.getProductId()) - && inventoryItemId.equals(line.getInventoryItemId()) - && packageSeq == line.getPackageSeq()) { + && orderItemSeqId.equals(line.getOrderItemSeqId()) + && shipGroupSeqId.equals(line.getShipGroupSeqId()) + && productId.equals(line.getProductId()) + && inventoryItemId.equals(line.getInventoryItemId()) + && packageSeq == line.getPackageSeq()) { return line; } } @@ -374,13 +374,13 @@ public class PackingSession implements java.io.Serializable { public Map getPackingSessionLinesByPackage() { Map> packageMap = new HashMap<>(); for (PackingSessionLine line : packLines) { - int pSeq = line.getPackageSeq(); - List packageLineList = packageMap.get(pSeq); - if (packageLineList == null) { - packageLineList = new LinkedList<>(); - packageMap.put(pSeq, packageLineList); - } - packageLineList.add(line); + int pSeq = line.getPackageSeq(); + List packageLineList = packageMap.get(pSeq); + if (packageLineList == null) { + packageLineList = new LinkedList<>(); + packageMap.put(pSeq, packageLineList); + } + packageLineList.add(line); } Object[] keys = packageMap.keySet().toArray(); java.util.Arrays.sort(keys); @@ -415,11 +415,11 @@ public class PackingSession implements java.io.Serializable { } public BigDecimal getPackedQuantity(String orderId, String orderItemSeqId, String shipGroupSeqId, String productId) { - return getPackedQuantity(orderId, orderItemSeqId, shipGroupSeqId, productId, null, -1); + return getPackedQuantity(orderId, orderItemSeqId, shipGroupSeqId, productId, null, -1); } public BigDecimal getPackedQuantity(String orderId, String orderItemSeqId, String shipGroupSeqId, String productId, int packageSeq) { - return getPackedQuantity(orderId, orderItemSeqId, shipGroupSeqId, productId, null, packageSeq); + return getPackedQuantity(orderId, orderItemSeqId, shipGroupSeqId, productId, null, packageSeq); } public BigDecimal getPackedQuantity(String orderId, String orderItemSeqId, String shipGroupSeqId, String productId, String inventoryItemId, int packageSeq) { @@ -735,7 +735,7 @@ public class PackingSession implements java.io.Serializable { lookupMap.put("shipGroupSeqId", shipGroupSeqId); } try { - issues = this.getDelegator().findByAnd("ItemIssuance", lookupMap, null, false); + issues = this.getDelegator().findByAnd("ItemIssuance", lookupMap, null, false); } catch (GenericEntityException e) { Debug.logError(e, MODULE); } @@ -801,7 +801,7 @@ public class PackingSession implements java.io.Serializable { List processedLines = new LinkedList<>(); for (PackingSessionLine line: this.getLines()) { if (this.checkLine(processedLines, line)) { - BigDecimal totalPacked = this.getPackedQuantity(line.getOrderId(), line.getOrderItemSeqId(), + BigDecimal totalPacked = this.getPackedQuantity(line.getOrderId(), line.getOrderItemSeqId(), line.getShipGroupSeqId(), line.getProductId(), line.getInventoryItemId(), -1); line.issueItemToShipment(shipmentId, picklistBinId, userLogin, totalPacked, getDispatcher()); diff --git a/applications/product/src/main/java/org/apache/ofbiz/shipment/shipment/ShipmentServices.java b/applications/product/src/main/java/org/apache/ofbiz/shipment/shipment/ShipmentServices.java index d750705180..c9b453bc64 100644 --- a/applications/product/src/main/java/org/apache/ofbiz/shipment/shipment/ShipmentServices.java +++ b/applications/product/src/main/java/org/apache/ofbiz/shipment/shipment/ShipmentServices.java @@ -401,12 +401,12 @@ public class ShipmentServices { } // Calculate priority based on available data. - double PRIORITY_PARTY = 9; - double PRIORITY_ROLE = 8; - double PRIORITY_GEO = 4; - double PRIORITY_WEIGHT = 1; - double PRIORITY_QTY = 1; - double PRIORITY_PRICE = 1; + double priorityParty = 9; + double priorityRole = 8; + double priorityGeo = 4; + double priorityWeight = 1; + double priorityQty = 1; + double priorityPrice = 1; int estimateIndex = 0; @@ -416,22 +416,22 @@ public class ShipmentServices { for (GenericValue currentEstimate: estimateList) { int prioritySum = 0; if (UtilValidate.isNotEmpty(currentEstimate.getString("partyId"))) { - prioritySum += PRIORITY_PARTY; + prioritySum += priorityParty; } if (UtilValidate.isNotEmpty(currentEstimate.getString("roleTypeId"))) { - prioritySum += PRIORITY_ROLE; + prioritySum += priorityRole; } if (UtilValidate.isNotEmpty(currentEstimate.getString("geoIdTo"))) { - prioritySum += PRIORITY_GEO; + prioritySum += priorityGeo; } if (UtilValidate.isNotEmpty(currentEstimate.getString("weightBreakId"))) { - prioritySum += PRIORITY_WEIGHT; + prioritySum += priorityWeight; } if (UtilValidate.isNotEmpty(currentEstimate.getString("quantityBreakId"))) { - prioritySum += PRIORITY_QTY; + prioritySum += priorityQty; } if (UtilValidate.isNotEmpty(currentEstimate.getString("priceBreakId"))) { - prioritySum += PRIORITY_PRICE; + prioritySum += priorityPrice; } // there will be only one of each priority; latest will replace @@ -684,10 +684,12 @@ public class ShipmentServices { if ("00001".equals(packageSeqId)) { // only need to do this for the first package GenericValue rtSeg = null; - rtSeg = EntityQuery.use(delegator).from("ShipmentRouteSegment").where("shipmentId", shipmentId, "shipmentRouteSegmentId", "00001").queryOne(); + rtSeg = EntityQuery.use(delegator).from("ShipmentRouteSegment").where("shipmentId", shipmentId, "shipmentRouteSegmentId", + "00001").queryOne(); if (rtSeg == null) { - rtSeg = delegator.makeValue("ShipmentRouteSegment", UtilMisc.toMap("shipmentId", shipmentId, "shipmentRouteSegmentId", "00001")); + rtSeg = delegator.makeValue("ShipmentRouteSegment", UtilMisc.toMap("shipmentId", shipmentId, "shipmentRouteSegmentId", + "00001")); try { delegator.create(rtSeg); } catch (GenericEntityException e) { @@ -700,7 +702,7 @@ public class ShipmentServices { rtSeg.set("billingWeight", pkgInfo.get("billingWeight")); rtSeg.set("actualCost", pkgInfo.get("shippingTotal")); rtSeg.set("trackingIdNumber", pkgInfo.get("trackingNumber")); - delegator.store(rtSeg); + delegator.store(rtSeg); } Map pkgCtx = new HashMap<>(); @@ -709,24 +711,22 @@ public class ShipmentServices { // first update the weight of the package GenericValue pkg = null; - pkg = EntityQuery.use(delegator).from("ShipmentPackage") - .where(pkgCtx) - .queryOne(); + pkg = EntityQuery.use(delegator).from("ShipmentPackage").where(pkgCtx).queryOne(); if (pkg == null) { return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, - "ProductShipmentPackageNotFound", - UtilMisc.toMap("shipmentPackageSeqId", packageSeqId, - "shipmentId", shipmentId), locale)); + "ProductShipmentPackageNotFound", + UtilMisc.toMap("shipmentPackageSeqId", packageSeqId, + "shipmentId", shipmentId), locale)); } pkg.set("weight", pkgInfo.get("packageWeight")); - delegator.store(pkg); + delegator.store(pkg); // need if we are the first package (only) update the route seg info pkgCtx.put("shipmentRouteSegmentId", "00001"); GenericValue pkgRtSeg = null; - pkgRtSeg = EntityQuery.use(delegator).from("ShipmentPackageRouteSeg").where(pkgCtx).queryOne(); + pkgRtSeg = EntityQuery.use(delegator).from("ShipmentPackageRouteSeg").where(pkgCtx).queryOne(); if (pkgRtSeg == null) { pkgRtSeg = delegator.makeValue("ShipmentPackageRouteSeg", pkgCtx); diff --git a/applications/product/src/main/java/org/apache/ofbiz/shipment/thirdparty/dhl/DhlServices.java b/applications/product/src/main/java/org/apache/ofbiz/shipment/thirdparty/dhl/DhlServices.java index fff4d271d4..5e61b1bd4f 100644 --- a/applications/product/src/main/java/org/apache/ofbiz/shipment/thirdparty/dhl/DhlServices.java +++ b/applications/product/src/main/java/org/apache/ofbiz/shipment/thirdparty/dhl/DhlServices.java @@ -207,8 +207,7 @@ public class DhlServices { return ServiceUtil.returnError(UtilProperties.getMessage(RES_ERROR, "FacilityShipmentUnableFoundShipToAddresss", locale)); } - } - catch (GenericEntityException e) { + } catch (GenericEntityException e) { Debug.logError(e, MODULE); } } @@ -595,7 +594,7 @@ public class DhlServices { if ((billingWeight != null) && (billingWeight.compareTo(BigDecimal.ZERO) > 0)) { hasBillingWeight = true; if (billingWeightUomId == null) { - Debug.logWarning("Shipment Route Segment missing billingWeightUomId in shipmentId " + shipmentId, MODULE); + Debug.logWarning("Shipment Route Segment missing billingWeightUomId in shipmentId " + shipmentId, MODULE); billingWeightUomId = "WT_lb"; // TODO: this should be specified in a properties file } // convert @@ -637,7 +636,7 @@ public class DhlServices { // convert weight String weightUomId = (String) shipmentPackage.get("weightUomId"); if (weightUomId == null) { - Debug.logWarning("Shipment Route Segment missing weightUomId in shipmentId " + shipmentId, MODULE); + Debug.logWarning("Shipment Route Segment missing weightUomId in shipmentId " + shipmentId, MODULE); weightUomId = "WT_lb"; // TODO: this should be specified in a properties file } results = dispatcher.runSync("convertUom", UtilMisc.toMap("uomId", weightUomId, "uomIdTo", DHL_WEIGHT_UOM_ID, "originalValue", packageWeight)); diff --git a/applications/product/src/main/java/org/apache/ofbiz/shipment/thirdparty/fedex/FedexServices.java b/applications/product/src/main/java/org/apache/ofbiz/shipment/thirdparty/fedex/FedexServices.java index b3d87d379b..fb6599fbc8 100644 --- a/applications/product/src/main/java/org/apache/ofbiz/shipment/thirdparty/fedex/FedexServices.java +++ b/applications/product/src/main/java/org/apache/ofbiz/shipment/thirdparty/fedex/FedexServices.java @@ -763,7 +763,7 @@ public class FedexServices { if ((billingWeight != null) && (billingWeight.compareTo(BigDecimal.ZERO) > 0)) { hasBillingWeight = true; if (billingWeightUomId == null) { - Debug.logWarning("Shipment Route Segment missing billingWeightUomId in shipmentId " + shipmentId + ", assuming default shipment.fedex.weightUomId of " + weightUomId + " from " + shipmentPropertiesFile, MODULE); + Debug.logWarning("Shipment Route Segment missing billingWeightUomId in shipmentId " + shipmentId + ", assuming default shipment.fedex.weightUomId of " + weightUomId + " from " + shipmentPropertiesFile, MODULE); billingWeightUomId = weightUomId; } @@ -830,7 +830,7 @@ public class FedexServices { if (!UtilValidate.isEmpty(boxDimensionsUom)) { boxDimensionsUomId = boxDimensionsUom.getString("uomId"); } else { - Debug.logWarning("Packaging type for package " + shipmentPackage.getString("shipmentPackageSeqId") + " of shipmentRouteSegment " + shipmentRouteSegmentId + " of shipment " + shipmentId + " is missing dimensionUomId, assuming default shipment.default.dimension.uom of " + dimensionsUomId + " from " + shipmentPropertiesFile, MODULE); + Debug.logWarning("Packaging type for package " + shipmentPackage.getString("shipmentPackageSeqId") + " of shipmentRouteSegment " + shipmentRouteSegmentId + " of shipment " + shipmentId + " is missing dimensionUomId, assuming default shipment.default.dimension.uom of " + dimensionsUomId + " from " + shipmentPropertiesFile, MODULE); boxDimensionsUomId = dimensionsUomId; } if (dimensionsLength != null && dimensionsLength.compareTo(BigDecimal.ZERO) > 0) { @@ -890,7 +890,7 @@ public class FedexServices { // Convert weight if necessary String packageWeightUomId = shipmentPackage.getString("weightUomId"); if (UtilValidate.isEmpty(packageWeightUomId)) { - Debug.logWarning("Shipment Route Segment missing weightUomId in shipmentId " + shipmentId + ", assuming shipment.default.weight.uom of " + weightUomId + " from " + shipmentPropertiesFile, MODULE); + Debug.logWarning("Shipment Route Segment missing weightUomId in shipmentId " + shipmentId + ", assuming shipment.default.weight.uom of " + weightUomId + " from " + shipmentPropertiesFile, MODULE); packageWeightUomId = weightUomId; } if (!packageWeightUomId.equals(weightUomId)) { @@ -914,17 +914,18 @@ public class FedexServices { } // Populate the Freemarker context with package-related information - shipRequestContext.put("CustomerReference", shipmentId + ":" + shipmentRouteSegmentId + ":" + shipmentPackage.getString("shipmentPackageSeqId")); + shipRequestContext.put("CustomerReference", shipmentId + ":" + shipmentRouteSegmentId + ":" + shipmentPackage.getString( + "shipmentPackageSeqId")); shipRequestContext.put("DropoffType", dropoffType); shipRequestContext.put("Packaging", packaging); if (UtilValidate.isNotEmpty(dimensionsUomId) - && dimensionsLength != null && dimensionsLength.setScale(0, RoundingMode.HALF_UP).compareTo(BigDecimal.ZERO) > 0 - && dimensionsWidth != null && dimensionsWidth.setScale(0, RoundingMode.HALF_UP).compareTo(BigDecimal.ZERO) > 0 - && dimensionsHeight != null && dimensionsHeight.setScale(0, RoundingMode.HALF_UP).compareTo(BigDecimal.ZERO) > 0) { - shipRequestContext.put("DimensionsUnits", "LEN_in".equals(dimensionsUomId) ? "IN" : "CM"); - shipRequestContext.put("DimensionsLength", dimensionsLength.setScale(0, RoundingMode.HALF_UP).toString()); - shipRequestContext.put("DimensionsWidth", dimensionsWidth.setScale(0, RoundingMode.HALF_UP).toString()); - shipRequestContext.put("DimensionsHeight", dimensionsHeight.setScale(0, RoundingMode.HALF_UP).toString()); + && dimensionsLength != null && dimensionsLength.setScale(0, RoundingMode.HALF_UP).compareTo(BigDecimal.ZERO) > 0 + && dimensionsWidth != null && dimensionsWidth.setScale(0, RoundingMode.HALF_UP).compareTo(BigDecimal.ZERO) > 0 + && dimensionsHeight != null && dimensionsHeight.setScale(0, RoundingMode.HALF_UP).compareTo(BigDecimal.ZERO) > 0) { + shipRequestContext.put("DimensionsUnits", "LEN_in".equals(dimensionsUomId) ? "IN" : "CM"); + shipRequestContext.put("DimensionsLength", dimensionsLength.setScale(0, RoundingMode.HALF_UP).toString()); + shipRequestContext.put("DimensionsWidth", dimensionsWidth.setScale(0, RoundingMode.HALF_UP).toString()); + shipRequestContext.put("DimensionsHeight", dimensionsHeight.setScale(0, RoundingMode.HALF_UP).toString()); } shipRequestContext.put("Weight", weight.setScale(1, RoundingMode.UP).toString()); } @@ -936,7 +937,7 @@ public class FedexServices { String errorMessage = "Cannot confirm Fedex shipment: Failed to render Fedex XML Ship Request Template [" + templateLocation + "]."; Debug.logError(e, errorMessage, MODULE); return ServiceUtil.returnError(UtilProperties.getMessage(RES_ERROR, - "FacilityShipmentFedexShipmentTemplateError", + "FacilityShipmentFedexShipmentTemplateError", UtilMisc.toMap("templateLocation", templateLocation, "errorString", e.getMessage()), locale)); } diff --git a/applications/product/src/main/java/org/apache/ofbiz/shipment/thirdparty/ups/UpsServices.java b/applications/product/src/main/java/org/apache/ofbiz/shipment/thirdparty/ups/UpsServices.java index 7bca6584b6..7fe51abb2a 100644 --- a/applications/product/src/main/java/org/apache/ofbiz/shipment/thirdparty/ups/UpsServices.java +++ b/applications/product/src/main/java/org/apache/ofbiz/shipment/thirdparty/ups/UpsServices.java @@ -92,7 +92,7 @@ public class UpsServices { static { UPS_TO_OFBIZ.put("LBS", "WT_lb"); UPS_TO_OFBIZ.put("KGS", "WT_kg"); - for (Map.Entry entry: UPS_TO_OFBIZ.entrySet()) { + for (Map.Entry entry : UPS_TO_OFBIZ.entrySet()) { OFBIZ_TO_UPS.put(entry.getValue(), entry.getKey()); } } @@ -111,8 +111,10 @@ public class UpsServices { if (UtilValidate.isEmpty(shipmentGatewayConfigId) && UtilValidate.isEmpty(resource)) { return ServiceUtil.returnError(UtilProperties.getMessage(RES_ERROR, "FacilityShipmentUpsGatewayNotAvailable", locale)); } - boolean shipmentUpsSaveCertificationInfo = "true".equals(getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "saveCertInfo", resource, "shipment.ups.save.certification.info", "true")); - String shipmentUpsSaveCertificationPath = FlexibleStringExpander.expandString(getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "saveCertPath", resource, "shipment.ups.save.certification.path", ""), context); + boolean shipmentUpsSaveCertificationInfo = "true".equals(getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "saveCertInfo", + resource, "shipment.ups.save.certification.info", "true")); + String shipmentUpsSaveCertificationPath = FlexibleStringExpander.expandString(getShipmentGatewayConfigValue(delegator, + shipmentGatewayConfigId, "saveCertPath", resource, "shipment.ups.save.certification.path", ""), context); File shipmentUpsSaveCertificationFile = null; if (shipmentUpsSaveCertificationInfo) { shipmentUpsSaveCertificationFile = new File(shipmentUpsSaveCertificationPath); @@ -128,7 +130,8 @@ public class UpsServices { if (shipment == null) { return ServiceUtil.returnError(UtilProperties.getMessage(RES_ERROR, "ProductShipmentNotFoundId", locale) + " " + shipmentId); } - GenericValue shipmentRouteSegment = EntityQuery.use(delegator).from("ShipmentRouteSegment").where("shipmentId", shipmentId, "shipmentRouteSegmentId", shipmentRouteSegmentId).queryOne(); + GenericValue shipmentRouteSegment = EntityQuery.use(delegator).from("ShipmentRouteSegment").where("shipmentId", shipmentId, + "shipmentRouteSegmentId", shipmentRouteSegmentId).queryOne(); if (shipmentRouteSegment == null) { return ServiceUtil.returnError(UtilProperties.getMessage(RES_ERROR, "ProductShipmentRouteSegmentNotFound", UtilMisc.toMap("shipmentId", shipmentId, "shipmentRouteSegmentId", shipmentRouteSegmentId), locale)); @@ -142,7 +145,8 @@ public class UpsServices { // add ShipmentRouteSegment carrierServiceStatusId, check before all UPS services if (UtilValidate.isNotEmpty(shipmentRouteSegment.getString("carrierServiceStatusId")) && !"SHRSCS_NOT_STARTED".equals(shipmentRouteSegment.getString("carrierServiceStatusId"))) { return ServiceUtil.returnError(UtilProperties.getMessage(RES_ERROR, "FacilityShipmentUpsRouteSegmentStatusNotStarted", - UtilMisc.toMap("shipmentRouteSegmentId", shipmentRouteSegmentId, "shipmentId", shipmentId, "shipmentRouteSegmentStatus", shipmentRouteSegment.getString("carrierServiceStatusId")), locale)); + UtilMisc.toMap("shipmentRouteSegmentId", shipmentRouteSegmentId, "shipmentId", shipmentId, "shipmentRouteSegmentStatus", + shipmentRouteSegment.getString("carrierServiceStatusId")), locale)); } // Get Origin Info @@ -179,7 +183,8 @@ public class UpsServices { GenericValue destTelecomNumber = shipmentRouteSegment.getRelatedOne("DestTelecomNumber", false); if (destTelecomNumber == null) { - String missingErrMsg = "DestTelecomNumber not found for ShipmentRouteSegment with shipmentId " + shipmentId + " and shipmentRouteSegmentId " + shipmentRouteSegmentId; + String missingErrMsg = "DestTelecomNumber not found for ShipmentRouteSegment with shipmentId " + shipmentId + " and " + + "shipmentRouteSegmentId " + shipmentRouteSegmentId; Debug.logError(missingErrMsg, MODULE); // for now we won't require the dest phone number, but is it required? } @@ -201,13 +206,18 @@ public class UpsServices { UtilMisc.toMap("shipmentId", shipmentId, "shipmentRouteSegmentId", shipmentRouteSegmentId), locale)); } - GenericValue carrierShipmentMethod = EntityQuery.use(delegator).from("CarrierShipmentMethod").where("partyId", shipmentRouteSegment.get("carrierPartyId"), "roleTypeId", "CARRIER", "shipmentMethodTypeId", shipmentRouteSegment.get("shipmentMethodTypeId")).queryOne(); + GenericValue carrierShipmentMethod = EntityQuery.use(delegator).from("CarrierShipmentMethod").where("partyId", + shipmentRouteSegment.get("carrierPartyId"), "roleTypeId", "CARRIER", "shipmentMethodTypeId", shipmentRouteSegment.get( + "shipmentMethodTypeId")).queryOne(); if (carrierShipmentMethod == null) { return ServiceUtil.returnError(UtilProperties.getMessage(RES_ERROR, "FacilityShipmentUpsRouteSegmentCarrierShipmentMethodNotFound", - UtilMisc.toMap("shipmentId", shipmentId, "shipmentRouteSegmentId", shipmentRouteSegmentId, "carrierPartyId", shipmentRouteSegment.get("carrierPartyId"), "shipmentMethodTypeId", shipmentRouteSegment.get("shipmentMethodTypeId")), locale)); + UtilMisc.toMap("shipmentId", shipmentId, "shipmentRouteSegmentId", shipmentRouteSegmentId, "carrierPartyId", + shipmentRouteSegment.get("carrierPartyId"), "shipmentMethodTypeId", shipmentRouteSegment.get("shipmentMethodTypeId")), + locale)); } - List shipmentPackageRouteSegs = shipmentRouteSegment.getRelated("ShipmentPackageRouteSeg", null, UtilMisc.toList("+shipmentPackageSeqId"), false); + List shipmentPackageRouteSegs = shipmentRouteSegment.getRelated("ShipmentPackageRouteSeg", null, UtilMisc.toList( + "+shipmentPackageSeqId"), false); if (UtilValidate.isEmpty(shipmentPackageRouteSegs)) { return ServiceUtil.returnError(UtilProperties.getMessage(RES_ERROR, "FacilityShipmentPackageRouteSegsNotFound", UtilMisc.toMap("shipmentId", shipmentId, "shipmentRouteSegmentId", shipmentRouteSegmentId), locale)); @@ -215,14 +225,14 @@ public class UpsServices { List itemIssuances = shipment.getRelated("ItemIssuance", null, null, false); Set orderIdSet = new TreeSet<>(); - for (GenericValue itemIssuance: itemIssuances) { + for (GenericValue itemIssuance : itemIssuances) { orderIdSet.add(itemIssuance.getString("orderId")); } String ordersDescription = ""; if (orderIdSet.size() > 1) { StringBuilder odBuf = new StringBuilder(UtilProperties.getMessage(RES_ORDER, "OrderOrders", locale) + " "); - for (String orderId: orderIdSet) { + for (String orderId : orderIdSet) { if (odBuf.length() > 0) { odBuf.append(", "); } @@ -234,14 +244,15 @@ public class UpsServices { } // COD Support - boolean allowCOD = "true".equalsIgnoreCase(getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "codAllowCod", resource, "shipment.ups.cod.allowCOD", "true")); + boolean allowCOD = "true".equalsIgnoreCase(getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "codAllowCod", resource, + "shipment.ups.cod.allowCOD", "true")); // COD only applies if all orders involved with the shipment were paid only with EXT_COD - anything else becomes too complicated if (allowCOD) { // Get the paymentMethodTypeIds of all the orderPaymentPreferences involved with the shipment List opps = EntityQuery.use(delegator).from("OrderPaymentPreference") - .where(EntityCondition.makeCondition("orderId", EntityOperator.IN, orderIdSet)).queryList(); + .where(EntityCondition.makeCondition("orderId", EntityOperator.IN, orderIdSet)).queryList(); List paymentMethodTypeIds = EntityUtil.getFieldListFromEntityList(opps, "paymentMethodTypeId", true); if (paymentMethodTypeIds.size() > 1 || !paymentMethodTypeIds.contains("EXT_COD")) { @@ -261,19 +272,25 @@ public class UpsServices { BigDecimal codSurchargePackageAmount = null; if (allowCOD) { - codSurchargeAmount = getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "codSurchargeAmount", resource, "shipment.ups.cod.surcharge.amount", ""); + codSurchargeAmount = getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "codSurchargeAmount", resource, "shipment" + + ".ups.cod.surcharge.amount", ""); if (UtilValidate.isEmpty(codSurchargeAmount)) { - return ServiceUtil.returnError(UtilProperties.getMessage(RES_ERROR, "FacilityShipmentUpsSurchargeAmountIsNotConfigurated", locale)); + return ServiceUtil.returnError(UtilProperties.getMessage(RES_ERROR, "FacilityShipmentUpsSurchargeAmountIsNotConfigurated", + locale)); } - codSurchargeCurrencyUomId = getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "codSurchargeCurrencyUomId", resource, "shipment.ups.cod.surcharge.currencyUomId", ""); + codSurchargeCurrencyUomId = getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "codSurchargeCurrencyUomId", resource + , "shipment.ups.cod.surcharge.currencyUomId", ""); if (UtilValidate.isEmpty(codSurchargeCurrencyUomId)) { - return ServiceUtil.returnError(UtilProperties.getMessage(RES_ERROR, "FacilityShipmentUpsSurchargeCurrencyIsNotConfigurated", locale)); + return ServiceUtil.returnError(UtilProperties.getMessage(RES_ERROR, "FacilityShipmentUpsSurchargeCurrencyIsNotConfigurated", + locale)); } - String codSurchargeApplyToPackages = getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "codSurchargeApplyToPackage", resource, "shipment.ups.cod.surcharge.applyToPackages", ""); + String codSurchargeApplyToPackages = getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "codSurchargeApplyToPackage" + , resource, "shipment.ups.cod.surcharge.applyToPackages", ""); if (UtilValidate.isEmpty(codSurchargeApplyToPackages)) { return ServiceUtil.returnError(UtilProperties.getMessage(RES_ERROR, "FacilityShipmentUpsApplyToPackagesIsNotConfigured", locale)); } - codFundsCode = getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "codFundsCode", resource, "shipment.ups.cod.codFundsCode", ""); + codFundsCode = getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "codFundsCode", resource, "shipment.ups.cod" + + ".codFundsCode", ""); if (UtilValidate.isEmpty(codFundsCode)) { return ServiceUtil.returnError(UtilProperties.getMessage(RES_ERROR, "FacilityShipmentUpsCodFundsCodeIsNotConfigured", locale)); } @@ -299,7 +316,8 @@ public class UpsServices { } } - // Determine the currency by trying the shipmentRouteSegment, then the Shipment, then the framework's default currency, and finally default to USD + // Determine the currency by trying the shipmentRouteSegment, then the Shipment, then the framework's default currency, and finally + // default to USD String currencyCode = null; if (UtilValidate.isNotEmpty(shipmentRouteSegment.getString("currencyUomId"))) { currencyCode = shipmentRouteSegment.getString("currencyUomId"); @@ -325,7 +343,8 @@ public class UpsServices { UtilXml.addChildElementValue(requestElement, "RequestOption", "nonvalidate", shipmentConfirmRequestDoc); // Top Level Element: LabelSpecification - Element labelSpecificationElement = UtilXml.addChildElement(shipmentConfirmRequestElement, "LabelSpecification", shipmentConfirmRequestDoc); + Element labelSpecificationElement = UtilXml.addChildElement(shipmentConfirmRequestElement, "LabelSpecification", + shipmentConfirmRequestDoc); Element labelPrintMethodElement = UtilXml.addChildElement(labelSpecificationElement, "LabelPrintMethod", shipmentConfirmRequestDoc); UtilXml.addChildElementValue(labelPrintMethodElement, "Code", "GIF", shipmentConfirmRequestDoc); @@ -337,41 +356,52 @@ public class UpsServices { // Top Level Element: Shipment Element shipmentElement = UtilXml.addChildElement(shipmentConfirmRequestElement, "Shipment", shipmentConfirmRequestDoc); - UtilXml.addChildElementValue(shipmentElement, "Description", "Goods for Shipment " + shipment.get("shipmentId") + " from " + ordersDescription, shipmentConfirmRequestDoc); + UtilXml.addChildElementValue(shipmentElement, "Description", + "Goods for Shipment " + shipment.get("shipmentId") + " from " + ordersDescription, shipmentConfirmRequestDoc); // Child of Shipment: Shipper - String shipperNumber = getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "shipperNumber", resource, "shipment.ups.shipper.number", ""); + String shipperNumber = getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "shipperNumber", resource, "shipment.ups" + + ".shipper.number", ""); Element shipperElement = UtilXml.addChildElement(shipmentElement, "Shipper", shipmentConfirmRequestDoc); - UtilXml.addChildElementValue(shipperElement, "Name", UtilValidate.isNotEmpty(originPostalAddress.getString("toName")) ? originPostalAddress.getString("toName") : "", shipmentConfirmRequestDoc); - UtilXml.addChildElementValue(shipperElement, "AttentionName", UtilValidate.isNotEmpty(originPostalAddress.getString("attnName")) ? originPostalAddress.getString("attnName") : "", shipmentConfirmRequestDoc); + UtilXml.addChildElementValue(shipperElement, "Name", UtilValidate.isNotEmpty(originPostalAddress.getString("toName")) ? + originPostalAddress.getString("toName") : "", shipmentConfirmRequestDoc); + UtilXml.addChildElementValue(shipperElement, "AttentionName", UtilValidate.isNotEmpty(originPostalAddress.getString("attnName")) ? + originPostalAddress.getString("attnName") : "", shipmentConfirmRequestDoc); UtilXml.addChildElementValue(shipperElement, "PhoneNumber", originPhoneNumber, shipmentConfirmRequestDoc); UtilXml.addChildElementValue(shipperElement, "ShipperNumber", shipperNumber, shipmentConfirmRequestDoc); Element shipperAddressElement = UtilXml.addChildElement(shipperElement, "Address", shipmentConfirmRequestDoc); UtilXml.addChildElementValue(shipperAddressElement, "AddressLine1", originPostalAddress.getString("address1"), shipmentConfirmRequestDoc); if (UtilValidate.isNotEmpty(originPostalAddress.getString("address2"))) { - UtilXml.addChildElementValue(shipperAddressElement, "AddressLine2", originPostalAddress.getString("address2"), shipmentConfirmRequestDoc); + UtilXml.addChildElementValue(shipperAddressElement, "AddressLine2", originPostalAddress.getString("address2"), + shipmentConfirmRequestDoc); } UtilXml.addChildElementValue(shipperAddressElement, "City", originPostalAddress.getString("city"), shipmentConfirmRequestDoc); - UtilXml.addChildElementValue(shipperAddressElement, "StateProvinceCode", originPostalAddress.getString("stateProvinceGeoId"), shipmentConfirmRequestDoc); + UtilXml.addChildElementValue(shipperAddressElement, "StateProvinceCode", originPostalAddress.getString("stateProvinceGeoId"), + shipmentConfirmRequestDoc); UtilXml.addChildElementValue(shipperAddressElement, "PostalCode", originPostalAddress.getString("postalCode"), shipmentConfirmRequestDoc); UtilXml.addChildElementValue(shipperAddressElement, "CountryCode", originCountryGeo.getString("geoCode"), shipmentConfirmRequestDoc); - // How to determine this? Add to data model...? UtilXml.addChildElement(shipperAddressElement, "ResidentialAddress", shipmentConfirmRequestDoc); + // How to determine this? Add to data model...? UtilXml.addChildElement(shipperAddressElement, "ResidentialAddress", + // shipmentConfirmRequestDoc); // Child of Shipment: ShipTo Element shipToElement = UtilXml.addChildElement(shipmentElement, "ShipTo", shipmentConfirmRequestDoc); - UtilXml.addChildElementValue(shipToElement, "CompanyName", UtilValidate.isNotEmpty(destPostalAddress.getString("toName")) ? destPostalAddress.getString("toName") : "", shipmentConfirmRequestDoc); - UtilXml.addChildElementValue(shipToElement, "AttentionName", UtilValidate.isNotEmpty(destPostalAddress.getString("attnName")) ? destPostalAddress.getString("attnName") : "", shipmentConfirmRequestDoc); + UtilXml.addChildElementValue(shipToElement, "CompanyName", UtilValidate.isNotEmpty(destPostalAddress.getString("toName")) ? + destPostalAddress.getString("toName") : "", shipmentConfirmRequestDoc); + UtilXml.addChildElementValue(shipToElement, "AttentionName", UtilValidate.isNotEmpty(destPostalAddress.getString("attnName")) ? + destPostalAddress.getString("attnName") : "", shipmentConfirmRequestDoc); if (UtilValidate.isNotEmpty(destPhoneNumber)) { UtilXml.addChildElementValue(shipToElement, "PhoneNumber", destPhoneNumber, shipmentConfirmRequestDoc); } Element shipToAddressElement = UtilXml.addChildElement(shipToElement, "Address", shipmentConfirmRequestDoc); UtilXml.addChildElementValue(shipToAddressElement, "AddressLine1", destPostalAddress.getString("address1"), shipmentConfirmRequestDoc); if (UtilValidate.isNotEmpty(destPostalAddress.getString("address2"))) { - UtilXml.addChildElementValue(shipToAddressElement, "AddressLine2", destPostalAddress.getString("address2"), shipmentConfirmRequestDoc); + UtilXml.addChildElementValue(shipToAddressElement, "AddressLine2", destPostalAddress.getString("address2"), + shipmentConfirmRequestDoc); } UtilXml.addChildElementValue(shipToAddressElement, "City", destPostalAddress.getString("city"), shipmentConfirmRequestDoc); - UtilXml.addChildElementValue(shipToAddressElement, "StateProvinceCode", destPostalAddress.getString("stateProvinceGeoId"), shipmentConfirmRequestDoc); + UtilXml.addChildElementValue(shipToAddressElement, "StateProvinceCode", destPostalAddress.getString("stateProvinceGeoId"), + shipmentConfirmRequestDoc); UtilXml.addChildElementValue(shipToAddressElement, "PostalCode", destPostalAddress.getString("postalCode"), shipmentConfirmRequestDoc); UtilXml.addChildElementValue(shipToAddressElement, "CountryCode", destCountryGeo.getString("geoCode"), shipmentConfirmRequestDoc); if (UtilValidate.isNotEmpty(shipmentRouteSegment.getString("homeDeliveryType"))) { @@ -384,29 +414,37 @@ public class UpsServices { UtilXml.addChildElementValue(shipFromElement, "AttentionName", originPostalAddress.getString("attnName"), shipmentConfirmRequestDoc); UtilXml.addChildElementValue(shipFromElement, "PhoneNumber", originPhoneNumber, shipmentConfirmRequestDoc); Element shipFromAddressElement = UtilXml.addChildElement(shipFromElement, "Address", shipmentConfirmRequestDoc); - UtilXml.addChildElementValue(shipFromAddressElement, "AddressLine1", originPostalAddress.getString("address1"), shipmentConfirmRequestDoc); + UtilXml.addChildElementValue(shipFromAddressElement, "AddressLine1", originPostalAddress.getString("address1"), + shipmentConfirmRequestDoc); if (UtilValidate.isNotEmpty(originPostalAddress.getString("address2"))) { - UtilXml.addChildElementValue(shipFromAddressElement, "AddressLine2", originPostalAddress.getString("address2"), shipmentConfirmRequestDoc); + UtilXml.addChildElementValue(shipFromAddressElement, "AddressLine2", originPostalAddress.getString("address2"), + shipmentConfirmRequestDoc); } UtilXml.addChildElementValue(shipFromAddressElement, "City", originPostalAddress.getString("city"), shipmentConfirmRequestDoc); - UtilXml.addChildElementValue(shipFromAddressElement, "StateProvinceCode", originPostalAddress.getString("stateProvinceGeoId"), shipmentConfirmRequestDoc); - UtilXml.addChildElementValue(shipFromAddressElement, "PostalCode", originPostalAddress.getString("postalCode"), shipmentConfirmRequestDoc); + UtilXml.addChildElementValue(shipFromAddressElement, "StateProvinceCode", originPostalAddress.getString("stateProvinceGeoId"), + shipmentConfirmRequestDoc); + UtilXml.addChildElementValue(shipFromAddressElement, "PostalCode", originPostalAddress.getString("postalCode"), + shipmentConfirmRequestDoc); UtilXml.addChildElementValue(shipFromAddressElement, "CountryCode", originCountryGeo.getString("geoCode"), shipmentConfirmRequestDoc); // Child of Shipment: SoldTo Element soldToElement = UtilXml.addChildElement(shipmentElement, "SoldTo", shipmentConfirmRequestDoc); - UtilXml.addChildElementValue(soldToElement, "CompanyName", UtilValidate.isNotEmpty(destPostalAddress.getString("toName")) ? destPostalAddress.getString("toName") : "", shipmentConfirmRequestDoc); - UtilXml.addChildElementValue(soldToElement, "AttentionName", UtilValidate.isNotEmpty(destPostalAddress.getString("attnName")) ? destPostalAddress.getString("attnName") : "", shipmentConfirmRequestDoc); + UtilXml.addChildElementValue(soldToElement, "CompanyName", UtilValidate.isNotEmpty(destPostalAddress.getString("toName")) ? + destPostalAddress.getString("toName") : "", shipmentConfirmRequestDoc); + UtilXml.addChildElementValue(soldToElement, "AttentionName", UtilValidate.isNotEmpty(destPostalAddress.getString("attnName")) ? + destPostalAddress.getString("attnName") : "", shipmentConfirmRequestDoc); if (UtilValidate.isNotEmpty(destPhoneNumber)) { UtilXml.addChildElementValue(soldToElement, "PhoneNumber", destPhoneNumber, shipmentConfirmRequestDoc); } Element soldToAddressElement = UtilXml.addChildElement(soldToElement, "Address", shipmentConfirmRequestDoc); UtilXml.addChildElementValue(soldToAddressElement, "AddressLine1", destPostalAddress.getString("address1"), shipmentConfirmRequestDoc); if (UtilValidate.isNotEmpty(destPostalAddress.getString("address2"))) { - UtilXml.addChildElementValue(soldToAddressElement, "AddressLine2", destPostalAddress.getString("address2"), shipmentConfirmRequestDoc); + UtilXml.addChildElementValue(soldToAddressElement, "AddressLine2", destPostalAddress.getString("address2"), + shipmentConfirmRequestDoc); } UtilXml.addChildElementValue(soldToAddressElement, "City", destPostalAddress.getString("city"), shipmentConfirmRequestDoc); - UtilXml.addChildElementValue(soldToAddressElement, "StateProvinceCode", destPostalAddress.getString("stateProvinceGeoId"), shipmentConfirmRequestDoc); + UtilXml.addChildElementValue(soldToAddressElement, "StateProvinceCode", destPostalAddress.getString("stateProvinceGeoId"), + shipmentConfirmRequestDoc); UtilXml.addChildElementValue(soldToAddressElement, "PostalCode", destPostalAddress.getString("postalCode"), shipmentConfirmRequestDoc); UtilXml.addChildElementValue(soldToAddressElement, "CountryCode", destCountryGeo.getString("geoCode"), shipmentConfirmRequestDoc); @@ -422,7 +460,8 @@ public class UpsServices { Element billShipperElement = UtilXml.addChildElement(prepaidElement, "BillShipper", shipmentConfirmRequestDoc); // fill in BillShipper AccountNumber element - String billShipperAccountNumber = getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "billShipperAccountNumber", resource, "shipment.ups.bill.shipper.account.number", ""); + String billShipperAccountNumber = getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "billShipperAccountNumber", + resource, "shipment.ups.bill.shipper.account.number", ""); UtilXml.addChildElementValue(billShipperElement, "AccountNumber", billShipperAccountNumber, shipmentConfirmRequestDoc); } else { @@ -441,7 +480,8 @@ public class UpsServices { } Element billThirdPartyElement = UtilXml.addChildElement(paymentInformationElement, "BillThirdParty", shipmentConfirmRequestDoc); - Element billThirdPartyShipperElement = UtilXml.addChildElement(billThirdPartyElement, "BillThirdPartyShipper", shipmentConfirmRequestDoc); + Element billThirdPartyShipperElement = UtilXml.addChildElement(billThirdPartyElement, "BillThirdPartyShipper", + shipmentConfirmRequestDoc); UtilXml.addChildElementValue(billThirdPartyShipperElement, "AccountNumber", thirdPartyAccountNumber, shipmentConfirmRequestDoc); Element thirdPartyElement = UtilXml.addChildElement(billThirdPartyShipperElement, "ThirdParty", shipmentConfirmRequestDoc); Element addressElement = UtilXml.addChildElement(thirdPartyElement, "Address", shipmentConfirmRequestDoc); @@ -458,10 +498,11 @@ public class UpsServices { List internationalServiceCodes = UtilMisc.toList("07", "08", "54", "65"); if (internationalServiceCodes.contains(carrierServiceCode)) { Element shipmentServiceOptionsElement = UtilXml.addChildElement(shipmentElement, "ShipmentServiceOptions", shipmentConfirmRequestDoc); - Element internationalFormsElement = UtilXml.addChildElement(shipmentServiceOptionsElement, "InternationalForms", shipmentConfirmRequestDoc); + Element internationalFormsElement = UtilXml.addChildElement(shipmentServiceOptionsElement, "InternationalForms", + shipmentConfirmRequestDoc); UtilXml.addChildElementValue(internationalFormsElement, "FormType", "01", shipmentConfirmRequestDoc); List shipmentItems = shipment.getRelated("ShipmentItem", null, null, false); - for (GenericValue shipmentItem :shipmentItems) { + for (GenericValue shipmentItem : shipmentItems) { Element productElement = UtilXml.addChildElement(internationalFormsElement, "Product", shipmentConfirmRequestDoc); UtilXml.addChildElementValue(productElement, "Description", "Product Description", shipmentConfirmRequestDoc); Element unitElement = UtilXml.addChildElement(productElement, "Unit", shipmentConfirmRequestDoc); @@ -487,7 +528,8 @@ public class UpsServices { GenericValue shipmentPackageRouteSeg = shipmentPackageRouteSegIter.next(); GenericValue shipmentPackage = shipmentPackageRouteSeg.getRelatedOne("ShipmentPackage", false); GenericValue shipmentBoxType = shipmentPackage.getRelatedOne("ShipmentBoxType", false); - List carrierShipmentBoxTypes = shipmentPackage.getRelated("CarrierShipmentBoxType", UtilMisc.toMap("partyId", "UPS"), null, false); + List carrierShipmentBoxTypes = shipmentPackage.getRelated("CarrierShipmentBoxType", UtilMisc.toMap("partyId", "UPS"), + null, false); GenericValue carrierShipmentBoxType = null; if (carrierShipmentBoxTypes.size() > 0) { carrierShipmentBoxType = carrierShipmentBoxTypes.get(0); @@ -496,7 +538,8 @@ public class UpsServices { Element packageElement = UtilXml.addChildElement(shipmentElement, "Package", shipmentConfirmRequestDoc); Element packagingTypeElement = UtilXml.addChildElement(packageElement, "PackagingType", shipmentConfirmRequestDoc); if (carrierShipmentBoxType != null && carrierShipmentBoxType.get("packagingTypeCode") != null) { - UtilXml.addChildElementValue(packagingTypeElement, "Code", carrierShipmentBoxType.getString("packagingTypeCode"), shipmentConfirmRequestDoc); + UtilXml.addChildElementValue(packagingTypeElement, "Code", carrierShipmentBoxType.getString("packagingTypeCode"), + shipmentConfirmRequestDoc); } else { // default to "02", plain old Package UtilXml.addChildElementValue(packagingTypeElement, "Code", "02", shipmentConfirmRequestDoc); @@ -506,7 +549,8 @@ public class UpsServices { Element unitOfMeasurementElement = UtilXml.addChildElement(dimensionsElement, "UnitOfMeasurement", shipmentConfirmRequestDoc); GenericValue dimensionUom = shipmentBoxType.getRelatedOne("DimensionUom", false); if (dimensionUom != null) { - UtilXml.addChildElementValue(unitOfMeasurementElement, "Code", dimensionUom.getString("abbreviation").toUpperCase(Locale.getDefault()), shipmentConfirmRequestDoc); + UtilXml.addChildElementValue(unitOfMeasurementElement, "Code", + dimensionUom.getString("abbreviation").toUpperCase(Locale.getDefault()), shipmentConfirmRequestDoc); } else { // I guess we'll default to inches... UtilXml.addChildElementValue(unitOfMeasurementElement, "Code", ModelService.IN_PARAM, shipmentConfirmRequestDoc); @@ -514,27 +558,35 @@ public class UpsServices { BigDecimal boxLength = shipmentBoxType.getBigDecimal("boxLength"); BigDecimal boxWidth = shipmentBoxType.getBigDecimal("boxWidth"); BigDecimal boxHeight = shipmentBoxType.getBigDecimal("boxHeight"); - UtilXml.addChildElementValue(dimensionsElement, "Length", UtilValidate.isNotEmpty(boxLength) ? ""+boxLength.intValue() : "", shipmentConfirmRequestDoc); - UtilXml.addChildElementValue(dimensionsElement, "Width", UtilValidate.isNotEmpty(boxWidth) ? ""+boxWidth.intValue() : "", shipmentConfirmRequestDoc); - UtilXml.addChildElementValue(dimensionsElement, "Height", UtilValidate.isNotEmpty(boxHeight) ? ""+boxHeight.intValue() : "", shipmentConfirmRequestDoc); + UtilXml.addChildElementValue(dimensionsElement, "Length", UtilValidate.isNotEmpty(boxLength) ? "" + boxLength.intValue() : "", + shipmentConfirmRequestDoc); + UtilXml.addChildElementValue(dimensionsElement, "Width", UtilValidate.isNotEmpty(boxWidth) ? "" + boxWidth.intValue() : "", + shipmentConfirmRequestDoc); + UtilXml.addChildElementValue(dimensionsElement, "Height", UtilValidate.isNotEmpty(boxHeight) ? "" + boxHeight.intValue() : "", + shipmentConfirmRequestDoc); } else if (UtilValidate.isNotEmpty(shipmentPackage.getBigDecimal("boxLength")) - && UtilValidate.isNotEmpty(shipmentPackage.getBigDecimal("boxWidth")) - && UtilValidate.isNotEmpty(shipmentPackage.getBigDecimal("boxHeight"))) { + && UtilValidate.isNotEmpty(shipmentPackage.getBigDecimal("boxWidth")) + && UtilValidate.isNotEmpty(shipmentPackage.getBigDecimal("boxHeight"))) { Element dimensionsElement = UtilXml.addChildElement(packageElement, "Dimensions", shipmentConfirmRequestDoc); Element unitOfMeasurementElement = UtilXml.addChildElement(dimensionsElement, "UnitOfMeasurement", shipmentConfirmRequestDoc); GenericValue dimensionUom = shipmentPackage.getRelatedOne("DimensionUom", false); if (dimensionUom != null) { - UtilXml.addChildElementValue(unitOfMeasurementElement, "Code", dimensionUom.getString("abbreviation").toUpperCase(Locale.getDefault()), shipmentConfirmRequestDoc); + UtilXml.addChildElementValue(unitOfMeasurementElement, "Code", + dimensionUom.getString("abbreviation").toUpperCase(Locale.getDefault()), shipmentConfirmRequestDoc); } else { UtilXml.addChildElementValue(unitOfMeasurementElement, "Code", ModelService.IN_PARAM, shipmentConfirmRequestDoc); } - UtilXml.addChildElementValue(dimensionsElement, "Length", ""+shipmentPackage.getBigDecimal("boxLength").intValue(), shipmentConfirmRequestDoc); - UtilXml.addChildElementValue(dimensionsElement, "Width", ""+shipmentPackage.getBigDecimal("boxWidth").intValue(), shipmentConfirmRequestDoc); - UtilXml.addChildElementValue(dimensionsElement, "Height", ""+shipmentPackage.getBigDecimal("boxHeight").intValue(), shipmentConfirmRequestDoc); + UtilXml.addChildElementValue(dimensionsElement, "Length", "" + shipmentPackage.getBigDecimal("boxLength").intValue(), + shipmentConfirmRequestDoc); + UtilXml.addChildElementValue(dimensionsElement, "Width", "" + shipmentPackage.getBigDecimal("boxWidth").intValue(), + shipmentConfirmRequestDoc); + UtilXml.addChildElementValue(dimensionsElement, "Height", "" + shipmentPackage.getBigDecimal("boxHeight").intValue(), + shipmentConfirmRequestDoc); } Element packageWeightElement = UtilXml.addChildElement(packageElement, "PackageWeight", shipmentConfirmRequestDoc); - Element packageWeightUnitOfMeasurementElement = UtilXml.addChildElement(packageElement, "UnitOfMeasurement", shipmentConfirmRequestDoc); + Element packageWeightUnitOfMeasurementElement = UtilXml.addChildElement(packageElement, "UnitOfMeasurement", + shipmentConfirmRequestDoc); String weightUomUps = null; if (shipmentPackage.get("weightUomId") != null) { weightUomUps = OFBIZ_TO_UPS.get(shipmentPackage.get("weightUomId")); @@ -548,18 +600,22 @@ public class UpsServices { if (shipmentPackage.getString("weight") == null) { return ServiceUtil.returnError(UtilProperties.getMessage(RES_ERROR, "FacilityShipmentUpsWeightValueNotFound", - UtilMisc.toMap("shipmentId", shipmentId, "shipmentRouteSegmentId", shipmentRouteSegmentId, "shipmentPackageSeqId", shipmentPackage.getString("shipmentPackageSeqId")), locale)); + UtilMisc.toMap("shipmentId", shipmentId, "shipmentRouteSegmentId", shipmentRouteSegmentId, "shipmentPackageSeqId", + shipmentPackage.getString("shipmentPackageSeqId")), locale)); } BigDecimal boxWeight = shipmentPackage.getBigDecimal("weight"); - UtilXml.addChildElementValue(packageWeightElement, "Weight", UtilValidate.isNotEmpty(boxWeight) ? ""+ boxWeight.setScale(0, RoundingMode.CEILING) : "", shipmentConfirmRequestDoc); + UtilXml.addChildElementValue(packageWeightElement, "Weight", UtilValidate.isNotEmpty(boxWeight) ? "" + boxWeight.setScale(0, + RoundingMode.CEILING) : "", shipmentConfirmRequestDoc); // Adding only when order is not an international order if (!internationalServiceCodes.contains(carrierServiceCode)) { Element referenceNumberElement = UtilXml.addChildElement(packageElement, "ReferenceNumber", shipmentConfirmRequestDoc); UtilXml.addChildElementValue(referenceNumberElement, "Code", "MK", shipmentConfirmRequestDoc); - UtilXml.addChildElementValue(referenceNumberElement, "Value", shipmentPackage.getString("shipmentPackageSeqId"), shipmentConfirmRequestDoc); + UtilXml.addChildElementValue(referenceNumberElement, "Value", shipmentPackage.getString("shipmentPackageSeqId"), + shipmentConfirmRequestDoc); } if (carrierShipmentBoxType != null && carrierShipmentBoxType.get("oversizeCode") != null) { - UtilXml.addChildElementValue(packageElement, "OversizePackage", carrierShipmentBoxType.getString("oversizeCode"), shipmentConfirmRequestDoc); + UtilXml.addChildElementValue(packageElement, "OversizePackage", carrierShipmentBoxType.getString("oversizeCode"), + shipmentConfirmRequestDoc); } Element packageServiceOptionsElement = UtilXml.addChildElement(packageElement, "PackageServiceOptions", shipmentConfirmRequestDoc); @@ -569,35 +625,42 @@ public class UpsServices { if (!UtilValidate.isEmpty(insuredValue)) { Element insuredValueElement = UtilXml.addChildElement(packageServiceOptionsElement, "InsuredValue", shipmentConfirmRequestDoc); - UtilXml.addChildElementValue(insuredValueElement, "MonetaryValue", insuredValue.setScale(2, RoundingMode.HALF_UP).toString(), shipmentConfirmRequestDoc); + UtilXml.addChildElementValue(insuredValueElement, "MonetaryValue", insuredValue.setScale(2, RoundingMode.HALF_UP).toString(), + shipmentConfirmRequestDoc); UtilXml.addChildElementValue(insuredValueElement, "CurrencyCode", currencyCode, shipmentConfirmRequestDoc); } if (allowCOD) { Element codElement = UtilXml.addChildElement(packageServiceOptionsElement, "COD", shipmentConfirmRequestDoc); - UtilXml.addChildElementValue(codElement, "CODCode", "3", shipmentConfirmRequestDoc); // "3" is the only valid value for package-level COD + UtilXml.addChildElementValue(codElement, "CODCode", "3", shipmentConfirmRequestDoc); // "3" is the only valid value for + // package-level COD UtilXml.addChildElementValue(codElement, "CODFundsCode", codFundsCode, shipmentConfirmRequestDoc); Element codAmountElement = UtilXml.addChildElement(codElement, "CODAmount", shipmentConfirmRequestDoc); UtilXml.addChildElementValue(codAmountElement, "CurrencyCode", currencyCode, shipmentConfirmRequestDoc); // Get the value of the package by going back to the orderItems - Map getPackageValueResult = dispatcher.runSync("getShipmentPackageValueFromOrders", UtilMisc.toMap("shipmentId", shipmentId, "shipmentPackageSeqId", shipmentPackage.get("shipmentPackageSeqId"), "currencyUomId", currencyCode, "userLogin", userLogin, "locale", locale)); + Map getPackageValueResult = dispatcher.runSync("getShipmentPackageValueFromOrders", UtilMisc.toMap("shipmentId" + , shipmentId, "shipmentPackageSeqId", shipmentPackage.get("shipmentPackageSeqId"), "currencyUomId", currencyCode, "userLogin", + userLogin, "locale", locale)); if (ServiceUtil.isError(getPackageValueResult)) return getPackageValueResult; BigDecimal packageValue = (BigDecimal) getPackageValueResult.get("packageValue"); // Convert the value of the COD surcharge to the shipment currency, if necessary - Map convertUomResult = dispatcher.runSync("convertUom", UtilMisc.toMap("uomId", codSurchargeCurrencyUomId, "uomIdTo", currencyCode, "originalValue", codSurchargePackageAmount)); + Map convertUomResult = dispatcher.runSync("convertUom", UtilMisc.toMap("uomId", + codSurchargeCurrencyUomId, "uomIdTo", currencyCode, "originalValue", codSurchargePackageAmount)); if (ServiceUtil.isError(convertUomResult)) return convertUomResult; if (convertUomResult.containsKey("convertedValue")) { codSurchargePackageAmount = ((BigDecimal) convertUomResult.get("convertedValue")).setScale(DECIMALS, ROUNDING); } - // Add the amount of the surcharge for the package, if the surcharge should be on all packages or the first and this is the first package + // Add the amount of the surcharge for the package, if the surcharge should be on all packages or the first and this is the + // first package if (codSurchargeApplyToAllPackages || codSurchargeSplitBetweenPackages || (codSurchargeApplyToFirstPackage && shipmentPackageRouteSegIter.previousIndex() <= 0)) { packageValue = packageValue.add(codSurchargePackageAmount); } - UtilXml.addChildElementValue(codAmountElement, "MonetaryValue", packageValue.setScale(DECIMALS, ROUNDING).toString(), shipmentConfirmRequestDoc); + UtilXml.addChildElementValue(codAmountElement, "MonetaryValue", packageValue.setScale(DECIMALS, ROUNDING).toString(), + shipmentConfirmRequestDoc); } } @@ -631,7 +694,9 @@ public class UpsServices { xmlString.append(shipmentConfirmRequestString); if (shipmentUpsSaveCertificationInfo) { - String outFileName = shipmentUpsSaveCertificationPath + "/UpsShipmentConfirmRequest" + shipmentId + "_" + shipmentRouteSegment.getString("shipmentRouteSegmentId") + ".xml"; + String outFileName = + shipmentUpsSaveCertificationPath + "/UpsShipmentConfirmRequest" + shipmentId + "_" + shipmentRouteSegment.getString( + "shipmentRouteSegmentId") + ".xml"; try (FileOutputStream fileOut = new FileOutputStream(outFileName)) { fileOut.write(xmlString.toString().getBytes(StandardCharsets.UTF_8)); fileOut.flush(); @@ -641,7 +706,8 @@ public class UpsServices { } try { - shipmentConfirmResponseString = sendUpsRequest("ShipConfirm", xmlString.toString(), shipmentGatewayConfigId, resource, delegator, locale); + shipmentConfirmResponseString = sendUpsRequest("ShipConfirm", xmlString.toString(), shipmentGatewayConfigId, resource, delegator, + locale); } catch (UpsConnectException e) { String uceErrMsg = "Error sending UPS request for UPS Service ShipConfirm: " + e.toString(); Debug.logError(e, uceErrMsg, MODULE); @@ -650,7 +716,9 @@ public class UpsServices { } if (shipmentUpsSaveCertificationInfo) { - String outFileName = shipmentUpsSaveCertificationPath + "/UpsShipmentConfirmResponse" + shipmentId + "_" + shipmentRouteSegment.getString("shipmentRouteSegmentId") + ".xml"; + String outFileName = + shipmentUpsSaveCertificationPath + "/UpsShipmentConfirmResponse" + shipmentId + "_" + shipmentRouteSegment.getString( + "shipmentRouteSegmentId") + ".xml"; try (FileOutputStream fileOut = new FileOutputStream(outFileName)) { fileOut.write(shipmentConfirmResponseString.getBytes(StandardCharsets.UTF_8)); fileOut.flush(); @@ -690,7 +758,8 @@ public class UpsServices { } } - public static Map handleUpsShipmentConfirmResponse(Document shipmentConfirmResponseDocument, GenericValue shipmentRouteSegment, Locale locale) throws GenericEntityException { + public static Map handleUpsShipmentConfirmResponse(Document shipmentConfirmResponseDocument, GenericValue shipmentRouteSegment, + Locale locale) throws GenericEntityException { // process ShipmentConfirmResponse, update data as needed Element shipmentConfirmResponseElement = shipmentConfirmResponseDocument.getDocumentElement(); @@ -810,8 +879,10 @@ public class UpsServices { if (UtilValidate.isEmpty(shipmentGatewayConfigId) && UtilValidate.isEmpty(resource)) { return ServiceUtil.returnError(UtilProperties.getMessage(RES_ERROR, "FacilityShipmentUpsGatewayNotAvailable", locale)); } - boolean shipmentUpsSaveCertificationInfo = "true".equals(getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "saveCertInfo", resource, "shipment.ups.save.certification.info", "true")); - String shipmentUpsSaveCertificationPath = FlexibleStringExpander.expandString(getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "saveCertPath", resource, "shipment.ups.save.certification.path", ""), context); + boolean shipmentUpsSaveCertificationInfo = "true".equals(getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "saveCertInfo", + resource, "shipment.ups.save.certification.info", "true")); + String shipmentUpsSaveCertificationPath = FlexibleStringExpander.expandString(getShipmentGatewayConfigValue(delegator, + shipmentGatewayConfigId, "saveCertPath", resource, "shipment.ups.save.certification.path", ""), context); File shipmentUpsSaveCertificationFile = null; if (shipmentUpsSaveCertificationInfo) { shipmentUpsSaveCertificationFile = new File(shipmentUpsSaveCertificationPath); @@ -823,19 +894,23 @@ public class UpsServices { String shipmentAcceptResponseString = null; try { - GenericValue shipmentRouteSegment = EntityQuery.use(delegator).from("ShipmentRouteSegment").where("shipmentId", shipmentId, "shipmentRouteSegmentId", shipmentRouteSegmentId).queryOne(); + GenericValue shipmentRouteSegment = EntityQuery.use(delegator).from("ShipmentRouteSegment").where("shipmentId", shipmentId, + "shipmentRouteSegmentId", shipmentRouteSegmentId).queryOne(); if (!"UPS".equals(shipmentRouteSegment.getString("carrierPartyId"))) { - return ServiceUtil.returnError(UtilProperties.getMessage(RES_ERROR, "FacilityShipmentUpsNotRouteSegmentCarrier", UtilMisc.toMap("shipmentRouteSegmentId", shipmentRouteSegmentId, "shipmentId", shipmentId), locale)); + return ServiceUtil.returnError(UtilProperties.getMessage(RES_ERROR, "FacilityShipmentUpsNotRouteSegmentCarrier", UtilMisc.toMap( + "shipmentRouteSegmentId", shipmentRouteSegmentId, "shipmentId", shipmentId), locale)); } // add ShipmentRouteSegment carrierServiceStatusId, check before all UPS services if (!"SHRSCS_CONFIRMED".equals(shipmentRouteSegment.getString("carrierServiceStatusId"))) { return ServiceUtil.returnError(UtilProperties.getMessage(RES_ERROR, "FacilityShipmentUpsRouteSegmentStatusNotConfirmed", - UtilMisc.toMap("shipmentRouteSegmentId", shipmentRouteSegmentId, "shipmentId", shipmentId, "shipmentRouteSegmentStatus", shipmentRouteSegment.getString("carrierServiceStatusId")), locale)); + UtilMisc.toMap("shipmentRouteSegmentId", shipmentRouteSegmentId, "shipmentId", shipmentId, "shipmentRouteSegmentStatus", + shipmentRouteSegment.getString("carrierServiceStatusId")), locale)); } - List shipmentPackageRouteSegs = shipmentRouteSegment.getRelated("ShipmentPackageRouteSeg", null, UtilMisc.toList("+shipmentPackageSeqId"), false); + List shipmentPackageRouteSegs = shipmentRouteSegment.getRelated("ShipmentPackageRouteSeg", null, UtilMisc.toList( + "+shipmentPackageSeqId"), false); if (UtilValidate.isEmpty(shipmentPackageRouteSegs)) { return ServiceUtil.returnError(UtilProperties.getMessage(RES_ERROR, "FacilityShipmentUpsPackageRouteSegsNotFound", UtilMisc.toMap("shipmentId", shipmentId, "shipmentRouteSegmentId", shipmentRouteSegmentId), locale)); @@ -860,7 +935,8 @@ public class UpsServices { UtilXml.addChildElementValue(requestElement, "RequestAction", "ShipAccept", shipmentAcceptRequestDoc); UtilXml.addChildElementValue(requestElement, "RequestOption", "01", shipmentAcceptRequestDoc); - UtilXml.addChildElementValue(shipmentAcceptRequestElement, "ShipmentDigest", shipmentRouteSegment.getString("trackingDigest"), shipmentAcceptRequestDoc); + UtilXml.addChildElementValue(shipmentAcceptRequestElement, "ShipmentDigest", shipmentRouteSegment.getString("trackingDigest"), + shipmentAcceptRequestDoc); String shipmentAcceptRequestString = null; @@ -870,7 +946,7 @@ public class UpsServices { String ioeErrMsg = "Error writing the ShipmentAcceptRequest XML Document to a String: " + e.toString(); Debug.logError(e, ioeErrMsg, MODULE); return ServiceUtil.returnError(UtilProperties.getMessage(RES_ERROR, - "FacilityShipmentUpsErrorShipmentAcceptRequestXmlToString", + "FacilityShipmentUpsErrorShipmentAcceptRequestXmlToString", UtilMisc.toMap("errorString", e.toString()), locale)); } @@ -894,7 +970,9 @@ public class UpsServices { xmlString.append(shipmentAcceptRequestString); if (shipmentUpsSaveCertificationInfo) { - String outFileName = shipmentUpsSaveCertificationPath + "/UpsShipmentAcceptRequest" + shipmentId + "_" + shipmentRouteSegment.getString("shipmentRouteSegmentId") + ".xml"; + String outFileName = + shipmentUpsSaveCertificationPath + "/UpsShipmentAcceptRequest" + shipmentId + "_" + shipmentRouteSegment.getString( + "shipmentRouteSegmentId") + ".xml"; try (FileOutputStream fileOut = new FileOutputStream(outFileName)) { fileOut.write(xmlString.toString().getBytes(StandardCharsets.UTF_8)); fileOut.flush(); @@ -904,7 +982,8 @@ public class UpsServices { } try { - shipmentAcceptResponseString = sendUpsRequest("ShipAccept", xmlString.toString(), shipmentGatewayConfigId, resource, delegator, locale); + shipmentAcceptResponseString = sendUpsRequest("ShipAccept", xmlString.toString(), shipmentGatewayConfigId, resource, delegator, + locale); } catch (UpsConnectException e) { String uceErrMsg = "Error sending UPS request for UPS Service ShipAccept: " + e.toString(); Debug.logError(e, uceErrMsg, MODULE); @@ -913,7 +992,9 @@ public class UpsServices { } if (shipmentUpsSaveCertificationInfo) { - String outFileName = shipmentUpsSaveCertificationPath + "/UpsShipmentAcceptResponse" + shipmentId + "_" + shipmentRouteSegment.getString("shipmentRouteSegmentId") + ".xml"; + String outFileName = + shipmentUpsSaveCertificationPath + "/UpsShipmentAcceptResponse" + shipmentId + "_" + shipmentRouteSegment.getString( + "shipmentRouteSegmentId") + ".xml"; try (FileOutputStream fileOut = new FileOutputStream(outFileName)) { fileOut.write(shipmentAcceptResponseString.getBytes(StandardCharsets.UTF_8)); fileOut.flush(); @@ -932,7 +1013,7 @@ public class UpsServices { UtilMisc.toMap("errorString", e2.toString()), locale)); } - return handleUpsShipmentAcceptResponse(shipmentAcceptResponseDocument, shipmentRouteSegment, shipmentPackageRouteSegs, delegator, + return handleUpsShipmentAcceptResponse(shipmentAcceptResponseDocument, shipmentRouteSegment, shipmentPackageRouteSegs, delegator, shipmentGatewayConfigId, resource, context, locale); } catch (GenericEntityException e) { Debug.logError(e, MODULE); @@ -941,10 +1022,14 @@ public class UpsServices { } } - public static Map handleUpsShipmentAcceptResponse(Document shipmentAcceptResponseDocument, GenericValue shipmentRouteSegment, List shipmentPackageRouteSegs, - Delegator delegator, String shipmentGatewayConfigId, String resource, Map context, Locale locale) throws GenericEntityException { - boolean shipmentUpsSaveCertificationInfo = "true".equals(getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "saveCertInfo", resource, "shipment.ups.save.certification.info", "true")); - String shipmentUpsSaveCertificationPath = FlexibleStringExpander.expandString(getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "saveCertPath", resource, "shipment.ups.save.certification.path", ""), context); + public static Map handleUpsShipmentAcceptResponse(Document shipmentAcceptResponseDocument, GenericValue shipmentRouteSegment, + List shipmentPackageRouteSegs, + Delegator delegator, String shipmentGatewayConfigId, String resource, + Map context, Locale locale) throws GenericEntityException { + boolean shipmentUpsSaveCertificationInfo = "true".equals(getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "saveCertInfo", + resource, "shipment.ups.save.certification.info", "true")); + String shipmentUpsSaveCertificationPath = FlexibleStringExpander.expandString(getShipmentGatewayConfigValue(delegator, + shipmentGatewayConfigId, "saveCertPath", resource, "shipment.ups.save.certification.path", ""), context); File shipmentUpsSaveCertificationFile = null; if (shipmentUpsSaveCertificationInfo) { shipmentUpsSaveCertificationFile = new File(shipmentUpsSaveCertificationPath); @@ -1047,7 +1132,7 @@ public class UpsServices { // now process the PackageResults elements List packageResultsElements = UtilXml.childElementList(shipmentResultsElement, "PackageResults"); Iterator shipmentPackageRouteSegIter = shipmentPackageRouteSegs.iterator(); - for (Element packageResultsElement: packageResultsElements) { + for (Element packageResultsElement : packageResultsElements) { String trackingNumber = UtilXml.childElementValue(packageResultsElement, "TrackingNumber"); Element packageServiceOptionsChargesElement = UtilXml.firstChildElement(packageResultsElement, "ServiceOptionsCharges"); @@ -1058,12 +1143,14 @@ public class UpsServices { //Element packageLabelImageFormatElement = UtilXml.firstChildElement(packageResultsElement, "LabelImageFormat"); // will be EPL or GIF, should always be GIF since that is what we requested String packageLabelGraphicImageString = UtilXml.childElementValue(packageLabelImageElement, "GraphicImage"); - String packageLabelInternationalSignatureGraphicImageString = UtilXml.childElementValue(packageLabelImageElement, "InternationalSignatureGraphicImage"); + String packageLabelInternationalSignatureGraphicImageString = UtilXml.childElementValue(packageLabelImageElement, + "InternationalSignatureGraphicImage"); String packageLabelHTMLImageString = UtilXml.childElementValue(packageLabelImageElement, "HTMLImage"); if (!shipmentPackageRouteSegIter.hasNext()) { errorList.add(UtilProperties.getMessage(RES_ERROR, "FacilityShipmentUpsErrorMorePackageResultsWereReturned", - UtilMisc.toMap("trackingNumber", trackingNumber, "ServiceOptionsCharges", packageServiceOptionsMonetaryValue + packageServiceOptionsCurrencyCode), locale)); + UtilMisc.toMap("trackingNumber", trackingNumber, "ServiceOptionsCharges", + packageServiceOptionsMonetaryValue + packageServiceOptionsCurrencyCode), locale)); // NOTE: if this happens much we should just create a new package to store all of the info... continue; } @@ -1076,7 +1163,8 @@ public class UpsServices { try { shipmentPackageRouteSeg.set("packageServiceCost", new BigDecimal(packageServiceOptionsMonetaryValue)); } catch (NumberFormatException e) { - String excErrMsg = "Error parsing the packageServiceOptionsMonetaryValue [" + packageServiceOptionsMonetaryValue + "] for Package [" + shipmentPackageRouteSeg.getString("shipmentPackageSeqId") + "]: " + e.toString(); + String excErrMsg = "Error parsing the packageServiceOptionsMonetaryValue [" + packageServiceOptionsMonetaryValue + "] for " + + "Package [" + shipmentPackageRouteSeg.getString("shipmentPackageSeqId") + "]: " + e.toString(); Debug.logError(e, excErrMsg, MODULE); errorList.add(UtilProperties.getMessage(RES_ERROR, "FacilityShipmentUpsErrorParsingServiceOptionsMonetaryValue", UtilMisc.toMap("serviceOptionsMonetaryValue", serviceOptionsMonetaryValue, "errorString", e.toString()), locale)); @@ -1088,10 +1176,12 @@ public class UpsServices { } byte[] labelInternationalSignatureGraphicImageBytes = null; if (packageLabelInternationalSignatureGraphicImageString != null) { - labelInternationalSignatureGraphicImageBytes = Base64.getMimeDecoder().decode(packageLabelInternationalSignatureGraphicImageString.getBytes(StandardCharsets.UTF_8)); + labelInternationalSignatureGraphicImageBytes = + Base64.getMimeDecoder().decode(packageLabelInternationalSignatureGraphicImageString.getBytes(StandardCharsets.UTF_8)); shipmentPackageRouteSeg.set("labelIntlSignImage", labelInternationalSignatureGraphicImageBytes); } - String packageLabelHTMLImageStringDecoded = Arrays.toString(Base64.getMimeDecoder().decode(packageLabelHTMLImageString.getBytes(StandardCharsets.UTF_8))); + String packageLabelHTMLImageStringDecoded = + Arrays.toString(Base64.getMimeDecoder().decode(packageLabelHTMLImageString.getBytes(StandardCharsets.UTF_8))); shipmentPackageRouteSeg.set("labelHtml", packageLabelHTMLImageStringDecoded); if (shipmentUpsSaveCertificationInfo) { @@ -1101,7 +1191,8 @@ public class UpsServices { fileOut.write(labelImageBytes); fileOut.flush(); } catch (IOException e) { - Debug.logInfo(e, "Could not save UPS LabelImage GIF file: [[[" + packageLabelGraphicImageString + "]]] to file: " + outFileName, MODULE); + Debug.logInfo(e, + "Could not save UPS LabelImage GIF file: [[[" + packageLabelGraphicImageString + "]]] to file: " + outFileName, MODULE); } } if (labelInternationalSignatureGraphicImageBytes != null) { @@ -1110,16 +1201,21 @@ public class UpsServices { fileOut.write(labelInternationalSignatureGraphicImageBytes); fileOut.flush(); } catch (IOException e) { - Debug.logInfo(e, "Could not save UPS IntlSign LabelImage GIF file: [[[" + packageLabelInternationalSignatureGraphicImageString + "]]] to file: " + outFileName, MODULE); + Debug.logInfo(e, + "Could not save UPS IntlSign LabelImage GIF file: [[[" + packageLabelInternationalSignatureGraphicImageString + "]]] " + + "to file: " + outFileName, MODULE); } } if (packageLabelHTMLImageStringDecoded != null) { - String outFileName = shipmentUpsSaveCertificationPath + "/UpsShipmentLabelHTMLImage" + shipmentRouteSegment.getString("shipmentId") + "_" + shipmentRouteSegment.getString("shipmentRouteSegmentId") + "_" + shipmentPackageRouteSeg.getString("shipmentPackageSeqId") + ".html"; + String outFileName = shipmentUpsSaveCertificationPath + "/UpsShipmentLabelHTMLImage" + shipmentRouteSegment.getString( + "shipmentId") + "_" + shipmentRouteSegment.getString("shipmentRouteSegmentId") + "_" + shipmentPackageRouteSeg.getString("shipmentPackageSeqId") + ".html"; try (FileOutputStream fileOut = new FileOutputStream(outFileName)) { fileOut.write(packageLabelHTMLImageStringDecoded.getBytes(StandardCharsets.UTF_8)); fileOut.flush(); } catch (IOException e) { - Debug.logInfo(e, "Could not save UPS LabelImage HTML file: [[[" + packageLabelHTMLImageStringDecoded + "]]] to file: " + outFileName, MODULE); + Debug.logInfo(e, + "Could not save UPS LabelImage HTML file: [[[" + packageLabelHTMLImageStringDecoded + "]]] to file: " + outFileName, + MODULE); } } } @@ -1145,12 +1241,14 @@ public class UpsServices { if (fileStringDecoded != null) { shipmentRouteSegment.set("upsHighValueReport", fileStringDecoded); shipmentRouteSegment.store(); - String outFileName = shipmentUpsSaveCertificationPath + "/HighValueReport" + shipmentRouteSegment.getString("shipmentId") + "_" + shipmentRouteSegment.getString("shipmentRouteSegmentId") + ".html"; + String outFileName = + shipmentUpsSaveCertificationPath + "/HighValueReport" + shipmentRouteSegment.getString("shipmentId") + "_" + shipmentRouteSegment.getString("shipmentRouteSegmentId") + ".html"; try (FileOutputStream fileOut = new FileOutputStream(outFileName)) { fileOut.write(fileStringDecoded.getBytes(StandardCharsets.UTF_8)); fileOut.flush(); } catch (IOException e) { - Debug.logInfo(e, "Could not save UPS High Value Report data: [[[" + fileStringDecoded + "]]] to file: " + outFileName, MODULE); + Debug.logInfo(e, "Could not save UPS High Value Report data: [[[" + fileStringDecoded + "]]] to file: " + outFileName, + MODULE); } } } @@ -1189,8 +1287,10 @@ public class UpsServices { if (UtilValidate.isEmpty(shipmentGatewayConfigId) && UtilValidate.isEmpty(resource)) { return ServiceUtil.returnError(UtilProperties.getMessage(RES_ERROR, "FacilityShipmentUpsGatewayNotAvailable", locale)); } - boolean shipmentUpsSaveCertificationInfo = "true".equals(getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "saveCertInfo", resource, "shipment.ups.save.certification.info", "true")); - String shipmentUpsSaveCertificationPath = FlexibleStringExpander.expandString(getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "saveCertPath", resource, "shipment.ups.save.certification.path", ""), context); + boolean shipmentUpsSaveCertificationInfo = "true".equals(getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "saveCertInfo", + resource, "shipment.ups.save.certification.info", "true")); + String shipmentUpsSaveCertificationPath = FlexibleStringExpander.expandString(getShipmentGatewayConfigValue(delegator, + shipmentGatewayConfigId, "saveCertPath", resource, "shipment.ups.save.certification.path", ""), context); File shipmentUpsSaveCertificationFile = null; if (shipmentUpsSaveCertificationInfo) { shipmentUpsSaveCertificationFile = new File(shipmentUpsSaveCertificationPath); @@ -1202,17 +1302,19 @@ public class UpsServices { String voidShipmentResponseString = null; try { - GenericValue shipmentRouteSegment = EntityQuery.use(delegator).from("ShipmentRouteSegment").where("shipmentId", shipmentId, "shipmentRouteSegmentId", shipmentRouteSegmentId).queryOne(); + GenericValue shipmentRouteSegment = EntityQuery.use(delegator).from("ShipmentRouteSegment").where("shipmentId", shipmentId, + "shipmentRouteSegmentId", shipmentRouteSegmentId).queryOne(); if (!"UPS".equals(shipmentRouteSegment.getString("carrierPartyId"))) { - return ServiceUtil.returnError(UtilProperties.getMessage(RES_ERROR, "FacilityShipmentUpsNotRouteSegmentCarrier", UtilMisc.toMap("shipmentRouteSegmentId", shipmentRouteSegmentId, "shipmentId", shipmentId), locale)); - } + return ServiceUtil.returnError(UtilProperties.getMessage(RES_ERROR, "FacilityShipmentUpsNotRouteSegmentCarrier", UtilMisc.toMap( + "shipmentRouteSegmentId", shipmentRouteSegmentId, "shipmentId", shipmentId), locale)); + } // add ShipmentRouteSegment carrierServiceStatusId, check before all UPS services if (!"SHRSCS_CONFIRMED".equals(shipmentRouteSegment.getString("carrierServiceStatusId")) && !"SHRSCS_ACCEPTED".equals(shipmentRouteSegment.getString("carrierServiceStatusId"))) { return ServiceUtil.returnError(UtilProperties.getMessage(RES_ERROR, "FacilityShipmentUpsRouteSegmentStatusMustBeConfirmedOrAccepted", - UtilMisc.toMap("shipmentRouteSegmentId", shipmentRouteSegmentId, "shipmentId", shipmentId, "shipmentRouteSegmentStatus", + UtilMisc.toMap("shipmentRouteSegmentId", shipmentRouteSegmentId, "shipmentId", shipmentId, "shipmentRouteSegmentStatus", shipmentRouteSegment.getString("carrierServiceStatusId")), locale)); } @@ -1234,7 +1336,8 @@ public class UpsServices { UtilXml.addChildElementValue(requestElement, "RequestAction", "Void", voidShipmentRequestDoc); UtilXml.addChildElementValue(requestElement, "RequestOption", "1", voidShipmentRequestDoc); - UtilXml.addChildElementValue(voidShipmentRequestElement, "ShipmentIdentificationNumber", shipmentRouteSegment.getString("trackingIdNumber"), voidShipmentRequestDoc); + UtilXml.addChildElementValue(voidShipmentRequestElement, "ShipmentIdentificationNumber", shipmentRouteSegment.getString( + "trackingIdNumber"), voidShipmentRequestDoc); String voidShipmentRequestString = null; try { @@ -1266,7 +1369,9 @@ public class UpsServices { xmlString.append(voidShipmentRequestString); if (shipmentUpsSaveCertificationInfo) { - String outFileName = shipmentUpsSaveCertificationPath + "/UpsVoidShipmentRequest" + shipmentId + "_" + shipmentRouteSegment.getString("shipmentRouteSegmentId") + ".xml"; + String outFileName = + shipmentUpsSaveCertificationPath + "/UpsVoidShipmentRequest" + shipmentId + "_" + shipmentRouteSegment.getString( + "shipmentRouteSegmentId") + ".xml"; try (FileOutputStream fileOut = new FileOutputStream(outFileName)) { fileOut.write(xmlString.toString().getBytes(StandardCharsets.UTF_8)); fileOut.flush(); @@ -1285,7 +1390,9 @@ public class UpsServices { } if (shipmentUpsSaveCertificationInfo) { - String outFileName = shipmentUpsSaveCertificationPath + "/UpsVoidShipmentResponse" + shipmentId + "_" + shipmentRouteSegment.getString("shipmentRouteSegmentId") + ".xml"; + String outFileName = + shipmentUpsSaveCertificationPath + "/UpsVoidShipmentResponse" + shipmentId + "_" + shipmentRouteSegment.getString( + "shipmentRouteSegmentId") + ".xml"; try (FileOutputStream fileOut = new FileOutputStream(outFileName)) { fileOut.write(voidShipmentResponseString.getBytes(StandardCharsets.UTF_8)); fileOut.flush(); @@ -1312,7 +1419,8 @@ public class UpsServices { } } - public static Map handleUpsVoidShipmentResponse(Document voidShipmentResponseDocument, GenericValue shipmentRouteSegment, Locale locale) throws GenericEntityException { + public static Map handleUpsVoidShipmentResponse(Document voidShipmentResponseDocument, GenericValue shipmentRouteSegment, + Locale locale) throws GenericEntityException { // process VoidShipmentResponse, update data as needed Element voidShipmentResponseElement = voidShipmentResponseDocument.getDocumentElement(); @@ -1340,7 +1448,7 @@ public class UpsServices { // -=-=-=- Okay, now done with that, just return any extra info... StringBuilder successString = new StringBuilder(UtilProperties.getMessage(RES_ERROR, "FacilityShipmentUpsShipmentVoidSucceeded", - UtilMisc.toMap("statusTypeCode", statusTypeCode, "statusTypeDescription", statusTypeDescription, + UtilMisc.toMap("statusTypeCode", statusTypeCode, "statusTypeDescription", statusTypeDescription, "statusCodeCode", statusCodeCode, "statusCodeDescription", statusCodeDescription), locale)); if (errorList.size() > 0) { // this shouldn't happen much, but handle it anyway @@ -1356,7 +1464,7 @@ public class UpsServices { return ServiceUtil.returnSuccess(successString.toString()); } else { errorList.add(0, UtilProperties.getMessage(RES_ERROR, "FacilityShipmentUpsShipmentVoidFailed", - UtilMisc.toMap("statusTypeCode", statusTypeCode, "statusTypeDescription", statusTypeDescription, + UtilMisc.toMap("statusTypeCode", statusTypeCode, "statusTypeDescription", statusTypeDescription, "statusCodeCode", statusCodeCode, "statusCodeDescription", statusCodeDescription), locale)); return ServiceUtil.returnError(errorList); } @@ -1374,8 +1482,10 @@ public class UpsServices { if (UtilValidate.isEmpty(shipmentGatewayConfigId) && UtilValidate.isEmpty(resource)) { return ServiceUtil.returnError(UtilProperties.getMessage(RES_ERROR, "FacilityShipmentUpsGatewayNotAvailable", locale)); } - boolean shipmentUpsSaveCertificationInfo = "true".equals(getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "saveCertInfo", resource, "shipment.ups.save.certification.info", "true")); - String shipmentUpsSaveCertificationPath = FlexibleStringExpander.expandString(getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "saveCertPath", resource, "shipment.ups.save.certification.path", ""), context); + boolean shipmentUpsSaveCertificationInfo = "true".equals(getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "saveCertInfo", + resource, "shipment.ups.save.certification.info", "true")); + String shipmentUpsSaveCertificationPath = FlexibleStringExpander.expandString(getShipmentGatewayConfigValue(delegator, + shipmentGatewayConfigId, "saveCertPath", resource, "shipment.ups.save.certification.path", ""), context); File shipmentUpsSaveCertificationFile = null; if (shipmentUpsSaveCertificationInfo) { shipmentUpsSaveCertificationFile = new File(shipmentUpsSaveCertificationPath); @@ -1387,20 +1497,26 @@ public class UpsServices { String trackResponseString = null; try { - GenericValue shipmentRouteSegment = EntityQuery.use(delegator).from("ShipmentRouteSegment").where("shipmentId", shipmentId, "shipmentRouteSegmentId", shipmentRouteSegmentId).queryOne(); + GenericValue shipmentRouteSegment = EntityQuery.use(delegator).from("ShipmentRouteSegment").where("shipmentId", shipmentId, + "shipmentRouteSegmentId", shipmentRouteSegmentId).queryOne(); if (!"UPS".equals(shipmentRouteSegment.getString("carrierPartyId"))) { - return ServiceUtil.returnError(UtilProperties.getMessage(RES_ERROR, "FacilityShipmentUpsNotRouteSegmentCarrier", UtilMisc.toMap("shipmentRouteSegmentId", shipmentRouteSegmentId, "shipmentId", shipmentId), locale)); + return ServiceUtil.returnError(UtilProperties.getMessage(RES_ERROR, "FacilityShipmentUpsNotRouteSegmentCarrier", UtilMisc.toMap( + "shipmentRouteSegmentId", shipmentRouteSegmentId, "shipmentId", shipmentId), locale)); } // add ShipmentRouteSegment carrierServiceStatusId, check before all UPS services if (!"SHRSCS_ACCEPTED".equals(shipmentRouteSegment.getString("carrierServiceStatusId"))) { - return ServiceUtil.returnError(UtilProperties.getMessage(RES_ERROR, "FacilityShipmentUpsRouteSegmentStatusNotAccepted", UtilMisc.toMap("shipmentRouteSegmentId", shipmentRouteSegmentId, "shipmentId", shipmentId, "shipmentRouteSegmentStatus", shipmentRouteSegment.getString("carrierServiceStatusId")), locale)); + return ServiceUtil.returnError(UtilProperties.getMessage(RES_ERROR, "FacilityShipmentUpsRouteSegmentStatusNotAccepted", + UtilMisc.toMap("shipmentRouteSegmentId", shipmentRouteSegmentId, "shipmentId", shipmentId, "shipmentRouteSegmentStatus", + shipmentRouteSegment.getString("carrierServiceStatusId")), locale)); } - List shipmentPackageRouteSegs = shipmentRouteSegment.getRelated("ShipmentPackageRouteSeg", null, UtilMisc.toList("+shipmentPackageSeqId"), false); + List shipmentPackageRouteSegs = shipmentRouteSegment.getRelated("ShipmentPackageRouteSeg", null, UtilMisc.toList( + "+shipmentPackageSeqId"), false); if (UtilValidate.isEmpty(shipmentPackageRouteSegs)) { - return ServiceUtil.returnError(UtilProperties.getMessage(RES_ERROR, "FacilityShipmentUpsPackageRouteSegsNotFound", UtilMisc.toMap("shipmentId", shipmentId, "shipmentRouteSegmentId", shipmentRouteSegmentId), locale)); + return ServiceUtil.returnError(UtilProperties.getMessage(RES_ERROR, "FacilityShipmentUpsPackageRouteSegsNotFound", UtilMisc.toMap( + "shipmentId", shipmentId, "shipmentRouteSegmentId", shipmentRouteSegmentId), locale)); } if (UtilValidate.isEmpty(shipmentRouteSegment.getString("trackingIdNumber"))) { @@ -1420,7 +1536,8 @@ public class UpsServices { UtilXml.addChildElementValue(requestElement, "RequestAction", "Track", trackRequestDoc); - UtilXml.addChildElementValue(trackRequestElement, "ShipmentIdentificationNumber", shipmentRouteSegment.getString("trackingIdNumber"), trackRequestDoc); + UtilXml.addChildElementValue(trackRequestElement, "ShipmentIdentificationNumber", shipmentRouteSegment.getString("trackingIdNumber"), + trackRequestDoc); String trackRequestString = null; try { @@ -1452,7 +1569,8 @@ public class UpsServices { xmlString.append(trackRequestString); if (shipmentUpsSaveCertificationInfo) { - String outFileName = shipmentUpsSaveCertificationPath + "/UpsTrackRequest" + shipmentId + "_" + shipmentRouteSegment.getString("shipmentRouteSegmentId") + ".xml"; + String outFileName = shipmentUpsSaveCertificationPath + "/UpsTrackRequest" + shipmentId + "_" + shipmentRouteSegment.getString( + "shipmentRouteSegmentId") + ".xml"; try (FileOutputStream fileOut = new FileOutputStream(outFileName)) { fileOut.write(xmlString.toString().getBytes(StandardCharsets.UTF_8)); fileOut.flush(); @@ -1471,7 +1589,9 @@ public class UpsServices { } if (shipmentUpsSaveCertificationInfo) { - String outFileName = shipmentUpsSaveCertificationPath + "/UpsTrackResponseString" + shipmentId + "_" + shipmentRouteSegment.getString("shipmentRouteSegmentId") + ".xml"; + String outFileName = + shipmentUpsSaveCertificationPath + "/UpsTrackResponseString" + shipmentId + "_" + shipmentRouteSegment.getString( + "shipmentRouteSegmentId") + ".xml"; try (FileOutputStream fileOut = new FileOutputStream(outFileName)) { fileOut.write(trackResponseString.getBytes(StandardCharsets.UTF_8)); fileOut.flush(); @@ -1499,7 +1619,7 @@ public class UpsServices { } public static Map handleUpsTrackShipmentResponse(Document trackResponseDocument, GenericValue shipmentRouteSegment, - List shipmentPackageRouteSegs, Locale locale) throws GenericEntityException { + List shipmentPackageRouteSegs, Locale locale) throws GenericEntityException { // process TrackResponse, update data as needed Element trackResponseElement = trackResponseDocument.getDocumentElement(); @@ -1547,7 +1667,8 @@ public class UpsServices { * */ // -=-=-=- Okay, now done with that, just return any extra info... - StringBuilder successString = new StringBuilder(UtilProperties.getMessage(RES_ERROR, "FacilityShipmentUpsShipmentTrackSucceeded", locale)); + StringBuilder successString = new StringBuilder(UtilProperties.getMessage(RES_ERROR, "FacilityShipmentUpsShipmentTrackSucceeded", + locale)); if (errorList.size() > 0) { // this shouldn't happen much, but handle it anyway successString.append(UtilProperties.getMessage(RES_ERROR, "FacilityShipmentUpsShipmentTrackError", locale)); @@ -1592,7 +1713,8 @@ public class UpsServices { shipFromAddress = EntityQuery.use(delegator).from("PostalAddress").where("contactMechId", shippingOriginContactMechId).queryOne(); } catch (GenericEntityException e) { Debug.logError(e, MODULE); - return ServiceUtil.returnError(UtilProperties.getMessage(RES_ERROR, "FacilityShipmentUnableFoundShipToAddresssForDropShipping", locale)); + return ServiceUtil.returnError(UtilProperties.getMessage(RES_ERROR, "FacilityShipmentUnableFoundShipToAddresssForDropShipping", + locale)); } } @@ -1606,7 +1728,8 @@ public class UpsServices { if (UtilValidate.isEmpty(destCountryGeo)) { return ServiceUtil.returnError(UtilProperties.getMessage(RES_ERROR, "FacilityShipmentUpsShipToAddresssNoDestionationCountry", locale)); } - Map cxt = UtilMisc.toMap("serviceConfigProps", context.get("serviceConfigProps"), "upsRateInquireMode", context.get("upsRateInquireMode"), + Map cxt = UtilMisc.toMap("serviceConfigProps", context.get("serviceConfigProps"), "upsRateInquireMode", context.get( + "upsRateInquireMode"), "productStoreId", context.get("productStoreId"), "carrierRoleTypeId", context.get("carrierRoleTypeId")); cxt.put("carrierPartyId", context.get("carrierPartyId")); cxt.put("shipmentMethodTypeId", context.get("shipmentMethodTypeId")); @@ -1633,11 +1756,12 @@ public class UpsServices { } } - private static void splitEstimatePackages(DispatchContext dctx, Document requestDoc, Element shipmentElement, List> shippableItemInfo, - BigDecimal maxWeight, BigDecimal minWeight, String totalWeightStr) { + private static void splitEstimatePackages(DispatchContext dctx, Document requestDoc, Element shipmentElement, + List> shippableItemInfo, + BigDecimal maxWeight, BigDecimal minWeight, String totalWeightStr) { List> packages = ShipmentWorker.getPackageSplit(dctx, shippableItemInfo, maxWeight); if (UtilValidate.isNotEmpty(packages)) { - for (Map packageMap: packages) { + for (Map packageMap : packages) { addPackageElement(dctx, requestDoc, shipmentElement, shippableItemInfo, packageMap, minWeight); } } else { @@ -1656,8 +1780,10 @@ public class UpsServices { } } - private static void addPackageElement(DispatchContext dctx, Document requestDoc, Element shipmentElement, List> shippableItemInfo, Map packageMap, BigDecimal minWeight) { - BigDecimal packageWeight = checkForDefaultPackageWeight(ShipmentWorker.calcPackageWeight(dctx, packageMap, shippableItemInfo, BigDecimal.ZERO), minWeight); + private static void addPackageElement(DispatchContext dctx, Document requestDoc, Element shipmentElement, + List> shippableItemInfo, Map packageMap, BigDecimal minWeight) { + BigDecimal packageWeight = checkForDefaultPackageWeight(ShipmentWorker.calcPackageWeight(dctx, packageMap, shippableItemInfo, + BigDecimal.ZERO), minWeight); Element packageElement = UtilXml.addChildElement(shipmentElement, "Package", requestDoc); Element packagingTypeElement = UtilXml.addChildElement(packageElement, "PackagingType", requestDoc); UtilXml.addChildElementValue(packagingTypeElement, "Code", "00", requestDoc); @@ -1671,7 +1797,7 @@ public class UpsServices { String productId = i.next(); Map productInfo = ShipmentWorker.getProductItemInfo(shippableItemInfo, productId); if (productInfo.get("inShippingBox") != null && "Y".equalsIgnoreCase((String) productInfo.get("inShippingBox")) - && productInfo.get("shippingDepth") !=null && productInfo.get("shippingWidth") !=null && productInfo.get("shippingHeight") !=null) { + && productInfo.get("shippingDepth") != null && productInfo.get("shippingWidth") != null && productInfo.get("shippingHeight") != null) { Element dimensionsElement = UtilXml.addChildElement(packageElement, "Dimensions", requestDoc); UtilXml.addChildElementValue(dimensionsElement, "Length", productInfo.get("shippingDepth").toString(), requestDoc); UtilXml.addChildElementValue(dimensionsElement, "Width", productInfo.get("shippingWidth").toString(), requestDoc); @@ -1713,7 +1839,7 @@ public class UpsServices { return ServiceUtil.returnError(UtilProperties.getMessage(RES_ERROR, "FacilityShipmentRateNotAvailable", locale)); } else { - for (Element element: rates) { + for (Element element : rates) { // get service Element service = UtilXml.firstChildElement(element, "Service"); String serviceCode = UtilXml.childElementValue(service, "Code"); @@ -1742,13 +1868,16 @@ public class UpsServices { } } - public static Document createAccessRequestDocument(Delegator delegator, String shipmentGatewayConfigId, - String serviceConfigProps) { + public static Document createAccessRequestDocument(Delegator delegator, String shipmentGatewayConfigId, + String serviceConfigProps) { Document accessRequestDocument = UtilXml.makeEmptyXmlDocument("AccessRequest"); Element accessRequestElement = accessRequestDocument.getDocumentElement(); - String accessLicenseNumber = getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "accessLicenseNumber", serviceConfigProps, "shipment.ups.access.license.number", ""); - String userId = getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "accessUserId", serviceConfigProps, "shipment.ups.access.user.id", ""); - String password = getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "accessPassword", serviceConfigProps, "shipment.ups.access.password", ""); + String accessLicenseNumber = getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "accessLicenseNumber", serviceConfigProps, + "shipment.ups.access.license.number", ""); + String userId = getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "accessUserId", serviceConfigProps, "shipment.ups.access" + + ".user.id", ""); + String password = getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "accessPassword", serviceConfigProps, "shipment.ups" + + ".access.password", ""); UtilXml.addChildElementValue(accessRequestElement, "AccessLicenseNumber", accessLicenseNumber, accessRequestDocument); UtilXml.addChildElementValue(accessRequestElement, "UserId", userId, accessRequestDocument); UtilXml.addChildElementValue(accessRequestElement, "Password", password, accessRequestDocument); @@ -1757,7 +1886,7 @@ public class UpsServices { public static void handleErrors(Element responseElement, List errorList, Locale locale) { List errorElements = UtilXml.childElementList(responseElement, "Error"); - for (Element errorElement: errorElements) { + for (Element errorElement : errorElements) { StringBuilder errorMessageBuf = new StringBuilder(); String errorSeverity = UtilXml.childElementValue(errorElement, "ErrorSeverity"); @@ -1775,7 +1904,7 @@ public class UpsServices { } List errorLocationElements = UtilXml.childElementList(errorElement, "ErrorLocation"); - for (Element errorLocationElement: errorLocationElements) { + for (Element errorLocationElement : errorLocationElements) { String errorLocationElementName = UtilXml.childElementValue(errorLocationElement, "ErrorLocationElementName"); String errorLocationAttributeName = UtilXml.childElementValue(errorLocationElement, "ErrorLocationAttributeName"); @@ -1788,7 +1917,7 @@ public class UpsServices { } List errorDigestElements = UtilXml.childElementList(errorLocationElement, "ErrorDigest"); - for (Element errorDigestElement: errorDigestElements) { + for (Element errorDigestElement : errorDigestElements) { errorMessageBuf.append(UtilProperties.getMessage(RES_ERROR, "FacilityShipmentUpsErrorWasAtElementFullText", UtilMisc.toMap("fullText", UtilXml.elementValue(errorDigestElement)), locale)); } @@ -1800,13 +1929,14 @@ public class UpsServices { /** * Opens a URL to UPS and makes a request. + * * @param upsService Name of the UPS service to invoke - * @param xmlString XML message to send + * @param xmlString XML message to send * @return XML string response from UPS * @throws UpsConnectException */ - public static String sendUpsRequest(String upsService, String xmlString, String shipmentGatewayConfigId, - String resource, Delegator delegator, Locale locale) throws UpsConnectException { + public static String sendUpsRequest(String upsService, String xmlString, String shipmentGatewayConfigId, + String resource, Delegator delegator, Locale locale) throws UpsConnectException { // need a ups service to call if (upsService == null) { @@ -1831,7 +1961,8 @@ public class UpsServices { } conStr = conStr + upsService; - String timeOutStr = getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "connectTimeout", resource, "shipment.ups.connect.timeout", "60"); + String timeOutStr = getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "connectTimeout", resource, "shipment.ups.connect" + + ".timeout", "60"); int timeout = 60; try { timeout = Integer.parseInt(timeOutStr); @@ -1893,7 +2024,8 @@ public class UpsServices { } // grab the pickup type; if none is defined we will assume daily pickup - String pickupType = getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "shipperPickupType", serviceConfigProps, "shipment.ups.shipper.pickup.type", "01"); + String pickupType = getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "shipperPickupType", serviceConfigProps, "shipment" + + ".ups.shipper.pickup.type", "01"); // if we're drop shipping from a supplier, then the address is given to us GenericValue shipFromAddress = (GenericValue) context.get("shipFromAddress"); @@ -1902,10 +2034,12 @@ public class UpsServices { // locate the ship-from address based on the product store's default facility GenericValue productStore = ProductStoreWorker.getProductStore(productStoreId, delegator); if (productStore != null && productStore.get("inventoryFacilityId") != null) { - GenericValue facilityContactMech = ContactMechWorker.getFacilityContactMechByPurpose(delegator, productStore.getString("inventoryFacilityId"), UtilMisc.toList("SHIP_ORIG_LOCATION", "PRIMARY_LOCATION")); + GenericValue facilityContactMech = ContactMechWorker.getFacilityContactMechByPurpose(delegator, productStore.getString( + "inventoryFacilityId"), UtilMisc.toList("SHIP_ORIG_LOCATION", "PRIMARY_LOCATION")); if (facilityContactMech != null) { try { - shipFromAddress = EntityQuery.use(delegator).from("PostalAddress").where("contactMechId", facilityContactMech.getString("contactMechId")).queryOne(); + shipFromAddress = EntityQuery.use(delegator).from("PostalAddress").where("contactMechId", facilityContactMech.getString( + "contactMechId")).queryOne(); } catch (GenericEntityException e) { Debug.logError(e, MODULE); } @@ -1929,7 +2063,8 @@ public class UpsServices { Debug.logError(e, MODULE); } if (carrierShipmentMethod == null) { - return ServiceUtil.returnError(UtilProperties.getMessage(RES_ERROR, "FacilityShipmentUpsUnableToLocateShippingMethodRequested", locale)); + return ServiceUtil.returnError(UtilProperties.getMessage(RES_ERROR, "FacilityShipmentUpsUnableToLocateShippingMethodRequested", + locale)); } // service code is 'carrierServiceCode' @@ -1965,7 +2100,8 @@ public class UpsServices { UtilXml.addChildElementValue(shipperAddrElement, "PostalCode", shipFromAddress.getString("postalCode"), rateRequestDoc); try { //If the warehouse you are shipping from its located in a country other than US, you need to supply its country code to UPS - UtilXml.addChildElementValue(shipperAddrElement, "CountryCode", shipFromAddress.getRelatedOne("CountryGeo", true).getString("geoCode"), rateRequestDoc); + UtilXml.addChildElementValue(shipperAddrElement, "CountryCode", shipFromAddress.getRelatedOne("CountryGeo", true).getString("geoCode"), + rateRequestDoc); } catch (GenericEntityException e) { return ServiceUtil.returnError(e.getMessage()); } @@ -1988,14 +2124,16 @@ public class UpsServices { } // package info - String maxWeightStr = getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "maxEstimateWeight", serviceConfigProps, "shipment.ups.max.estimate.weight", "99"); + String maxWeightStr = getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "maxEstimateWeight", serviceConfigProps, "shipment" + + ".ups.max.estimate.weight", "99"); BigDecimal maxWeight; try { maxWeight = new BigDecimal(maxWeightStr); } catch (NumberFormatException e) { maxWeight = new BigDecimal("99"); } - String minWeightStr = getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "minEstimateWeight", serviceConfigProps, "shipment.ups.min.estimate.weight", ".1"); + String minWeightStr = getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "minEstimateWeight", serviceConfigProps, "shipment" + + ".ups.min.estimate.weight", ".1"); BigDecimal minWeight; try { minWeight = new BigDecimal(minWeightStr); @@ -2005,11 +2143,12 @@ public class UpsServices { // Passing in a list of package weights overrides the calculation of same via shippableItemInfo if (UtilValidate.isEmpty(packageWeights)) { - String totalWeightStr = getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "minEstimateWeight", serviceConfigProps, "shipment.ups.min.estimate.weight", "1"); + String totalWeightStr = getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "minEstimateWeight", serviceConfigProps, + "shipment.ups.min.estimate.weight", "1"); splitEstimatePackages(dctx, rateRequestDoc, shipmentElement, shippableItemInfo, maxWeight, minWeight, totalWeightStr); } else { - for (BigDecimal packageWeight: packageWeights) { - addPackageElement(rateRequestDoc, shipmentElement, packageWeight); + for (BigDecimal packageWeight : packageWeights) { + addPackageElement(rateRequestDoc, shipmentElement, packageWeight); } } @@ -2023,7 +2162,7 @@ public class UpsServices { String ioeErrMsg = "Error writing the RatingServiceSelectionRequest XML Document to a String: " + e.toString(); Debug.logError(e, ioeErrMsg, MODULE); return ServiceUtil.returnFailure(UtilProperties.getMessage(RES_ERROR, - "FacilityShipmentUpsErrorRatingServiceSelectionRequestXmlToString", + "FacilityShipmentUpsErrorRatingServiceSelectionRequestXmlToString", UtilMisc.toMap("errorString", e.toString()), locale)); } @@ -2182,7 +2321,7 @@ public class UpsServices { List avResultList = UtilXml.childElementList(avResponseElement, "AddressValidationResult"); // TODO: return error if there are no matches? if (UtilValidate.isNotEmpty(avResultList)) { - for (Element avResultElement: avResultList) { + for (Element avResultElement : avResultList) { Map match = new HashMap<>(); match.put("Rank", UtilXml.childElementValue(avResultElement, "Rank")); @@ -2223,8 +2362,10 @@ public class UpsServices { if (UtilValidate.isEmpty(shipmentGatewayConfigId) && UtilValidate.isEmpty(resource)) { return ServiceUtil.returnError(UtilProperties.getMessage(RES_ERROR, "FacilityShipmentUpsGatewayNotAvailable", locale)); } - boolean shipmentUpsSaveCertificationInfo = "true".equals(getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "saveCertInfo", resource, "shipment.ups.save.certification.info", "true")); - String shipmentUpsSaveCertificationPath = FlexibleStringExpander.expandString(getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "saveCertPath", resource, "shipment.ups.save.certification.path", ""), context); + boolean shipmentUpsSaveCertificationInfo = "true".equals(getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "saveCertInfo", + resource, "shipment.ups.save.certification.info", "true")); + String shipmentUpsSaveCertificationPath = FlexibleStringExpander.expandString(getShipmentGatewayConfigValue(delegator, + shipmentGatewayConfigId, "saveCertPath", resource, "shipment.ups.save.certification.path", ""), context); File shipmentUpsSaveCertificationFile = null; if (shipmentUpsSaveCertificationInfo) { shipmentUpsSaveCertificationFile = new File(shipmentUpsSaveCertificationPath); @@ -2241,14 +2382,16 @@ public class UpsServices { if (shipment == null) { return ServiceUtil.returnError(UtilProperties.getMessage(RES_ERROR, "ProductShipmentNotFoundId", locale) + " " + shipmentId); } - GenericValue shipmentRouteSegment = EntityQuery.use(delegator).from("ShipmentRouteSegment").where("shipmentId", shipmentId, "shipmentRouteSegmentId", shipmentRouteSegmentId).queryOne(); + GenericValue shipmentRouteSegment = EntityQuery.use(delegator).from("ShipmentRouteSegment").where("shipmentId", shipmentId, + "shipmentRouteSegmentId", shipmentRouteSegmentId).queryOne(); if (shipmentRouteSegment == null) { return ServiceUtil.returnError(UtilProperties.getMessage(RES_ERROR, "ProductShipmentRouteSegmentNotFound", UtilMisc.toMap("shipmentId", shipmentId, "shipmentRouteSegmentId", shipmentRouteSegmentId), locale)); } if (!"UPS".equals(shipmentRouteSegment.getString("carrierPartyId"))) { - return ServiceUtil.returnError(UtilProperties.getMessage(RES_ERROR, "FacilityShipmentUpsNotRouteSegmentCarrier", UtilMisc.toMap("shipmentRouteSegmentId", shipmentRouteSegmentId, "shipmentId", shipmentId), locale)); + return ServiceUtil.returnError(UtilProperties.getMessage(RES_ERROR, "FacilityShipmentUpsNotRouteSegmentCarrier", UtilMisc.toMap( + "shipmentRouteSegmentId", shipmentRouteSegmentId, "shipmentId", shipmentId), locale)); } // Get Origin Info @@ -2285,7 +2428,8 @@ public class UpsServices { GenericValue destTelecomNumber = shipmentRouteSegment.getRelatedOne("DestTelecomNumber", false); if (destTelecomNumber == null) { - String missingErrMsg = "DestTelecomNumber not found for ShipmentRouteSegment with shipmentId " + shipmentId + " and shipmentRouteSegmentId " + shipmentRouteSegmentId; + String missingErrMsg = "DestTelecomNumber not found for ShipmentRouteSegment with shipmentId " + shipmentId + " and " + + "shipmentRouteSegmentId " + shipmentRouteSegmentId; Debug.logError(missingErrMsg, MODULE); } String destPhoneNumber = null; @@ -2307,14 +2451,18 @@ public class UpsServices { } GenericValue carrierShipmentMethod = EntityQuery.use(delegator).from("CarrierShipmentMethod") - .where("partyId", shipmentRouteSegment.get("carrierPartyId"), "roleTypeId", "CARRIER", "shipmentMethodTypeId", shipmentRouteSegment.get("shipmentMethodTypeId")) + .where("partyId", shipmentRouteSegment.get("carrierPartyId"), "roleTypeId", "CARRIER", "shipmentMethodTypeId", + shipmentRouteSegment.get("shipmentMethodTypeId")) .queryOne(); if (carrierShipmentMethod == null) { return ServiceUtil.returnError(UtilProperties.getMessage(RES_ERROR, "FacilityShipmentUpsRouteSegmentCarrierShipmentMethodNotFound", - UtilMisc.toMap("shipmentId", shipmentId, "shipmentRouteSegmentId", shipmentRouteSegmentId, "carrierPartyId", shipmentRouteSegment.get("carrierPartyId"), "shipmentMethodTypeId", shipmentRouteSegment.get("shipmentMethodTypeId")), locale)); + UtilMisc.toMap("shipmentId", shipmentId, "shipmentRouteSegmentId", shipmentRouteSegmentId, "carrierPartyId", + shipmentRouteSegment.get("carrierPartyId"), "shipmentMethodTypeId", shipmentRouteSegment.get("shipmentMethodTypeId")), + locale)); } - Map destEmail = dispatcher.runSync("getPartyEmail", UtilMisc.toMap("partyId", shipment.get("partyIdTo"), "userLogin", userLogin)); + Map destEmail = dispatcher.runSync("getPartyEmail", UtilMisc.toMap("partyId", shipment.get("partyIdTo"), "userLogin", + userLogin)); if (ServiceUtil.isError(destEmail)) { return ServiceUtil.returnError(ServiceUtil.getErrorMessage(destEmail)); } @@ -2323,7 +2471,8 @@ public class UpsServices { recipientEmail = (String) destEmail.get("emailAddress"); } String senderEmail = null; - Map originEmail = dispatcher.runSync("getPartyEmail", UtilMisc.toMap("partyId", shipment.get("partyIdFrom"), "userLogin", userLogin)); + Map originEmail = dispatcher.runSync("getPartyEmail", UtilMisc.toMap("partyId", shipment.get("partyIdFrom"), "userLogin" + , userLogin)); if (ServiceUtil.isError(originEmail)) { return ServiceUtil.returnError(ServiceUtil.getErrorMessage(originEmail)); } @@ -2331,7 +2480,8 @@ public class UpsServices { senderEmail = (String) originEmail.get("emailAddress"); } - List shipmentPackageRouteSegs = shipmentRouteSegment.getRelated("ShipmentPackageRouteSeg", null, UtilMisc.toList("+shipmentPackageSeqId"), false); + List shipmentPackageRouteSegs = shipmentRouteSegment.getRelated("ShipmentPackageRouteSeg", null, UtilMisc.toList( + "+shipmentPackageSeqId"), false); if (UtilValidate.isEmpty(shipmentPackageRouteSegs)) { return ServiceUtil.returnError(UtilProperties.getMessage(RES_ERROR, "FacilityShipmentUpsPackageRouteSegsNotFound", UtilMisc.toMap("shipmentId", shipmentId, "shipmentRouteSegmentId", shipmentRouteSegmentId), locale)); @@ -2350,44 +2500,54 @@ public class UpsServices { // Top Level Element: Shipment Element shipmentElement = UtilXml.addChildElement(shipmentConfirmRequestElement, "Shipment", shipmentConfirmRequestDoc); - UtilXml.addChildElementValue(shipmentElement, "Description", "Goods for Shipment " + shipment.get("shipmentId"), shipmentConfirmRequestDoc); + UtilXml.addChildElementValue(shipmentElement, "Description", "Goods for Shipment " + shipment.get("shipmentId"), + shipmentConfirmRequestDoc); // Child of Shipment: ReturnService Element returnServiceElement = UtilXml.addChildElement(shipmentElement, "ReturnService", shipmentConfirmRequestDoc); UtilXml.addChildElementValue(returnServiceElement, "Code", String.valueOf(RET_SERVICE_CODE), shipmentConfirmRequestDoc); // Child of Shipment: Shipper - String shipperNumber = getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "shipperNumber", resource, "shipment.ups.shipper.number", ""); + String shipperNumber = getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "shipperNumber", resource, "shipment.ups" + + ".shipper.number", ""); Element shipperElement = UtilXml.addChildElement(shipmentElement, "Shipper", shipmentConfirmRequestDoc); - UtilXml.addChildElementValue(shipperElement, "Name", UtilValidate.isNotEmpty(originPostalAddress.getString("toName")) ? originPostalAddress.getString("toName"): "", shipmentConfirmRequestDoc); - UtilXml.addChildElementValue(shipperElement, "AttentionName", UtilValidate.isNotEmpty(originPostalAddress.getString("attnName")) ? originPostalAddress.getString("attnName") : "", shipmentConfirmRequestDoc); + UtilXml.addChildElementValue(shipperElement, "Name", UtilValidate.isNotEmpty(originPostalAddress.getString("toName")) ? + originPostalAddress.getString("toName") : "", shipmentConfirmRequestDoc); + UtilXml.addChildElementValue(shipperElement, "AttentionName", UtilValidate.isNotEmpty(originPostalAddress.getString("attnName")) ? + originPostalAddress.getString("attnName") : "", shipmentConfirmRequestDoc); UtilXml.addChildElementValue(shipperElement, "PhoneNumber", originPhoneNumber, shipmentConfirmRequestDoc); UtilXml.addChildElementValue(shipperElement, "ShipperNumber", shipperNumber, shipmentConfirmRequestDoc); Element shipperAddressElement = UtilXml.addChildElement(shipperElement, "Address", shipmentConfirmRequestDoc); UtilXml.addChildElementValue(shipperAddressElement, "AddressLine1", originPostalAddress.getString("address1"), shipmentConfirmRequestDoc); if (UtilValidate.isNotEmpty(originPostalAddress.getString("address2"))) { - UtilXml.addChildElementValue(shipperAddressElement, "AddressLine2", originPostalAddress.getString("address2"), shipmentConfirmRequestDoc); + UtilXml.addChildElementValue(shipperAddressElement, "AddressLine2", originPostalAddress.getString("address2"), + shipmentConfirmRequestDoc); } UtilXml.addChildElementValue(shipperAddressElement, "City", originPostalAddress.getString("city"), shipmentConfirmRequestDoc); - UtilXml.addChildElementValue(shipperAddressElement, "StateProvinceCode", originPostalAddress.getString("stateProvinceGeoId"), shipmentConfirmRequestDoc); + UtilXml.addChildElementValue(shipperAddressElement, "StateProvinceCode", originPostalAddress.getString("stateProvinceGeoId"), + shipmentConfirmRequestDoc); UtilXml.addChildElementValue(shipperAddressElement, "PostalCode", originPostalAddress.getString("postalCode"), shipmentConfirmRequestDoc); UtilXml.addChildElementValue(shipperAddressElement, "CountryCode", originCountryGeo.getString("geoCode"), shipmentConfirmRequestDoc); // Child of Shipment: ShipTo Element shipToElement = UtilXml.addChildElement(shipmentElement, "ShipTo", shipmentConfirmRequestDoc); - UtilXml.addChildElementValue(shipToElement, "CompanyName", UtilValidate.isNotEmpty(destPostalAddress.getString("toName")) ? destPostalAddress.getString("toName") : "", shipmentConfirmRequestDoc); - UtilXml.addChildElementValue(shipToElement, "AttentionName", UtilValidate.isNotEmpty(destPostalAddress.getString("attnName")) ? destPostalAddress.getString("attnName") : "", shipmentConfirmRequestDoc); + UtilXml.addChildElementValue(shipToElement, "CompanyName", UtilValidate.isNotEmpty(destPostalAddress.getString("toName")) ? + destPostalAddress.getString("toName") : "", shipmentConfirmRequestDoc); + UtilXml.addChildElementValue(shipToElement, "AttentionName", UtilValidate.isNotEmpty(destPostalAddress.getString("attnName")) ? + destPostalAddress.getString("attnName") : "", shipmentConfirmRequestDoc); if (UtilValidate.isNotEmpty(destPhoneNumber)) { UtilXml.addChildElementValue(shipToElement, "PhoneNumber", destPhoneNumber, shipmentConfirmRequestDoc); } Element shipToAddressElement = UtilXml.addChildElement(shipToElement, "Address", shipmentConfirmRequestDoc); UtilXml.addChildElementValue(shipToAddressElement, "AddressLine1", destPostalAddress.getString("address1"), shipmentConfirmRequestDoc); if (UtilValidate.isNotEmpty(destPostalAddress.getString("address2"))) { - UtilXml.addChildElementValue(shipToAddressElement, "AddressLine2", destPostalAddress.getString("address2"), shipmentConfirmRequestDoc); + UtilXml.addChildElementValue(shipToAddressElement, "AddressLine2", destPostalAddress.getString("address2"), + shipmentConfirmRequestDoc); } UtilXml.addChildElementValue(shipToAddressElement, "City", destPostalAddress.getString("city"), shipmentConfirmRequestDoc); - UtilXml.addChildElementValue(shipToAddressElement, "StateProvinceCode", destPostalAddress.getString("stateProvinceGeoId"), shipmentConfirmRequestDoc); + UtilXml.addChildElementValue(shipToAddressElement, "StateProvinceCode", destPostalAddress.getString("stateProvinceGeoId"), + shipmentConfirmRequestDoc); UtilXml.addChildElementValue(shipToAddressElement, "PostalCode", destPostalAddress.getString("postalCode"), shipmentConfirmRequestDoc); UtilXml.addChildElementValue(shipToAddressElement, "CountryCode", destCountryGeo.getString("geoCode"), shipmentConfirmRequestDoc); if (UtilValidate.isNotEmpty(shipmentRouteSegment.getString("homeDeliveryType"))) { @@ -2396,17 +2556,23 @@ public class UpsServices { // Child of Shipment: ShipFrom Element shipFromElement = UtilXml.addChildElement(shipmentElement, "ShipFrom", shipmentConfirmRequestDoc); - UtilXml.addChildElementValue(shipFromElement, "CompanyName", UtilValidate.isNotEmpty(originPostalAddress.getString("toName")) ? originPostalAddress.getString("toName") : "", shipmentConfirmRequestDoc); - UtilXml.addChildElementValue(shipFromElement, "AttentionName", UtilValidate.isNotEmpty(originPostalAddress.getString("attnName")) ? originPostalAddress.getString("attnName") : "", shipmentConfirmRequestDoc); + UtilXml.addChildElementValue(shipFromElement, "CompanyName", UtilValidate.isNotEmpty(originPostalAddress.getString("toName")) ? + originPostalAddress.getString("toName") : "", shipmentConfirmRequestDoc); + UtilXml.addChildElementValue(shipFromElement, "AttentionName", UtilValidate.isNotEmpty(originPostalAddress.getString("attnName")) ? + originPostalAddress.getString("attnName") : "", shipmentConfirmRequestDoc); UtilXml.addChildElementValue(shipFromElement, "PhoneNumber", originPhoneNumber, shipmentConfirmRequestDoc); Element shipFromAddressElement = UtilXml.addChildElement(shipFromElement, "Address", shipmentConfirmRequestDoc); - UtilXml.addChildElementValue(shipFromAddressElement, "AddressLine1", originPostalAddress.getString("address1"), shipmentConfirmRequestDoc); + UtilXml.addChildElementValue(shipFromAddressElement, "AddressLine1", originPostalAddress.getString("address1"), + shipmentConfirmRequestDoc); if (UtilValidate.isNotEmpty(originPostalAddress.getString("address2"))) { - UtilXml.addChildElementValue(shipFromAddressElement, "AddressLine2", originPostalAddress.getString("address2"), shipmentConfirmRequestDoc); + UtilXml.addChildElementValue(shipFromAddressElement, "AddressLine2", originPostalAddress.getString("address2"), + shipmentConfirmRequestDoc); } UtilXml.addChildElementValue(shipFromAddressElement, "City", originPostalAddress.getString("city"), shipmentConfirmRequestDoc); - UtilXml.addChildElementValue(shipFromAddressElement, "StateProvinceCode", originPostalAddress.getString("stateProvinceGeoId"), shipmentConfirmRequestDoc); - UtilXml.addChildElementValue(shipFromAddressElement, "PostalCode", originPostalAddress.getString("postalCode"), shipmentConfirmRequestDoc); + UtilXml.addChildElementValue(shipFromAddressElement, "StateProvinceCode", originPostalAddress.getString("stateProvinceGeoId"), + shipmentConfirmRequestDoc); + UtilXml.addChildElementValue(shipFromAddressElement, "PostalCode", originPostalAddress.getString("postalCode"), + shipmentConfirmRequestDoc); UtilXml.addChildElementValue(shipFromAddressElement, "CountryCode", originCountryGeo.getString("geoCode"), shipmentConfirmRequestDoc); // Child of Shipment: PaymentInformation @@ -2420,7 +2586,8 @@ public class UpsServices { Element billShipperElement = UtilXml.addChildElement(prepaidElement, "BillShipper", shipmentConfirmRequestDoc); // fill in BillShipper AccountNumber element from properties file - String billShipperAccountNumber = getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "billShipperAccountNumber", resource, "shipment.ups.bill.shipper.account.number", ""); + String billShipperAccountNumber = getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "billShipperAccountNumber", + resource, "shipment.ups.bill.shipper.account.number", ""); UtilXml.addChildElementValue(billShipperElement, "AccountNumber", billShipperAccountNumber, shipmentConfirmRequestDoc); } @@ -2429,14 +2596,17 @@ public class UpsServices { UtilXml.addChildElementValue(serviceElement, "Code", carrierShipmentMethod.getString("carrierServiceCode"), shipmentConfirmRequestDoc); // Child of Shipment: ShipmentServiceOptions - String defaultReturnLabelMemo = getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "defaultReturnLabelMemo", resource, "shipment.ups.default.returnLabel.memo", ""); - String defaultReturnLabelSubject = getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "defaultReturnLabelSubject", resource, "shipment.ups.default.returnLabel.subject", ""); + String defaultReturnLabelMemo = getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "defaultReturnLabelMemo", resource, + "shipment.ups.default.returnLabel.memo", ""); + String defaultReturnLabelSubject = getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "defaultReturnLabelSubject", + resource, "shipment.ups.default.returnLabel.subject", ""); Element shipmentServiceOptionsElement = UtilXml.addChildElement(shipmentElement, "ShipmentServiceOptions", shipmentConfirmRequestDoc); Element labelDeliveryElement = UtilXml.addChildElement(shipmentServiceOptionsElement, "LabelDelivery", shipmentConfirmRequestDoc); Element emailMessageElement = UtilXml.addChildElement(labelDeliveryElement, "EMailMessage", shipmentConfirmRequestDoc); UtilXml.addChildElementValue(emailMessageElement, "EMailAddress", recipientEmail, shipmentConfirmRequestDoc); UtilXml.addChildElementValue(emailMessageElement, "FromEMailAddress", senderEmail, shipmentConfirmRequestDoc); - UtilXml.addChildElementValue(emailMessageElement, "FromName", UtilValidate.isNotEmpty(originPostalAddress.getString("attnName")) ? originPostalAddress.getString("attnName") : "", shipmentConfirmRequestDoc); + UtilXml.addChildElementValue(emailMessageElement, "FromName", UtilValidate.isNotEmpty(originPostalAddress.getString("attnName")) ? + originPostalAddress.getString("attnName") : "", shipmentConfirmRequestDoc); UtilXml.addChildElementValue(emailMessageElement, "Memo", defaultReturnLabelMemo, shipmentConfirmRequestDoc); UtilXml.addChildElementValue(emailMessageElement, "Subject", defaultReturnLabelSubject, shipmentConfirmRequestDoc); @@ -2448,7 +2618,8 @@ public class UpsServices { Element packageWeightElement = UtilXml.addChildElement(packageElement, "PackageWeight", shipmentConfirmRequestDoc); Element packageWeightUnitOfMeasurementElement = UtilXml.addChildElement(packageElement, "UnitOfMeasurement", shipmentConfirmRequestDoc); UtilXml.addChildElementValue(packageWeightUnitOfMeasurementElement, "Code", "LBS", shipmentConfirmRequestDoc); - UtilXml.addChildElementValue(packageWeightElement, "Weight", EntityUtilProperties.getPropertyValue("shipment", "shipment.default.weight.value", delegator), shipmentConfirmRequestDoc); + UtilXml.addChildElementValue(packageWeightElement, "Weight", EntityUtilProperties.getPropertyValue("shipment", "shipment.default.weight" + + ".value", delegator), shipmentConfirmRequestDoc); String shipmentConfirmRequestString = null; try { @@ -2479,7 +2650,8 @@ public class UpsServices { xmlString.append(accessRequestString); xmlString.append(shipmentConfirmRequestString); try { - shipmentConfirmResponseString = sendUpsRequest("ShipConfirm", xmlString.toString(), shipmentGatewayConfigId, resource, delegator, locale); + shipmentConfirmResponseString = sendUpsRequest("ShipConfirm", xmlString.toString(), shipmentGatewayConfigId, resource, delegator, + locale); } catch (UpsConnectException e) { String uceErrMsg = "Error sending UPS request for UPS Service ShipConfirm: " + e.toString(); Debug.logError(e, uceErrMsg, MODULE); @@ -2509,7 +2681,8 @@ public class UpsServices { //Shipment Accept Request follows if (!"UPS".equals(shipmentRouteSegment.getString("carrierPartyId"))) { - return ServiceUtil.returnError(UtilProperties.getMessage(RES_ERROR, "FacilityShipmentUpsNotRouteSegmentCarrier", UtilMisc.toMap("shipmentRouteSegmentId", shipmentRouteSegmentId, "shipmentId", shipmentId), locale)); + return ServiceUtil.returnError(UtilProperties.getMessage(RES_ERROR, "FacilityShipmentUpsNotRouteSegmentCarrier", UtilMisc.toMap( + "shipmentRouteSegmentId", shipmentRouteSegmentId, "shipmentId", shipmentId), locale)); } if (UtilValidate.isEmpty(shipmentPackageRouteSegs)) { @@ -2530,7 +2703,8 @@ public class UpsServices { // Top Level Element: Request Element acceptRequestElement = UtilXml.addChildElement(shipmentAcceptRequestElement, "Request", shipmentAcceptRequestDoc); - Element acceptTransactionReferenceElement = UtilXml.addChildElement(acceptRequestElement, "TransactionReference", shipmentAcceptRequestDoc); + Element acceptTransactionReferenceElement = UtilXml.addChildElement(acceptRequestElement, "TransactionReference", + shipmentAcceptRequestDoc); UtilXml.addChildElementValue(acceptTransactionReferenceElement, "CustomerContext", "ShipAccept / 01", shipmentAcceptRequestDoc); UtilXml.addChildElementValue(acceptTransactionReferenceElement, "XpciVersion", "1.0001", shipmentAcceptRequestDoc); @@ -2569,7 +2743,9 @@ public class UpsServices { acceptXmlString.append(shipmentAcceptRequestString); if (shipmentUpsSaveCertificationInfo) { - String outFileName = shipmentUpsSaveCertificationPath + "/UpsShipmentAcceptRequest" + shipmentId + "_" + shipmentRouteSegment.getString("shipmentRouteSegmentId") + ".xml"; + String outFileName = + shipmentUpsSaveCertificationPath + "/UpsShipmentAcceptRequest" + shipmentId + "_" + shipmentRouteSegment.getString( + "shipmentRouteSegmentId") + ".xml"; try (FileOutputStream fileOut = new FileOutputStream(outFileName)) { fileOut.write(xmlString.toString().getBytes(StandardCharsets.UTF_8)); fileOut.flush(); @@ -2618,9 +2794,11 @@ public class UpsServices { try { if (shipmentRouteSegmentId != null) { - shipmentRouteSegment = EntityQuery.use(delegator).from("ShipmentRouteSegment").where("shipmentId", shipmentId, "shipmentRouteSegmentId", shipmentRouteSegmentId).queryOne(); + shipmentRouteSegment = EntityQuery.use(delegator).from("ShipmentRouteSegment").where("shipmentId", shipmentId, + "shipmentRouteSegmentId", shipmentRouteSegmentId).queryOne(); } else { - shipmentRouteSegment = EntityQuery.use(delegator).from("ShipmentRouteSegment").where(EntityCondition.makeCondition("shipmentId", EntityOperator.EQUALS, shipmentId)).queryFirst(); + shipmentRouteSegment = EntityQuery.use(delegator).from("ShipmentRouteSegment").where(EntityCondition.makeCondition("shipmentId", + EntityOperator.EQUALS, shipmentId)).queryFirst(); } if (shipmentRouteSegment == null) { @@ -2630,7 +2808,8 @@ public class UpsServices { shipmentRouteSegmentId = shipmentRouteSegment.getString("shipmentRouteSegmentId"); if (!"UPS".equals(shipmentRouteSegment.getString("carrierPartyId"))) { - return ServiceUtil.returnError(UtilProperties.getMessage(RES_ERROR, "FacilityShipmentUpsNotRouteSegmentCarrier", UtilMisc.toMap("shipmentRouteSegmentId", shipmentRouteSegmentId, "shipmentId", shipmentId), locale)); + return ServiceUtil.returnError(UtilProperties.getMessage(RES_ERROR, "FacilityShipmentUpsNotRouteSegmentCarrier", UtilMisc.toMap( + "shipmentRouteSegmentId", shipmentRouteSegmentId, "shipmentId", shipmentId), locale)); } // Get Origin Info @@ -2667,7 +2846,8 @@ public class UpsServices { GenericValue destTelecomNumber = shipmentRouteSegment.getRelatedOne("DestTelecomNumber", false); if (destTelecomNumber == null) { - String missingErrMsg = "DestTelecomNumber not found for ShipmentRouteSegment with shipmentId " + shipmentId + " and shipmentRouteSegmentId " + shipmentRouteSegmentId; + String missingErrMsg = "DestTelecomNumber not found for ShipmentRouteSegment with shipmentId " + shipmentId + " and " + + "shipmentRouteSegmentId " + shipmentRouteSegmentId; Debug.logError(missingErrMsg, MODULE); // for now we won't require the dest phone number, but is it required? } @@ -2690,10 +2870,12 @@ public class UpsServices { } // grab the pickup type; if none is defined we will assume daily pickup - String pickupType = getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "shipperPickupType", resource, "shipment.ups.shipper.pickup.type", "01"); + String pickupType = getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "shipperPickupType", resource, "shipment.ups" + + ".shipper.pickup.type", "01"); // grab the customer classification; if none is defined we will assume daily pickup - String customerClassification = getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "customerClassification", resource, "shipment.ups.customerclassification", "01"); + String customerClassification = getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "customerClassification", resource, + "shipment.ups.customerclassification", "01"); // should be shop to get estimates for all the possible shipping method of UPS upsRateInquireMode = "Shop"; @@ -2723,10 +2905,13 @@ public class UpsServices { // shipment info Element shipmentElement = UtilXml.addChildElement(rateRequestElement, "Shipment", rateRequestDoc); Element shipperElement = UtilXml.addChildElement(shipmentElement, "Shipper", rateRequestDoc); - UtilXml.addChildElementValue(shipperElement, "Name", UtilValidate.isNotEmpty(originPostalAddress.getString("toName")) ? originPostalAddress.getString("toName") : "", rateRequestDoc); - UtilXml.addChildElementValue(shipperElement, "AttentionName", UtilValidate.isNotEmpty(originPostalAddress.getString("attnName")) ? originPostalAddress.getString("attnName") : "", rateRequestDoc); + UtilXml.addChildElementValue(shipperElement, "Name", UtilValidate.isNotEmpty(originPostalAddress.getString("toName")) ? + originPostalAddress.getString("toName") : "", rateRequestDoc); + UtilXml.addChildElementValue(shipperElement, "AttentionName", UtilValidate.isNotEmpty(originPostalAddress.getString("attnName")) ? + originPostalAddress.getString("attnName") : "", rateRequestDoc); UtilXml.addChildElementValue(shipperElement, "PhoneNumber", originPhoneNumber, rateRequestDoc); - UtilXml.addChildElementValue(shipperElement, "ShipperNumber", EntityUtilProperties.getPropertyValue("shipment", "shipment.ups.shipper.number", delegator), rateRequestDoc); + UtilXml.addChildElementValue(shipperElement, "ShipperNumber", EntityUtilProperties.getPropertyValue("shipment", "shipment.ups.shipper" + + ".number", delegator), rateRequestDoc); Element shipperAddressElement = UtilXml.addChildElement(shipperElement, "Address", rateRequestDoc); UtilXml.addChildElementValue(shipperAddressElement, "AddressLine1", originPostalAddress.getString("address1"), rateRequestDoc); @@ -2735,14 +2920,17 @@ public class UpsServices { } UtilXml.addChildElementValue(shipperAddressElement, "City", originPostalAddress.getString("city"), rateRequestDoc); - UtilXml.addChildElementValue(shipperAddressElement, "StateProvinceCode", originPostalAddress.getString("stateProvinceGeoId"), rateRequestDoc); + UtilXml.addChildElementValue(shipperAddressElement, "StateProvinceCode", originPostalAddress.getString("stateProvinceGeoId"), + rateRequestDoc); UtilXml.addChildElementValue(shipperAddressElement, "PostalCode", originPostalAddress.getString("postalCode"), rateRequestDoc); UtilXml.addChildElementValue(shipperAddressElement, "CountryCode", originCountryGeo.getString("geoCode"), rateRequestDoc); // Child of Shipment: ShipTo Element shipToElement = UtilXml.addChildElement(shipmentElement, "ShipTo", rateRequestDoc); - UtilXml.addChildElementValue(shipToElement, "CompanyName", UtilValidate.isNotEmpty(destPostalAddress.getString("toName")) ? destPostalAddress.getString("toName") : "", rateRequestDoc); - UtilXml.addChildElementValue(shipToElement, "AttentionName", UtilValidate.isNotEmpty(destPostalAddress.getString("attnName")) ? destPostalAddress.getString("attnName") : "", rateRequestDoc); + UtilXml.addChildElementValue(shipToElement, "CompanyName", UtilValidate.isNotEmpty(destPostalAddress.getString("toName")) ? + destPostalAddress.getString("toName") : "", rateRequestDoc); + UtilXml.addChildElementValue(shipToElement, "AttentionName", UtilValidate.isNotEmpty(destPostalAddress.getString("attnName")) ? + destPostalAddress.getString("attnName") : "", rateRequestDoc); if (UtilValidate.isNotEmpty(destPhoneNumber)) { UtilXml.addChildElementValue(shipToElement, "PhoneNumber", destPhoneNumber, rateRequestDoc); } @@ -2753,7 +2941,8 @@ public class UpsServices { } UtilXml.addChildElementValue(shipToAddressElement, "City", destPostalAddress.getString("city"), rateRequestDoc); - UtilXml.addChildElementValue(shipToAddressElement, "StateProvinceCode", destPostalAddress.getString("stateProvinceGeoId"), rateRequestDoc); + UtilXml.addChildElementValue(shipToAddressElement, "StateProvinceCode", destPostalAddress.getString("stateProvinceGeoId"), + rateRequestDoc); UtilXml.addChildElementValue(shipToAddressElement, "PostalCode", destPostalAddress.getString("postalCode"), rateRequestDoc); UtilXml.addChildElementValue(shipToAddressElement, "CountryCode", destCountryGeo.getString("geoCode"), rateRequestDoc); if (UtilValidate.isNotEmpty(shipmentRouteSegment.getString("homeDeliveryType"))) { @@ -2762,8 +2951,10 @@ public class UpsServices { // Child of Shipment: ShipFrom Element shipFromElement = UtilXml.addChildElement(shipmentElement, "ShipFrom", rateRequestDoc); - UtilXml.addChildElementValue(shipFromElement, "CompanyName", UtilValidate.isNotEmpty(originPostalAddress.getString("toName")) ? originPostalAddress.getString("toName") : "", rateRequestDoc); - UtilXml.addChildElementValue(shipFromElement, "AttentionName", UtilValidate.isNotEmpty(originPostalAddress.getString("attnName")) ? originPostalAddress.getString("attnName") : "", rateRequestDoc); + UtilXml.addChildElementValue(shipFromElement, "CompanyName", UtilValidate.isNotEmpty(originPostalAddress.getString("toName")) ? + originPostalAddress.getString("toName") : "", rateRequestDoc); + UtilXml.addChildElementValue(shipFromElement, "AttentionName", UtilValidate.isNotEmpty(originPostalAddress.getString("attnName")) ? + originPostalAddress.getString("attnName") : "", rateRequestDoc); UtilXml.addChildElementValue(shipFromElement, "PhoneNumber", originPhoneNumber, rateRequestDoc); Element shipFromAddressElement = UtilXml.addChildElement(shipFromElement, "Address", rateRequestDoc); UtilXml.addChildElementValue(shipFromAddressElement, "AddressLine1", originPostalAddress.getString("address1"), rateRequestDoc); @@ -2771,20 +2962,23 @@ public class UpsServices { UtilXml.addChildElementValue(shipFromAddressElement, "AddressLine2", originPostalAddress.getString("address2"), rateRequestDoc); } UtilXml.addChildElementValue(shipFromAddressElement, "City", originPostalAddress.getString("city"), rateRequestDoc); - UtilXml.addChildElementValue(shipFromAddressElement, "StateProvinceCode", originPostalAddress.getString("stateProvinceGeoId"), rateRequestDoc); + UtilXml.addChildElementValue(shipFromAddressElement, "StateProvinceCode", originPostalAddress.getString("stateProvinceGeoId"), + rateRequestDoc); UtilXml.addChildElementValue(shipFromAddressElement, "PostalCode", originPostalAddress.getString("postalCode"), rateRequestDoc); UtilXml.addChildElementValue(shipFromAddressElement, "CountryCode", originCountryGeo.getString("geoCode"), rateRequestDoc); - List shipmentPackageRouteSegs = shipmentRouteSegment.getRelated("ShipmentPackageRouteSeg", null, UtilMisc.toList("+shipmentPackageSeqId"), false); + List shipmentPackageRouteSegs = shipmentRouteSegment.getRelated("ShipmentPackageRouteSeg", null, UtilMisc.toList( + "+shipmentPackageSeqId"), false); if (UtilValidate.isEmpty(shipmentPackageRouteSegs)) { return ServiceUtil.returnError(UtilProperties.getMessage(RES_ERROR, "FacilityShipmentUpsPackageRouteSegsNotFound", UtilMisc.toMap("shipmentId", shipmentId, "shipmentRouteSegmentId", shipmentRouteSegmentId), locale)); } - for (GenericValue shipmentPackageRouteSeg :shipmentPackageRouteSegs) { + for (GenericValue shipmentPackageRouteSeg : shipmentPackageRouteSegs) { GenericValue shipmentPackage = shipmentPackageRouteSeg.getRelatedOne("ShipmentPackage", false); GenericValue shipmentBoxType = shipmentPackage.getRelatedOne("ShipmentBoxType", false); - List carrierShipmentBoxTypes = shipmentPackage.getRelated("CarrierShipmentBoxType", UtilMisc.toMap("partyId", "UPS"), null, false); + List carrierShipmentBoxTypes = shipmentPackage.getRelated("CarrierShipmentBoxType", UtilMisc.toMap("partyId", "UPS"), + null, false); GenericValue carrierShipmentBoxType = null; if (carrierShipmentBoxTypes.size() > 0) { carrierShipmentBoxType = carrierShipmentBoxTypes.get(0); @@ -2797,35 +2991,38 @@ public class UpsServices { } else { // default to "02", plain old Package UtilXml.addChildElementValue(packagingTypeElement, "Code", "02", rateRequestDoc); - } + } if (shipmentBoxType != null) { Element dimensionsElement = UtilXml.addChildElement(packageElement, "Dimensions", rateRequestDoc); Element unitOfMeasurementElement = UtilXml.addChildElement(dimensionsElement, "UnitOfMeasurement", rateRequestDoc); GenericValue dimensionUom = shipmentBoxType.getRelatedOne("DimensionUom", false); if (dimensionUom != null) { - UtilXml.addChildElementValue(unitOfMeasurementElement, "Code", dimensionUom.getString("abbreviation").toUpperCase(Locale.getDefault()), rateRequestDoc); + UtilXml.addChildElementValue(unitOfMeasurementElement, "Code", + dimensionUom.getString("abbreviation").toUpperCase(Locale.getDefault()), rateRequestDoc); } else { UtilXml.addChildElementValue(unitOfMeasurementElement, "Code", ModelService.IN_PARAM, rateRequestDoc); } BigDecimal boxLength = shipmentBoxType.getBigDecimal("boxLength"); BigDecimal boxWidth = shipmentBoxType.getBigDecimal("boxWidth"); BigDecimal boxHeight = shipmentBoxType.getBigDecimal("boxHeight"); - UtilXml.addChildElementValue(dimensionsElement, "Length", UtilValidate.isNotEmpty(boxLength) ? ""+boxLength.intValue() : "", rateRequestDoc); - UtilXml.addChildElementValue(dimensionsElement, "Width", UtilValidate.isNotEmpty(boxWidth) ? ""+boxWidth.intValue() : "", rateRequestDoc); - UtilXml.addChildElementValue(dimensionsElement, "Height", UtilValidate.isNotEmpty(boxHeight) ? ""+boxHeight.intValue() : "", rateRequestDoc); - } - else if - (UtilValidate.isNotEmpty(shipmentPackage.get("boxLength")) && UtilValidate.isNotEmpty(shipmentPackage.get("boxWidth")) && - UtilValidate.isNotEmpty(shipmentPackage.get("boxHeight"))) { - Element dimensionsElement = UtilXml.addChildElement(packageElement, "Dimensions", rateRequestDoc); - Element unitOfMeasurementElement = UtilXml.addChildElement(dimensionsElement, "UnitOfMeasurement", rateRequestDoc); - UtilXml.addChildElementValue(unitOfMeasurementElement, "Code", ModelService.IN_PARAM, rateRequestDoc); - BigDecimal length = (BigDecimal) shipmentPackage.get("boxLength"); - BigDecimal width = (BigDecimal) shipmentPackage.get("boxWidth"); - BigDecimal height = (BigDecimal) shipmentPackage.get("boxHeight"); - UtilXml.addChildElementValue(dimensionsElement, "Length", length.setScale(DECIMALS, ROUNDING).toString(), rateRequestDoc); - UtilXml.addChildElementValue(dimensionsElement, "Width", width.setScale(DECIMALS, ROUNDING).toString(), rateRequestDoc); - UtilXml.addChildElementValue(dimensionsElement, "Height", height.setScale(DECIMALS, ROUNDING).toString(), rateRequestDoc); + UtilXml.addChildElementValue(dimensionsElement, "Length", UtilValidate.isNotEmpty(boxLength) ? "" + boxLength.intValue() : "", + rateRequestDoc); + UtilXml.addChildElementValue(dimensionsElement, "Width", UtilValidate.isNotEmpty(boxWidth) ? "" + boxWidth.intValue() : "", + rateRequestDoc); + UtilXml.addChildElementValue(dimensionsElement, "Height", UtilValidate.isNotEmpty(boxHeight) ? "" + boxHeight.intValue() : "", + rateRequestDoc); + } else if + (UtilValidate.isNotEmpty(shipmentPackage.get("boxLength")) && UtilValidate.isNotEmpty(shipmentPackage.get("boxWidth")) && + UtilValidate.isNotEmpty(shipmentPackage.get("boxHeight"))) { + Element dimensionsElement = UtilXml.addChildElement(packageElement, "Dimensions", rateRequestDoc); + Element unitOfMeasurementElement = UtilXml.addChildElement(dimensionsElement, "UnitOfMeasurement", rateRequestDoc); + UtilXml.addChildElementValue(unitOfMeasurementElement, "Code", ModelService.IN_PARAM, rateRequestDoc); + BigDecimal length = (BigDecimal) shipmentPackage.get("boxLength"); + BigDecimal width = (BigDecimal) shipmentPackage.get("boxWidth"); + BigDecimal height = (BigDecimal) shipmentPackage.get("boxHeight"); + UtilXml.addChildElementValue(dimensionsElement, "Length", length.setScale(DECIMALS, ROUNDING).toString(), rateRequestDoc); + UtilXml.addChildElementValue(dimensionsElement, "Width", width.setScale(DECIMALS, ROUNDING).toString(), rateRequestDoc); + UtilXml.addChildElementValue(dimensionsElement, "Height", height.setScale(DECIMALS, ROUNDING).toString(), rateRequestDoc); } Element packageWeightElement = UtilXml.addChildElement(packageElement, "PackageWeight", rateRequestDoc); @@ -2840,10 +3037,12 @@ public class UpsServices { if (shipmentPackage.getString("weight") == null) { return ServiceUtil.returnError(UtilProperties.getMessage(RES_ERROR, "FacilityShipmentUpsWeightValueNotFound", - UtilMisc.toMap("shipmentId", shipmentId, "shipmentRouteSegmentId", shipmentRouteSegmentId, "shipmentPackageSeqId", shipmentPackage.getString("shipmentPackageSeqId")), locale)); + UtilMisc.toMap("shipmentId", shipmentId, "shipmentRouteSegmentId", shipmentRouteSegmentId, "shipmentPackageSeqId", + shipmentPackage.getString("shipmentPackageSeqId")), locale)); } BigDecimal boxWeight = shipmentPackage.getBigDecimal("weight"); - UtilXml.addChildElementValue(packageWeightElement, "Weight", UtilValidate.isNotEmpty(boxWeight) ? ""+boxWeight.intValue() : "", rateRequestDoc); + UtilXml.addChildElementValue(packageWeightElement, "Weight", UtilValidate.isNotEmpty(boxWeight) ? "" + boxWeight.intValue() : "", + rateRequestDoc); } // service options @@ -2855,7 +3054,7 @@ public class UpsServices { String ioeErrMsg = "Error writing the RatingServiceSelectionRequest XML Document to a String: " + e.toString(); Debug.logError(e, ioeErrMsg, MODULE); return ServiceUtil.returnFailure(UtilProperties.getMessage(RES_ERROR, - "FacilityShipmentUpsErrorRatingServiceSelectionRequestXmlToString", + "FacilityShipmentUpsErrorRatingServiceSelectionRequestXmlToString", UtilMisc.toMap("errorString", e.toString()), locale)); } @@ -2868,7 +3067,7 @@ public class UpsServices { String ioeErrMsg = "Error writing the AccessRequest XML Document to a String: " + e.toString(); Debug.logError(e, ioeErrMsg, MODULE); return ServiceUtil.returnFailure(UtilProperties.getMessage(RES_ERROR, - "FacilityShipmentUpsErrorAccessRequestXmlToString", + "FacilityShipmentUpsErrorAccessRequestXmlToString", UtilMisc.toMap("errorString", e.toString()), locale)); } @@ -2903,12 +3102,14 @@ public class UpsServices { GenericValue carrierShipmentMethod = null; // Filtering out rates of shipping methods which are not configured in ProductStoreShipmentMeth entity. try { - List productStoreShipmentMethods = EntityQuery.use(delegator).from("ProductStoreShipmentMethView").where("productStoreId", productStoreId).queryList(); - for (GenericValue productStoreShipmentMethod :productStoreShipmentMethods) { + List productStoreShipmentMethods = EntityQuery.use(delegator).from("ProductStoreShipmentMethView").where( + "productStoreId", productStoreId).queryList(); + for (GenericValue productStoreShipmentMethod : productStoreShipmentMethods) { if ("UPS".equals(productStoreShipmentMethod.get("partyId"))) { Map thisUpsRateCodeMap = new HashMap<>(); carrierShipmentMethod = EntityQuery.use(delegator).from("CarrierShipmentMethod") - .where("shipmentMethodTypeId", productStoreShipmentMethod.getString("shipmentMethodTypeId"), "partyId", productStoreShipmentMethod.getString("partyId"), "roleTypeId", productStoreShipmentMethod.getString("roleTypeId")) + .where("shipmentMethodTypeId", productStoreShipmentMethod.getString("shipmentMethodTypeId"), "partyId", + productStoreShipmentMethod.getString("partyId"), "roleTypeId", productStoreShipmentMethod.getString("roleTypeId")) .queryOne(); String serviceCode = carrierShipmentMethod.getString("carrierServiceCode"); for (String thisServiceCode : upsRateCodeMap.keySet()) { @@ -2948,14 +3149,14 @@ public class UpsServices { if (UtilValidate.isEmpty(rates)) { return ServiceUtil.returnError(UtilProperties.getMessage(RES_ERROR, "FacilityShipmentUpsNoRateAvailable", locale)); } else { - for (Element element: rates) { + for (Element element : rates) { // get service Element service = UtilXml.firstChildElement(element, "Service"); String serviceCode = UtilXml.childElementValue(service, "Code"); // get negotiated rates Element negotiatedRates = UtilXml.firstChildElement(element, "NegotiatedRates"); - if (negotiatedRates !=null) { + if (negotiatedRates != null) { Element netSummaryCharges = UtilXml.firstChildElement(negotiatedRates, "NetSummaryCharges"); Element grandTotal = UtilXml.firstChildElement(netSummaryCharges, "GrandTotal"); totalRates = UtilXml.childElementValue(grandTotal, "MonetaryValue"); @@ -2978,12 +3179,14 @@ public class UpsServices { } } - private static String getShipmentGatewayConfigValue(Delegator delegator, String shipmentGatewayConfigId, String shipmentGatewayConfigParameterName, - String resource, String parameterName) { + private static String getShipmentGatewayConfigValue(Delegator delegator, String shipmentGatewayConfigId, + String shipmentGatewayConfigParameterName, + String resource, String parameterName) { String returnValue = ""; if (UtilValidate.isNotEmpty(shipmentGatewayConfigId)) { try { - GenericValue ups = EntityQuery.use(delegator).from("ShipmentGatewayUps").where("shipmentGatewayConfigId", shipmentGatewayConfigId).queryOne(); + GenericValue ups = + EntityQuery.use(delegator).from("ShipmentGatewayUps").where("shipmentGatewayConfigId", shipmentGatewayConfigId).queryOne(); if (UtilValidate.isNotEmpty(ups)) { Object upsField = ups.get(shipmentGatewayConfigParameterName); if (upsField != null) { @@ -3002,14 +3205,16 @@ public class UpsServices { return returnValue; } - private static String getShipmentGatewayConfigValue(Delegator delegator, String shipmentGatewayConfigId, String shipmentGatewayConfigParameterName, - String resource, String parameterName, String defaultValue) { - String returnValue = getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, shipmentGatewayConfigParameterName, resource, parameterName); + private static String getShipmentGatewayConfigValue(Delegator delegator, String shipmentGatewayConfigId, + String shipmentGatewayConfigParameterName, + String resource, String parameterName, String defaultValue) { + String returnValue = getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, shipmentGatewayConfigParameterName, resource, + parameterName); if (UtilValidate.isEmpty(returnValue)) { returnValue = defaultValue; } return returnValue; - } + } } @SuppressWarnings("serial") diff --git a/applications/product/src/main/java/org/apache/ofbiz/shipment/thirdparty/usps/UspsServices.java b/applications/product/src/main/java/org/apache/ofbiz/shipment/thirdparty/usps/UspsServices.java index 05ab643a52..d1b6f92c3b 100644 --- a/applications/product/src/main/java/org/apache/ofbiz/shipment/thirdparty/usps/UspsServices.java +++ b/applications/product/src/main/java/org/apache/ofbiz/shipment/thirdparty/usps/UspsServices.java @@ -536,7 +536,7 @@ public class UspsServices { Locale locale = (Locale) context.get("locale"); if ((UtilValidate.isEmpty(state) && UtilValidate.isEmpty(city) && UtilValidate.isEmpty(zip5)) || // No state, city or zip5 (UtilValidate.isEmpty(zip5) && (UtilValidate.isEmpty(state) || UtilValidate.isEmpty(city)))) { // Both state and city are required if no zip5 - Debug.logError("USPS address validation requires either zip5 or city and state", MODULE); + Debug.logError("USPS address validation requires either zip5 or city and state", MODULE); return ServiceUtil.returnError(UtilProperties.getMessage(RES_ERROR, "FacilityShipmentUspsAddressValidationStateAndCityOrZipRqd", locale)); } diff --git a/applications/product/src/main/java/org/apache/ofbiz/shipment/verify/VerifyPickSession.java b/applications/product/src/main/java/org/apache/ofbiz/shipment/verify/VerifyPickSession.java index 3ab9c1dcdd..1af6720271 100644 --- a/applications/product/src/main/java/org/apache/ofbiz/shipment/verify/VerifyPickSession.java +++ b/applications/product/src/main/java/org/apache/ofbiz/shipment/verify/VerifyPickSession.java @@ -372,7 +372,7 @@ public class VerifyPickSession implements Serializable { List processedRows = new LinkedList<>(); for (VerifyPickSessionRow pickRow : this.getPickRows()) { if (this.checkLine(processedRows, pickRow)) { - BigDecimal totalVerifiedQty = this.getVerifiedQuantity(pickRow.getOrderId(), pickRow.getOrderItemSeqId(), pickRow.getShipGroupSeqId(), pickRow.getProductId(), pickRow.getInventoryItemId()); + BigDecimal totalVerifiedQty = this.getVerifiedQuantity(pickRow.getOrderId(), pickRow.getOrderItemSeqId(), pickRow.getShipGroupSeqId(), pickRow.getProductId(), pickRow.getInventoryItemId()); pickRow.issueItemToShipment(shipmentId, picklistBinId, userLogin, totalVerifiedQty, getDispatcher(), locale); processedRows.add(pickRow); } diff --git a/applications/workeffort/src/main/java/org/apache/ofbiz/workeffort/content/WorkEffortContentWrapper.java b/applications/workeffort/src/main/java/org/apache/ofbiz/workeffort/content/WorkEffortContentWrapper.java index 1e118cb8e9..9940e496cf 100644 --- a/applications/workeffort/src/main/java/org/apache/ofbiz/workeffort/content/WorkEffortContentWrapper.java +++ b/applications/workeffort/src/main/java/org/apache/ofbiz/workeffort/content/WorkEffortContentWrapper.java @@ -254,8 +254,8 @@ public class WorkEffortContentWrapper implements ContentWrapper { getWorkEffortContentAsText(contentId, null, workEffort, workEffortContentTypeId, locale, mimeTypeId, delegator, dispatcher, outWriter, false); String outString = outWriter.toString(); if (UtilValidate.isEmpty(outString)) { - outString = workEffort.getModelEntity().isField(candidateFieldName) ? workEffort.getString(candidateFieldName): ""; - outString = outString == null? "" : outString; + outString = workEffort.getModelEntity().isField(candidateFieldName) ? workEffort.getString(candidateFieldName) : ""; + outString = outString == null ? "" : outString; } outString = encoder.sanitize(outString, null); if (workEffortContentCache != null) { @@ -264,8 +264,8 @@ public class WorkEffortContentWrapper implements ContentWrapper { return outString; } catch (GeneralException | IOException e) { Debug.logError(e, "Error rendering WorkEffortContent, inserting empty String", MODULE); - String candidateOut = workEffort.getModelEntity().isField(candidateFieldName) ? workEffort.getString(candidateFieldName): ""; - return candidateOut == null? "" : encoder.sanitize(candidateOut, null); + String candidateOut = workEffort.getModelEntity().isField(candidateFieldName) ? workEffort.getString(candidateFieldName) : ""; + return candidateOut == null ? "" : encoder.sanitize(candidateOut, null); } } diff --git a/applications/workeffort/src/main/java/org/apache/ofbiz/workeffort/workeffort/WorkEffortSearch.java b/applications/workeffort/src/main/java/org/apache/ofbiz/workeffort/workeffort/WorkEffortSearch.java index acd752ad81..e7c86a6dd4 100644 --- a/applications/workeffort/src/main/java/org/apache/ofbiz/workeffort/workeffort/WorkEffortSearch.java +++ b/applications/workeffort/src/main/java/org/apache/ofbiz/workeffort/workeffort/WorkEffortSearch.java @@ -1062,23 +1062,24 @@ public class WorkEffortSearch { EntityConditionList dateConditions = null; EntityExpr dateCondition=null; - if (fromDate !=null && thruDate!=null) { - dateConditions= EntityCondition.makeCondition(UtilMisc.toList( - EntityCondition.makeCondition("lastModifiedDate", EntityOperator.GREATER_THAN_EQUAL_TO, fromDate), - EntityCondition.makeCondition("lastModifiedDate", EntityOperator.LESS_THAN_EQUAL_TO, thruDate)), EntityOperator.AND); - } if (fromDate !=null) { - dateCondition=EntityCondition.makeCondition("lastModifiedDate", EntityOperator.GREATER_THAN_EQUAL_TO, fromDate); + if (fromDate != null && thruDate != null) { + dateConditions = EntityCondition.makeCondition(UtilMisc.toList( + EntityCondition.makeCondition("lastModifiedDate", EntityOperator.GREATER_THAN_EQUAL_TO, fromDate), + EntityCondition.makeCondition("lastModifiedDate", EntityOperator.LESS_THAN_EQUAL_TO, thruDate)), EntityOperator.AND); + } + if (fromDate != null) { + dateCondition = EntityCondition.makeCondition("lastModifiedDate", EntityOperator.GREATER_THAN_EQUAL_TO, fromDate); } else if (thruDate != null) { dateCondition = EntityCondition.makeCondition("lastModifiedDate", EntityOperator.LESS_THAN_EQUAL_TO, thruDate); } EntityConditionList conditions = null; - if (fromDate !=null && thruDate!=null) { - conditions=EntityCondition.makeCondition(UtilMisc.toList( - dateConditions, - EntityCondition.makeCondition("lastModifiedDate", EntityOperator.EQUALS, null)), - EntityOperator.OR); + if (fromDate != null && thruDate != null) { + conditions = EntityCondition.makeCondition(UtilMisc.toList( + dateConditions, + EntityCondition.makeCondition("lastModifiedDate", EntityOperator.EQUALS, null)), + EntityOperator.OR); } else { - conditions=EntityCondition.makeCondition(UtilMisc.toList( + conditions = EntityCondition.makeCondition(UtilMisc.toList( dateCondition, EntityCondition.makeCondition("lastModifiedDate", EntityOperator.EQUALS, null)), EntityOperator.OR); diff --git a/applications/workeffort/src/main/java/org/apache/ofbiz/workeffort/workeffort/WorkEffortSearchSession.java b/applications/workeffort/src/main/java/org/apache/ofbiz/workeffort/workeffort/WorkEffortSearchSession.java index 86217c04fe..02a3ee4fd6 100644 --- a/applications/workeffort/src/main/java/org/apache/ofbiz/workeffort/workeffort/WorkEffortSearchSession.java +++ b/applications/workeffort/src/main/java/org/apache/ofbiz/workeffort/workeffort/WorkEffortSearchSession.java @@ -193,16 +193,17 @@ public class WorkEffortSearchSession { } // add a Work Effort Assoc Type to the search if (UtilValidate.isNotEmpty(parameters.get("SEARCH_WORK_EFFORT_ID"))) { - String workEffortId=(String) parameters.get("SEARCH_WORK_EFFORT_ID"); - String workEffortAssocTypeId=(String) parameters.get("workEffortAssocTypeId"); - boolean includeAllSubWorkEfforts =!"N".equalsIgnoreCase((String) parameters.get("SEARCH_SUB_WORK_EFFORTS")); - searchAddConstraint(new WorkEffortSearch.WorkEffortAssocConstraint(workEffortId, workEffortAssocTypeId, includeAllSubWorkEfforts), session); + String workEffortId = (String) parameters.get("SEARCH_WORK_EFFORT_ID"); + String workEffortAssocTypeId = (String) parameters.get("workEffortAssocTypeId"); + boolean includeAllSubWorkEfforts = !"N".equalsIgnoreCase((String) parameters.get("SEARCH_SUB_WORK_EFFORTS")); + searchAddConstraint(new WorkEffortSearch.WorkEffortAssocConstraint(workEffortId, workEffortAssocTypeId, includeAllSubWorkEfforts), + session); constraintsChanged = true; } -// add a Work Effort Party Assignment to the search + // add a Work Effort Party Assignment to the search if (UtilValidate.isNotEmpty(parameters.get("partyId"))) { - String partyId=(String) parameters.get("partyId"); - String roleTypeId=(String) parameters.get("roleTypeId"); + String partyId = (String) parameters.get("partyId"); + String roleTypeId = (String) parameters.get("roleTypeId"); searchAddConstraint(new WorkEffortSearch.PartyAssignmentConstraint(partyId, roleTypeId), session); constraintsChanged = true; } @@ -220,9 +221,9 @@ public class WorkEffortSearchSession { // add a WorkEfort fromDate thruDate to the search if (UtilValidate.isNotEmpty(parameters.get("fromDate")) || UtilValidate.isNotEmpty(parameters.get("thruDate"))) { - Timestamp fromDate =null; + Timestamp fromDate = null; if (UtilValidate.isNotEmpty(parameters.get("fromDate"))) { - fromDate=Timestamp.valueOf((String) parameters.get("fromDate")); + fromDate = Timestamp.valueOf((String) parameters.get("fromDate")); } Timestamp thruDate = null;