use of org.apache.ofbiz.entity.condition.EntityExpr in project ofbiz-framework by apache.
the class ShoppingCartServices method loadCartFromOrder.
public static Map<String, Object> loadCartFromOrder(DispatchContext dctx, Map<String, Object> context) {
LocalDispatcher dispatcher = dctx.getDispatcher();
Delegator delegator = dctx.getDelegator();
GenericValue userLogin = (GenericValue) context.get("userLogin");
String orderId = (String) context.get("orderId");
Boolean skipInventoryChecks = (Boolean) context.get("skipInventoryChecks");
Boolean skipProductChecks = (Boolean) context.get("skipProductChecks");
boolean includePromoItems = Boolean.TRUE.equals(context.get("includePromoItems"));
Locale locale = (Locale) context.get("locale");
// FIXME: deepak:Personally I don't like the idea of passing flag but for orderItem quantity calculation we need this flag.
String createAsNewOrder = (String) context.get("createAsNewOrder");
List<GenericValue> orderTerms = null;
List<GenericValue> orderContactMechs = null;
if (UtilValidate.isEmpty(skipInventoryChecks)) {
skipInventoryChecks = Boolean.FALSE;
}
if (UtilValidate.isEmpty(skipProductChecks)) {
skipProductChecks = Boolean.FALSE;
}
// get the order header
GenericValue orderHeader = null;
try {
orderHeader = EntityQuery.use(delegator).from("OrderHeader").where("orderId", orderId).queryOne();
orderTerms = orderHeader.getRelated("OrderTerm", null, null, false);
orderContactMechs = orderHeader.getRelated("OrderContactMech", null, null, false);
} catch (GenericEntityException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(e.getMessage());
}
// initial require cart info
OrderReadHelper orh = new OrderReadHelper(orderHeader);
String productStoreId = orh.getProductStoreId();
String orderTypeId = orh.getOrderTypeId();
String currency = orh.getCurrency();
String website = orh.getWebSiteId();
String currentStatusString = orh.getCurrentStatusString();
// create the cart
ShoppingCart cart = new ShoppingCart(delegator, productStoreId, website, locale, currency);
cart.setDoPromotions(!includePromoItems);
cart.setOrderType(orderTypeId);
cart.setChannelType(orderHeader.getString("salesChannelEnumId"));
cart.setInternalCode(orderHeader.getString("internalCode"));
if ("Y".equals(createAsNewOrder)) {
cart.setOrderDate(UtilDateTime.nowTimestamp());
} else {
cart.setOrderDate(orderHeader.getTimestamp("orderDate"));
}
cart.setOrderId(orderHeader.getString("orderId"));
cart.setOrderName(orderHeader.getString("orderName"));
cart.setOrderStatusId(orderHeader.getString("statusId"));
cart.setOrderStatusString(currentStatusString);
cart.setFacilityId(orderHeader.getString("originFacilityId"));
cart.setAgreementId(orderHeader.getString("agreementId"));
try {
cart.setUserLogin(userLogin, dispatcher);
} catch (CartItemModifyException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(e.getMessage());
}
// set the role information
GenericValue placingParty = orh.getPlacingParty();
if (placingParty != null) {
cart.setPlacingCustomerPartyId(placingParty.getString("partyId"));
}
GenericValue billFromParty = orh.getBillFromParty();
if (billFromParty != null) {
cart.setBillFromVendorPartyId(billFromParty.getString("partyId"));
}
GenericValue billToParty = orh.getBillToParty();
if (billToParty != null) {
cart.setBillToCustomerPartyId(billToParty.getString("partyId"));
}
GenericValue shipToParty = orh.getShipToParty();
if (shipToParty != null) {
cart.setShipToCustomerPartyId(shipToParty.getString("partyId"));
}
GenericValue endUserParty = orh.getEndUserParty();
if (endUserParty != null) {
cart.setEndUserCustomerPartyId(endUserParty.getString("partyId"));
cart.setOrderPartyId(endUserParty.getString("partyId"));
}
// load order attributes
List<GenericValue> orderAttributesList = null;
try {
orderAttributesList = EntityQuery.use(delegator).from("OrderAttribute").where("orderId", orderId).queryList();
if (UtilValidate.isNotEmpty(orderAttributesList)) {
for (GenericValue orderAttr : orderAttributesList) {
String name = orderAttr.getString("attrName");
String value = orderAttr.getString("attrValue");
cart.setOrderAttribute(name, value);
}
}
} catch (GenericEntityException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(e.getMessage());
}
// load the payment infos
List<GenericValue> orderPaymentPrefs = null;
try {
List<EntityExpr> exprs = UtilMisc.toList(EntityCondition.makeCondition("orderId", EntityOperator.EQUALS, orderId));
exprs.add(EntityCondition.makeCondition("statusId", EntityOperator.NOT_EQUAL, "PAYMENT_RECEIVED"));
exprs.add(EntityCondition.makeCondition("statusId", EntityOperator.NOT_EQUAL, "PAYMENT_CANCELLED"));
exprs.add(EntityCondition.makeCondition("statusId", EntityOperator.NOT_EQUAL, "PAYMENT_DECLINED"));
exprs.add(EntityCondition.makeCondition("statusId", EntityOperator.NOT_EQUAL, "PAYMENT_SETTLED"));
orderPaymentPrefs = EntityQuery.use(delegator).from("OrderPaymentPreference").where(exprs).queryList();
} catch (GenericEntityException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(e.getMessage());
}
if (UtilValidate.isNotEmpty(orderPaymentPrefs)) {
Iterator<GenericValue> oppi = orderPaymentPrefs.iterator();
while (oppi.hasNext()) {
GenericValue opp = oppi.next();
String paymentId = opp.getString("paymentMethodId");
if (paymentId == null) {
paymentId = opp.getString("paymentMethodTypeId");
}
BigDecimal maxAmount = opp.getBigDecimal("maxAmount");
String overflow = opp.getString("overflowFlag");
ShoppingCart.CartPaymentInfo cpi = null;
if ((overflow == null || !"Y".equals(overflow)) && oppi.hasNext()) {
cpi = cart.addPaymentAmount(paymentId, maxAmount);
Debug.logInfo("Added Payment: " + paymentId + " / " + maxAmount, module);
} else {
cpi = cart.addPayment(paymentId);
Debug.logInfo("Added Payment: " + paymentId + " / [no max]", module);
}
// for finance account the finAccountId needs to be set
if ("FIN_ACCOUNT".equals(paymentId)) {
cpi.finAccountId = opp.getString("finAccountId");
}
// set the billing account and amount
cart.setBillingAccount(orderHeader.getString("billingAccountId"), orh.getBillingAccountMaxAmount());
}
} else {
Debug.logInfo("No payment preferences found for order #" + orderId, module);
}
// set the order term
if (UtilValidate.isNotEmpty(orderTerms)) {
for (GenericValue orderTerm : orderTerms) {
BigDecimal termValue = BigDecimal.ZERO;
if (UtilValidate.isNotEmpty(orderTerm.getString("termValue"))) {
termValue = new BigDecimal(orderTerm.getString("termValue"));
}
long termDays = 0;
if (UtilValidate.isNotEmpty(orderTerm.getString("termDays"))) {
termDays = Long.parseLong(orderTerm.getString("termDays").trim());
}
String orderItemSeqId = orderTerm.getString("orderItemSeqId");
cart.addOrderTerm(orderTerm.getString("termTypeId"), orderItemSeqId, termValue, termDays, orderTerm.getString("textValue"), orderTerm.getString("description"));
}
}
if (UtilValidate.isNotEmpty(orderContactMechs)) {
for (GenericValue orderContactMech : orderContactMechs) {
cart.addContactMech(orderContactMech.getString("contactMechPurposeTypeId"), orderContactMech.getString("contactMechId"));
}
}
List<GenericValue> orderItemShipGroupList = orh.getOrderItemShipGroups();
for (GenericValue orderItemShipGroup : orderItemShipGroupList) {
// should be sorted by shipGroupSeqId
int newShipInfoIndex = cart.addShipInfo();
CartShipInfo cartShipInfo = cart.getShipInfo(newShipInfoIndex);
cartShipInfo.shipAfterDate = orderItemShipGroup.getTimestamp("shipAfterDate");
cartShipInfo.shipBeforeDate = orderItemShipGroup.getTimestamp("shipByDate");
cartShipInfo.shipmentMethodTypeId = orderItemShipGroup.getString("shipmentMethodTypeId");
cartShipInfo.carrierPartyId = orderItemShipGroup.getString("carrierPartyId");
cartShipInfo.supplierPartyId = orderItemShipGroup.getString("supplierPartyId");
cartShipInfo.setMaySplit(orderItemShipGroup.getBoolean("maySplit"));
cartShipInfo.giftMessage = orderItemShipGroup.getString("giftMessage");
cartShipInfo.setContactMechId(orderItemShipGroup.getString("contactMechId"));
cartShipInfo.shippingInstructions = orderItemShipGroup.getString("shippingInstructions");
cartShipInfo.setFacilityId(orderItemShipGroup.getString("facilityId"));
cartShipInfo.setVendorPartyId(orderItemShipGroup.getString("vendorPartyId"));
cartShipInfo.setShipGroupSeqId(orderItemShipGroup.getString("shipGroupSeqId"));
cartShipInfo.shipTaxAdj.addAll(orh.getOrderHeaderAdjustmentsTax(orderItemShipGroup.getString("shipGroupSeqId")));
}
List<GenericValue> orderItems = orh.getOrderItems();
long nextItemSeq = 0;
if (UtilValidate.isNotEmpty(orderItems)) {
Pattern pattern = Pattern.compile("\\P{Digit}");
for (GenericValue item : orderItems) {
// get the next item sequence id
String orderItemSeqId = item.getString("orderItemSeqId");
Matcher pmatcher = pattern.matcher(orderItemSeqId);
orderItemSeqId = pmatcher.replaceAll("");
// get product Id
String productId = item.getString("productId");
GenericValue product = null;
// creates survey responses for Gift cards same as last Order created
Map<String, Object> surveyResponseResult = null;
try {
long seq = Long.parseLong(orderItemSeqId);
if (seq > nextItemSeq) {
nextItemSeq = seq;
}
} catch (NumberFormatException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(e.getMessage());
}
if ("ITEM_REJECTED".equals(item.getString("statusId")) || "ITEM_CANCELLED".equals(item.getString("statusId"))) {
continue;
}
try {
product = EntityQuery.use(delegator).from("Product").where("productId", productId).queryOne();
if ("DIGITAL_GOOD".equals(product.getString("productTypeId"))) {
Map<String, Object> surveyResponseMap = new HashMap<>();
Map<String, Object> answers = new HashMap<>();
List<GenericValue> surveyResponseAndAnswers = EntityQuery.use(delegator).from("SurveyResponseAndAnswer").where("orderId", orderId, "orderItemSeqId", orderItemSeqId).queryList();
if (UtilValidate.isNotEmpty(surveyResponseAndAnswers)) {
String surveyId = EntityUtil.getFirst(surveyResponseAndAnswers).getString("surveyId");
for (GenericValue surveyResponseAndAnswer : surveyResponseAndAnswers) {
answers.put((surveyResponseAndAnswer.get("surveyQuestionId").toString()), surveyResponseAndAnswer.get("textResponse"));
}
surveyResponseMap.put("answers", answers);
surveyResponseMap.put("surveyId", surveyId);
surveyResponseResult = dispatcher.runSync("createSurveyResponse", surveyResponseMap);
if (ServiceUtil.isError(surveyResponseResult)) {
return ServiceUtil.returnError(ServiceUtil.getErrorMessage(surveyResponseResult));
}
}
}
} catch (GenericEntityException | GenericServiceException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(e.getMessage());
}
// do not include PROMO items
if (!includePromoItems && item.get("isPromo") != null && "Y".equals(item.getString("isPromo"))) {
continue;
}
// not a promo item; go ahead and add it in
BigDecimal amount = item.getBigDecimal("selectedAmount");
if (amount == null) {
amount = BigDecimal.ZERO;
}
// BigDecimal quantity = item.getBigDecimal("quantity");
BigDecimal quantity = BigDecimal.ZERO;
if ("ITEM_COMPLETED".equals(item.getString("statusId")) && "N".equals(createAsNewOrder)) {
quantity = item.getBigDecimal("quantity");
} else {
quantity = OrderReadHelper.getOrderItemQuantity(item);
}
if (quantity == null) {
quantity = BigDecimal.ZERO;
}
BigDecimal unitPrice = null;
if ("Y".equals(item.getString("isModifiedPrice"))) {
unitPrice = item.getBigDecimal("unitPrice");
}
int itemIndex = -1;
if (item.get("productId") == null) {
// non-product item
String itemType = item.getString("orderItemTypeId");
String desc = item.getString("itemDescription");
try {
// TODO: passing in null now for itemGroupNumber, but should reproduce from OrderItemGroup records
itemIndex = cart.addNonProductItem(itemType, desc, null, unitPrice, quantity, null, null, null, dispatcher);
} catch (CartItemModifyException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(e.getMessage());
}
} else {
// product item
String prodCatalogId = item.getString("prodCatalogId");
// prepare the rental data
Timestamp reservStart = null;
BigDecimal reservLength = null;
BigDecimal reservPersons = null;
String accommodationMapId = null;
String accommodationSpotId = null;
GenericValue workEffort = null;
String workEffortId = orh.getCurrentOrderItemWorkEffort(item);
if (workEffortId != null) {
try {
workEffort = EntityQuery.use(delegator).from("WorkEffort").where("workEffortId", workEffortId).queryOne();
} catch (GenericEntityException e) {
Debug.logError(e, module);
}
}
if (workEffort != null && "ASSET_USAGE".equals(workEffort.getString("workEffortTypeId"))) {
reservStart = workEffort.getTimestamp("estimatedStartDate");
reservLength = OrderReadHelper.getWorkEffortRentalLength(workEffort);
reservPersons = workEffort.getBigDecimal("reservPersons");
accommodationMapId = workEffort.getString("accommodationMapId");
accommodationSpotId = workEffort.getString("accommodationSpotId");
}
// end of rental data
// check for AGGREGATED products
ProductConfigWrapper configWrapper = null;
String configId = null;
try {
product = EntityQuery.use(delegator).from("Product").where("productId", productId).queryOne();
if (EntityTypeUtil.hasParentType(delegator, "ProductType", "productTypeId", product.getString("productTypeId"), "parentTypeId", "AGGREGATED")) {
GenericValue productAssoc = EntityQuery.use(delegator).from("ProductAssoc").where("productAssocTypeId", "PRODUCT_CONF", "productIdTo", product.getString("productId")).filterByDate().queryFirst();
if (productAssoc != null) {
productId = productAssoc.getString("productId");
configId = product.getString("configId");
}
}
} catch (GenericEntityException e) {
Debug.logError(e, module);
}
if (UtilValidate.isNotEmpty(configId)) {
configWrapper = ProductConfigWorker.loadProductConfigWrapper(delegator, dispatcher, configId, productId, productStoreId, prodCatalogId, website, currency, locale, userLogin);
}
try {
itemIndex = cart.addItemToEnd(productId, amount, quantity, unitPrice, reservStart, reservLength, reservPersons, accommodationMapId, accommodationSpotId, null, null, prodCatalogId, configWrapper, item.getString("orderItemTypeId"), dispatcher, null, unitPrice == null ? null : false, skipInventoryChecks, skipProductChecks);
} catch (ItemNotFoundException | CartItemModifyException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(e.getMessage());
}
}
// flag the item w/ the orderItemSeqId so we can reference it
ShoppingCartItem cartItem = cart.findCartItem(itemIndex);
cartItem.setIsPromo(item.get("isPromo") != null && "Y".equals(item.getString("isPromo")));
cartItem.setOrderItemSeqId(item.getString("orderItemSeqId"));
try {
cartItem.setItemGroup(cart.addItemGroup(item.getRelatedOne("OrderItemGroup", true)));
} catch (GenericEntityException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(e.getMessage());
}
// attach surveyResponseId for each item
if (UtilValidate.isNotEmpty(surveyResponseResult)) {
cartItem.setAttribute("surveyResponses", UtilMisc.toList(surveyResponseResult.get("surveyResponseId")));
}
// attach addition item information
cartItem.setStatusId(item.getString("statusId"));
cartItem.setItemType(item.getString("orderItemTypeId"));
cartItem.setItemComment(item.getString("comments"));
cartItem.setQuoteId(item.getString("quoteId"));
cartItem.setQuoteItemSeqId(item.getString("quoteItemSeqId"));
cartItem.setProductCategoryId(item.getString("productCategoryId"));
cartItem.setDesiredDeliveryDate(item.getTimestamp("estimatedDeliveryDate"));
cartItem.setShipBeforeDate(item.getTimestamp("shipBeforeDate"));
cartItem.setShipAfterDate(item.getTimestamp("shipAfterDate"));
cartItem.setShoppingList(item.getString("shoppingListId"), item.getString("shoppingListItemSeqId"));
cartItem.setIsModifiedPrice("Y".equals(item.getString("isModifiedPrice")));
cartItem.setName(item.getString("itemDescription"));
cartItem.setExternalId(item.getString("externalId"));
cartItem.setListPrice(item.getBigDecimal("unitListPrice"));
// load order item attributes
List<GenericValue> orderItemAttributesList = null;
try {
orderItemAttributesList = EntityQuery.use(delegator).from("OrderItemAttribute").where("orderId", orderId, "orderItemSeqId", orderItemSeqId).queryList();
if (UtilValidate.isNotEmpty(orderItemAttributesList)) {
for (GenericValue orderItemAttr : orderItemAttributesList) {
String name = orderItemAttr.getString("attrName");
String value = orderItemAttr.getString("attrValue");
cartItem.setOrderItemAttribute(name, value);
}
}
} catch (GenericEntityException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(e.getMessage());
}
// load order item contact mechs
List<GenericValue> orderItemContactMechList = null;
try {
orderItemContactMechList = EntityQuery.use(delegator).from("OrderItemContactMech").where("orderId", orderId, "orderItemSeqId", orderItemSeqId).queryList();
if (UtilValidate.isNotEmpty(orderItemContactMechList)) {
for (GenericValue orderItemContactMech : orderItemContactMechList) {
String contactMechPurposeTypeId = orderItemContactMech.getString("contactMechPurposeTypeId");
String contactMechId = orderItemContactMech.getString("contactMechId");
cartItem.addContactMech(contactMechPurposeTypeId, contactMechId);
}
}
} catch (GenericEntityException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(e.getMessage());
}
// set the PO number on the cart
cart.setPoNumber(item.getString("correspondingPoId"));
// get all item adjustments EXCEPT tax adjustments
List<GenericValue> itemAdjustments = orh.getOrderItemAdjustments(item);
if (itemAdjustments != null) {
for (GenericValue itemAdjustment : itemAdjustments) {
if (!isTaxAdjustment(itemAdjustment)) {
cartItem.addAdjustment(itemAdjustment);
}
}
}
}
// setup the OrderItemShipGroupAssoc records
if (UtilValidate.isNotEmpty(orderItems)) {
int itemIndex = 0;
for (GenericValue item : orderItems) {
// if rejected or cancelled ignore, just like above otherwise all indexes will be off by one!
if ("ITEM_REJECTED".equals(item.getString("statusId")) || "ITEM_CANCELLED".equals(item.getString("statusId"))) {
continue;
}
List<GenericValue> orderItemAdjustments = orh.getOrderItemAdjustments(item);
// set the item's ship group info
List<GenericValue> shipGroupAssocs = orh.getOrderItemShipGroupAssocs(item);
if (UtilValidate.isNotEmpty(shipGroupAssocs)) {
shipGroupAssocs = EntityUtil.orderBy(shipGroupAssocs, UtilMisc.toList("-shipGroupSeqId"));
}
for (int g = 0; g < shipGroupAssocs.size(); g++) {
GenericValue sgAssoc = shipGroupAssocs.get(g);
BigDecimal shipGroupQty = OrderReadHelper.getOrderItemShipGroupQuantity(sgAssoc);
if (shipGroupQty == null) {
shipGroupQty = BigDecimal.ZERO;
}
String cartShipGroupIndexStr = sgAssoc.getString("shipGroupSeqId");
int cartShipGroupIndex = cart.getShipInfoIndex(cartShipGroupIndexStr);
if (cartShipGroupIndex > 0) {
cart.positionItemToGroup(itemIndex, shipGroupQty, 0, cartShipGroupIndex, false);
}
// because the ship groups are setup before loading items, and the ShoppingCart.addItemToEnd
// method is called when loading items above and it calls ShoppingCart.setItemShipGroupQty,
// this may not be necessary here, so check it first as calling it here with 0 quantity and
// such ends up removing cart items from the group, which causes problems later with inventory
// reservation, tax calculation, etc.
ShoppingCart.CartShipInfo csi = cart.getShipInfo(cartShipGroupIndex);
ShoppingCartItem cartItem = cart.findCartItem(itemIndex);
if (cartItem == null || cartItem.getQuantity() == null || BigDecimal.ZERO.equals(cartItem.getQuantity()) || shipGroupQty.equals(cartItem.getQuantity())) {
Debug.logInfo("In loadCartFromOrder not adding item [" + item.getString("orderItemSeqId") + "] to ship group with index [" + itemIndex + "]; group quantity is [" + shipGroupQty + "] item quantity is [" + (cartItem != null ? cartItem.getQuantity() : "no cart item") + "] cartShipGroupIndex is [" + cartShipGroupIndex + "], csi.shipItemInfo.size(): " + (cartShipGroupIndex < 0 ? 0 : csi.shipItemInfo.size()), module);
} else {
cart.setItemShipGroupQty(itemIndex, shipGroupQty, cartShipGroupIndex);
}
List<GenericValue> shipGroupItemAdjustments = EntityUtil.filterByAnd(orderItemAdjustments, UtilMisc.toMap("shipGroupSeqId", cartShipGroupIndexStr));
if (cartItem == null || cartShipGroupIndex < 0) {
Debug.logWarning("In loadCartFromOrder could not find cart item for itemIndex=" + itemIndex + ", for orderId=" + orderId, module);
} else {
CartShipItemInfo cartShipItemInfo = csi.getShipItemInfo(cartItem);
if (cartShipItemInfo == null) {
Debug.logWarning("In loadCartFromOrder could not find CartShipItemInfo for itemIndex=" + itemIndex + ", for orderId=" + orderId, module);
} else {
List<GenericValue> itemTaxAdj = cartShipItemInfo.itemTaxAdj;
for (GenericValue shipGroupItemAdjustment : shipGroupItemAdjustments) {
if (isTaxAdjustment(shipGroupItemAdjustment)) {
itemTaxAdj.add(shipGroupItemAdjustment);
}
}
}
}
}
itemIndex++;
}
}
// set the item seq in the cart
if (nextItemSeq > 0) {
try {
cart.setNextItemSeq(nextItemSeq + 1);
} catch (GeneralException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(e.getMessage());
}
}
}
if (includePromoItems) {
for (String productPromoCode : orh.getProductPromoCodesEntered()) {
cart.addProductPromoCode(productPromoCode, dispatcher);
}
for (GenericValue productPromoUse : orh.getProductPromoUse()) {
cart.addProductPromoUse(productPromoUse.getString("productPromoId"), productPromoUse.getString("productPromoCodeId"), productPromoUse.getBigDecimal("totalDiscountAmount"), productPromoUse.getBigDecimal("quantityLeftInActions"), new HashMap<ShoppingCartItem, BigDecimal>());
}
}
List<GenericValue> adjustments = orh.getOrderHeaderAdjustments();
// If applyQuoteAdjustments is set to false then standard cart adjustments are used.
if (!adjustments.isEmpty()) {
// The cart adjustments are added to the cart
cart.getAdjustments().addAll(adjustments);
}
Map<String, Object> result = ServiceUtil.returnSuccess();
result.put("shoppingCart", cart);
return result;
}
use of org.apache.ofbiz.entity.condition.EntityExpr in project ofbiz-framework by apache.
the class ShoppingCartItem method getFeatureIdQtyMap.
public Map<String, BigDecimal> getFeatureIdQtyMap(BigDecimal quantity) {
Map<String, BigDecimal> featureMap = new HashMap<>();
GenericValue product = this.getProduct();
if (product != null) {
List<GenericValue> featureAppls = null;
try {
featureAppls = product.getRelated("ProductFeatureAppl", null, null, false);
List<EntityExpr> filterExprs = UtilMisc.toList(EntityCondition.makeCondition("productFeatureApplTypeId", EntityOperator.EQUALS, "STANDARD_FEATURE"));
filterExprs.add(EntityCondition.makeCondition("productFeatureApplTypeId", EntityOperator.EQUALS, "REQUIRED_FEATURE"));
filterExprs.add(EntityCondition.makeCondition("productFeatureApplTypeId", EntityOperator.EQUALS, "DISTINGUISHING_FEAT"));
featureAppls = EntityUtil.filterByOr(featureAppls, filterExprs);
} catch (GenericEntityException e) {
Debug.logError(e, "Unable to get features from product : " + product.get("productId"), module);
}
if (featureAppls != null) {
for (GenericValue appl : featureAppls) {
BigDecimal lastQuantity = featureMap.get(appl.getString("productFeatureId"));
if (lastQuantity == null) {
lastQuantity = BigDecimal.ZERO;
}
BigDecimal newQuantity = lastQuantity.add(quantity);
featureMap.put(appl.getString("productFeatureId"), newQuantity);
}
}
}
if (this.additionalProductFeatureAndAppls != null) {
for (GenericValue appl : this.additionalProductFeatureAndAppls.values()) {
BigDecimal lastQuantity = featureMap.get(appl.getString("productFeatureId"));
if (lastQuantity == null) {
lastQuantity = BigDecimal.ZERO;
}
BigDecimal newQuantity = lastQuantity.add(quantity);
featureMap.put(appl.getString("productFeatureId"), newQuantity);
}
}
return featureMap;
}
use of org.apache.ofbiz.entity.condition.EntityExpr in project ofbiz-framework by apache.
the class PartyWorker method getAssociatedPartyIdsByRelationshipType.
public static List<String> getAssociatedPartyIdsByRelationshipType(Delegator delegator, String partyIdFrom, String partyRelationshipTypeId) {
List<GenericValue> partyList = new LinkedList<>();
List<String> partyIds = null;
try {
EntityConditionList<EntityExpr> baseExprs = EntityCondition.makeCondition(UtilMisc.toList(EntityCondition.makeCondition("partyIdFrom", partyIdFrom), EntityCondition.makeCondition("partyRelationshipTypeId", partyRelationshipTypeId)), EntityOperator.AND);
List<GenericValue> associatedParties = EntityQuery.use(delegator).from("PartyRelationship").where(baseExprs).cache(true).queryList();
partyList.addAll(associatedParties);
while (UtilValidate.isNotEmpty(associatedParties)) {
List<GenericValue> currentAssociatedParties = new LinkedList<>();
for (GenericValue associatedParty : associatedParties) {
EntityConditionList<EntityExpr> innerExprs = EntityCondition.makeCondition(UtilMisc.toList(EntityCondition.makeCondition("partyIdFrom", associatedParty.get("partyIdTo")), EntityCondition.makeCondition("partyRelationshipTypeId", partyRelationshipTypeId)), EntityOperator.AND);
List<GenericValue> associatedPartiesChilds = EntityQuery.use(delegator).from("PartyRelationship").where(innerExprs).cache(true).queryList();
if (UtilValidate.isNotEmpty(associatedPartiesChilds)) {
currentAssociatedParties.addAll(associatedPartiesChilds);
}
partyList.add(associatedParty);
}
associatedParties = currentAssociatedParties;
}
partyIds = EntityUtil.getFieldListFromEntityList(partyList, "partyIdTo", true);
} catch (GenericEntityException e) {
Debug.logWarning(e, module);
}
return partyIds;
}
use of org.apache.ofbiz.entity.condition.EntityExpr in project ofbiz-framework by apache.
the class CheckOutHelper method checkOrderBlackList.
public Map<String, Object> checkOrderBlackList() {
if (cart == null) {
return ServiceUtil.returnSuccess("success");
}
GenericValue shippingAddressObj = this.cart.getShippingAddress();
if (shippingAddressObj == null) {
return ServiceUtil.returnSuccess("success");
}
String shippingAddress = UtilFormatOut.checkNull(shippingAddressObj.getString("address1")).toUpperCase(Locale.getDefault());
shippingAddress = UtilFormatOut.makeSqlSafe(shippingAddress);
List<EntityExpr> exprs = UtilMisc.toList(EntityCondition.makeCondition(EntityCondition.makeCondition(EntityFunction.UPPER_FIELD("blacklistString"), EntityOperator.EQUALS, EntityFunction.UPPER(shippingAddress)), EntityOperator.AND, EntityCondition.makeCondition("orderBlacklistTypeId", EntityOperator.EQUALS, "BLACKLIST_ADDRESS")));
String errMsg = null;
List<GenericValue> paymentMethods = this.cart.getPaymentMethods();
for (GenericValue paymentMethod : paymentMethods) {
if ((paymentMethod != null) && ("CREDIT_CARD".equals(paymentMethod.getString("paymentMethodTypeId")))) {
GenericValue creditCard = null;
GenericValue billingAddress = null;
try {
creditCard = paymentMethod.getRelatedOne("CreditCard", false);
if (creditCard != null) {
billingAddress = creditCard.getRelatedOne("PostalAddress", false);
}
} catch (GenericEntityException e) {
Debug.logError(e, "Problems getting credit card from payment method", module);
errMsg = UtilProperties.getMessage(resource_error, "checkhelper.problems_reading_database", cart.getLocale());
return ServiceUtil.returnError(errMsg);
}
if (creditCard != null) {
String creditCardNumber = UtilFormatOut.checkNull(creditCard.getString("cardNumber"));
exprs.add(EntityCondition.makeCondition(EntityCondition.makeCondition("blacklistString", EntityOperator.EQUALS, creditCardNumber), EntityOperator.AND, EntityCondition.makeCondition("orderBlacklistTypeId", EntityOperator.EQUALS, "BLACKLIST_CREDITCARD")));
}
if (billingAddress != null) {
String address = UtilFormatOut.checkNull(billingAddress.getString("address1").toUpperCase(Locale.getDefault()));
address = UtilFormatOut.makeSqlSafe(address);
exprs.add(EntityCondition.makeCondition(EntityCondition.makeCondition(EntityFunction.UPPER_FIELD("blacklistString"), EntityOperator.EQUALS, EntityFunction.UPPER(address)), EntityOperator.AND, EntityCondition.makeCondition("orderBlacklistTypeId", EntityOperator.EQUALS, "BLACKLIST_ADDRESS")));
}
}
}
List<GenericValue> blacklistFound = null;
if (exprs.size() > 0) {
try {
blacklistFound = EntityQuery.use(this.delegator).from("OrderBlacklist").where(exprs).queryList();
} catch (GenericEntityException e) {
Debug.logError(e, "Problems with OrderBlacklist lookup.", module);
errMsg = UtilProperties.getMessage(resource_error, "checkhelper.problems_reading_database", cart.getLocale());
return ServiceUtil.returnError(errMsg);
}
}
if (UtilValidate.isNotEmpty(blacklistFound)) {
return ServiceUtil.returnFailure(UtilProperties.getMessage(resource_error, "OrderFailed", cart.getLocale()));
}
return ServiceUtil.returnSuccess("success");
}
use of org.apache.ofbiz.entity.condition.EntityExpr in project ofbiz-framework by apache.
the class CheckOutHelper method processPayment.
public static Map<String, Object> 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";
}
List<GenericValue> allPaymentPreferences = null;
try {
allPaymentPreferences = EntityQuery.use(delegator).from("OrderPaymentPreference").where("orderId", orderId).queryList();
} catch (GenericEntityException e) {
throw new GeneralException("Problems getting payment preferences", e);
}
// filter out cancelled preferences
List<EntityExpr> canExpr = UtilMisc.toList(EntityCondition.makeCondition("statusId", EntityOperator.NOT_EQUAL, "PAYMENT_CANCELLED"));
allPaymentPreferences = EntityUtil.filterByAnd(allPaymentPreferences, canExpr);
// check for online payment methods or in-hand payment types with verbal or external refs
List<EntityExpr> exprs = UtilMisc.toList(EntityCondition.makeCondition("manualRefNum", EntityOperator.NOT_EQUAL, null));
List<GenericValue> manualRefPaymentPrefs = EntityUtil.filterByAnd(allPaymentPreferences, exprs);
if (UtilValidate.isNotEmpty(manualRefPaymentPrefs)) {
for (GenericValue opp : manualRefPaymentPrefs) {
Map<String, Object> authCtx = new HashMap<>();
authCtx.put("orderPaymentPreference", opp);
if (opp.get("paymentMethodId") == null) {
authCtx.put("serviceTypeEnum", "PRDS_PAY_EXTERNAL");
}
authCtx.put("processAmount", opp.getBigDecimal("maxAmount"));
authCtx.put("authRefNum", opp.getString("manualRefNum"));
authCtx.put("authResult", Boolean.TRUE);
authCtx.put("userLogin", userLogin);
authCtx.put("currencyUomId", currencyUomId);
Map<String, Object> authResp = dispatcher.runSync("processAuthResult", authCtx);
if (ServiceUtil.isError(authResp)) {
String errorMessage = ServiceUtil.getErrorMessage(authResp);
Debug.logError(errorMessage, module);
throw new GeneralException(errorMessage);
}
// approve the order
OrderChangeHelper.approveOrder(dispatcher, userLogin, orderId, manualHold);
if ("Y".equalsIgnoreCase(productStore.getString("manualAuthIsCapture"))) {
Map<String, Object> captCtx = new HashMap<>();
captCtx.put("orderPaymentPreference", opp);
if (opp.get("paymentMethodId") == null) {
captCtx.put("serviceTypeEnum", "PRDS_PAY_EXTERNAL");
}
captCtx.put("payToPartyId", productStore.get("payToPartyId"));
captCtx.put("captureResult", Boolean.TRUE);
captCtx.put("captureAmount", opp.getBigDecimal("maxAmount"));
captCtx.put("captureRefNum", opp.getString("manualRefNum"));
captCtx.put("userLogin", userLogin);
captCtx.put("currencyUomId", currencyUomId);
Map<String, Object> capResp = dispatcher.runSync("processCaptureResult", captCtx);
if (ServiceUtil.isError(capResp)) {
String errorMessage = ServiceUtil.getErrorMessage(capResp);
Debug.logError(errorMessage, module);
throw new GeneralException(errorMessage);
}
}
}
}
// check for a paypal express checkout needing completion
List<EntityExpr> payPalExprs = UtilMisc.toList(EntityCondition.makeCondition("paymentMethodId", EntityOperator.NOT_EQUAL, null), EntityCondition.makeCondition("paymentMethodTypeId", "EXT_PAYPAL"));
List<GenericValue> payPalPaymentPrefs = EntityUtil.filterByAnd(allPaymentPreferences, payPalExprs);
if (UtilValidate.isNotEmpty(payPalPaymentPrefs)) {
GenericValue payPalPaymentPref = EntityUtil.getFirst(payPalPaymentPrefs);
ExpressCheckoutEvents.doExpressCheckout(productStore.getString("productStoreId"), orderId, payPalPaymentPref, userLogin, delegator, dispatcher);
}
// check for online payment methods needing authorization
Map<String, Object> paymentFields = UtilMisc.<String, Object>toMap("statusId", "PAYMENT_NOT_AUTH");
List<GenericValue> onlinePaymentPrefs = EntityUtil.filterByAnd(allPaymentPreferences, paymentFields);
// Invoke payment processing.
if (UtilValidate.isNotEmpty(onlinePaymentPrefs)) {
boolean autoApproveOrder = UtilValidate.isEmpty(productStore.get("autoApproveOrder")) || "Y".equalsIgnoreCase(productStore.getString("autoApproveOrder"));
if (orderTotal.compareTo(BigDecimal.ZERO) == 0 && autoApproveOrder) {
// if there is nothing to authorize; don't bother
boolean ok = OrderChangeHelper.approveOrder(dispatcher, userLogin, orderId, manualHold);
if (!ok) {
throw new GeneralException("Problem with order change; see above error");
}
}
// now there should be something to authorize; go ahead
Map<String, Object> paymentResult = null;
try {
// invoke the payment gateway service.
paymentResult = dispatcher.runSync("authOrderPayments", UtilMisc.<String, Object>toMap("orderId", orderId, "userLogin", userLogin), 180, false);
if (ServiceUtil.isError(paymentResult)) {
String errorMessage = ServiceUtil.getErrorMessage(paymentResult);
Debug.logError(errorMessage, module);
throw new GeneralException(errorMessage);
}
} catch (GenericServiceException e) {
Debug.logWarning(e, module);
throw new GeneralException("Error in authOrderPayments service: " + e.toString(), e.getNested());
}
if (Debug.verboseOn()) {
Debug.logVerbose("Finished w/ Payment Service", module);
}
if (paymentResult != null && paymentResult.containsKey("processResult")) {
// grab the customer messages -- only passed back in the case of an error or failure
List<String> messages = UtilGenerics.checkList(paymentResult.get("authResultMsgs"));
String authResp = (String) paymentResult.get("processResult");
if ("FAILED".equals(authResp)) {
// order was NOT approved
if (Debug.verboseOn()) {
Debug.logVerbose("Payment auth was NOT a success!", module);
}
boolean ok = OrderChangeHelper.rejectOrder(dispatcher, userLogin, orderId);
if (!ok) {
throw new GeneralException("Problem with order change; see above error");
}
if (UtilValidate.isEmpty(messages)) {
return ServiceUtil.returnError(DECLINE_MESSAGE);
}
return ServiceUtil.returnError(messages);
} else if ("APPROVED".equals(authResp)) {
// order WAS approved
if (Debug.verboseOn()) {
Debug.logVerbose("Payment auth was a success!", module);
}
// set the order and item status to approved
if (autoApproveOrder) {
List<GenericValue> productStorePaymentSettingList = EntityQuery.use(delegator).from("ProductStorePaymentSetting").where("productStoreId", productStore.getString("productStoreId"), "paymentMethodTypeId", "CREDIT_CARD", "paymentService", "cyberSourceCCAuth").queryList();
if (productStorePaymentSettingList.size() > 0) {
String decision = (String) paymentResult.get("authCode");
if (UtilValidate.isNotEmpty(decision)) {
if ("ACCEPT".equalsIgnoreCase(decision)) {
boolean ok = OrderChangeHelper.approveOrder(dispatcher, userLogin, orderId, manualHold);
if (!ok) {
throw new GeneralException("Problem with order change; see above error");
}
}
} else {
boolean ok = OrderChangeHelper.approveOrder(dispatcher, userLogin, orderId, manualHold);
if (!ok) {
throw new GeneralException("Problem with order change; see above error");
}
}
} else {
boolean ok = OrderChangeHelper.approveOrder(dispatcher, userLogin, orderId, manualHold);
if (!ok) {
throw new GeneralException("Problem with order change; see above error");
}
}
}
} else if ("ERROR".equals(authResp)) {
// service failed
if (Debug.verboseOn()) {
Debug.logVerbose("Payment auth failed due to processor trouble.", module);
}
if (!faceToFace && "Y".equalsIgnoreCase(RETRY_ON_ERROR)) {
// never do this for a face to face purchase regardless of store setting
return ServiceUtil.returnSuccess(ERROR_MESSAGE);
}
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(messages);
} else {
// should never happen
return ServiceUtil.returnError(UtilProperties.getMessage(resource_error, "OrderPleaseContactCustomerServicePaymentReturnCodeUnknown", Locale.getDefault()));
}
} else {
// result returned null == service failed
if (Debug.verboseOn()) {
Debug.logVerbose("Payment auth failed due to processor trouble.", module);
}
if (!faceToFace && "Y".equalsIgnoreCase(RETRY_ON_ERROR)) {
// never do this for a face to face purchase regardless of store setting
return ServiceUtil.returnSuccess(ERROR_MESSAGE);
}
boolean ok = OrderChangeHelper.cancelOrder(dispatcher, userLogin, orderId);
if (!ok) {
throw new GeneralException("Problem with order change; see above error");
}
return ServiceUtil.returnError(ERROR_MESSAGE);
}
} else {
// Get the paymentMethodTypeIds - this will need to change when ecom supports multiple payments
List<EntityExpr> cashCodPcBaExpr = UtilMisc.toList(EntityCondition.makeCondition("paymentMethodTypeId", EntityOperator.EQUALS, "CASH"), EntityCondition.makeCondition("paymentMethodTypeId", EntityOperator.EQUALS, "EXT_COD"), EntityCondition.makeCondition("paymentMethodTypeId", EntityOperator.EQUALS, "PERSONAL_CHECK"), EntityCondition.makeCondition("paymentMethodTypeId", EntityOperator.EQUALS, "EXT_BILLACT"));
List<GenericValue> cashCodPcBaPaymentPreferences = EntityUtil.filterByOr(allPaymentPreferences, cashCodPcBaExpr);
if (UtilValidate.isNotEmpty(cashCodPcBaPaymentPreferences) && UtilValidate.isNotEmpty(allPaymentPreferences) && cashCodPcBaPaymentPreferences.size() == allPaymentPreferences.size()) {
// if there are Check type, approve the order only if it is face to face
List<GenericValue> checkPreferences = EntityUtil.filterByAnd(cashCodPcBaPaymentPreferences, UtilMisc.toMap("paymentMethodTypeId", "PERSONAL_CHECK"));
if (UtilValidate.isNotEmpty(checkPreferences)) {
if (faceToFace) {
boolean ok = OrderChangeHelper.approveOrder(dispatcher, userLogin, orderId, manualHold);
if (!ok) {
throw new GeneralException("Problem with order change; see above error");
}
}
// approve this as long as there are only CASH, COD and Billing Account types
} else {
boolean ok = OrderChangeHelper.approveOrder(dispatcher, userLogin, orderId, manualHold);
if (!ok) {
throw new GeneralException("Problem with order change; see above error");
}
}
} else {
// There is nothing to do, we just treat this as a success
}
}
// check to see if we should auto-invoice/bill
if (faceToFace) {
if (Debug.verboseOn()) {
Debug.logVerbose("Face-To-Face Sale - " + orderId, module);
}
CheckOutHelper.adjustFaceToFacePayment(orderId, orderTotal, allPaymentPreferences, userLogin, delegator);
boolean ok = OrderChangeHelper.completeOrder(dispatcher, userLogin, orderId);
if (Debug.verboseOn()) {
Debug.logVerbose("Complete Order Result - " + ok, module);
}
if (!ok) {
throw new GeneralException("Problem with order change; see error logs");
}
}
return ServiceUtil.returnSuccess();
}
Aggregations