use of org.apache.ofbiz.product.config.ProductConfigWrapper in project ofbiz-framework by apache.
the class ProductionRunServices method createProductionRunFromConfiguration.
public static Map<String, Object> createProductionRunFromConfiguration(DispatchContext ctx, Map<String, ? extends Object> context) {
Map<String, Object> result = new HashMap<String, Object>();
Delegator delegator = ctx.getDelegator();
LocalDispatcher dispatcher = ctx.getDispatcher();
Locale locale = (Locale) context.get("locale");
GenericValue userLogin = (GenericValue) context.get("userLogin");
// Mandatory input fields
String facilityId = (String) context.get("facilityId");
// Optional input fields
String configId = (String) context.get("configId");
ProductConfigWrapper config = (ProductConfigWrapper) context.get("config");
BigDecimal quantity = (BigDecimal) context.get("quantity");
String orderId = (String) context.get("orderId");
String orderItemSeqId = (String) context.get("orderItemSeqId");
if (config == null && configId == null) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ManufacturingConfigurationNotAvailable", locale));
}
if (config == null && configId != null) {
// TODO: load the configuration
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ManufacturingProductionRunFromConfigurationNotYetImplemented", locale));
}
if (!config.isCompleted()) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ManufacturingProductionRunFromConfigurationNotValid", locale));
}
if (quantity == null) {
quantity = BigDecimal.ONE;
}
String instanceProductId = null;
try {
instanceProductId = ProductWorker.getAggregatedInstanceId(delegator, config.getProduct().getString("productId"), config.getConfigId());
} catch (Exception e) {
return ServiceUtil.returnError(e.getMessage());
}
Map<String, Object> serviceContext = new HashMap<String, Object>();
serviceContext.clear();
serviceContext.put("productId", instanceProductId);
serviceContext.put("pRQuantity", quantity);
serviceContext.put("startDate", UtilDateTime.nowTimestamp());
serviceContext.put("facilityId", facilityId);
serviceContext.put("userLogin", userLogin);
Map<String, Object> serviceResult = null;
try {
serviceResult = dispatcher.runSync("createProductionRun", serviceContext);
if (ServiceUtil.isError(serviceResult)) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ManufacturingProductionRunNotCreated", locale));
}
} catch (GenericServiceException e) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ManufacturingProductionRunNotCreated", locale));
}
String productionRunId = (String) serviceResult.get("productionRunId");
result.put("productionRunId", productionRunId);
Map<String, BigDecimal> components = new HashMap<String, BigDecimal>();
for (ConfigOption co : config.getSelectedOptions()) {
for (GenericValue selComponent : co.getComponents()) {
BigDecimal componentQuantity = null;
if (selComponent.get("quantity") != null) {
componentQuantity = selComponent.getBigDecimal("quantity");
}
if (componentQuantity == null) {
componentQuantity = BigDecimal.ONE;
}
String componentProductId = selComponent.getString("productId");
if (co.isVirtualComponent(selComponent)) {
Map<String, String> componentOptions = co.getComponentOptions();
if (UtilValidate.isNotEmpty(componentOptions) && UtilValidate.isNotEmpty(componentOptions.get(componentProductId))) {
componentProductId = componentOptions.get(componentProductId);
}
}
componentQuantity = quantity.multiply(componentQuantity);
if (components.containsKey(componentProductId)) {
BigDecimal totalQuantity = components.get(componentProductId);
componentQuantity = totalQuantity.add(componentQuantity);
}
// check if a bom exists
List<GenericValue> bomList = null;
try {
bomList = EntityQuery.use(delegator).from("ProductAssoc").where("productId", componentProductId, "productAssocTypeId", "MANUF_COMPONENT").filterByDate().queryList();
} catch (GenericEntityException e) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ManufacturingProductionRunTryToGetBomListError", locale));
}
// if so create a mandatory predecessor to this production run
if (UtilValidate.isNotEmpty(bomList)) {
serviceContext.clear();
serviceContext.put("productId", componentProductId);
serviceContext.put("quantity", componentQuantity);
serviceContext.put("startDate", UtilDateTime.nowTimestamp());
serviceContext.put("facilityId", facilityId);
serviceContext.put("userLogin", userLogin);
serviceResult = null;
try {
serviceResult = dispatcher.runSync("createProductionRunsForProductBom", serviceContext);
if (ServiceUtil.isError(serviceResult)) {
return ServiceUtil.returnError(ServiceUtil.getErrorMessage(serviceResult));
}
GenericValue workEffortPreDecessor = delegator.makeValue("WorkEffortAssoc", UtilMisc.toMap("workEffortIdTo", productionRunId, "workEffortIdFrom", serviceResult.get("productionRunId"), "workEffortAssocTypeId", "WORK_EFF_PRECEDENCY", "fromDate", UtilDateTime.nowTimestamp()));
workEffortPreDecessor.create();
} catch (GenericServiceException e) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ManufacturingProductionRunNotCreated", locale));
} catch (GenericEntityException e) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ManufacturingProductionRunTryToCreateWorkEffortAssoc", locale));
}
} else {
components.put(componentProductId, componentQuantity);
}
// create production run notes from comments
String comments = co.getComments();
if (UtilValidate.isNotEmpty(comments)) {
serviceResult.clear();
serviceContext.clear();
serviceContext.put("workEffortId", productionRunId);
serviceContext.put("internalNote", "Y");
serviceContext.put("noteInfo", comments);
serviceContext.put("noteName", co.getDescription());
serviceContext.put("userLogin", userLogin);
serviceContext.put("noteParty", userLogin.getString("partyId"));
try {
serviceResult = dispatcher.runSync("createWorkEffortNote", serviceContext);
if (ServiceUtil.isError(serviceResult)) {
return ServiceUtil.returnError(ServiceUtil.getErrorMessage(serviceResult));
}
} catch (GenericServiceException e) {
Debug.logWarning(e.getMessage(), module);
return ServiceUtil.returnError(e.getMessage());
}
}
}
}
for (Map.Entry<String, BigDecimal> component : components.entrySet()) {
String productId = component.getKey();
BigDecimal componentQuantity = component.getValue();
if (componentQuantity == null) {
componentQuantity = BigDecimal.ONE;
}
serviceResult = null;
serviceContext = new HashMap<String, Object>();
serviceContext.put("productionRunId", productionRunId);
serviceContext.put("productId", productId);
serviceContext.put("estimatedQuantity", componentQuantity);
serviceContext.put("userLogin", userLogin);
try {
serviceResult = dispatcher.runSync("addProductionRunComponent", serviceContext);
if (ServiceUtil.isError(serviceResult)) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ManufacturingProductionRunNotCreated", locale));
}
} catch (GenericServiceException e) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ManufacturingProductionRunNotCreated", locale));
}
}
try {
if (productionRunId != null && orderId != null && orderItemSeqId != null) {
delegator.create("WorkOrderItemFulfillment", UtilMisc.toMap("workEffortId", productionRunId, "orderId", orderId, "orderItemSeqId", orderItemSeqId));
}
} catch (GenericEntityException e) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ManufacturingRequirementNotDeleted", locale));
}
result.put(ModelService.SUCCESS_MESSAGE, UtilProperties.getMessage(resource, "ManufacturingProductionRunCreated", UtilMisc.toMap("productionRunId", productionRunId), locale));
return result;
}
use of org.apache.ofbiz.product.config.ProductConfigWrapper in project ofbiz-framework by apache.
the class ShoppingCartEvents method getConfigDetailsEvent.
public static String getConfigDetailsEvent(HttpServletRequest request, HttpServletResponse response) {
Delegator delegator = (Delegator) request.getAttribute("delegator");
String productId = request.getParameter("product_id");
String currencyUomId = ShoppingCartEvents.getCartObject(request).getCurrency();
ProductConfigWrapper configWrapper = ProductConfigWorker.getProductConfigWrapper(productId, currencyUomId, request);
if (configWrapper == null) {
Debug.logWarning("configWrapper is null", module);
request.setAttribute("_ERROR_MESSAGE_", "configWrapper is null");
return "error";
}
ProductConfigWorker.fillProductConfigWrapper(configWrapper, request);
if (configWrapper.isCompleted()) {
ProductConfigWorker.storeProductConfigWrapper(configWrapper, delegator);
request.setAttribute("configId", configWrapper.getConfigId());
}
request.setAttribute("totalPrice", org.apache.ofbiz.base.util.UtilFormatOut.formatCurrency(configWrapper.getTotalPrice(), currencyUomId, UtilHttp.getLocale(request)));
return "success";
}
use of org.apache.ofbiz.product.config.ProductConfigWrapper in project ofbiz-framework by apache.
the class ShoppingCartEvents method addToCart.
/**
* Event to add an item to the shopping cart.
*/
public static String addToCart(HttpServletRequest request, HttpServletResponse response) {
Delegator delegator = (Delegator) request.getAttribute("delegator");
LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
ShoppingCart cart = getCartObject(request);
ShoppingCartHelper cartHelper = new ShoppingCartHelper(delegator, dispatcher, cart);
String controlDirective = null;
Map<String, Object> result = null;
String productId = null;
String parentProductId = null;
String itemType = null;
String itemDescription = null;
String productCategoryId = null;
String priceStr = null;
BigDecimal price = null;
String quantityStr = null;
BigDecimal quantity = BigDecimal.ZERO;
String reservStartStr = null;
String reservEndStr = null;
Timestamp reservStart = null;
Timestamp reservEnd = null;
String reservLengthStr = null;
BigDecimal reservLength = null;
String reservPersonsStr = null;
BigDecimal reservPersons = null;
String accommodationMapId = null;
String accommodationSpotId = null;
String shipBeforeDateStr = null;
String shipAfterDateStr = null;
Timestamp shipBeforeDate = null;
Timestamp shipAfterDate = null;
String numberOfDay = null;
// not used right now: Map attributes = null;
String catalogId = CatalogWorker.getCurrentCatalogId(request);
Locale locale = UtilHttp.getLocale(request);
// Get the parameters as a MAP, remove the productId and quantity params.
Map<String, Object> paramMap = UtilHttp.getCombinedMap(request);
String itemGroupNumber = (String) paramMap.get("itemGroupNumber");
// Get shoppingList info if passed
String shoppingListId = (String) paramMap.get("shoppingListId");
String shoppingListItemSeqId = (String) paramMap.get("shoppingListItemSeqId");
if (paramMap.containsKey("ADD_PRODUCT_ID")) {
productId = (String) paramMap.remove("ADD_PRODUCT_ID");
} else if (paramMap.containsKey("add_product_id")) {
Object object = paramMap.remove("add_product_id");
try {
productId = (String) object;
} catch (ClassCastException e) {
List<String> productList = UtilGenerics.checkList(object);
productId = productList.get(0);
}
}
if (paramMap.containsKey("PRODUCT_ID")) {
parentProductId = (String) paramMap.remove("PRODUCT_ID");
} else if (paramMap.containsKey("product_id")) {
parentProductId = (String) paramMap.remove("product_id");
}
Debug.logInfo("adding item product " + productId, module);
Debug.logInfo("adding item parent product " + parentProductId, module);
if (paramMap.containsKey("ADD_CATEGORY_ID")) {
productCategoryId = (String) paramMap.remove("ADD_CATEGORY_ID");
} else if (paramMap.containsKey("add_category_id")) {
productCategoryId = (String) paramMap.remove("add_category_id");
}
if (productCategoryId != null && productCategoryId.length() == 0) {
productCategoryId = null;
}
if (paramMap.containsKey("ADD_ITEM_TYPE")) {
itemType = (String) paramMap.remove("ADD_ITEM_TYPE");
} else if (paramMap.containsKey("add_item_type")) {
itemType = (String) paramMap.remove("add_item_type");
}
if (UtilValidate.isEmpty(productId)) {
// before returning error; check make sure we aren't adding a special item type
if (UtilValidate.isEmpty(itemType)) {
request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resource_error, "cart.addToCart.noProductInfoPassed", locale));
// not critical return to same page
return "success";
}
} else {
try {
String pId = ProductWorker.findProductId(delegator, productId);
if (pId != null) {
productId = pId;
}
} catch (Throwable e) {
Debug.logWarning(e, module);
}
}
// check for an itemDescription
if (paramMap.containsKey("ADD_ITEM_DESCRIPTION")) {
itemDescription = (String) paramMap.remove("ADD_ITEM_DESCRIPTION");
} else if (paramMap.containsKey("add_item_description")) {
itemDescription = (String) paramMap.remove("add_item_description");
}
if (itemDescription != null && itemDescription.length() == 0) {
itemDescription = null;
}
// Get the ProductConfigWrapper (it's not null only for configurable items)
ProductConfigWrapper configWrapper = null;
configWrapper = ProductConfigWorker.getProductConfigWrapper(productId, cart.getCurrency(), request);
if (configWrapper != null) {
if (paramMap.containsKey("configId")) {
try {
configWrapper.loadConfig(delegator, (String) paramMap.remove("configId"));
} catch (Exception e) {
Debug.logWarning(e, "Could not load configuration", module);
}
} else {
// The choices selected by the user are taken from request and set in the wrapper
ProductConfigWorker.fillProductConfigWrapper(configWrapper, request);
}
if (!configWrapper.isCompleted()) {
// The configuration is not valid
request.setAttribute("product_id", productId);
request.setAttribute("_EVENT_MESSAGE_", UtilProperties.getMessage(resource_error, "cart.addToCart.configureProductBeforeAddingToCart", locale));
return "product";
}
// load the Config Id
ProductConfigWorker.storeProductConfigWrapper(configWrapper, delegator);
}
// Check for virtual products
if (ProductWorker.isVirtual(delegator, productId)) {
if ("VV_FEATURETREE".equals(ProductWorker.getProductVirtualVariantMethod(delegator, productId))) {
// get the selected features.
List<String> selectedFeatures = new LinkedList<>();
Enumeration<String> paramNames = UtilGenerics.cast(request.getParameterNames());
while (paramNames.hasMoreElements()) {
String paramName = paramNames.nextElement();
if (paramName.startsWith("FT")) {
selectedFeatures.add(request.getParameterValues(paramName)[0]);
}
}
// check if features are selected
if (UtilValidate.isEmpty(selectedFeatures)) {
request.setAttribute("paramMap", paramMap);
request.setAttribute("product_id", productId);
request.setAttribute("_EVENT_MESSAGE_", UtilProperties.getMessage(resource_error, "cart.addToCart.chooseVariationBeforeAddingToCart", locale));
return "product";
}
String variantProductId = ProductWorker.getVariantFromFeatureTree(productId, selectedFeatures, delegator);
if (UtilValidate.isNotEmpty(variantProductId)) {
productId = variantProductId;
} else {
request.setAttribute("paramMap", paramMap);
request.setAttribute("product_id", productId);
request.setAttribute("_EVENT_MESSAGE_", UtilProperties.getMessage(resource_error, "cart.addToCart.incompatibilityVariantFeature", locale));
return "product";
}
} else {
request.setAttribute("paramMap", paramMap);
request.setAttribute("product_id", productId);
request.setAttribute("_EVENT_MESSAGE_", UtilProperties.getMessage(resource_error, "cart.addToCart.chooseVariationBeforeAddingToCart", locale));
return "product";
}
}
// get the override price
if (paramMap.containsKey("PRICE")) {
priceStr = (String) paramMap.remove("PRICE");
} else if (paramMap.containsKey("price")) {
priceStr = (String) paramMap.remove("price");
}
if (priceStr == null) {
// default price is 0
priceStr = "0";
}
if ("ASSET_USAGE_OUT_IN".equals(ProductWorker.getProductTypeId(delegator, productId))) {
if (paramMap.containsKey("numberOfDay")) {
numberOfDay = (String) paramMap.remove("numberOfDay");
reservStart = UtilDateTime.addDaysToTimestamp(UtilDateTime.nowTimestamp(), 1);
reservEnd = UtilDateTime.addDaysToTimestamp(reservStart, Integer.parseInt(numberOfDay));
}
}
// get the renting data
if ("ASSET_USAGE".equals(ProductWorker.getProductTypeId(delegator, productId)) || "ASSET_USAGE_OUT_IN".equals(ProductWorker.getProductTypeId(delegator, productId))) {
if (paramMap.containsKey("reservStart")) {
reservStartStr = (String) paramMap.remove("reservStart");
if (reservStartStr.length() == 10) {
// should have format: yyyy-mm-dd hh:mm:ss.fffffffff
reservStartStr += " 00:00:00.000000000";
}
if (reservStartStr.length() > 0) {
try {
reservStart = java.sql.Timestamp.valueOf(reservStartStr);
} catch (Exception e) {
Debug.logWarning(e, "Problems parsing Reservation start string: " + reservStartStr, module);
reservStart = null;
request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resource_error, "cart.addToCart.rental.startDate", locale));
return "error";
}
} else {
reservStart = null;
}
}
if (paramMap.containsKey("reservEnd")) {
reservEndStr = (String) paramMap.remove("reservEnd");
if (reservEndStr.length() == 10) {
// should have format: yyyy-mm-dd hh:mm:ss.fffffffff
reservEndStr += " 00:00:00.000000000";
}
if (reservEndStr.length() > 0) {
try {
reservEnd = java.sql.Timestamp.valueOf(reservEndStr);
} catch (Exception e) {
Debug.logWarning(e, "Problems parsing Reservation end string: " + reservEndStr, module);
reservEnd = null;
request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resource_error, "cart.addToCart.rental.endDate", locale));
return "error";
}
} else {
reservEnd = null;
}
}
if (reservStart != null && reservEnd != null) {
reservLength = new BigDecimal(UtilDateTime.getInterval(reservStart, reservEnd)).divide(new BigDecimal("86400000"), generalRounding);
}
if (reservStart != null && paramMap.containsKey("reservLength")) {
reservLengthStr = (String) paramMap.remove("reservLength");
// parse the reservation Length
try {
reservLength = (BigDecimal) ObjectType.simpleTypeConvert(reservLengthStr, "BigDecimal", null, locale);
} catch (Exception e) {
Debug.logWarning(e, "Problems parsing reservation length string: " + reservLengthStr, module);
request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resource_error, "OrderReservationLengthShouldBeAPositiveNumber", locale));
return "error";
}
}
if (reservStart != null && paramMap.containsKey("reservPersons")) {
reservPersonsStr = (String) paramMap.remove("reservPersons");
// parse the number of persons
try {
reservPersons = (BigDecimal) ObjectType.simpleTypeConvert(reservPersonsStr, "BigDecimal", null, locale);
} catch (Exception e) {
Debug.logWarning(e, "Problems parsing reservation number of persons string: " + reservPersonsStr, module);
request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resource_error, "OrderNumberOfPersonsShouldBeOneOrLarger", locale));
return "error";
}
}
// check for valid rental parameters
if (UtilValidate.isEmpty(reservStart) && UtilValidate.isEmpty(reservLength) && UtilValidate.isEmpty(reservPersons)) {
request.setAttribute("product_id", productId);
request.setAttribute("_EVENT_MESSAGE_", UtilProperties.getMessage(resource_error, "cart.addToCart.enterBookingInforamtionBeforeAddingToCart", locale));
return "product";
}
// check accommodation for reservations
if ((paramMap.containsKey("accommodationMapId")) && (paramMap.containsKey("accommodationSpotId"))) {
accommodationMapId = (String) paramMap.remove("accommodationMapId");
accommodationSpotId = (String) paramMap.remove("accommodationSpotId");
}
}
// get the quantity
if (paramMap.containsKey("QUANTITY")) {
quantityStr = (String) paramMap.remove("QUANTITY");
} else if (paramMap.containsKey("quantity")) {
quantityStr = (String) paramMap.remove("quantity");
}
if (UtilValidate.isEmpty(quantityStr)) {
// default quantity is 1
quantityStr = "1";
}
// parse the price
try {
price = (BigDecimal) ObjectType.simpleTypeConvert(priceStr, "BigDecimal", null, locale);
} catch (Exception e) {
Debug.logWarning(e, "Problems parsing price string: " + priceStr, module);
price = null;
}
// parse the quantity
try {
quantity = (BigDecimal) ObjectType.simpleTypeConvert(quantityStr, "BigDecimal", null, locale);
// if not and if quantity is in decimal format then return error.
if (!ProductWorker.isDecimalQuantityOrderAllowed(delegator, productId, cart.getProductStoreId())) {
BigDecimal remainder = quantity.remainder(BigDecimal.ONE);
if (remainder.compareTo(BigDecimal.ZERO) != 0) {
request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resource_error, "cart.addToCart.quantityInDecimalNotAllowed", locale));
return "error";
}
quantity = quantity.setScale(0, UtilNumber.getRoundingMode("order.rounding"));
} else {
quantity = quantity.setScale(UtilNumber.getBigDecimalScale("order.decimals"), UtilNumber.getRoundingMode("order.rounding"));
}
} catch (Exception e) {
Debug.logWarning(e, "Problems parsing quantity string: " + quantityStr, module);
quantity = BigDecimal.ONE;
}
// get the selected amount
String selectedAmountStr = null;
if (paramMap.containsKey("ADD_AMOUNT")) {
selectedAmountStr = (String) paramMap.remove("ADD_AMOUNT");
} else if (paramMap.containsKey("add_amount")) {
selectedAmountStr = (String) paramMap.remove("add_amount");
}
// parse the amount
BigDecimal amount = null;
if (UtilValidate.isNotEmpty(selectedAmountStr)) {
try {
amount = (BigDecimal) ObjectType.simpleTypeConvert(selectedAmountStr, "BigDecimal", null, locale);
} catch (Exception e) {
Debug.logWarning(e, "Problem parsing amount string: " + selectedAmountStr, module);
amount = null;
}
} else {
amount = BigDecimal.ZERO;
}
// check for required amount
if ((ProductWorker.isAmountRequired(delegator, productId)) && (amount == null || amount.doubleValue() == 0.0)) {
request.setAttribute("product_id", productId);
request.setAttribute("_EVENT_MESSAGE_", UtilProperties.getMessage(resource_error, "cart.addToCart.enterAmountBeforeAddingToCart", locale));
return "product";
}
// get the ship before date (handles both yyyy-mm-dd input and full timestamp)
shipBeforeDateStr = (String) paramMap.remove("shipBeforeDate");
if (UtilValidate.isNotEmpty(shipBeforeDateStr)) {
if (shipBeforeDateStr.length() == 10) {
shipBeforeDateStr += " 00:00:00.000";
}
try {
shipBeforeDate = java.sql.Timestamp.valueOf(shipBeforeDateStr);
} catch (IllegalArgumentException e) {
Debug.logWarning(e, "Bad shipBeforeDate input: " + e.getMessage(), module);
shipBeforeDate = null;
}
}
// get the ship after date (handles both yyyy-mm-dd input and full timestamp)
shipAfterDateStr = (String) paramMap.remove("shipAfterDate");
if (UtilValidate.isNotEmpty(shipAfterDateStr)) {
if (shipAfterDateStr.length() == 10) {
shipAfterDateStr += " 00:00:00.000";
}
try {
shipAfterDate = java.sql.Timestamp.valueOf(shipAfterDateStr);
} catch (IllegalArgumentException e) {
Debug.logWarning(e, "Bad shipAfterDate input: " + e.getMessage(), module);
shipAfterDate = null;
}
}
// check for an add-to cart survey
List<String> surveyResponses = null;
if (productId != null) {
String productStoreId = ProductStoreWorker.getProductStoreId(request);
List<GenericValue> productSurvey = ProductStoreWorker.getProductSurveys(delegator, productStoreId, productId, "CART_ADD", parentProductId);
if (UtilValidate.isNotEmpty(productSurvey)) {
// TODO: implement multiple survey per product
GenericValue survey = EntityUtil.getFirst(productSurvey);
String surveyResponseId = (String) request.getAttribute("surveyResponseId");
if (surveyResponseId != null) {
surveyResponses = UtilMisc.toList(surveyResponseId);
} else {
String origParamMapId = UtilHttp.stashParameterMap(request);
Map<String, Object> surveyContext = UtilMisc.<String, Object>toMap("_ORIG_PARAM_MAP_ID_", origParamMapId);
GenericValue userLogin = cart.getUserLogin();
String partyId = null;
if (userLogin != null) {
partyId = userLogin.getString("partyId");
}
String formAction = "/additemsurvey";
String nextPage = RequestHandler.getOverrideViewUri(request.getPathInfo());
if (nextPage != null) {
formAction = formAction + "/" + nextPage;
}
ProductStoreSurveyWrapper wrapper = new ProductStoreSurveyWrapper(survey, partyId, surveyContext);
request.setAttribute("surveyWrapper", wrapper);
// will be used as the form action of the survey
request.setAttribute("surveyAction", formAction);
return "survey";
}
}
}
if (surveyResponses != null) {
paramMap.put("surveyResponses", surveyResponses);
}
GenericValue productStore = ProductStoreWorker.getProductStore(request);
if (productStore != null) {
String addToCartRemoveIncompat = productStore.getString("addToCartRemoveIncompat");
String addToCartReplaceUpsell = productStore.getString("addToCartReplaceUpsell");
try {
if ("Y".equals(addToCartRemoveIncompat)) {
List<GenericValue> productAssocs = null;
EntityCondition cond = EntityCondition.makeCondition(UtilMisc.toList(EntityCondition.makeCondition(EntityCondition.makeCondition("productId", EntityOperator.EQUALS, productId), EntityOperator.OR, EntityCondition.makeCondition("productIdTo", EntityOperator.EQUALS, productId)), EntityCondition.makeCondition("productAssocTypeId", EntityOperator.EQUALS, "PRODUCT_INCOMPATABLE")), EntityOperator.AND);
productAssocs = EntityQuery.use(delegator).from("ProductAssoc").where(cond).filterByDate().queryList();
List<String> productList = new LinkedList<>();
for (GenericValue productAssoc : productAssocs) {
if (productId.equals(productAssoc.getString("productId"))) {
productList.add(productAssoc.getString("productIdTo"));
continue;
}
if (productId.equals(productAssoc.getString("productIdTo"))) {
productList.add(productAssoc.getString("productId"));
continue;
}
}
for (ShoppingCartItem sci : cart) {
if (productList.contains(sci.getProductId())) {
try {
cart.removeCartItem(sci, dispatcher);
} catch (CartItemModifyException e) {
Debug.logError(e.getMessage(), module);
}
}
}
}
if ("Y".equals(addToCartReplaceUpsell)) {
List<GenericValue> productList = null;
productList = EntityQuery.use(delegator).select("productId").from("ProductAssoc").where("productIdTo", productId, "productAssocTypeId", "PRODUCT_UPGRADE").queryList();
if (productList != null) {
for (ShoppingCartItem sci : cart) {
if (productList.parallelStream().anyMatch(p -> sci.getProductId().equals(p.getString("productId")))) {
try {
cart.removeCartItem(sci, dispatcher);
} catch (CartItemModifyException e) {
Debug.logError(e.getMessage(), module);
}
}
}
}
}
} catch (GenericEntityException e) {
Debug.logError(e.getMessage(), module);
}
}
// check for alternative packing
if (ProductWorker.isAlternativePacking(delegator, productId, parentProductId)) {
GenericValue parentProduct = null;
try {
parentProduct = EntityQuery.use(delegator).from("Product").where("productId", parentProductId).queryOne();
} catch (GenericEntityException e) {
Debug.logError(e, "Error getting parent product", module);
}
BigDecimal piecesIncluded = BigDecimal.ZERO;
if (parentProduct != null) {
piecesIncluded = new BigDecimal(parentProduct.getLong("piecesIncluded"));
quantity = quantity.multiply(piecesIncluded);
}
}
// Translate the parameters and add to the cart
result = cartHelper.addToCart(catalogId, shoppingListId, shoppingListItemSeqId, productId, productCategoryId, itemType, itemDescription, price, amount, quantity, reservStart, reservLength, reservPersons, accommodationMapId, accommodationSpotId, shipBeforeDate, shipAfterDate, configWrapper, itemGroupNumber, paramMap, parentProductId);
controlDirective = processResult(result, request);
Integer itemId = (Integer) result.get("itemId");
if (UtilValidate.isNotEmpty(itemId)) {
request.setAttribute("itemId", itemId);
}
try {
GenericValue product = EntityQuery.use(delegator).from("Product").where("productId", productId).queryOne();
// Reset shipment method information in cart only if shipping applies on product.
if (UtilValidate.isNotEmpty(product) && ProductWorker.shippingApplies(product)) {
for (int shipGroupIndex = 0; shipGroupIndex < cart.getShipGroupSize(); shipGroupIndex++) {
String shipContactMechId = cart.getShippingContactMechId(shipGroupIndex);
if (UtilValidate.isNotEmpty(shipContactMechId)) {
cart.setShipmentMethodTypeId(shipGroupIndex, null);
}
}
}
} catch (GenericEntityException e) {
Debug.logError(e, "Error getting product" + e.getMessage(), module);
}
// Determine where to send the browser
if (controlDirective.equals(ERROR)) {
return "error";
}
if (cart.viewCartOnAdd()) {
return "viewcart";
}
return "success";
}
use of org.apache.ofbiz.product.config.ProductConfigWrapper in project ofbiz-framework by apache.
the class ShoppingCartServices method loadCartFromQuote.
public static Map<String, Object> loadCartFromQuote(DispatchContext dctx, Map<String, Object> context) {
LocalDispatcher dispatcher = dctx.getDispatcher();
Delegator delegator = dctx.getDelegator();
GenericValue userLogin = (GenericValue) context.get("userLogin");
String quoteId = (String) context.get("quoteId");
String applyQuoteAdjustmentsString = (String) context.get("applyQuoteAdjustments");
Locale locale = (Locale) context.get("locale");
boolean applyQuoteAdjustments = applyQuoteAdjustmentsString == null || "true".equals(applyQuoteAdjustmentsString);
// get the quote header
GenericValue quote = null;
try {
quote = EntityQuery.use(delegator).from("Quote").where("quoteId", quoteId).queryOne();
} catch (GenericEntityException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(e.getMessage());
}
// initial require cart info
String productStoreId = quote.getString("productStoreId");
String currency = quote.getString("currencyUomId");
// create the cart
ShoppingCart cart = new ShoppingCart(delegator, productStoreId, locale, currency);
// set shopping cart type
if ("PURCHASE_QUOTE".equals(quote.getString("quoteTypeId"))) {
cart.setOrderType("PURCHASE_ORDER");
cart.setBillFromVendorPartyId(quote.getString("partyId"));
}
try {
cart.setUserLogin(userLogin, dispatcher);
} catch (CartItemModifyException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(e.getMessage());
}
cart.setQuoteId(quoteId);
cart.setOrderName(quote.getString("quoteName"));
cart.setChannelType(quote.getString("salesChannelEnumId"));
List<GenericValue> quoteItems = null;
List<GenericValue> quoteAdjs = null;
List<GenericValue> quoteRoles = null;
List<GenericValue> quoteAttributes = null;
List<GenericValue> quoteTerms = null;
try {
quoteItems = quote.getRelated("QuoteItem", null, UtilMisc.toList("quoteItemSeqId"), false);
quoteAdjs = quote.getRelated("QuoteAdjustment", null, null, false);
quoteRoles = quote.getRelated("QuoteRole", null, null, false);
quoteAttributes = quote.getRelated("QuoteAttribute", null, null, false);
quoteTerms = quote.getRelated("QuoteTerm", null, null, false);
} catch (GenericEntityException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(e.getMessage());
}
// set the role information
cart.setOrderPartyId(quote.getString("partyId"));
if (UtilValidate.isNotEmpty(quoteRoles)) {
for (GenericValue quoteRole : quoteRoles) {
String quoteRoleTypeId = quoteRole.getString("roleTypeId");
String quoteRolePartyId = quoteRole.getString("partyId");
if ("PLACING_CUSTOMER".equals(quoteRoleTypeId)) {
cart.setPlacingCustomerPartyId(quoteRolePartyId);
} else if ("BILL_TO_CUSTOMER".equals(quoteRoleTypeId)) {
cart.setBillToCustomerPartyId(quoteRolePartyId);
} else if ("SHIP_TO_CUSTOMER".equals(quoteRoleTypeId)) {
cart.setShipToCustomerPartyId(quoteRolePartyId);
} else if ("END_USER_CUSTOMER".equals(quoteRoleTypeId)) {
cart.setEndUserCustomerPartyId(quoteRolePartyId);
} else if ("BILL_FROM_VENDOR".equals(quoteRoleTypeId)) {
cart.setBillFromVendorPartyId(quoteRolePartyId);
} else {
cart.addAdditionalPartyRole(quoteRolePartyId, quoteRoleTypeId);
}
}
}
// set the order term
if (UtilValidate.isNotEmpty(quoteTerms)) {
// create order term from quote term
for (GenericValue quoteTerm : quoteTerms) {
BigDecimal termValue = BigDecimal.ZERO;
if (UtilValidate.isNotEmpty(quoteTerm.getString("termValue"))) {
termValue = new BigDecimal(quoteTerm.getString("termValue"));
}
long termDays = 0;
if (UtilValidate.isNotEmpty(quoteTerm.getString("termDays"))) {
termDays = Long.parseLong(quoteTerm.getString("termDays").trim());
}
String orderItemSeqId = quoteTerm.getString("quoteItemSeqId");
cart.addOrderTerm(quoteTerm.getString("termTypeId"), orderItemSeqId, termValue, termDays, quoteTerm.getString("textValue"), quoteTerm.getString("description"));
}
}
// set the attribute information
if (UtilValidate.isNotEmpty(quoteAttributes)) {
for (GenericValue quoteAttribute : quoteAttributes) {
cart.setOrderAttribute(quoteAttribute.getString("attrName"), quoteAttribute.getString("attrValue"));
}
}
// Convert the quote adjustment to order header adjustments and
// put them in a map: the key/values pairs are quoteItemSeqId/List of adjs
Map<String, List<GenericValue>> orderAdjsMap = new HashMap<>();
for (GenericValue quoteAdj : quoteAdjs) {
List<GenericValue> orderAdjs = orderAdjsMap.get(UtilValidate.isNotEmpty(quoteAdj.getString("quoteItemSeqId")) ? quoteAdj.getString("quoteItemSeqId") : quoteId);
if (orderAdjs == null) {
orderAdjs = new LinkedList<>();
orderAdjsMap.put(UtilValidate.isNotEmpty(quoteAdj.getString("quoteItemSeqId")) ? quoteAdj.getString("quoteItemSeqId") : quoteId, orderAdjs);
}
// convert quote adjustments to order adjustments
GenericValue orderAdj = delegator.makeValue("OrderAdjustment");
orderAdj.put("orderAdjustmentId", quoteAdj.get("quoteAdjustmentId"));
orderAdj.put("orderAdjustmentTypeId", quoteAdj.get("quoteAdjustmentTypeId"));
orderAdj.put("orderItemSeqId", quoteAdj.get("quoteItemSeqId"));
orderAdj.put("comments", quoteAdj.get("comments"));
orderAdj.put("description", quoteAdj.get("description"));
orderAdj.put("amount", quoteAdj.get("amount"));
orderAdj.put("productPromoId", quoteAdj.get("productPromoId"));
orderAdj.put("productPromoRuleId", quoteAdj.get("productPromoRuleId"));
orderAdj.put("productPromoActionSeqId", quoteAdj.get("productPromoActionSeqId"));
orderAdj.put("productFeatureId", quoteAdj.get("productFeatureId"));
orderAdj.put("correspondingProductId", quoteAdj.get("correspondingProductId"));
orderAdj.put("sourceReferenceId", quoteAdj.get("sourceReferenceId"));
orderAdj.put("sourcePercentage", quoteAdj.get("sourcePercentage"));
orderAdj.put("customerReferenceId", quoteAdj.get("customerReferenceId"));
orderAdj.put("primaryGeoId", quoteAdj.get("primaryGeoId"));
orderAdj.put("secondaryGeoId", quoteAdj.get("secondaryGeoId"));
orderAdj.put("exemptAmount", quoteAdj.get("exemptAmount"));
orderAdj.put("taxAuthGeoId", quoteAdj.get("taxAuthGeoId"));
orderAdj.put("taxAuthPartyId", quoteAdj.get("taxAuthPartyId"));
orderAdj.put("overrideGlAccountId", quoteAdj.get("overrideGlAccountId"));
orderAdj.put("includeInTax", quoteAdj.get("includeInTax"));
orderAdj.put("includeInShipping", quoteAdj.get("includeInShipping"));
orderAdj.put("createdDate", quoteAdj.get("createdDate"));
orderAdj.put("createdByUserLogin", quoteAdj.get("createdByUserLogin"));
orderAdjs.add(orderAdj);
}
long nextItemSeq = 0;
if (UtilValidate.isNotEmpty(quoteItems)) {
Pattern pattern = Pattern.compile("\\P{Digit}");
for (GenericValue quoteItem : quoteItems) {
// get the next item sequence id
String orderItemSeqId = quoteItem.getString("quoteItemSeqId");
Matcher pmatcher = pattern.matcher(orderItemSeqId);
orderItemSeqId = pmatcher.replaceAll("");
try {
long seq = Long.parseLong(orderItemSeqId);
if (seq > nextItemSeq) {
nextItemSeq = seq;
}
} catch (NumberFormatException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(e.getMessage());
}
boolean isPromo = quoteItem.get("isPromo") != null && "Y".equals(quoteItem.getString("isPromo"));
if (isPromo && !applyQuoteAdjustments) {
// do not include PROMO items
continue;
}
// not a promo item; go ahead and add it in
BigDecimal amount = quoteItem.getBigDecimal("selectedAmount");
if (amount == null) {
amount = BigDecimal.ZERO;
}
BigDecimal quantity = quoteItem.getBigDecimal("quantity");
if (quantity == null) {
quantity = BigDecimal.ZERO;
}
BigDecimal quoteUnitPrice = quoteItem.getBigDecimal("quoteUnitPrice");
if (quoteUnitPrice == null) {
quoteUnitPrice = BigDecimal.ZERO;
}
if (amount.compareTo(BigDecimal.ZERO) > 0) {
// If, in the quote, an amount is set, we need to
// pass to the cart the quoteUnitPrice/amount value.
quoteUnitPrice = quoteUnitPrice.divide(amount, generalRounding);
}
// rental product data
Timestamp reservStart = quoteItem.getTimestamp("reservStart");
BigDecimal reservLength = quoteItem.getBigDecimal("reservLength");
BigDecimal reservPersons = quoteItem.getBigDecimal("reservPersons");
int itemIndex = -1;
if (quoteItem.get("productId") == null) {
// non-product item
String desc = quoteItem.getString("comments");
try {
// note that passing in null for itemGroupNumber as there is no real grouping concept in the quotes right now
itemIndex = cart.addNonProductItem(null, desc, null, null, quantity, null, null, null, dispatcher);
} catch (CartItemModifyException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(e.getMessage());
}
} else {
// product item
String productId = quoteItem.getString("productId");
ProductConfigWrapper configWrapper = null;
if (UtilValidate.isNotEmpty(quoteItem.getString("configId"))) {
configWrapper = ProductConfigWorker.loadProductConfigWrapper(delegator, dispatcher, quoteItem.getString("configId"), productId, productStoreId, null, null, currency, locale, userLogin);
}
try {
itemIndex = cart.addItemToEnd(productId, amount, quantity, quoteUnitPrice, reservStart, reservLength, reservPersons, null, null, null, null, null, configWrapper, null, dispatcher, Boolean.valueOf(!applyQuoteAdjustments), Boolean.valueOf(quoteUnitPrice.compareTo(BigDecimal.ZERO) == 0), Boolean.FALSE, Boolean.FALSE);
} 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.setOrderItemSeqId(orderItemSeqId);
// attach additional item information
cartItem.setItemComment(quoteItem.getString("comments"));
cartItem.setQuoteId(quoteItem.getString("quoteId"));
cartItem.setQuoteItemSeqId(quoteItem.getString("quoteItemSeqId"));
cartItem.setIsPromo(isPromo);
}
}
// If applyQuoteAdjustments is set to false then standard cart adjustments are used.
if (applyQuoteAdjustments) {
// The cart adjustments, derived from quote adjustments, are added to the cart
// Tax adjustments should be added to the shipping group and shipping group item info
// Other adjustments like promotional price should be added to the cart independent of
// the ship group.
// We're creating the cart right now using data from the quote, so there cannot yet be more than one ship group.
List<GenericValue> cartAdjs = cart.getAdjustments();
CartShipInfo shipInfo = cart.getShipInfo(0);
List<GenericValue> adjs = orderAdjsMap.get(quoteId);
if (adjs != null) {
for (GenericValue adj : adjs) {
if (isTaxAdjustment(adj)) {
shipInfo.shipTaxAdj.add(adj);
} else {
cartAdjs.add(adj);
}
}
}
// The cart item adjustments, derived from quote item adjustments, are added to the cart
if (quoteItems != null) {
for (ShoppingCartItem item : cart) {
String orderItemSeqId = item.getOrderItemSeqId();
if (orderItemSeqId != null) {
adjs = orderAdjsMap.get(orderItemSeqId);
} else {
adjs = null;
}
if (adjs != null) {
for (GenericValue adj : adjs) {
if (isTaxAdjustment(adj)) {
CartShipItemInfo csii = shipInfo.getShipItemInfo(item);
if (csii.itemTaxAdj == null) {
shipInfo.setItemInfo(item, UtilMisc.toList(adj));
} else {
csii.itemTaxAdj.add(adj);
}
} else {
item.addAdjustment(adj);
}
}
}
}
}
}
// 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());
}
}
Map<String, Object> result = ServiceUtil.returnSuccess();
result.put("shoppingCart", cart);
return result;
}
use of org.apache.ofbiz.product.config.ProductConfigWrapper 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;
}
Aggregations