use of org.apache.ofbiz.service.GenericServiceException 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.service.GenericServiceException in project ofbiz-framework by apache.
the class ProductWorker method isProductInventoryAvailableByFacility.
/**
* invokes the getInventoryAvailableByFacility service, returns true if specified quantity is available, else false
* this is only used in the related method that uses a ProductConfigWrapper, until that is refactored into a service as well...
*/
private static boolean isProductInventoryAvailableByFacility(String productId, String inventoryFacilityId, BigDecimal quantity, LocalDispatcher dispatcher) {
BigDecimal availableToPromise = null;
try {
Map<String, Object> result = dispatcher.runSync("getInventoryAvailableByFacility", UtilMisc.toMap("productId", productId, "facilityId", inventoryFacilityId));
availableToPromise = (BigDecimal) result.get("availableToPromiseTotal");
if (availableToPromise == null) {
Debug.logWarning("The getInventoryAvailableByFacility service returned a null availableToPromise, the error message was:\n" + result.get(ModelService.ERROR_MESSAGE), module);
return false;
}
} catch (GenericServiceException e) {
Debug.logWarning(e, "Error invoking getInventoryAvailableByFacility service in isCatalogInventoryAvailable", module);
return false;
}
// check to see if we got enough back...
if (availableToPromise.compareTo(quantity) >= 0) {
if (Debug.infoOn()) {
Debug.logInfo("Inventory IS available in facility with id " + inventoryFacilityId + " for product id " + productId + "; desired quantity is " + quantity + ", available quantity is " + availableToPromise, module);
}
return true;
}
if (Debug.infoOn()) {
Debug.logInfo("Returning false because there is insufficient inventory available in facility with id " + inventoryFacilityId + " for product id " + productId + "; desired quantity is " + quantity + ", available quantity is " + availableToPromise, module);
}
return false;
}
use of org.apache.ofbiz.service.GenericServiceException in project ofbiz-framework by apache.
the class PromoServices method importPromoCodesFromFile.
public static Map<String, Object> importPromoCodesFromFile(DispatchContext dctx, Map<String, ? extends Object> context) {
LocalDispatcher dispatcher = dctx.getDispatcher();
Locale locale = (Locale) context.get("locale");
// check the uploaded file
ByteBuffer fileBytes = (ByteBuffer) context.get("uploadedFile");
if (fileBytes == null) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ProductPromoCodeImportUploadedFileNotValid", locale));
}
String encoding = System.getProperty("file.encoding");
String file = Charset.forName(encoding).decode(fileBytes).toString();
// get the createProductPromoCode Model
ModelService promoModel;
try {
promoModel = dispatcher.getDispatchContext().getModelService("createProductPromoCode");
} catch (GenericServiceException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(e.getMessage());
}
// make a temp context for invocations
Map<String, Object> invokeCtx = promoModel.makeValid(context, ModelService.IN_PARAM);
// read the bytes into a reader
BufferedReader reader = new BufferedReader(new StringReader(file));
List<Object> errors = new LinkedList<>();
int lines = 0;
String line;
// read the uploaded file and process each line
try {
while ((line = reader.readLine()) != null) {
// check to see if we should ignore this line
if (line.length() > 0 && !line.startsWith("#")) {
if (line.length() <= 20) {
// valid promo code
Map<String, Object> inContext = new HashMap<>();
inContext.putAll(invokeCtx);
inContext.put("productPromoCodeId", line);
Map<String, Object> result = dispatcher.runSync("createProductPromoCode", inContext);
if (result != null && ServiceUtil.isError(result)) {
errors.add(line + ": " + ServiceUtil.getErrorMessage(result));
}
} else {
// not valid ignore and notify
errors.add(line + UtilProperties.getMessage(resource, "ProductPromoCodeInvalidCode", locale));
}
++lines;
}
}
} catch (IOException | GenericServiceException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(e.getMessage());
} finally {
try {
reader.close();
} catch (IOException e) {
Debug.logError(e, module);
}
}
// return errors or success
if (errors.size() > 0) {
return ServiceUtil.returnError(errors);
} else if (lines == 0) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ProductPromoCodeImportEmptyFile", locale));
}
return ServiceUtil.returnSuccess();
}
use of org.apache.ofbiz.service.GenericServiceException in project ofbiz-framework by apache.
the class PromoServices method importPromoCodeEmailsFromFile.
public static Map<String, Object> importPromoCodeEmailsFromFile(DispatchContext dctx, Map<String, ? extends Object> context) {
LocalDispatcher dispatcher = dctx.getDispatcher();
String productPromoCodeId = (String) context.get("productPromoCodeId");
GenericValue userLogin = (GenericValue) context.get("userLogin");
Locale locale = (Locale) context.get("locale");
ByteBuffer bytebufferwrapper = (ByteBuffer) context.get("uploadedFile");
if (bytebufferwrapper == null) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ProductPromoCodeImportUploadedFileNotValid", locale));
}
byte[] wrapper = bytebufferwrapper.array();
// read the bytes into a reader
BufferedReader reader = new BufferedReader(new StringReader(new String(wrapper, UtilIO.getUtf8())));
List<Object> errors = new LinkedList<>();
int lines = 0;
String line;
// read the uploaded file and process each line
try {
while ((line = reader.readLine()) != null) {
if (line.length() > 0 && !line.startsWith("#")) {
if (UtilValidate.isEmail(line)) {
// valid email address
Map<String, Object> result = dispatcher.runSync("createProductPromoCodeEmail", UtilMisc.<String, Object>toMap("productPromoCodeId", productPromoCodeId, "emailAddress", line, "userLogin", userLogin));
if (result != null && ServiceUtil.isError(result)) {
errors.add(line + ": " + ServiceUtil.getErrorMessage(result));
}
} else {
// not valid ignore and notify
errors.add(line + ": is not a valid email address");
}
++lines;
}
}
} catch (IOException | GenericServiceException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(e.getMessage());
} finally {
try {
reader.close();
} catch (IOException e) {
Debug.logError(e, module);
}
}
// return errors or success
if (errors.size() > 0) {
return ServiceUtil.returnError(errors);
} else if (lines == 0) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ProductPromoCodeImportEmptyFile", locale));
}
return ServiceUtil.returnSuccess();
}
use of org.apache.ofbiz.service.GenericServiceException in project ofbiz-framework by apache.
the class PromoServices method createProductPromoCodeSet.
public static Map<String, Object> createProductPromoCodeSet(DispatchContext dctx, Map<String, ? extends Object> context) {
Locale locale = (Locale) context.get("locale");
Delegator delegator = dctx.getDelegator();
LocalDispatcher dispatcher = dctx.getDispatcher();
Long quantity = (Long) context.get("quantity");
int codeLength = (Integer) context.get("codeLength");
String promoCodeLayout = (String) context.get("promoCodeLayout");
// For PromoCodes we give the option not to use chars that are easy to mix up like 0<>O, 1<>I, ...
boolean useSmartLayout = false;
boolean useNormalLayout = false;
if ("smart".equals(promoCodeLayout)) {
useSmartLayout = true;
} else if ("normal".equals(promoCodeLayout)) {
useNormalLayout = true;
}
String newPromoCodeId = "";
StringBuilder bankOfNumbers = new StringBuilder();
bankOfNumbers.append(UtilProperties.getMessage(resource, "ProductPromoCodesCreated", locale));
for (long i = 0; i < quantity; i++) {
Map<String, Object> createProductPromoCodeMap = null;
boolean foundUniqueNewCode = false;
long count = 0;
while (!foundUniqueNewCode) {
if (useSmartLayout) {
newPromoCodeId = RandomStringUtils.random(codeLength, smartChars);
} else if (useNormalLayout) {
newPromoCodeId = RandomStringUtils.randomAlphanumeric(codeLength);
}
GenericValue existingPromoCode = null;
try {
existingPromoCode = EntityQuery.use(delegator).from("ProductPromoCode").where("productPromoCodeId", newPromoCodeId).cache().queryOne();
} catch (GenericEntityException e) {
Debug.logWarning("Could not find ProductPromoCode for just generated ID: " + newPromoCodeId, module);
}
if (existingPromoCode == null) {
foundUniqueNewCode = true;
}
count++;
if (count > 999999) {
return ServiceUtil.returnError("Unable to locate unique PromoCode! Length [" + codeLength + "]");
}
}
try {
Map<String, Object> newContext = dctx.makeValidContext("createProductPromoCode", ModelService.IN_PARAM, context);
newContext.put("productPromoCodeId", newPromoCodeId);
createProductPromoCodeMap = dispatcher.runSync("createProductPromoCode", newContext);
} catch (GenericServiceException err) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ProductPromoCodeCannotBeCreated", locale), null, null, null);
}
if (ServiceUtil.isError(createProductPromoCodeMap)) {
// what to do here? try again?
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ProductPromoCodeCannotBeCreated", locale), null, null, createProductPromoCodeMap);
}
bankOfNumbers.append((String) createProductPromoCodeMap.get("productPromoCodeId"));
bankOfNumbers.append(",");
}
return ServiceUtil.returnSuccess(bankOfNumbers.toString());
}
Aggregations