use of org.apache.ofbiz.order.order.OrderReadHelper in project ofbiz-framework by apache.
the class InvoiceServices method createInvoicesFromShipments.
public static Map<String, Object> createInvoicesFromShipments(DispatchContext dctx, Map<String, ? extends Object> context) {
Delegator delegator = dctx.getDelegator();
LocalDispatcher dispatcher = dctx.getDispatcher();
List<String> shipmentIds = UtilGenerics.checkList(context.get("shipmentIds"));
Locale locale = (Locale) context.get("locale");
Boolean createSalesInvoicesForDropShipments = (Boolean) context.get("createSalesInvoicesForDropShipments");
if (UtilValidate.isEmpty(createSalesInvoicesForDropShipments)) {
createSalesInvoicesForDropShipments = Boolean.FALSE;
}
boolean salesShipmentFound = false;
boolean purchaseShipmentFound = false;
boolean dropShipmentFound = false;
List<String> invoicesCreated = new LinkedList<>();
// DEJ20060520: not used? planned to be used? List shipmentIdList = new LinkedList();
for (String tmpShipmentId : shipmentIds) {
try {
GenericValue shipment = EntityQuery.use(delegator).from("Shipment").where("shipmentId", tmpShipmentId).queryOne();
if ((shipment.getString("shipmentTypeId") != null) && ("PURCHASE_SHIPMENT".equals(shipment.getString("shipmentTypeId")))) {
purchaseShipmentFound = true;
} else if ((shipment.getString("shipmentTypeId") != null) && ("DROP_SHIPMENT".equals(shipment.getString("shipmentTypeId")))) {
dropShipmentFound = true;
} else {
salesShipmentFound = true;
}
if (purchaseShipmentFound && salesShipmentFound && dropShipmentFound) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "AccountingShipmentsOfDifferentTypes", UtilMisc.toMap("tmpShipmentId", tmpShipmentId, "shipmentTypeId", shipment.getString("shipmentTypeId")), locale));
}
} catch (GenericEntityException e) {
Debug.logError(e, "Trouble getting Shipment entity for shipment " + tmpShipmentId, module);
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "AccountingTroubleGettingShipmentEntity", UtilMisc.toMap("tmpShipmentId", tmpShipmentId), locale));
}
}
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
// if it were a purchase order or from the order items of the (possibly linked) orders if the shipment is a drop shipment
List<GenericValue> items = null;
List<GenericValue> orderItemAssocs = null;
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
Iterator<GenericValue> itemsIter = items.iterator();
while (itemsIter.hasNext()) {
GenericValue item = itemsIter.next();
GenericValue inventoryItem = item.getRelatedOne("InventoryItem", false);
GenericValue ownerPartyRole = EntityQuery.use(delegator).from("PartyRole").where("partyId", inventoryItem.get("ownerPartyId"), "roleTypeId", "INTERNAL_ORGANIZATIO").cache().queryOne();
if (UtilValidate.isEmpty(ownerPartyRole)) {
itemsIter.remove();
}
}
} else if (dropShipmentFound) {
List<GenericValue> shipments = shipmentQuery.from("Shipment").queryList();
// Get the list of purchase order IDs related to the shipments
List<String> purchaseOrderIds = EntityUtil.getFieldListFromEntityList(shipments, "primaryOrderId", true);
if (createSalesInvoicesForDropShipments) {
// If a sales invoice is being created for a drop shipment, we have to reference the original sales order items
// Get the list of the linked orderIds (original sales orders)
orderItemAssocs = EntityQuery.use(delegator).from("OrderItemAssoc").where(EntityCondition.makeCondition("toOrderId", EntityOperator.IN, purchaseOrderIds)).queryList();
// Get only the order items which are indirectly related to the purchase order - this limits the list to the drop ship group(s)
items = EntityUtil.getRelated("FromOrderItem", null, orderItemAssocs, false);
} else {
// If it's a purchase invoice being created, the order items for that purchase orders can be used directly
items = EntityQuery.use(delegator).from("OrderItem").where(EntityCondition.makeCondition("orderId", EntityOperator.IN, purchaseOrderIds)).queryList();
}
} else {
items = shipmentQuery.from("ItemIssuance").queryList();
}
} catch (GenericEntityException e) {
Debug.logError(e, "Problem getting issued items from shipments", module);
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "AccountingProblemGettingItemsFromShipments", locale));
}
if (items.size() == 0) {
Debug.logInfo("No items issued for shipments", module);
return ServiceUtil.returnSuccess();
}
// group items by order
Map<String, List<GenericValue>> shippedOrderItems = new HashMap<>();
for (GenericValue item : items) {
String orderId = item.getString("orderId");
String orderItemSeqId = item.getString("orderItemSeqId");
List<GenericValue> itemsByOrder = shippedOrderItems.get(orderId);
if (itemsByOrder == null) {
itemsByOrder = new LinkedList<>();
}
// check and make sure we haven't already billed for this issuance or shipment receipt
List<EntityCondition> billFields = new LinkedList<>();
billFields.add(EntityCondition.makeCondition("orderId", orderId));
billFields.add(EntityCondition.makeCondition("orderItemSeqId", orderItemSeqId));
billFields.add(EntityCondition.makeCondition("statusId", EntityOperator.NOT_EQUAL, "INVOICE_CANCELLED"));
if (dropShipmentFound) {
// Drop shipments have neither issuances nor receipts, so this check is meaningless
itemsByOrder.add(item);
shippedOrderItems.put(orderId, itemsByOrder);
continue;
} else if ("ItemIssuance".equals(item.getEntityName())) {
billFields.add(EntityCondition.makeCondition("itemIssuanceId", item.get("itemIssuanceId")));
} else if ("ShipmentReceipt".equals(item.getEntityName())) {
billFields.add(EntityCondition.makeCondition("shipmentReceiptId", item.getString("receiptId")));
}
List<GenericValue> itemBillings = null;
try {
itemBillings = EntityQuery.use(delegator).from("OrderItemBillingAndInvoiceAndItem").where(billFields).queryList();
} catch (GenericEntityException e) {
Debug.logError(e, "Problem looking up OrderItemBilling records for " + billFields, module);
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "AccountingProblemLookingUpOrderItemBilling", UtilMisc.toMap("billFields", billFields), locale));
}
// if none found, then okay to bill
if (itemBillings.size() == 0) {
itemsByOrder.add(item);
}
// update the map with modified list
shippedOrderItems.put(orderId, itemsByOrder);
}
// make sure we aren't billing items already invoiced i.e. items billed as digital (FINDIG)
for (Entry<String, List<GenericValue>> order : shippedOrderItems.entrySet()) {
String orderId = order.getKey();
// we'll only use this list to figure out which ones to send
List<GenericValue> billItems = order.getValue();
// a new list to be used to pass to the create invoice service
List<GenericValue> toBillItems = new LinkedList<>();
// map of available quantities so we only have to calc once
Map<String, BigDecimal> itemQtyAvail = new HashMap<>();
// now we will check each issuance and make sure it hasn't already been billed
for (GenericValue issue : billItems) {
BigDecimal issueQty = BigDecimal.ZERO;
if ("ShipmentReceipt".equals(issue.getEntityName())) {
issueQty = issue.getBigDecimal("quantityAccepted");
} else {
issueQty = issue.getBigDecimal("quantity");
}
BigDecimal billAvail = itemQtyAvail.get(issue.getString("orderItemSeqId"));
if (billAvail == null) {
List<EntityCondition> lookup = new LinkedList<>();
lookup.add(EntityCondition.makeCondition("orderId", orderId));
lookup.add(EntityCondition.makeCondition("orderItemSeqId", issue.get("orderItemSeqId")));
lookup.add(EntityCondition.makeCondition("statusId", EntityOperator.NOT_EQUAL, "INVOICE_CANCELLED"));
GenericValue orderItem = null;
List<GenericValue> billed = null;
BigDecimal orderedQty = null;
try {
orderItem = "OrderItem".equals(issue.getEntityName()) ? issue : issue.getRelatedOne("OrderItem", false);
// total ordered
orderedQty = orderItem.getBigDecimal("quantity");
if (dropShipmentFound && createSalesInvoicesForDropShipments.booleanValue()) {
// 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 purchaseOrderItem = orderItemAssoc.getRelatedOne("ToOrderItem", false);
orderItem.set("quantity", purchaseOrderItem.getBigDecimal("quantity"));
issueQty = purchaseOrderItem.getBigDecimal("quantity");
}
billed = EntityQuery.use(delegator).from("OrderItemBillingAndInvoiceAndItem").where(lookup).queryList();
} catch (GenericEntityException e) {
Debug.logError(e, "Problem getting OrderItem/OrderItemBilling records " + lookup, module);
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "AccountingProblemGettingOrderItemOrderItemBilling", UtilMisc.toMap("lookup", lookup), locale));
}
// add up the already billed total
if (billed.size() > 0) {
BigDecimal billedQuantity = BigDecimal.ZERO;
for (GenericValue oib : billed) {
BigDecimal qty = oib.getBigDecimal("quantity");
if (qty != null) {
billedQuantity = billedQuantity.add(qty).setScale(DECIMALS, ROUNDING);
}
}
BigDecimal leftToBill = orderedQty.subtract(billedQuantity).setScale(DECIMALS, ROUNDING);
billAvail = leftToBill;
} else {
billAvail = orderedQty;
}
}
// no available means we cannot bill anymore
if (billAvail != null && billAvail.signum() == 1) {
// this checks if billAvail is a positive non-zero number
if (issueQty != null && issueQty.compareTo(billAvail) > 0) {
// can only bill some of the issuance; others have been billed already
if ("ShipmentReceipt".equals(issue.getEntityName())) {
issue.set("quantityAccepted", billAvail);
} else {
issue.set("quantity", billAvail);
}
billAvail = BigDecimal.ZERO;
} else {
// now have been billed
if (issueQty == null) {
issueQty = BigDecimal.ZERO;
}
billAvail = billAvail.subtract(issueQty).setScale(DECIMALS, ROUNDING);
}
// okay to bill these items; but none else
toBillItems.add(issue);
}
// update the available to bill quantity for the next pass
itemQtyAvail.put(issue.getString("orderItemSeqId"), billAvail);
}
OrderReadHelper orh = new OrderReadHelper(delegator, orderId);
GenericValue productStore = orh.getProductStore();
String prorateShipping = productStore != null ? productStore.getString("prorateShipping") : "N";
// If shipping charges are not prorated, the shipments need to be examined for additional shipping charges
if ("N".equalsIgnoreCase(prorateShipping)) {
// Get the set of filtered shipments
List<GenericValue> invoiceableShipments = null;
try {
if (dropShipmentFound) {
List<String> invoiceablePrimaryOrderIds = null;
if (createSalesInvoicesForDropShipments) {
// If a sales invoice is being created for the drop shipment, we need to reference back to the original purchase order IDs
// Get the IDs for orders which have billable items
List<String> 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
// invoiced in a previous sales invoice
List<GenericValue> reverseOrderItemAssocs = EntityUtil.filterByCondition(orderItemAssocs, EntityCondition.makeCondition("orderId", EntityOperator.IN, invoiceableLinkedOrderIds));
invoiceablePrimaryOrderIds = EntityUtil.getFieldListFromEntityList(reverseOrderItemAssocs, "toOrderId", true);
} else {
// If a purchase order is being created for a drop shipment, the purchase order IDs can be used directly
invoiceablePrimaryOrderIds = EntityUtil.getFieldListFromEntityList(toBillItems, "orderId", true);
}
// Get the list of shipments which are associated with the filtered purchase orders
if (!UtilValidate.isEmpty(invoiceablePrimaryOrderIds)) {
invoiceableShipments = EntityQuery.use(delegator).from("Shipment").where(UtilMisc.toList(EntityCondition.makeCondition("primaryOrderId", EntityOperator.IN, invoiceablePrimaryOrderIds), EntityCondition.makeCondition("shipmentId", EntityOperator.IN, shipmentIds))).queryList();
}
} else {
List<String> invoiceableShipmentIds = EntityUtil.getFieldListFromEntityList(toBillItems, "shipmentId", true);
if (UtilValidate.isNotEmpty(invoiceableShipmentIds)) {
invoiceableShipments = EntityQuery.use(delegator).from("Shipment").where(EntityCondition.makeCondition("shipmentId", EntityOperator.IN, invoiceableShipmentIds)).queryList();
}
}
} catch (GenericEntityException e) {
Debug.logError(e, "Trouble calling createInvoicesFromShipments service", module);
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "AccountingTroubleCallingCreateInvoicesFromShipmentsService", locale));
}
// Total the additional shipping charges for the shipments
Map<GenericValue, BigDecimal> additionalShippingCharges = new HashMap<>();
BigDecimal totalAdditionalShippingCharges = BigDecimal.ZERO;
if (UtilValidate.isNotEmpty(invoiceableShipments)) {
for (GenericValue shipment : invoiceableShipments) {
if (shipment.get("additionalShippingCharge") == null) {
continue;
}
BigDecimal shipmentAdditionalShippingCharges = shipment.getBigDecimal("additionalShippingCharge").setScale(DECIMALS, ROUNDING);
additionalShippingCharges.put(shipment, shipmentAdditionalShippingCharges);
totalAdditionalShippingCharges = totalAdditionalShippingCharges.add(shipmentAdditionalShippingCharges);
}
}
// If the additional shipping charges are greater than zero, process them
if (totalAdditionalShippingCharges.signum() == 1) {
// Add an OrderAdjustment to the order for each additional shipping charge
for (Map.Entry<GenericValue, BigDecimal> entry : additionalShippingCharges.entrySet()) {
GenericValue shipment = entry.getKey();
BigDecimal additionalShippingCharge = entry.getValue();
String shipmentId = shipment.getString("shipmentId");
Map<String, Object> createOrderAdjustmentContext = new HashMap<>();
createOrderAdjustmentContext.put("orderId", orderId);
createOrderAdjustmentContext.put("orderAdjustmentTypeId", "SHIPPING_CHARGES");
String addtlChargeDescription = shipment.getString("addtlShippingChargeDesc");
if (UtilValidate.isEmpty(addtlChargeDescription)) {
addtlChargeDescription = UtilProperties.getMessage(resource, "AccountingAdditionalShippingChargeForShipment", UtilMisc.toMap("shipmentId", shipmentId), locale);
}
createOrderAdjustmentContext.put("description", addtlChargeDescription);
createOrderAdjustmentContext.put("sourceReferenceId", shipmentId);
createOrderAdjustmentContext.put("amount", additionalShippingCharge);
createOrderAdjustmentContext.put("userLogin", context.get("userLogin"));
String shippingOrderAdjustmentId = null;
try {
Map<String, Object> createOrderAdjustmentResult = dispatcher.runSync("createOrderAdjustment", createOrderAdjustmentContext);
if (ServiceUtil.isError(createOrderAdjustmentResult)) {
return ServiceUtil.returnError(ServiceUtil.getErrorMessage(createOrderAdjustmentResult));
}
shippingOrderAdjustmentId = (String) createOrderAdjustmentResult.get("orderAdjustmentId");
} catch (GenericServiceException e) {
Debug.logError(e, "Trouble calling createOrderAdjustment service", module);
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "AccountingTroubleCallingCreateOrderAdjustmentService", locale));
}
// Obtain a list of OrderAdjustments due to tax on the shipping charges, if any
GenericValue billToParty = orh.getBillToParty();
GenericValue payToParty = orh.getBillFromParty();
GenericValue destinationContactMech = null;
try {
destinationContactMech = shipment.getRelatedOne("DestinationPostalAddress", false);
} catch (GenericEntityException e) {
Debug.logError(e, "Trouble calling createInvoicesFromShipment service; invoice not created for shipment " + shipmentId, module);
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "AccountingTroubleCallingCreateInvoicesFromShipmentService", locale));
}
List<Object> emptyList = new LinkedList<>();
Map<String, Object> calcTaxContext = new HashMap<>();
calcTaxContext.put("productStoreId", orh.getProductStoreId());
calcTaxContext.put("payToPartyId", payToParty.getString("partyId"));
calcTaxContext.put("billToPartyId", billToParty.getString("partyId"));
calcTaxContext.put("orderShippingAmount", totalAdditionalShippingCharges);
calcTaxContext.put("shippingAddress", destinationContactMech);
// These parameters don't matter if we're only worried about adjustments on the shipping charges
calcTaxContext.put("itemProductList", emptyList);
calcTaxContext.put("itemAmountList", emptyList);
calcTaxContext.put("itemPriceList", emptyList);
calcTaxContext.put("itemQuantityList", emptyList);
calcTaxContext.put("itemShippingList", emptyList);
Map<String, Object> calcTaxResult = null;
try {
calcTaxResult = dispatcher.runSync("calcTax", calcTaxContext);
if (ServiceUtil.isError(calcTaxResult)) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "AccountingTroubleCallingCalcTaxService", locale));
}
} catch (GenericServiceException e) {
Debug.logError(e, "Trouble calling calcTaxService", module);
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "AccountingTroubleCallingCalcTaxService", locale));
}
List<GenericValue> orderAdjustments = UtilGenerics.checkList(calcTaxResult.get("orderAdjustments"));
// 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));
orderAdjustment.set("orderAdjustmentId", delegator.getNextSeqId("OrderAdjustment"));
orderAdjustment.set("orderId", orderId);
orderAdjustment.set("orderItemSeqId", "_NA_");
orderAdjustment.set("shipGroupSeqId", shipment.getString("primaryShipGroupSeqId"));
orderAdjustment.set("originalAdjustmentId", shippingOrderAdjustmentId);
}
try {
delegator.storeAll(orderAdjustments);
} catch (GenericEntityException e) {
Debug.logError(e, "Problem storing OrderAdjustments: " + orderAdjustments, module);
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "AccountingProblemStoringOrderAdjustments", UtilMisc.toMap("orderAdjustments", orderAdjustments), locale));
}
}
// If part of the order was paid via credit card, try to charge it for the additional shipping
List<GenericValue> orderPaymentPreferences = null;
try {
orderPaymentPreferences = EntityQuery.use(delegator).from("OrderPaymentPreference").where("orderId", orderId, "paymentMethodTypeId", "CREDIT_CARD").queryList();
} catch (GenericEntityException e) {
Debug.logError(e, "Problem getting OrderPaymentPreference records", module);
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "AccountingProblemGettingOrderPaymentPreferences", locale));
}
// Use the first credit card we find, for the sake of simplicity
String paymentMethodId = null;
GenericValue cardOrderPaymentPref = EntityUtil.getFirst(orderPaymentPreferences);
if (cardOrderPaymentPref != null) {
paymentMethodId = cardOrderPaymentPref.getString("paymentMethodId");
}
if (paymentMethodId != null) {
// Release all outstanding (not settled or cancelled) authorizations, while keeping a running
// total of their amounts so that the total plus the additional shipping charges can be authorized again
// all at once.
BigDecimal totalNewAuthAmount = totalAdditionalShippingCharges.setScale(DECIMALS, ROUNDING);
for (GenericValue orderPaymentPreference : orderPaymentPreferences) {
if (!("PAYMENT_SETTLED".equals(orderPaymentPreference.getString("statusId")) || "PAYMENT_CANCELLED".equals(orderPaymentPreference.getString("statusId")))) {
GenericValue authTransaction = PaymentGatewayServices.getAuthTransaction(orderPaymentPreference);
if (authTransaction != null && authTransaction.get("amount") != null) {
// Update the total authorized amount
totalNewAuthAmount = totalNewAuthAmount.add(authTransaction.getBigDecimal("amount").setScale(DECIMALS, ROUNDING));
// Release the authorization for the OrderPaymentPreference
Map<String, Object> prefReleaseResult = null;
try {
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, "AccountingTroubleCallingReleaseOrderPaymentPreferenceService", locale));
}
if (ServiceUtil.isError(prefReleaseResult) || ServiceUtil.isFailure(prefReleaseResult)) {
String errMsg = ServiceUtil.getErrorMessage(prefReleaseResult);
Debug.logError(errMsg, module);
return ServiceUtil.returnError(errMsg);
}
}
}
}
// 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<String, Object> serviceContext = UtilMisc.toMap("orderId", orderId, "paymentMethodId", paymentMethodId, "paymentMethodTypeId", "CREDIT_CARD", "userLogin", context.get("userLogin"));
String orderPaymentPreferenceId = null;
try {
Map<String, Object> result = dispatcher.runSync("createOrderPaymentPreference", serviceContext);
if (ServiceUtil.isError(result)) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "AccountingTroubleCallingCreateOrderPaymentPreferenceService", locale));
}
orderPaymentPreferenceId = (String) result.get("orderPaymentPreferenceId");
} catch (GenericServiceException e) {
Debug.logError(e, "Trouble calling createOrderPaymentPreference service", module);
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "AccountingTroubleCallingCreateOrderPaymentPreferenceService", locale));
}
// Attempt to authorize the new orderPaymentPreference
Map<String, Object> 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")));
if (ServiceUtil.isError(authResult)) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "AccountingTroubleCallingAuthOrderPaymentPreferenceService", locale));
}
} catch (GenericServiceException e) {
Debug.logError(e, "Trouble calling authOrderPaymentPreference service", module);
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "AccountingTroubleCallingAuthOrderPaymentPreferenceService", locale));
}
// If the authorization fails, create the invoice anyway, but make a note of it
boolean authFinished = ((Boolean) authResult.get("finished")).booleanValue();
boolean authErrors = ((Boolean) authResult.get("errors")).booleanValue();
if (authErrors || !authFinished) {
String errMsg = UtilProperties.getMessage(resource, "AccountingUnableToAuthAdditionalShipCharges", UtilMisc.toMap("shipmentId", shipmentId, "paymentMethodId", paymentMethodId, "orderPaymentPreferenceId", orderPaymentPreferenceId), locale);
Debug.logError(errMsg, module);
}
}
}
}
} else {
Debug.logInfo(UtilProperties.getMessage(resource, "AccountingIgnoringAdditionalShipCharges", UtilMisc.toMap("productStoreId", orh.getProductStoreId()), locale), module);
}
String invoiceId = null;
GenericValue shipmentItemBilling = null;
String shipmentId = shipmentIds.get(0);
try {
shipmentItemBilling = EntityQuery.use(delegator).from("ShipmentItemBilling").where("shipmentId", shipmentId).queryFirst();
} catch (GenericEntityException e) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "AccountingProblemGettingShipmentItemBilling", locale));
}
if (shipmentItemBilling != null) {
invoiceId = shipmentItemBilling.getString("invoiceId");
}
// call the createInvoiceForOrder service for each order
Map<String, Object> serviceContext = UtilMisc.toMap("orderId", orderId, "billItems", toBillItems, "invoiceId", invoiceId, "eventDate", context.get("eventDate"), "userLogin", context.get("userLogin"));
try {
Map<String, Object> result = dispatcher.runSync("createInvoiceForOrder", serviceContext);
if (ServiceUtil.isError(result)) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "AccountingTroubleCallingCreateInvoiceForOrderService", locale));
}
invoicesCreated.add((String) result.get("invoiceId"));
} catch (GenericServiceException e) {
Debug.logError(e, "Trouble calling createInvoiceForOrder service; invoice not created for shipment", module);
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "AccountingTroubleCallingCreateInvoiceForOrderService", locale));
}
}
Map<String, Object> response = ServiceUtil.returnSuccess();
response.put("invoicesCreated", invoicesCreated);
return response;
}
use of org.apache.ofbiz.order.order.OrderReadHelper in project ofbiz-framework by apache.
the class GiftCertificateServices method giftCertificatePurchase.
public static Map<String, Object> giftCertificatePurchase(DispatchContext dctx, Map<String, ? extends Object> context) {
// this service should always be called via FULFILLMENT_EXTASYNC
LocalDispatcher dispatcher = dctx.getDispatcher();
Delegator delegator = dctx.getDelegator();
GenericValue userLogin = (GenericValue) context.get("userLogin");
GenericValue orderItem = (GenericValue) context.get("orderItem");
Locale locale = (Locale) context.get("locale");
// order ID for tracking
String orderId = orderItem.getString("orderId");
// the order header for store info
GenericValue orderHeader = null;
try {
orderHeader = orderItem.getRelatedOne("OrderHeader", false);
} catch (GenericEntityException e) {
Debug.logError(e, "Unable to get OrderHeader from OrderItem", module);
return ServiceUtil.returnError(UtilProperties.getMessage(resourceOrderError, "OrderCannotGetOrderHeader", UtilMisc.toMap("orderId", orderId), locale));
}
// get the order read helper
OrderReadHelper orh = new OrderReadHelper(orderHeader);
// get the currency
String currency = orh.getCurrency();
// make sure we have a currency
if (currency == null) {
currency = EntityUtilProperties.getPropertyValue("general", "currency.uom.id.default", "USD", delegator);
}
// get the product store
String productStoreId = null;
if (orderHeader != null) {
productStoreId = orh.getProductStoreId();
}
if (productStoreId == null) {
return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "AccountingGiftCerticateNumberCannotProcess", UtilMisc.toMap("orderId", orderId), locale));
}
// party ID for tracking
GenericValue placingParty = orh.getPlacingParty();
String partyId = null;
if (placingParty != null) {
partyId = placingParty.getString("partyId");
}
// amount/quantity of the gift card(s)
BigDecimal amount = orderItem.getBigDecimal("unitPrice");
BigDecimal quantity = orderItem.getBigDecimal("quantity");
// the product entity needed for information
GenericValue product = null;
try {
product = orderItem.getRelatedOne("Product", false);
} catch (GenericEntityException e) {
Debug.logError(e, "Unable to get Product from OrderItem", module);
}
if (product == null) {
return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "AccountingGiftCerticateNumberCannotFulfill", locale));
}
// Gift certificate settings are per store in this entity
GenericValue giftCertSettings = null;
try {
giftCertSettings = EntityQuery.use(delegator).from("ProductStoreFinActSetting").where("productStoreId", productStoreId, "finAccountTypeId", FinAccountHelper.giftCertFinAccountTypeId).cache().queryOne();
} catch (GenericEntityException e) {
Debug.logError(e, "Unable to get Product Store FinAccount settings for " + FinAccountHelper.giftCertFinAccountTypeId, module);
return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "AccountingFinAccountSetting", UtilMisc.toMap("productStoreId", productStoreId, "finAccountTypeId", FinAccountHelper.giftCertFinAccountTypeId), locale) + ": " + e.getMessage());
}
// survey information
String surveyId = giftCertSettings.getString("purchaseSurveyId");
// get the survey response
GenericValue surveyResponse = null;
try {
// there should be only one
surveyResponse = EntityQuery.use(delegator).from("SurveyResponse").where("orderId", orderId, "orderItemSeqId", orderItem.get("orderItemSeqId"), "surveyId", surveyId).orderBy("-responseDate").queryFirst();
} catch (GenericEntityException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "AccountingGiftCerticateNumberCannotFulfill", locale));
}
if (surveyResponse == null) {
return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "AccountingGiftCerticateNumberCannotFulfill", locale));
}
// get the response answers
List<GenericValue> responseAnswers = null;
try {
responseAnswers = surveyResponse.getRelated("SurveyResponseAnswer", null, null, false);
} catch (GenericEntityException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "AccountingGiftCerticateNumberCannotFulfillFromSurveyAnswers", locale));
}
// make a map of answer info
Map<String, Object> answerMap = new HashMap<>();
if (responseAnswers != null) {
for (GenericValue answer : responseAnswers) {
GenericValue question = null;
try {
question = answer.getRelatedOne("SurveyQuestion", false);
} catch (GenericEntityException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "AccountingGiftCerticateNumberCannotFulfillFromSurveyAnswers", locale));
}
if (question != null) {
String desc = question.getString("description");
// only support text response types for now
String ans = answer.getString("textResponse");
answerMap.put(desc, ans);
}
}
}
// get the send to email address - key defined in product store settings entity
String sendToKey = giftCertSettings.getString("purchSurveySendTo");
String sendToEmail = (String) answerMap.get(sendToKey);
// get the copyMe flag and set the order email address
String orderEmails = orh.getOrderEmailString();
String copyMeField = giftCertSettings.getString("purchSurveyCopyMe");
String copyMeResp = copyMeField != null ? (String) answerMap.get(copyMeField) : null;
boolean copyMe = (UtilValidate.isNotEmpty(copyMeField) && UtilValidate.isNotEmpty(copyMeResp) && "true".equalsIgnoreCase(copyMeResp)) ? true : false;
int qtyLoop = quantity.intValue();
for (int i = 0; i < qtyLoop; i++) {
// create a gift certificate
Map<String, Object> createGcCtx = new HashMap<>();
createGcCtx.put("productStoreId", productStoreId);
createGcCtx.put("currency", currency);
createGcCtx.put("partyId", partyId);
createGcCtx.put("initialAmount", amount);
createGcCtx.put("userLogin", userLogin);
Map<String, Object> createGcResult = null;
try {
createGcResult = dispatcher.runSync("createGiftCertificate", createGcCtx);
} catch (GenericServiceException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "AccountingGiftCerticateNumberCreationError", locale) + e.getMessage());
}
if (ServiceUtil.isError(createGcResult)) {
return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "AccountingGiftCerticateNumberCreationError", locale) + ServiceUtil.getErrorMessage(createGcResult));
}
// create the fulfillment record
Map<String, Object> gcFulFill = new HashMap<>();
gcFulFill.put("typeEnumId", "GC_ACTIVATE");
gcFulFill.put("partyId", partyId);
gcFulFill.put("orderId", orderId);
gcFulFill.put("orderItemSeqId", orderItem.get("orderItemSeqId"));
gcFulFill.put("surveyResponseId", surveyResponse.get("surveyResponseId"));
gcFulFill.put("cardNumber", createGcResult.get("cardNumber"));
gcFulFill.put("pinNumber", createGcResult.get("pinNumber"));
gcFulFill.put("amount", createGcResult.get("initialAmount"));
gcFulFill.put("responseCode", createGcResult.get("responseCode"));
gcFulFill.put("referenceNum", createGcResult.get("referenceNum"));
gcFulFill.put("userLogin", userLogin);
try {
dispatcher.runAsync("createGcFulFillmentRecord", gcFulFill, true);
} catch (GenericServiceException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "AccountingGiftCerticateNumberCannotStoreFulfillmentInfo", UtilMisc.toMap("errorString", e.getMessage()), locale));
}
// add some information to the answerMap for the email
answerMap.put("cardNumber", createGcResult.get("cardNumber"));
answerMap.put("pinNumber", createGcResult.get("pinNumber"));
answerMap.put("amount", createGcResult.get("initialAmount"));
// get the email setting for this email type
GenericValue productStoreEmail = null;
String emailType = "PRDS_GC_PURCHASE";
try {
productStoreEmail = EntityQuery.use(delegator).from("ProductStoreEmailSetting").where("productStoreId", productStoreId, "emailType", emailType).queryOne();
} catch (GenericEntityException e) {
Debug.logError(e, "Unable to get product store email setting for gift card purchase", module);
}
if (productStoreEmail == null) {
Debug.logError("No gift card purchase email setting found for this store; cannot send gift card information", module);
} else {
answerMap.put("locale", locale);
// set the bcc address(s)
String bcc = productStoreEmail.getString("bccAddress");
if (copyMe) {
if (UtilValidate.isNotEmpty(bcc)) {
bcc = bcc + "," + orderEmails;
} else {
bcc = orderEmails;
}
}
Map<String, Object> emailCtx = new HashMap<>();
String bodyScreenLocation = productStoreEmail.getString("bodyScreenLocation");
if (UtilValidate.isEmpty(bodyScreenLocation)) {
bodyScreenLocation = ProductStoreWorker.getDefaultProductStoreEmailScreenLocation(emailType);
}
emailCtx.put("bodyScreenUri", bodyScreenLocation);
emailCtx.put("bodyParameters", answerMap);
emailCtx.put("sendTo", sendToEmail);
emailCtx.put("contentType", productStoreEmail.get("contentType"));
emailCtx.put("sendFrom", productStoreEmail.get("fromAddress"));
emailCtx.put("sendCc", productStoreEmail.get("ccAddress"));
emailCtx.put("sendBcc", bcc);
emailCtx.put("subject", productStoreEmail.getString("subject"));
emailCtx.put("userLogin", userLogin);
// Problem serializing service attributes (Cannot serialize object of class java.util.PropertyResourceBundle)
try {
Map<String, Object> serviceResults = dispatcher.runSync("sendMailFromScreen", emailCtx);
if (ServiceUtil.isError(serviceResults)) {
return ServiceUtil.returnError(ServiceUtil.getErrorMessage(serviceResults));
}
} catch (GenericServiceException e) {
Debug.logError(e, "Problem sending mail", module);
// this is fatal; we will rollback and try again later
return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "AccountingGiftCerticateNumberCannotSendEmailNotice", UtilMisc.toMap("errorString", e.toString()), locale));
}
}
}
return ServiceUtil.returnSuccess();
}
use of org.apache.ofbiz.order.order.OrderReadHelper in project ofbiz-framework by apache.
the class GiftCertificateServices method giftCertificateRestore.
private static Map<String, Object> giftCertificateRestore(DispatchContext dctx, GenericValue userLogin, GenericValue paymentPref, BigDecimal amount, String currency, String resultPrefix, Locale locale) {
LocalDispatcher dispatcher = dctx.getDispatcher();
Delegator delegator = dctx.getDelegator();
// get the orderId for tracking
String orderId = paymentPref.getString("orderId");
OrderReadHelper orh = new OrderReadHelper(delegator, orderId);
String productStoreId = orh.getProductStoreId();
// party ID for tracking
GenericValue placingParty = orh.getPlacingParty();
String partyId = null;
if (placingParty != null) {
partyId = placingParty.getString("partyId");
}
// get the GiftCard VO
GenericValue giftCard = null;
try {
giftCard = paymentPref.getRelatedOne("GiftCard", false);
} catch (GenericEntityException e) {
Debug.logError(e, "Unable to get GiftCard from OrderPaymentPreference", module);
return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "AccountingGiftCerticateNumberCannotLocateItFromOrderPaymentPreference", locale));
}
if (giftCard == null) {
return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "AccountingGiftCerticateNumberCannotRelease", locale));
}
// make sure we have a currency
if (currency == null) {
currency = EntityUtilProperties.getPropertyValue("general", "currency.uom.id.default", "USD", delegator);
}
Map<String, Object> refundCtx = new HashMap<>();
refundCtx.put("productStoreId", productStoreId);
refundCtx.put("currency", currency);
refundCtx.put("partyId", partyId);
refundCtx.put("cardNumber", giftCard.get("cardNumber"));
refundCtx.put("pinNumber", giftCard.get("pinNumber"));
refundCtx.put("amount", amount);
refundCtx.put("userLogin", userLogin);
Map<String, Object> restoreGcResult = null;
try {
restoreGcResult = dispatcher.runSync("addFundsToGiftCertificate", refundCtx);
} catch (GenericServiceException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "AccountingGiftCerticateNumberRefundCallError", locale));
}
if (ServiceUtil.isError(restoreGcResult)) {
return ServiceUtil.returnError(ServiceUtil.getErrorMessage(restoreGcResult));
}
Map<String, Object> result = ServiceUtil.returnSuccess();
if (restoreGcResult != null) {
Boolean processResult = (Boolean) restoreGcResult.get("processResult");
result.put(resultPrefix + "Amount", amount);
result.put(resultPrefix + "Result", processResult);
result.put(resultPrefix + "Code", "R");
result.put(resultPrefix + "Flag", restoreGcResult.get("responseCode"));
result.put(resultPrefix + "RefNum", restoreGcResult.get("referenceNum"));
}
return result;
}
use of org.apache.ofbiz.order.order.OrderReadHelper in project ofbiz-framework by apache.
the class PaymentGatewayServices method authOrderPayments.
/**
* Processes payments through service calls to the defined processing service for the ProductStore/PaymentMethodType
* @return APPROVED|FAILED|ERROR for complete processing of ALL payment methods.
*/
public static Map<String, Object> authOrderPayments(DispatchContext dctx, Map<String, ? extends Object> context) {
Delegator delegator = dctx.getDelegator();
LocalDispatcher dispatcher = dctx.getDispatcher();
String orderId = (String) context.get("orderId");
Locale locale = (Locale) context.get("locale");
Map<String, Object> result = new HashMap<>();
boolean reAuth = false;
if (context.get("reAuth") != null) {
reAuth = ((Boolean) context.get("reAuth")).booleanValue();
}
// get the order header and payment preferences
GenericValue orderHeader = null;
List<GenericValue> paymentPrefs = null;
try {
// get the OrderHeader
orderHeader = EntityQuery.use(delegator).from("OrderHeader").where("orderId", orderId).queryOne();
// get the payments to auth
Map<String, String> lookupMap = UtilMisc.toMap("orderId", orderId, "statusId", "PAYMENT_NOT_AUTH");
List<String> orderList = UtilMisc.toList("maxAmount");
paymentPrefs = EntityQuery.use(delegator).from("OrderPaymentPreference").where(lookupMap).orderBy(orderList).queryList();
if (reAuth) {
lookupMap.put("orderId", orderId);
lookupMap.put("statusId", "PAYMENT_AUTHORIZED");
paymentPrefs.addAll(EntityQuery.use(delegator).from("OrderPaymentPreference").where(lookupMap).orderBy(orderList).queryList());
}
} catch (GenericEntityException gee) {
Debug.logError(gee, "Problems getting the order information", module);
result.put(ModelService.RESPONSE_MESSAGE, ModelService.RESPOND_ERROR);
result.put(ModelService.ERROR_MESSAGE, "ERROR: Could not get order information (" + gee.toString() + ").");
return result;
}
// make sure we have a OrderHeader
if (orderHeader == null) {
return ServiceUtil.returnError(UtilProperties.getMessage(resourceOrder, "OrderOrderNotFound", UtilMisc.toMap("orderId", orderId), locale));
}
// get the order amounts
OrderReadHelper orh = new OrderReadHelper(orderHeader);
BigDecimal totalRemaining = orh.getOrderGrandTotal();
// loop through and auth each order payment preference
int finished = 0;
int hadError = 0;
List<String> messages = new LinkedList<>();
for (GenericValue paymentPref : paymentPrefs) {
if (reAuth && "PAYMENT_AUTHORIZED".equals(paymentPref.getString("statusId"))) {
String paymentConfig = null;
// get the payment settings i.e. serviceName and config properties file name
GenericValue paymentSettings = getPaymentSettings(orh.getOrderHeader(), paymentPref, AUTH_SERVICE_TYPE, false);
if (paymentSettings != null) {
paymentConfig = paymentSettings.getString("paymentPropertiesPath");
if (UtilValidate.isEmpty(paymentConfig)) {
paymentConfig = "payment.properties";
}
}
// check the validity of the authorization; re-auth if necessary
if (PaymentGatewayServices.checkAuthValidity(paymentPref, paymentConfig)) {
finished += 1;
continue;
}
}
Map<String, Object> authContext = new HashMap<>();
authContext.put("orderPaymentPreferenceId", paymentPref.getString("orderPaymentPreferenceId"));
authContext.put("userLogin", context.get("userLogin"));
Map<String, Object> results = null;
try {
results = dispatcher.runSync("authOrderPaymentPreference", authContext);
if (ServiceUtil.isError(results)) {
return ServiceUtil.returnError(ServiceUtil.getErrorMessage(results));
}
} catch (GenericServiceException se) {
Debug.logError(se, "Error in calling authOrderPaymentPreference from authOrderPayments", module);
hadError += 1;
messages.add("Could not authorize OrderPaymentPreference [" + paymentPref.getString("orderPaymentPreferenceId") + "] for order [" + orderId + "]: " + se.toString());
continue;
}
// add authorization code to the result
result.put("authCode", results.get("authCode"));
if (ServiceUtil.isError(results)) {
hadError += 1;
messages.add("Could not authorize OrderPaymentPreference [" + paymentPref.getString("orderPaymentPreferenceId") + "] for order [" + orderId + "]: " + results.get(ModelService.ERROR_MESSAGE));
continue;
}
if (((Boolean) results.get("finished")).booleanValue()) {
finished += 1;
}
if (((Boolean) results.get("errors")).booleanValue()) {
hadError += 1;
}
if (results.get("messages") != null) {
List<String> message = UtilGenerics.checkList(results.get("messages"));
messages.addAll(message);
}
if (results.get("processAmount") != null) {
totalRemaining = totalRemaining.subtract(((BigDecimal) results.get("processAmount")));
}
}
Debug.logInfo("Finished with auth(s) checking results", module);
// add messages to the result
result.put("authResultMsgs", messages);
if (hadError > 0) {
Debug.logError("Error(s) (" + hadError + ") during auth; returning ERROR", module);
result.put(ModelService.RESPONSE_MESSAGE, ModelService.RESPOND_SUCCESS);
result.put("processResult", "ERROR");
return result;
} else if (finished == paymentPrefs.size()) {
Debug.logInfo("All auth(s) passed total remaining : " + totalRemaining, module);
result.put(ModelService.RESPONSE_MESSAGE, ModelService.RESPOND_SUCCESS);
result.put("processResult", "APPROVED");
return result;
} else {
Debug.logInfo("Only [" + finished + "/" + paymentPrefs.size() + "] OrderPaymentPreference authorizations passed; returning processResult=FAILED with no message so that message from ProductStore will be used", module);
result.put(ModelService.RESPONSE_MESSAGE, ModelService.RESPOND_SUCCESS);
result.put("processResult", "FAILED");
return result;
}
}
use of org.apache.ofbiz.order.order.OrderReadHelper in project ofbiz-framework by apache.
the class PaymentGatewayServices method processManualCcTx.
// manual processing service
public static Map<String, Object> processManualCcTx(DispatchContext dctx, Map<String, ? extends Object> context) {
GenericValue userLogin = (GenericValue) context.get("userLogin");
Locale locale = (Locale) context.get("locale");
LocalDispatcher dispatcher = dctx.getDispatcher();
Delegator delegator = dctx.getDelegator();
Security security = dctx.getSecurity();
// security check
if (!security.hasEntityPermission("MANUAL", "_PAYMENT", userLogin) && !security.hasEntityPermission("ACCOUNTING", "_CREATE", userLogin)) {
Debug.logWarning("**** Security [" + (new Date()).toString() + "]: " + userLogin.get("userLoginId") + " attempt to run manual payment transaction!", module);
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "AccountingPaymentTransactionNotAuthorized", locale));
}
String orderPaymentPreferenceId = (String) context.get("orderPaymentPreferenceId");
String paymentMethodTypeId = (String) context.get("paymentMethodTypeId");
String productStoreId = (String) context.get("productStoreId");
String transactionType = (String) context.get("transactionType");
String referenceCode = (String) context.get("referenceCode");
if (referenceCode == null) {
referenceCode = Long.valueOf(System.currentTimeMillis()).toString();
}
// Get the OrderPaymentPreference
GenericValue paymentPref = null;
try {
paymentPref = EntityQuery.use(delegator).from("OrderPaymentPreference").where("orderPaymentPreferenceId", orderPaymentPreferenceId).queryOne();
} catch (GenericEntityException e) {
Debug.logWarning(e, "Problem getting OrderPaymentPreference for orderPaymentPreferenceId " + orderPaymentPreferenceId, module);
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "AccountingProblemGettingOrderPaymentPreferences", locale) + " " + orderPaymentPreferenceId);
}
// Error if no OrderPaymentPreference was found
if (paymentPref == null) {
Debug.logWarning("Could not find OrderPaymentPreference with orderPaymentPreferenceId: " + orderPaymentPreferenceId, module);
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "AccountingProblemGettingOrderPaymentPreferences", locale) + " " + orderPaymentPreferenceId);
}
// Get the OrderHeader
GenericValue orderHeader = null;
String orderId = paymentPref.getString("orderId");
try {
orderHeader = EntityQuery.use(delegator).from("OrderHeader").where("orderId", orderId).queryOne();
} catch (GenericEntityException e) {
Debug.logWarning(e, "Problem getting OrderHeader for orderId " + orderId, module);
return ServiceUtil.returnError(UtilProperties.getMessage(resourceOrder, "OrderOrderNotFound", UtilMisc.toMap("orderId", orderId), locale));
}
// Error if no OrderHeader was found
if (orderHeader == null) {
Debug.logWarning("Could not find OrderHeader with orderId: " + orderId + "; not processing payments.", module);
return ServiceUtil.returnError(UtilProperties.getMessage(resourceOrder, "OrderOrderNotFound", UtilMisc.toMap("orderId", orderId), locale));
}
OrderReadHelper orh = new OrderReadHelper(orderHeader);
// check valid implemented types
if (!transactionType.equals(CREDIT_SERVICE_TYPE)) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "AccountingPaymentTransactionNotYetSupported", locale));
}
// transaction request context
Map<String, Object> requestContext = new HashMap<>();
String paymentService = null;
String paymentConfig = null;
String paymentGatewayConfigId = null;
// get the transaction settings
GenericValue paymentSettings = ProductStoreWorker.getProductStorePaymentSetting(delegator, productStoreId, paymentMethodTypeId, transactionType, false);
if (paymentSettings == null) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "AccountingPaymentSettingNotFound", UtilMisc.toMap("productStoreId", productStoreId, "transactionType", transactionType), locale));
} else {
paymentGatewayConfigId = paymentSettings.getString("paymentGatewayConfigId");
String customMethodId = paymentSettings.getString("paymentCustomMethodId");
if (UtilValidate.isNotEmpty(customMethodId)) {
paymentService = getPaymentCustomMethod(delegator, customMethodId);
}
if (UtilValidate.isEmpty(paymentService)) {
paymentService = paymentSettings.getString("paymentService");
}
paymentConfig = paymentSettings.getString("paymentPropertiesPath");
if (paymentConfig == null) {
paymentConfig = "payment.properties";
}
requestContext.put("paymentConfig", paymentConfig);
requestContext.put("paymentGatewayConfigId", paymentGatewayConfigId);
}
// check the service name
if (paymentService == null || paymentGatewayConfigId == null) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "AccountingPaymentSettingNotValid", locale));
}
if ("CREDIT_CARD".equals(paymentMethodTypeId)) {
GenericValue creditCard = delegator.makeValue("CreditCard");
creditCard.setAllFields(context, true, null, null);
if (creditCard.get("firstNameOnCard") == null || creditCard.get("lastNameOnCard") == null || creditCard.get("cardType") == null || creditCard.get("cardNumber") == null) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "AccountingPaymentCreditCardMissingMandatoryFields", locale));
}
String expMonth = (String) context.get("expMonth");
String expYear = (String) context.get("expYear");
String expDate = expMonth + "/" + expYear;
creditCard.set("expireDate", expDate);
requestContext.put("creditCard", creditCard);
requestContext.put("cardSecurityCode", context.get("cardSecurityCode"));
GenericValue billingAddress = delegator.makeValue("PostalAddress");
billingAddress.setAllFields(context, true, null, null);
if (billingAddress.get("address1") == null || billingAddress.get("city") == null || billingAddress.get("postalCode") == null) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "AccountingPaymentCreditCardBillingAddressMssingMandatoryFields", locale));
}
requestContext.put("billingAddress", billingAddress);
GenericValue billToEmail = delegator.makeValue("ContactMech");
billToEmail.set("infoString", context.get("infoString"));
if (billToEmail.get("infoString") == null) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "AccountingPaymentCreditCardEmailAddressCannotBeEmpty", locale));
}
requestContext.put("billToParty", orh.getBillToParty());
requestContext.put("billToEmail", billToEmail);
requestContext.put("referenceCode", referenceCode);
String currency = EntityUtilProperties.getPropertyValue("general", "currency.uom.id.default", "USD", delegator);
requestContext.put("currency", currency);
requestContext.put("creditAmount", context.get("amount"));
} else {
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "AccountingPaymentTransactionNotYetSupported", locale) + " " + paymentMethodTypeId);
}
// process the transaction
Map<String, Object> response = null;
try {
response = dispatcher.runSync(paymentService, requestContext, TX_TIME, true);
if (ServiceUtil.isError(response)) {
return ServiceUtil.returnError(ServiceUtil.getErrorMessage(response));
}
} catch (GenericServiceException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "AccountingPaymentServiceError", UtilMisc.toMap("paymentService", paymentService, "authContext", requestContext), locale));
}
// get the response result code
if (response != null && ServiceUtil.isSuccess(response)) {
Map<String, Object> responseRes;
try {
ModelService model = dctx.getModelService("processCreditResult");
response.put("orderPaymentPreference", paymentPref);
response.put("userLogin", userLogin);
Map<String, Object> resCtx = model.makeValid(response, ModelService.IN_PARAM);
responseRes = dispatcher.runSync(model.name, resCtx);
} catch (GenericServiceException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "AccountingPaymentCreditError", UtilMisc.toMap("errorString", e.getMessage()), locale));
}
if (responseRes != null && ServiceUtil.isError(responseRes)) {
return ServiceUtil.returnError(ServiceUtil.getErrorMessage(responseRes));
}
} else if (ServiceUtil.isError(response)) {
saveError(dispatcher, userLogin, paymentPref, response, CREDIT_SERVICE_TYPE, "PGT_CREDIT");
return ServiceUtil.returnError(ServiceUtil.getErrorMessage(response));
}
// check for errors
if (ServiceUtil.isError(response)) {
return ServiceUtil.returnError(ServiceUtil.makeErrorMessage(response, null, null, null, null));
}
// get the reference number
String refNum = (String) response.get("creditRefNum");
String code = (String) response.get("creditCode");
String msg = (String) response.get("creditMessage");
Map<String, Object> returnResults = ServiceUtil.returnSuccess(UtilProperties.getMessage(resource, "AccountingPaymentTransactionManualResult", UtilMisc.toMap("msg", msg, "code", code, "refNum", refNum), locale));
returnResults.put("referenceNum", refNum);
return returnResults;
}
Aggregations