use of org.apache.ofbiz.entity.Delegator in project ofbiz-framework by apache.
the class PriceServices method calculatePurchasePrice.
/**
* Calculates the purchase price of a product
*/
public static Map<String, Object> calculatePurchasePrice(DispatchContext dctx, Map<String, ? extends Object> context) {
Delegator delegator = dctx.getDelegator();
LocalDispatcher dispatcher = dctx.getDispatcher();
Map<String, Object> result = new HashMap<String, Object>();
List<GenericValue> orderItemPriceInfos = new LinkedList<GenericValue>();
boolean validPriceFound = false;
BigDecimal price = BigDecimal.ZERO;
GenericValue product = (GenericValue) context.get("product");
String productId = product.getString("productId");
String agreementId = (String) context.get("agreementId");
String currencyUomId = (String) context.get("currencyUomId");
String partyId = (String) context.get("partyId");
BigDecimal quantity = (BigDecimal) context.get("quantity");
Locale locale = (Locale) context.get("locale");
// a) Get the Price from the Agreement* data model
if (Debug.infoOn())
Debug.logInfo("Try to resolve purchase price from agreement " + agreementId, module);
if (UtilValidate.isNotEmpty(agreementId)) {
// TODO Search before if agreement is associate to SupplierProduct.
// confirm that agreement is price application on purchase type and contains a value for the product
EntityCondition cond = EntityCondition.makeCondition(UtilMisc.toList(EntityExpr.makeCondition("agreementId", agreementId), EntityExpr.makeCondition("agreementItemTypeId", "AGREEMENT_PRICING_PR"), EntityExpr.makeCondition("agreementTypeId", "PURCHASE_AGREEMENT"), EntityExpr.makeCondition("productId", productId)));
try {
List<GenericValue> agreementPrices = delegator.findList("AgreementItemAndProductAppl", cond, UtilMisc.toSet("price", "currencyUomId"), null, null, true);
if (UtilValidate.isNotEmpty(agreementPrices)) {
GenericValue priceFound = null;
// resolve price on given currency. If not define, try to convert a present price
priceFound = EntityUtil.getFirst(EntityUtil.filterByAnd(agreementPrices, UtilMisc.toMap("currencyUomId", currencyUomId)));
if (Debug.infoOn()) {
Debug.logInfo(" AgreementItem " + agreementPrices, module);
Debug.logInfo(" currencyUomId " + currencyUomId, module);
Debug.logInfo(" priceFound " + priceFound, module);
}
if (priceFound == null) {
priceFound = EntityUtil.getFirst(agreementPrices);
try {
Map<String, Object> priceConvertMap = UtilMisc.toMap("uomId", priceFound.getString("currencyUomId"), "uomIdTo", currencyUomId, "originalValue", priceFound.getBigDecimal("price"), "defaultDecimalScale", Long.valueOf(2), "defaultRoundingMode", "HalfUp");
Map<String, Object> priceResults = dispatcher.runSync("convertUom", priceConvertMap);
if (ServiceUtil.isError(priceResults) || (priceResults.get("convertedValue") == null)) {
Debug.logWarning("Unable to convert " + priceFound + " for product " + productId, module);
} else {
price = (BigDecimal) priceResults.get("convertedValue");
validPriceFound = true;
}
} catch (GenericServiceException e) {
Debug.logError(e, module);
}
} else {
price = priceFound.getBigDecimal("price");
validPriceFound = true;
}
}
if (validPriceFound) {
GenericValue agreement = delegator.findOne("Agreement", true, UtilMisc.toMap("agreementId", agreementId));
StringBuilder priceInfoDescription = new StringBuilder();
priceInfoDescription.append(UtilProperties.getMessage(resource, "ProductAgreementUse", locale));
priceInfoDescription.append("[");
priceInfoDescription.append(agreementId);
priceInfoDescription.append("] ");
priceInfoDescription.append(agreement.get("description"));
GenericValue orderItemPriceInfo = delegator.makeValue("OrderItemPriceInfo");
// make sure description is <= than 250 chars
String priceInfoDescriptionString = priceInfoDescription.toString();
if (priceInfoDescriptionString.length() > 250) {
priceInfoDescriptionString = priceInfoDescriptionString.substring(0, 250);
}
orderItemPriceInfo.set("description", priceInfoDescriptionString);
orderItemPriceInfos.add(orderItemPriceInfo);
}
} catch (GenericEntityException gee) {
Debug.logError(gee, module);
return ServiceUtil.returnError(gee.getMessage());
}
}
// b) If no price can be found, get the lastPrice from the SupplierProduct entity
if (!validPriceFound) {
Map<String, Object> priceContext = UtilMisc.toMap("currencyUomId", currencyUomId, "partyId", partyId, "productId", productId, "quantity", quantity);
List<GenericValue> productSuppliers = null;
try {
Map<String, Object> priceResult = dispatcher.runSync("getSuppliersForProduct", priceContext);
if (ServiceUtil.isError(priceResult)) {
String errMsg = ServiceUtil.getErrorMessage(priceResult);
Debug.logError(errMsg, module);
return ServiceUtil.returnError(errMsg);
}
productSuppliers = UtilGenerics.checkList(priceResult.get("supplierProducts"));
} catch (GenericServiceException gse) {
Debug.logError(gse, module);
return ServiceUtil.returnError(gse.getMessage());
}
if (productSuppliers != null) {
for (GenericValue productSupplier : productSuppliers) {
if (!validPriceFound) {
price = ((BigDecimal) productSupplier.get("lastPrice"));
validPriceFound = true;
}
// add a orderItemPriceInfo element too, without orderId or orderItemId
StringBuilder priceInfoDescription = new StringBuilder();
priceInfoDescription.append(UtilProperties.getMessage(resource, "ProductSupplier", locale));
priceInfoDescription.append(" [");
priceInfoDescription.append(UtilProperties.getMessage(resource, "ProductSupplierMinimumOrderQuantity", locale));
priceInfoDescription.append(productSupplier.getBigDecimal("minimumOrderQuantity"));
priceInfoDescription.append(UtilProperties.getMessage(resource, "ProductSupplierLastPrice", locale));
priceInfoDescription.append(productSupplier.getBigDecimal("lastPrice"));
priceInfoDescription.append("]");
GenericValue orderItemPriceInfo = delegator.makeValue("OrderItemPriceInfo");
// make sure description is <= than 250 chars
String priceInfoDescriptionString = priceInfoDescription.toString();
if (priceInfoDescriptionString.length() > 250) {
priceInfoDescriptionString = priceInfoDescriptionString.substring(0, 250);
}
orderItemPriceInfo.set("description", priceInfoDescriptionString);
orderItemPriceInfos.add(orderItemPriceInfo);
}
}
}
// c) If no price can be found, get the averageCost from the ProductPrice entity
if (!validPriceFound) {
List<GenericValue> prices = null;
try {
prices = EntityQuery.use(delegator).from("ProductPrice").where("productId", productId, "productPricePurposeId", "PURCHASE").orderBy("-fromDate").queryList();
// if no prices are found; find the prices of the parent product
if (UtilValidate.isEmpty(prices)) {
GenericValue parentProduct = ProductWorker.getParentProduct(productId, delegator);
if (parentProduct != null) {
String parentProductId = parentProduct.getString("productId");
prices = EntityQuery.use(delegator).from("ProductPrice").where("productId", parentProductId, "productPricePurposeId", "PURCHASE").orderBy("-fromDate").queryList();
}
}
} catch (GenericEntityException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(e.getMessage());
}
// filter out the old prices
prices = EntityUtil.filterByDate(prices);
// first check for the AVERAGE_COST price type
List<GenericValue> pricesToUse = EntityUtil.filterByAnd(prices, UtilMisc.toMap("productPriceTypeId", "AVERAGE_COST"));
if (UtilValidate.isEmpty(pricesToUse)) {
// next go with default price
pricesToUse = EntityUtil.filterByAnd(prices, UtilMisc.toMap("productPriceTypeId", "DEFAULT_PRICE"));
if (UtilValidate.isEmpty(pricesToUse)) {
// finally use list price
pricesToUse = EntityUtil.filterByAnd(prices, UtilMisc.toMap("productPriceTypeId", "LIST_PRICE"));
}
}
// use the most current price
GenericValue thisPrice = EntityUtil.getFirst(pricesToUse);
if (thisPrice != null) {
price = thisPrice.getBigDecimal("price");
validPriceFound = true;
}
}
result.put("price", price);
result.put("validPriceFound", Boolean.valueOf(validPriceFound));
result.put("orderItemPriceInfos", orderItemPriceInfos);
return result;
}
use of org.apache.ofbiz.entity.Delegator in project ofbiz-framework by apache.
the class ProductEvents method updateProductQuickAdminShipping.
public static String updateProductQuickAdminShipping(HttpServletRequest request, HttpServletResponse response) {
Delegator delegator = (Delegator) request.getAttribute("delegator");
Timestamp nowTimestamp = UtilDateTime.nowTimestamp();
GenericValue userLogin = (GenericValue) request.getSession().getAttribute("userLogin");
String variantProductId = request.getParameter("productId0");
boolean applyToAll = (request.getParameter("applyToAll") != null);
try {
boolean beganTransaction = TransactionUtil.begin();
try {
// check for variantProductId - this will mean that we have multiple ship info to update
if (variantProductId == null) {
// only single product to update
String productId = request.getParameter("productId");
GenericValue product = EntityQuery.use(delegator).from("Product").where("productId", productId).queryOne();
product.set("lastModifiedDate", nowTimestamp);
product.setString("lastModifiedByUserLogin", userLogin.getString("userLoginId"));
try {
product.set("productHeight", parseBigDecimalForEntity(request.getParameter("productHeight")));
product.set("productWidth", parseBigDecimalForEntity(request.getParameter("productWidth")));
product.set("productDepth", parseBigDecimalForEntity(request.getParameter("productDepth")));
product.set("productWeight", parseBigDecimalForEntity(request.getParameter("weight")));
// default unit settings for shipping parameters
product.set("heightUomId", "LEN_in");
product.set("widthUomId", "LEN_in");
product.set("depthUomId", "LEN_in");
product.set("weightUomId", "WT_oz");
BigDecimal floz = parseBigDecimalForEntity(request.getParameter("~floz"));
BigDecimal ml = parseBigDecimalForEntity(request.getParameter("~ml"));
BigDecimal ntwt = parseBigDecimalForEntity(request.getParameter("~ntwt"));
BigDecimal grams = parseBigDecimalForEntity(request.getParameter("~grams"));
List<GenericValue> currentProductFeatureAndAppls = EntityQuery.use(delegator).from("ProductFeatureAndAppl").where("productId", productId, "productFeatureApplTypeId", "STANDARD_FEATURE").filterByDate().queryList();
setOrCreateProdFeature(delegator, productId, currentProductFeatureAndAppls, "VLIQ_ozUS", "AMOUNT", floz);
setOrCreateProdFeature(delegator, productId, currentProductFeatureAndAppls, "VLIQ_ml", "AMOUNT", ml);
setOrCreateProdFeature(delegator, productId, currentProductFeatureAndAppls, "WT_g", "AMOUNT", grams);
setOrCreateProdFeature(delegator, productId, currentProductFeatureAndAppls, "WT_oz", "AMOUNT", ntwt);
product.store();
} catch (NumberFormatException nfe) {
String errMsg = "Shipping Dimensions and Weights must be numbers.";
request.setAttribute("_ERROR_MESSAGE_", errMsg);
Debug.logError(nfe, errMsg, module);
return "error";
}
} else {
// multiple products, so use a numeric suffix to get them all
int prodIdx = 0;
int attribIdx = 0;
String productId = variantProductId;
do {
GenericValue product = EntityQuery.use(delegator).from("Product").where("productId", productId).queryOne();
try {
product.set("productHeight", parseBigDecimalForEntity(request.getParameter("productHeight" + attribIdx)));
product.set("productWidth", parseBigDecimalForEntity(request.getParameter("productWidth" + attribIdx)));
product.set("productDepth", parseBigDecimalForEntity(request.getParameter("productDepth" + attribIdx)));
product.set("productWeight", parseBigDecimalForEntity(request.getParameter("weight" + attribIdx)));
BigDecimal floz = parseBigDecimalForEntity(request.getParameter("~floz" + attribIdx));
BigDecimal ml = parseBigDecimalForEntity(request.getParameter("~ml" + attribIdx));
BigDecimal ntwt = parseBigDecimalForEntity(request.getParameter("~ntwt" + attribIdx));
BigDecimal grams = parseBigDecimalForEntity(request.getParameter("~grams" + attribIdx));
List<GenericValue> currentProductFeatureAndAppls = EntityQuery.use(delegator).from("ProductFeatureAndAppl").where("productId", productId, "productFeatureApplTypeId", "STANDARD_FEATURE").filterByDate().queryList();
setOrCreateProdFeature(delegator, productId, currentProductFeatureAndAppls, "VLIQ_ozUS", "AMOUNT", floz);
setOrCreateProdFeature(delegator, productId, currentProductFeatureAndAppls, "VLIQ_ml", "AMOUNT", ml);
setOrCreateProdFeature(delegator, productId, currentProductFeatureAndAppls, "WT_g", "AMOUNT", grams);
setOrCreateProdFeature(delegator, productId, currentProductFeatureAndAppls, "WT_oz", "AMOUNT", ntwt);
product.store();
} catch (NumberFormatException nfe) {
String errMsg = "Shipping Dimensions and Weights must be numbers.";
request.setAttribute("_ERROR_MESSAGE_", errMsg);
Debug.logError(nfe, errMsg, module);
return "error";
}
prodIdx++;
if (!applyToAll) {
attribIdx = prodIdx;
}
productId = request.getParameter("productId" + prodIdx);
} while (productId != null);
}
TransactionUtil.commit(beganTransaction);
} catch (GenericEntityException e) {
String errMsg = "Error updating quick admin shipping settings: " + e.toString();
Debug.logError(e, errMsg, module);
request.setAttribute("_ERROR_MESSAGE_", errMsg);
TransactionUtil.rollback(beganTransaction, errMsg, e);
return "error";
}
} catch (GenericTransactionException gte) {
String errMsg = "Error updating quick admin shipping settings: " + gte.toString();
Debug.logError(gte, errMsg, module);
request.setAttribute("_ERROR_MESSAGE_", errMsg);
return "error";
}
return "success";
}
use of org.apache.ofbiz.entity.Delegator in project ofbiz-framework by apache.
the class ProductEvents method updateProductCategoryMember.
public static String updateProductCategoryMember(HttpServletRequest request, HttpServletResponse response) {
Delegator delegator = (Delegator) request.getAttribute("delegator");
String productId = request.getParameter("productId");
String productCategoryId = request.getParameter("productCategoryId");
String thruDate = request.getParameter("thruDate");
if ((thruDate == null) || (thruDate.trim().length() == 0)) {
thruDate = UtilDateTime.nowTimestamp().toString();
}
try {
List<GenericValue> prodCatMembs = EntityQuery.use(delegator).from("ProductCategoryMember").where("productCategoryId", productCategoryId, "productId", productId).filterByDate().queryList();
if (prodCatMembs.size() > 0) {
// there is one to modify
GenericValue prodCatMemb = prodCatMembs.get(0);
prodCatMemb.setString("thruDate", thruDate);
prodCatMemb.store();
}
} catch (GenericEntityException e) {
String errMsg = "Error adding to category: " + e.toString();
request.setAttribute("_ERROR_MESSAGE_", errMsg);
return "error";
}
return "success";
}
use of org.apache.ofbiz.entity.Delegator in project ofbiz-framework by apache.
the class ProductEvents method removeProductFromComparisonList.
public static String removeProductFromComparisonList(HttpServletRequest request, HttpServletResponse response) {
HttpSession session = request.getSession();
Delegator delegator = (Delegator) request.getAttribute("delegator");
String productId = request.getParameter("productId");
GenericValue product = null;
if (UtilValidate.isNotEmpty(productId)) {
try {
product = ProductWorker.findProduct(delegator, productId);
} catch (GenericEntityException e) {
productId = null;
Debug.logError(e, module);
}
}
if (product == null) {
String errMsg = UtilProperties.getMessage(resource, "productevents.product_with_id_not_found", UtilMisc.toMap("productId", productId), UtilHttp.getLocale(request));
request.setAttribute("_ERROR_MESSAGE_", errMsg);
return "error";
}
List<GenericValue> compareList = getProductCompareList(request);
Iterator<GenericValue> it = compareList.iterator();
while (it.hasNext()) {
GenericValue compProduct = it.next();
if (product.getString("productId").equals(compProduct.getString("productId"))) {
it.remove();
break;
}
}
session.setAttribute("productCompareList", compareList);
String productName = ProductContentWrapper.getProductContentAsText(product, "PRODUCT_NAME", request, "html");
String eventMsg = UtilProperties.getMessage("ProductUiLabels", "ProductRemoveFromCompareListSuccess", UtilMisc.toMap("name", productName), UtilHttp.getLocale(request));
request.setAttribute("_EVENT_MESSAGE_", eventMsg);
return "success";
}
use of org.apache.ofbiz.entity.Delegator in project ofbiz-framework by apache.
the class ProductEvents method updateAllKeywords.
/**
* Updates/adds keywords for all products
*
* @param request HTTPRequest object for the current request
* @param response HTTPResponse object for the current request
* @return String specifying the exit status of this event
*/
public static String updateAllKeywords(HttpServletRequest request, HttpServletResponse response) {
Delegator delegator = (Delegator) request.getAttribute("delegator");
Security security = (Security) request.getAttribute("security");
Timestamp nowTimestamp = UtilDateTime.nowTimestamp();
String updateMode = "CREATE";
String errMsg = null;
String doAll = request.getParameter("doAll");
// check permissions before moving on...
if (!security.hasEntityPermission("CATALOG", "_" + updateMode, request.getSession())) {
Map<String, String> messageMap = UtilMisc.toMap("updateMode", updateMode);
errMsg = UtilProperties.getMessage(resource, "productevents.not_sufficient_permissions", messageMap, UtilHttp.getLocale(request));
request.setAttribute("_ERROR_MESSAGE_", errMsg);
return "error";
}
EntityCondition condition = null;
if (!"Y".equals(doAll)) {
List<EntityCondition> condList = new LinkedList<>();
condList.add(EntityCondition.makeCondition(EntityCondition.makeCondition("autoCreateKeywords", EntityOperator.EQUALS, null), EntityOperator.OR, EntityCondition.makeCondition("autoCreateKeywords", EntityOperator.NOT_EQUAL, "N")));
if ("true".equals(EntityUtilProperties.getPropertyValue("prodsearch", "index.ignore.variants", delegator))) {
condList.add(EntityCondition.makeCondition(EntityCondition.makeCondition("isVariant", EntityOperator.EQUALS, null), EntityOperator.OR, EntityCondition.makeCondition("isVariant", EntityOperator.NOT_EQUAL, "Y")));
}
if ("true".equals(EntityUtilProperties.getPropertyValue("prodsearch", "index.ignore.discontinued.sales", delegator))) {
condList.add(EntityCondition.makeCondition(EntityCondition.makeCondition("salesDiscontinuationDate", EntityOperator.EQUALS, null), EntityOperator.OR, EntityCondition.makeCondition("salesDiscontinuationDate", EntityOperator.GREATER_THAN_EQUAL_TO, nowTimestamp)));
}
condition = EntityCondition.makeCondition(condList, EntityOperator.AND);
} else {
condition = EntityCondition.makeCondition(EntityCondition.makeCondition("autoCreateKeywords", EntityOperator.EQUALS, null), EntityOperator.OR, EntityCondition.makeCondition("autoCreateKeywords", EntityOperator.NOT_EQUAL, "N"));
}
int numProds = 0;
int errProds = 0;
boolean beganTx = false;
try {
// begin the transaction
beganTx = TransactionUtil.begin(7200);
} catch (GenericTransactionException gte) {
Debug.logError(gte, "Unable to begin transaction", module);
}
try (EntityListIterator entityListIterator = EntityQuery.use(delegator).from("Product").where(condition).queryIterator()) {
try {
if (Debug.infoOn()) {
long count = EntityQuery.use(delegator).from("Product").where(condition).queryCount();
Debug.logInfo("========== Found " + count + " products to index ==========", module);
}
} catch (GenericEntityException gee) {
Debug.logWarning(gee, gee.getMessage(), module);
Map<String, String> messageMap = UtilMisc.toMap("gee", gee.toString());
errMsg = UtilProperties.getMessage(resource, "productevents.error_getting_product_list", messageMap, UtilHttp.getLocale(request));
request.setAttribute("_ERROR_MESSAGE_", errMsg);
return "error";
}
GenericValue product;
while ((product = entityListIterator.next()) != null) {
try {
KeywordIndex.indexKeywords(product, "Y".equals(doAll));
} catch (GenericEntityException e) {
Debug.logWarning("[ProductEvents.updateAllKeywords] Could not create product-keyword (write error); message: " + e.getMessage(), module);
errProds++;
}
numProds++;
if (numProds % 500 == 0) {
Debug.logInfo("Keywords indexed for " + numProds + " so far", module);
}
}
} catch (GenericEntityException e) {
try {
TransactionUtil.rollback(beganTx, e.getMessage(), e);
} catch (GenericTransactionException e1) {
Debug.logError(e1, module);
}
return "error";
} catch (Throwable t) {
Debug.logError(t, module);
request.setAttribute("_ERROR_MESSAGE_", t.getMessage());
try {
TransactionUtil.rollback(beganTx, t.getMessage(), t);
} catch (GenericTransactionException e2) {
Debug.logError(e2, module);
}
return "error";
}
// commit the transaction
try {
TransactionUtil.commit(beganTx);
} catch (GenericTransactionException e) {
Debug.logError(e, module);
}
if (errProds == 0) {
Map<String, String> messageMap = UtilMisc.toMap("numProds", Integer.toString(numProds));
errMsg = UtilProperties.getMessage(resource, "productevents.keyword_creation_complete_for_products", messageMap, UtilHttp.getLocale(request));
request.setAttribute("_EVENT_MESSAGE_", errMsg);
return "success";
} else {
Map<String, String> messageMap = UtilMisc.toMap("numProds", Integer.toString(numProds));
messageMap.put("errProds", Integer.toString(errProds));
errMsg = UtilProperties.getMessage(resource, "productevents.keyword_creation_complete_for_products_with_errors", messageMap, UtilHttp.getLocale(request));
request.setAttribute("_ERROR_MESSAGE_", errMsg);
return "error";
}
}
Aggregations