Search in sources :

Example 6 with LocalDispatcher

use of org.apache.ofbiz.service.LocalDispatcher in project ofbiz-framework by apache.

the class ShipmentServices method duplicateShipmentRouteSegment.

public static Map<String, Object> duplicateShipmentRouteSegment(DispatchContext dctx, Map<String, ? extends Object> context) {
    Delegator delegator = dctx.getDelegator();
    LocalDispatcher dispatcher = dctx.getDispatcher();
    GenericValue userLogin = (GenericValue) context.get("userLogin");
    String shipmentId = (String) context.get("shipmentId");
    String shipmentRouteSegmentId = (String) context.get("shipmentRouteSegmentId");
    Locale locale = (Locale) context.get("locale");
    Map<String, Object> results = ServiceUtil.returnSuccess();
    try {
        GenericValue shipmentRouteSeg = EntityQuery.use(delegator).from("ShipmentRouteSegment").where("shipmentId", shipmentId, "shipmentRouteSegmentId", shipmentRouteSegmentId).queryOne();
        if (shipmentRouteSeg == null) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ProductShipmentRouteSegmentNotFound", UtilMisc.toMap("shipmentId", shipmentId, "shipmentRouteSegmentId", shipmentRouteSegmentId), locale));
        }
        Map<String, Object> params = UtilMisc.<String, Object>toMap("shipmentId", shipmentId, "carrierPartyId", shipmentRouteSeg.getString("carrierPartyId"), "shipmentMethodTypeId", shipmentRouteSeg.getString("shipmentMethodTypeId"), "originFacilityId", shipmentRouteSeg.getString("originFacilityId"), "originContactMechId", shipmentRouteSeg.getString("originContactMechId"), "originTelecomNumberId", shipmentRouteSeg.getString("originTelecomNumberId"));
        params.put("destFacilityId", shipmentRouteSeg.getString("destFacilityId"));
        params.put("destContactMechId", shipmentRouteSeg.getString("destContactMechId"));
        params.put("destTelecomNumberId", shipmentRouteSeg.getString("destTelecomNumberId"));
        params.put("billingWeight", shipmentRouteSeg.get("billingWeight"));
        params.put("billingWeightUomId", shipmentRouteSeg.get("billingWeightUomId"));
        params.put("userLogin", userLogin);
        Map<String, Object> tmpResult = dispatcher.runSync("createShipmentRouteSegment", params);
        if (ServiceUtil.isError(tmpResult)) {
            return ServiceUtil.returnError(ServiceUtil.getErrorMessage(tmpResult));
        } else {
            results.put("newShipmentRouteSegmentId", tmpResult.get("shipmentRouteSegmentId"));
            return results;
        }
    } catch (GenericEntityException ex) {
        return ServiceUtil.returnError(ex.getMessage());
    } catch (GenericServiceException ex) {
        return ServiceUtil.returnError(ex.getMessage());
    }
}
Also used : Locale(java.util.Locale) GenericValue(org.apache.ofbiz.entity.GenericValue) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) Delegator(org.apache.ofbiz.entity.Delegator) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) GenericServiceException(org.apache.ofbiz.service.GenericServiceException)

Example 7 with LocalDispatcher

use of org.apache.ofbiz.service.LocalDispatcher in project ofbiz-framework by apache.

the class ShipmentServices method sendShipmentCompleteNotification.

public static Map<String, Object> sendShipmentCompleteNotification(DispatchContext dctx, Map<String, ? extends Object> context) {
    LocalDispatcher dispatcher = dctx.getDispatcher();
    Delegator delegator = dctx.getDelegator();
    GenericValue userLogin = (GenericValue) context.get("userLogin");
    String shipmentId = (String) context.get("shipmentId");
    String sendTo = (String) context.get("sendTo");
    String screenUri = (String) context.get("screenUri");
    Locale localePar = (Locale) context.get("locale");
    // prepare the shipment information
    Map<String, Object> sendMap = new HashMap<String, Object>();
    GenericValue shipment = null;
    GenericValue orderHeader = null;
    try {
        shipment = EntityQuery.use(delegator).from("Shipment").where("shipmentId", shipmentId).queryOne();
        orderHeader = EntityQuery.use(delegator).from("OrderHeader").where("orderId", shipment.getString("primaryOrderId")).queryOne();
    } catch (GenericEntityException e) {
        Debug.logError(e, "Problem getting info from database", module);
    }
    GenericValue productStoreEmail = null;
    try {
        productStoreEmail = EntityQuery.use(delegator).from("ProductStoreEmailSetting").where("productStoreId", orderHeader.get("productStoreId"), "emailType", "PRDS_ODR_SHIP_COMPLT").queryOne();
    } catch (GenericEntityException e) {
        Debug.logError(e, "Problem getting the ProductStoreEmailSetting for productStoreId =" + orderHeader.get("productStoreId") + " and emailType = PRDS_ODR_SHIP_COMPLT", module);
    }
    if (productStoreEmail == null) {
        return ServiceUtil.returnFailure(UtilProperties.getMessage(resource, "ProductProductStoreEmailSettingsNotValid", UtilMisc.toMap("productStoreId", orderHeader.get("productStoreId"), "emailType", "PRDS_ODR_SHIP_COMPLT"), localePar));
    }
    // the override screenUri
    if (UtilValidate.isEmpty(screenUri)) {
        String bodyScreenLocation = productStoreEmail.getString("bodyScreenLocation");
        sendMap.put("bodyScreenUri", bodyScreenLocation);
    } else {
        sendMap.put("bodyScreenUri", screenUri);
    }
    String partyId = shipment.getString("partyIdTo");
    // get the email address
    String emailString = null;
    GenericValue email = PartyWorker.findPartyLatestContactMech(partyId, "EMAIL_ADDRESS", delegator);
    if (UtilValidate.isNotEmpty(email)) {
        emailString = email.getString("infoString");
    }
    if (UtilValidate.isEmpty(emailString)) {
        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ProductProductStoreEmailSettingsNoSendToFound", localePar));
    }
    Locale locale = PartyWorker.findPartyLastLocale(partyId, delegator);
    if (locale == null) {
        locale = Locale.getDefault();
    }
    Map<String, Object> bodyParameters = UtilMisc.<String, Object>toMap("partyId", partyId, "shipmentId", shipmentId, "orderId", shipment.getString("primaryOrderId"), "userLogin", userLogin, "locale", locale);
    sendMap.put("bodyParameters", bodyParameters);
    sendMap.put("userLogin", userLogin);
    sendMap.put("subject", productStoreEmail.getString("subject"));
    sendMap.put("contentType", productStoreEmail.get("contentType"));
    sendMap.put("sendFrom", productStoreEmail.get("fromAddress"));
    sendMap.put("sendCc", productStoreEmail.get("ccAddress"));
    sendMap.put("sendBcc", productStoreEmail.get("bccAddress"));
    if ((sendTo != null) && UtilValidate.isEmail(sendTo)) {
        sendMap.put("sendTo", sendTo);
    } else {
        sendMap.put("sendTo", emailString);
    }
    // send the notification
    Map<String, Object> sendResp = null;
    try {
        sendResp = dispatcher.runSync("sendMailFromScreen", sendMap);
    } catch (GenericServiceException gse) {
        Debug.logError(gse, "Problem sending mail", module);
        return ServiceUtil.returnError(UtilProperties.getMessage(resource_error, "OrderProblemSendingEmail", localePar));
    } catch (Exception e) {
        Debug.logError(e, "Problem sending mail", module);
        return ServiceUtil.returnError(UtilProperties.getMessage(resource_error, "OrderProblemSendingEmail", localePar));
    }
    // check for errors
    if (sendResp != null && ServiceUtil.isError(sendResp)) {
        sendResp.put("emailType", "PRDS_ODR_SHIP_COMPLT");
        return ServiceUtil.returnError(UtilProperties.getMessage(resource_error, "OrderProblemSendingEmail", localePar), null, null, sendResp);
    }
    return sendResp;
}
Also used : Locale(java.util.Locale) GenericValue(org.apache.ofbiz.entity.GenericValue) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) Delegator(org.apache.ofbiz.entity.Delegator) HashMap(java.util.HashMap) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException)

Example 8 with LocalDispatcher

use of org.apache.ofbiz.service.LocalDispatcher in project ofbiz-framework by apache.

the class ShipmentServices method updatePurchaseShipmentFromReceipt.

/**
 * Whenever a ShipmentReceipt is generated, check the Shipment associated
 * with it to see if all items were received. If so, change its status to
 * PURCH_SHIP_RECEIVED. The check is accomplished by counting the
 * products shipped (from ShipmentAndItem) and matching them with the
 * products received (from ShipmentReceipt).
 */
public static Map<String, Object> updatePurchaseShipmentFromReceipt(DispatchContext dctx, Map<String, ? extends Object> context) {
    Delegator delegator = dctx.getDelegator();
    LocalDispatcher dispatcher = dctx.getDispatcher();
    String shipmentId = (String) context.get("shipmentId");
    GenericValue userLogin = (GenericValue) context.get("userLogin");
    try {
        List<GenericValue> shipmentReceipts = EntityQuery.use(delegator).from("ShipmentReceipt").where("shipmentId", shipmentId).queryList();
        if (shipmentReceipts.size() == 0)
            return ServiceUtil.returnSuccess();
        // If there are shipment receipts, the shipment must have been shipped, so set the shipment status to PURCH_SHIP_SHIPPED if it's only PURCH_SHIP_CREATED
        GenericValue shipment = EntityQuery.use(delegator).from("Shipment").where("shipmentId", shipmentId).queryOne();
        if ((!UtilValidate.isEmpty(shipment)) && "PURCH_SHIP_CREATED".equals(shipment.getString("statusId"))) {
            Map<String, Object> updateShipmentMap = dispatcher.runSync("updateShipment", UtilMisc.<String, Object>toMap("shipmentId", shipmentId, "statusId", "PURCH_SHIP_SHIPPED", "userLogin", userLogin));
            if (ServiceUtil.isError(updateShipmentMap)) {
                return updateShipmentMap;
            }
        }
        List<GenericValue> shipmentAndItems = EntityQuery.use(delegator).from("ShipmentAndItem").where("shipmentId", shipmentId, "statusId", "PURCH_SHIP_SHIPPED").queryList();
        if (shipmentAndItems.size() == 0) {
            return ServiceUtil.returnSuccess();
        }
        // store the quantity of each product shipped in a hashmap keyed to productId
        Map<String, BigDecimal> shippedCountMap = new HashMap<String, BigDecimal>();
        for (GenericValue item : shipmentAndItems) {
            BigDecimal shippedQuantity = item.getBigDecimal("quantity");
            BigDecimal quantity = shippedCountMap.get(item.getString("productId"));
            quantity = quantity == null ? shippedQuantity : shippedQuantity.add(quantity);
            shippedCountMap.put(item.getString("productId"), quantity);
        }
        // store the quantity of each product received in a hashmap keyed to productId
        Map<String, BigDecimal> receivedCountMap = new HashMap<String, BigDecimal>();
        for (GenericValue item : shipmentReceipts) {
            BigDecimal receivedQuantity = item.getBigDecimal("quantityAccepted");
            BigDecimal quantity = receivedCountMap.get(item.getString("productId"));
            quantity = quantity == null ? receivedQuantity : receivedQuantity.add(quantity);
            receivedCountMap.put(item.getString("productId"), quantity);
        }
        // let Map.equals do all the hard comparison work
        if (!shippedCountMap.equals(receivedCountMap)) {
            return ServiceUtil.returnSuccess();
        }
        // now update the shipment
        Map<String, Object> serviceResult = dispatcher.runSync("updateShipment", UtilMisc.<String, Object>toMap("shipmentId", shipmentId, "statusId", "PURCH_SHIP_RECEIVED", "userLogin", userLogin));
        if (ServiceUtil.isError(serviceResult)) {
            return ServiceUtil.returnError(ServiceUtil.getErrorMessage(serviceResult));
        }
    } catch (GenericEntityException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(e.getMessage());
    } catch (GenericServiceException se) {
        Debug.logError(se, module);
        return ServiceUtil.returnError(se.getMessage());
    }
    return ServiceUtil.returnSuccess();
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) Delegator(org.apache.ofbiz.entity.Delegator) HashMap(java.util.HashMap) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) BigDecimal(java.math.BigDecimal)

Example 9 with LocalDispatcher

use of org.apache.ofbiz.service.LocalDispatcher in project ofbiz-framework by apache.

the class DhlConnectException method dhlShipmentConfirm.

/*
     * Pass a shipment request to DHL via ShipIT and get a tracking number and a label back, among other things
     */
public static Map<String, Object> dhlShipmentConfirm(DispatchContext dctx, Map<String, ? extends Object> context) {
    Delegator delegator = dctx.getDelegator();
    LocalDispatcher dispatcher = dctx.getDispatcher();
    Locale locale = (Locale) context.get("locale");
    GenericValue userLogin = (GenericValue) context.get("userLogin");
    String shipmentId = (String) context.get("shipmentId");
    String shipmentRouteSegmentId = (String) context.get("shipmentRouteSegmentId");
    Map<String, Object> shipmentGatewayConfig = ShipmentServices.getShipmentGatewayConfigFromShipment(delegator, shipmentId, locale);
    String shipmentGatewayConfigId = (String) shipmentGatewayConfig.get("shipmentGatewayConfigId");
    String resource = (String) shipmentGatewayConfig.get("configProps");
    if (UtilValidate.isEmpty(shipmentGatewayConfigId) && UtilValidate.isEmpty(resource)) {
        return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentDhlGatewayNotAvailable", locale));
    }
    try {
        GenericValue shipment = EntityQuery.use(delegator).from("Shipment").where("shipmentId", shipmentId).queryOne();
        if (shipment == null) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "ProductShipmentNotFoundId", locale) + shipmentId);
        }
        GenericValue shipmentRouteSegment = EntityQuery.use(delegator).from("ShipmentRouteSegment").where("shipmentId", shipmentId, "shipmentRouteSegmentId", shipmentRouteSegmentId).queryOne();
        if (shipmentRouteSegment == null) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "ProductShipmentRouteSegmentNotFound", UtilMisc.toMap("shipmentId", shipmentId, "shipmentRouteSegmentId", shipmentRouteSegmentId), locale));
        }
        if (!"DHL".equals(shipmentRouteSegment.getString("carrierPartyId"))) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentDhlNotRouteSegmentCarrier", UtilMisc.toMap("shipmentRouteSegmentId", shipmentRouteSegmentId, "shipmentId", shipmentId), locale));
        }
        // add ShipmentRouteSegment carrierServiceStatusId, check before all DHL services
        if (UtilValidate.isNotEmpty(shipmentRouteSegment.getString("carrierServiceStatusId")) && !"SHRSCS_NOT_STARTED".equals(shipmentRouteSegment.getString("carrierServiceStatusId"))) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentDhlRouteSegmentStatusNotStarted", UtilMisc.toMap("shipmentRouteSegmentId", shipmentRouteSegmentId, "shipmentId", shipmentId, "shipmentRouteSegmentStatus", shipmentRouteSegment.getString("carrierServiceStatusId")), locale));
        }
        // Get Origin Info
        GenericValue originPostalAddress = shipmentRouteSegment.getRelatedOne("OriginPostalAddress", false);
        if (originPostalAddress == null) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentRouteSegmentOriginPostalAddressNotFound", UtilMisc.toMap("shipmentId", shipmentId, "shipmentRouteSegmentId", shipmentRouteSegmentId), locale));
        }
        GenericValue originTelecomNumber = shipmentRouteSegment.getRelatedOne("OriginTelecomNumber", false);
        if (originTelecomNumber == null) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentRouteSegmentOriginTelecomNumberNotFound", UtilMisc.toMap("shipmentId", shipmentId, "shipmentRouteSegmentId", shipmentRouteSegmentId), locale));
        }
        String originPhoneNumber = originTelecomNumber.getString("areaCode") + originTelecomNumber.getString("contactNumber");
        // don't put on country code if not specified or is the US country code (UPS wants it this way and assuming DHL will accept this)
        if (UtilValidate.isNotEmpty(originTelecomNumber.getString("countryCode")) && !"001".equals(originTelecomNumber.getString("countryCode"))) {
            originPhoneNumber = originTelecomNumber.getString("countryCode") + originPhoneNumber;
        }
        originPhoneNumber = StringUtil.replaceString(originPhoneNumber, "-", "");
        originPhoneNumber = StringUtil.replaceString(originPhoneNumber, " ", "");
        // lookup the two letter country code (in the geoCode field)
        GenericValue originCountryGeo = originPostalAddress.getRelatedOne("CountryGeo", false);
        if (originCountryGeo == null) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentRouteSegmentOriginCountryGeoNotFound", UtilMisc.toMap("shipmentId", shipmentId, "shipmentRouteSegmentId", shipmentRouteSegmentId), locale));
        }
        // Get Dest Info
        GenericValue destPostalAddress = shipmentRouteSegment.getRelatedOne("DestPostalAddress", false);
        if (destPostalAddress == null) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentRouteSegmentDestPostalAddressNotFound", UtilMisc.toMap("shipmentId", shipmentId, "shipmentRouteSegmentId", shipmentRouteSegmentId), locale));
        }
        // DHL requires destination phone number, default to sender # if no customer number
        String destPhoneNumber = originPhoneNumber;
        GenericValue destTelecomNumber = shipmentRouteSegment.getRelatedOne("DestTelecomNumber", false);
        if (destTelecomNumber != null) {
            destPhoneNumber = destTelecomNumber.getString("areaCode") + destTelecomNumber.getString("contactNumber");
            // don't put on country code if not specified or is the US country code (UPS wants it this way)
            if (UtilValidate.isNotEmpty(destTelecomNumber.getString("countryCode")) && !"001".equals(destTelecomNumber.getString("countryCode"))) {
                destPhoneNumber = destTelecomNumber.getString("countryCode") + destPhoneNumber;
            }
            destPhoneNumber = StringUtil.replaceString(destPhoneNumber, "-", "");
            destPhoneNumber = StringUtil.replaceString(destPhoneNumber, " ", "");
        }
        String recipientEmail = null;
        Map<String, Object> results = dispatcher.runSync("getPartyEmail", UtilMisc.toMap("partyId", shipment.get("partyIdTo"), "userLogin", userLogin));
        if (ServiceUtil.isError(results)) {
            return ServiceUtil.returnError(ServiceUtil.getErrorMessage(results));
        }
        if (results.get("emailAddress") != null) {
            recipientEmail = (String) results.get("emailAddress");
        }
        // lookup the two letter country code (in the geoCode field)
        GenericValue destCountryGeo = destPostalAddress.getRelatedOne("CountryGeo", false);
        if (destCountryGeo == null) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentRouteSegmentDestCountryGeoNotFound", UtilMisc.toMap("shipmentId", shipmentId, "shipmentRouteSegmentId", shipmentRouteSegmentId), locale));
        }
        List<GenericValue> shipmentPackageRouteSegs = shipmentRouteSegment.getRelated("ShipmentPackageRouteSeg", null, UtilMisc.toList("+shipmentPackageSeqId"), false);
        if (UtilValidate.isEmpty(shipmentPackageRouteSegs)) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentPackageRouteSegsNotFound", UtilMisc.toMap("shipmentId", shipmentId, "shipmentRouteSegmentId", shipmentRouteSegmentId), locale));
        }
        if (shipmentPackageRouteSegs.size() != 1) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentDhlMultiplePackagesNotSupported", locale));
        }
        // get the weight from the ShipmentRouteSegment first, which overrides all later weight computations
        // for later overrides
        boolean hasBillingWeight = false;
        BigDecimal billingWeight = shipmentRouteSegment.getBigDecimal("billingWeight");
        String billingWeightUomId = shipmentRouteSegment.getString("billingWeightUomId");
        if ((billingWeight != null) && (billingWeight.compareTo(BigDecimal.ZERO) > 0)) {
            hasBillingWeight = true;
            if (billingWeightUomId == null) {
                Debug.logWarning("Shipment Route Segment missing billingWeightUomId in shipmentId " + shipmentId, module);
                // TODO: this should be specified in a properties file
                billingWeightUomId = "WT_lb";
            }
            // convert
            results = dispatcher.runSync("convertUom", UtilMisc.<String, Object>toMap("uomId", billingWeightUomId, "uomIdTo", DHL_WEIGHT_UOM_ID, "originalValue", billingWeight));
            if (ServiceUtil.isError(results) || (results.get("convertedValue") == null)) {
                Debug.logWarning("Unable to convert billing weights for shipmentId " + shipmentId, module);
                // try getting the weight from package instead
                hasBillingWeight = false;
            } else {
                billingWeight = (BigDecimal) results.get("convertedValue");
            }
        }
        // loop through Shipment segments (NOTE: only one supported, loop is here for future refactoring reference)
        BigDecimal packageWeight = null;
        for (GenericValue shipmentPackageRouteSeg : shipmentPackageRouteSegs) {
            GenericValue shipmentPackage = shipmentPackageRouteSeg.getRelatedOne("ShipmentPackage", false);
            GenericValue shipmentBoxType = shipmentPackage.getRelatedOne("ShipmentBoxType", false);
            if (shipmentBoxType != null) {
            // TODO: determine what default UoM is (assuming inches) - there should be a defaultDimensionUomId in Facility
            }
            // next step is weight determination, so skip if we have a billing weight
            if (hasBillingWeight)
                continue;
            // compute total packageWeight (for now, just one package)
            if (shipmentPackage.getString("weight") != null) {
                packageWeight = new BigDecimal(shipmentPackage.getString("weight"));
            } else {
                // use default weight if available
                try {
                    packageWeight = EntityUtilProperties.getPropertyAsBigDecimal(shipmentPropertiesFile, "shipment.default.weight.value", BigDecimal.ZERO);
                } catch (NumberFormatException ne) {
                    Debug.logWarning("Default shippable weight not configured (shipment.default.weight.value)", module);
                    packageWeight = BigDecimal.ONE;
                }
            }
            // convert weight
            String weightUomId = (String) shipmentPackage.get("weightUomId");
            if (weightUomId == null) {
                Debug.logWarning("Shipment Route Segment missing weightUomId in shipmentId " + shipmentId, module);
                // TODO: this should be specified in a properties file
                weightUomId = "WT_lb";
            }
            results = dispatcher.runSync("convertUom", UtilMisc.<String, Object>toMap("uomId", weightUomId, "uomIdTo", DHL_WEIGHT_UOM_ID, "originalValue", packageWeight));
            if (ServiceUtil.isError(results)) {
                return ServiceUtil.returnError(ServiceUtil.getErrorMessage(results));
            }
            if ((results == null) || (results.get(ModelService.RESPONSE_MESSAGE).equals(ModelService.RESPOND_ERROR)) || (results.get("convertedValue") == null)) {
                Debug.logWarning("Unable to convert weights for shipmentId " + shipmentId, module);
                packageWeight = BigDecimal.ONE;
            } else {
                packageWeight = (BigDecimal) results.get("convertedValue");
            }
        }
        // pick which weight to use and round it
        BigDecimal weight = null;
        if (hasBillingWeight) {
            weight = billingWeight;
        } else {
            weight = packageWeight;
        }
        // want the rounded weight as a string, so we use the "" + int shortcut
        String roundedWeight = weight.setScale(0, RoundingMode.HALF_UP).toPlainString();
        // translate shipmentMethodTypeId to DHL service code
        String shipmentMethodTypeId = shipmentRouteSegment.getString("shipmentMethodTypeId");
        String dhlShipmentDetailCode = null;
        GenericValue carrierShipmentMethod = EntityQuery.use(delegator).from("CarrierShipmentMethod").where("shipmentMethodTypeId", shipmentMethodTypeId, "partyId", "DHL", "roleTypeId", "CARRIER").queryOne();
        if (carrierShipmentMethod == null) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentDhlNoCarrierShipmentMethod", UtilMisc.toMap("carrierPartyId", "DHL", "shipmentMethodTypeId", shipmentMethodTypeId), locale));
        }
        dhlShipmentDetailCode = carrierShipmentMethod.getString("carrierServiceCode");
        // shipping credentials (configured in properties)
        String userid = getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "accessUserId", resource, "shipment.dhl.access.userid");
        String password = getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "accessPassword", resource, "shipment.dhl.access.password");
        String shippingKey = getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "accessShippingKey", resource, "shipment.dhl.access.shippingKey");
        String accountNbr = getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "accessAccountNbr", resource, "shipment.dhl.access.accountNbr");
        if ((shippingKey.length() == 0) || (accountNbr.length() == 0)) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentDhlGatewayNotAvailable", locale));
        }
        // label image preference (PNG or GIF)
        String labelImagePreference = getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "labelImageFormat", resource, "shipment.dhl.label.image.format");
        if (labelImagePreference.isEmpty()) {
            Debug.logInfo("shipment.dhl.label.image.format not specified, assuming PNG", module);
            labelImagePreference = "PNG";
        } else if (!("PNG".equals(labelImagePreference) || "GIF".equals(labelImagePreference))) {
            Debug.logError("Illegal shipment.dhl.label.image.format: " + labelImagePreference, module);
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentDhlUnknownLabelImageFormat", UtilMisc.toMap("labelImagePreference", labelImagePreference), locale));
        }
        // create AccessRequest XML doc using FreeMarker template
        String templateName = getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "rateEstimateTemplate", resource, "shipment.dhl.template.rate.estimate");
        if ((templateName.trim().length() == 0)) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentDhlRateEstimateTemplateNotConfigured", locale));
        }
        StringWriter outWriter = new StringWriter();
        Map<String, Object> inContext = new HashMap<String, Object>();
        inContext.put("action", "GenerateLabel");
        inContext.put("userid", userid);
        inContext.put("password", password);
        inContext.put("accountNbr", accountNbr);
        inContext.put("shippingKey", shippingKey);
        inContext.put("shipDate", UtilDateTime.nowTimestamp());
        inContext.put("dhlShipmentDetailCode", dhlShipmentDetailCode);
        inContext.put("weight", roundedWeight);
        inContext.put("senderPhoneNbr", originPhoneNumber);
        inContext.put("companyName", destPostalAddress.getString("toName"));
        inContext.put("attnTo", destPostalAddress.getString("attnName"));
        inContext.put("street", destPostalAddress.getString("address1"));
        inContext.put("streetLine2", destPostalAddress.getString("address2"));
        inContext.put("city", destPostalAddress.getString("city"));
        inContext.put("state", destPostalAddress.getString("stateProvinceGeoId"));
        // DHL ShipIT API does not accept ZIP+4
        if ((destPostalAddress.getString("postalCode") != null) && (destPostalAddress.getString("postalCode").length() > 5)) {
            inContext.put("postalCode", destPostalAddress.getString("postalCode").substring(0, 5));
        } else {
            inContext.put("postalCode", destPostalAddress.getString("postalCode"));
        }
        inContext.put("phoneNbr", destPhoneNumber);
        inContext.put("labelImageType", labelImagePreference);
        inContext.put("shipperReference", shipment.getString("primaryOrderId") + "-" + shipment.getString("primaryShipGroupSeqId"));
        inContext.put("notifyEmailAddress", recipientEmail);
        try {
            ContentWorker.renderContentAsText(dispatcher, templateName, outWriter, inContext, locale, "text/plain", null, null, false);
        } catch (Exception e) {
            Debug.logError(e, "Cannot confirm DHL shipment: Failed to render DHL XML Request.", module);
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentFedexRateTemplateRenderingError", locale));
        }
        String requestString = outWriter.toString();
        if (Debug.verboseOn()) {
            Debug.logVerbose(requestString, module);
        }
        // send the request
        String responseString = null;
        try {
            responseString = sendDhlRequest(requestString, delegator, shipmentGatewayConfigId, resource, locale);
            if (Debug.verboseOn()) {
                Debug.logVerbose(responseString, module);
            }
        } catch (DhlConnectException e) {
            String uceErrMsg = "Error sending DHL request for DHL Service Rate: " + e.toString();
            Debug.logError(e, uceErrMsg, module);
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentFedexRateTemplateSendingError", UtilMisc.toMap("errorString", e.toString()), locale));
        }
        // pass to handler method
        return handleDhlShipmentConfirmResponse(responseString, shipmentRouteSegment, shipmentPackageRouteSegs, locale);
    } catch (GenericEntityException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentFedexRateTemplateReadingError", UtilMisc.toMap("errorString", e.toString()), locale));
    } catch (GenericServiceException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentFedexRateTemplateReadingError", UtilMisc.toMap("errorString", e.toString()), locale));
    }
}
Also used : Locale(java.util.Locale) GenericValue(org.apache.ofbiz.entity.GenericValue) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) HashMap(java.util.HashMap) BigDecimal(java.math.BigDecimal) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) HttpClientException(org.apache.ofbiz.base.util.HttpClientException) IOException(java.io.IOException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) SAXException(org.xml.sax.SAXException) GeneralException(org.apache.ofbiz.base.util.GeneralException) Delegator(org.apache.ofbiz.entity.Delegator) StringWriter(java.io.StringWriter) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) GenericServiceException(org.apache.ofbiz.service.GenericServiceException)

Example 10 with LocalDispatcher

use of org.apache.ofbiz.service.LocalDispatcher in project ofbiz-framework by apache.

the class InventoryServices method checkInventoryAvailability.

/**
 * In spite of the generic name this does the very specific task of checking availability of all back-ordered items and sends notices, etc
 */
public static Map<String, Object> checkInventoryAvailability(DispatchContext dctx, Map<String, ? extends Object> context) {
    Delegator delegator = dctx.getDelegator();
    LocalDispatcher dispatcher = dctx.getDispatcher();
    GenericValue userLogin = (GenericValue) context.get("userLogin");
    Locale locale = (Locale) context.get("locale");
    Map<String, Map<String, Timestamp>> ordersToUpdate = new HashMap<>();
    Map<String, Map<String, Timestamp>> ordersToCancel = new HashMap<>();
    // find all inventory items w/ a negative ATP
    List<GenericValue> inventoryItems = null;
    try {
        inventoryItems = EntityQuery.use(delegator).from("InventoryItem").where(EntityCondition.makeCondition("availableToPromiseTotal", EntityOperator.LESS_THAN, BigDecimal.ZERO)).queryList();
    } catch (GenericEntityException e) {
        Debug.logError(e, "Trouble getting inventory items", module);
        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ProductPriceCannotRetrieveInventoryItem", locale));
    }
    if (inventoryItems == null) {
        Debug.logInfo("No items out of stock; no backorders to worry about", module);
        return ServiceUtil.returnSuccess();
    }
    Debug.logInfo("OOS Inventory Items: " + inventoryItems.size(), module);
    for (GenericValue inventoryItem : inventoryItems) {
        // get the incomming shipment information for the item
        List<GenericValue> shipmentAndItems = null;
        try {
            List<EntityExpr> exprs = new ArrayList<>();
            exprs.add(EntityCondition.makeCondition("productId", EntityOperator.EQUALS, inventoryItem.get("productId")));
            exprs.add(EntityCondition.makeCondition("destinationFacilityId", EntityOperator.EQUALS, inventoryItem.get("facilityId")));
            exprs.add(EntityCondition.makeCondition("statusId", EntityOperator.NOT_EQUAL, "SHIPMENT_DELIVERED"));
            exprs.add(EntityCondition.makeCondition("statusId", EntityOperator.NOT_EQUAL, "SHIPMENT_CANCELLED"));
            shipmentAndItems = EntityQuery.use(delegator).from("ShipmentAndItem").where(EntityCondition.makeCondition(exprs, EntityOperator.AND)).orderBy("estimatedArrivalDate").queryList();
        } catch (GenericEntityException e) {
            Debug.logError(e, "Problem getting ShipmentAndItem records", module);
            return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ProductPriceCannotRetrieveShipmentAndItem", locale));
        }
        // get the reservations in order of newest first
        List<GenericValue> reservations = null;
        try {
            reservations = inventoryItem.getRelated("OrderItemShipGrpInvRes", null, UtilMisc.toList("-reservedDatetime"), false);
        } catch (GenericEntityException e) {
            Debug.logError(e, "Problem getting related reservations", module);
            return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ProductPriceCannotRetrieveRelativeReservation", locale));
        }
        if (reservations == null) {
            Debug.logWarning("No outstanding reservations for this inventory item, why is it negative then?", module);
            continue;
        }
        Debug.logInfo("Reservations for item: " + reservations.size(), module);
        // available at the time of order
        BigDecimal availableBeforeReserved = inventoryItem.getBigDecimal("availableToPromiseTotal");
        // go through all the reservations in order
        for (GenericValue reservation : reservations) {
            String orderId = reservation.getString("orderId");
            String orderItemSeqId = reservation.getString("orderItemSeqId");
            Timestamp promisedDate = reservation.getTimestamp("promisedDatetime");
            Timestamp currentPromiseDate = reservation.getTimestamp("currentPromisedDate");
            Timestamp actualPromiseDate = currentPromiseDate;
            if (actualPromiseDate == null) {
                if (promisedDate != null) {
                    actualPromiseDate = promisedDate;
                } else {
                    // fall back if there is no promised date stored
                    actualPromiseDate = reservation.getTimestamp("reservedDatetime");
                }
            }
            Debug.logInfo("Promised Date: " + actualPromiseDate, module);
            // find the next possible ship date
            Timestamp nextShipDate = null;
            BigDecimal availableAtTime = BigDecimal.ZERO;
            for (GenericValue shipmentItem : shipmentAndItems) {
                availableAtTime = availableAtTime.add(shipmentItem.getBigDecimal("quantity"));
                if (availableAtTime.compareTo(availableBeforeReserved) >= 0) {
                    nextShipDate = shipmentItem.getTimestamp("estimatedArrivalDate");
                    break;
                }
            }
            Debug.logInfo("Next Ship Date: " + nextShipDate, module);
            // create a modified promise date (promise date - 1 day)
            Calendar pCal = Calendar.getInstance();
            pCal.setTimeInMillis(actualPromiseDate.getTime());
            pCal.add(Calendar.DAY_OF_YEAR, -1);
            Timestamp modifiedPromisedDate = new Timestamp(pCal.getTimeInMillis());
            Timestamp now = UtilDateTime.nowTimestamp();
            Debug.logInfo("Promised Date + 1: " + modifiedPromisedDate, module);
            Debug.logInfo("Now: " + now, module);
            // check the promised date vs the next ship date
            if (nextShipDate == null || nextShipDate.after(actualPromiseDate)) {
                if (nextShipDate == null && modifiedPromisedDate.after(now)) {
                    // do nothing; we are okay to assume it will be shipped on time
                    Debug.logInfo("No ship date known yet, but promised date hasn't approached, assuming it will be here on time", module);
                } else {
                    // we cannot ship by the promised date; need to notify the customer
                    Debug.logInfo("We won't ship on time, getting notification info", module);
                    Map<String, Timestamp> notifyItems = ordersToUpdate.get(orderId);
                    if (notifyItems == null) {
                        notifyItems = new HashMap<>();
                    }
                    notifyItems.put(orderItemSeqId, nextShipDate);
                    ordersToUpdate.put(orderId, notifyItems);
                    // need to know if nextShipDate is more then 30 days after promised
                    Calendar sCal = Calendar.getInstance();
                    sCal.setTimeInMillis(actualPromiseDate.getTime());
                    sCal.add(Calendar.DAY_OF_YEAR, 30);
                    Timestamp farPastPromised = new Timestamp(sCal.getTimeInMillis());
                    // check to see if this is >30 days or second run, if so flag to cancel
                    boolean needToCancel = false;
                    if (nextShipDate == null || nextShipDate.after(farPastPromised)) {
                        // we cannot ship until >30 days after promised; using cancel rule
                        Debug.logInfo("Ship date is >30 past the promised date", module);
                        needToCancel = true;
                    } else if (currentPromiseDate != null && actualPromiseDate.equals(currentPromiseDate)) {
                        // this is the second notification; using cancel rule
                        needToCancel = true;
                    }
                    // add the info to the cancel map if we need to schedule a cancel
                    if (needToCancel) {
                        // queue the item to be cancelled
                        Debug.logInfo("Flagging the item to auto-cancel", module);
                        Map<String, Timestamp> cancelItems = ordersToCancel.get(orderId);
                        if (cancelItems == null) {
                            cancelItems = new HashMap<>();
                        }
                        cancelItems.put(orderItemSeqId, farPastPromised);
                        ordersToCancel.put(orderId, cancelItems);
                    }
                    // store the updated promiseDate as the nextShipDate
                    try {
                        reservation.set("currentPromisedDate", nextShipDate);
                        reservation.store();
                    } catch (GenericEntityException e) {
                        Debug.logError(e, "Problem storing reservation : " + reservation, module);
                    }
                }
            }
            // subtract our qty from reserved to get the next value
            availableBeforeReserved = availableBeforeReserved.subtract(reservation.getBigDecimal("quantity"));
        }
    }
    // all items to cancel will also be in the notify list so start with that
    List<String> ordersToNotify = new LinkedList<>();
    for (Map.Entry<String, Map<String, Timestamp>> entry : ordersToUpdate.entrySet()) {
        String orderId = entry.getKey();
        Map<String, Timestamp> backOrderedItems = entry.getValue();
        Map<String, Timestamp> cancelItems = ordersToCancel.get(orderId);
        boolean cancelAll = false;
        Timestamp cancelAllTime = null;
        List<GenericValue> orderItemShipGroups = null;
        try {
            orderItemShipGroups = EntityQuery.use(delegator).from("OrderItemShipGroup").where("orderId", orderId).queryList();
        } catch (GenericEntityException e) {
            Debug.logError(e, "Cannot get OrderItemShipGroups from orderId" + orderId, module);
        }
        for (GenericValue orderItemShipGroup : orderItemShipGroups) {
            List<GenericValue> orderItems = new LinkedList<>();
            List<GenericValue> orderItemShipGroupAssoc = null;
            try {
                orderItemShipGroupAssoc = EntityQuery.use(delegator).from("OrderItemShipGroupAssoc").where("shipGroupSeqId", orderItemShipGroup.get("shipGroupSeqId"), "orderId", orderId).queryList();
                for (GenericValue assoc : orderItemShipGroupAssoc) {
                    GenericValue orderItem = assoc.getRelatedOne("OrderItem", false);
                    if (orderItem != null) {
                        orderItems.add(orderItem);
                    }
                }
            } catch (GenericEntityException e) {
                Debug.logError(e, "Problem fetching OrderItemShipGroupAssoc", module);
            }
            /* Check the split preference. */
            boolean maySplit = false;
            if (orderItemShipGroup.get("maySplit") != null) {
                maySplit = orderItemShipGroup.getBoolean("maySplit").booleanValue();
            }
            /* Figure out if we must cancel all items. */
            if (!maySplit && cancelItems != null) {
                cancelAll = true;
                Set<String> cancelSet = cancelItems.keySet();
                cancelAllTime = cancelItems.get(cancelSet.iterator().next());
            }
            // if there are none to cancel just create an empty map
            if (cancelItems == null) {
                cancelItems = new HashMap<>();
            }
            List<GenericValue> toBeStored = new LinkedList<>();
            for (GenericValue orderItem : orderItems) {
                String orderItemSeqId = orderItem.getString("orderItemSeqId");
                Timestamp shipDate = backOrderedItems.get(orderItemSeqId);
                Timestamp cancelDate = cancelItems.get(orderItemSeqId);
                Timestamp currentCancelDate = orderItem.getTimestamp("autoCancelDate");
                Debug.logInfo("OI: " + orderId + " SEQID: " + orderItemSeqId + " cancelAll: " + cancelAll + " cancelDate: " + cancelDate, module);
                if (backOrderedItems.containsKey(orderItemSeqId)) {
                    orderItem.set("estimatedShipDate", shipDate);
                    if (currentCancelDate == null) {
                        if (cancelAll || cancelDate != null) {
                            if (orderItem.get("dontCancelSetUserLogin") == null && orderItem.get("dontCancelSetDate") == null) {
                                if (cancelAllTime != null) {
                                    orderItem.set("autoCancelDate", cancelAllTime);
                                } else {
                                    orderItem.set("autoCancelDate", cancelDate);
                                }
                            }
                        }
                        // only notify orders which have not already sent the final notice
                        ordersToNotify.add(orderId);
                    }
                    toBeStored.add(orderItem);
                }
                if (toBeStored.size() > 0) {
                    try {
                        delegator.storeAll(toBeStored);
                    } catch (GenericEntityException e) {
                        Debug.logError(e, "Problem storing order items", module);
                    }
                }
            }
        }
    }
    // send off a notification for each order
    for (String orderId : ordersToNotify) {
        try {
            dispatcher.runAsync("sendOrderBackorderNotification", UtilMisc.<String, Object>toMap("orderId", orderId, "userLogin", userLogin));
        } catch (GenericServiceException e) {
            Debug.logError(e, "Problems sending off the notification", module);
            continue;
        }
    }
    return ServiceUtil.returnSuccess();
}
Also used : Locale(java.util.Locale) GenericValue(org.apache.ofbiz.entity.GenericValue) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) HashMap(java.util.HashMap) Calendar(com.ibm.icu.util.Calendar) ArrayList(java.util.ArrayList) Timestamp(java.sql.Timestamp) BigDecimal(java.math.BigDecimal) LinkedList(java.util.LinkedList) Delegator(org.apache.ofbiz.entity.Delegator) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) HashMap(java.util.HashMap) Map(java.util.Map) ModelKeyMap(org.apache.ofbiz.entity.model.ModelKeyMap) EntityExpr(org.apache.ofbiz.entity.condition.EntityExpr)

Aggregations

LocalDispatcher (org.apache.ofbiz.service.LocalDispatcher)427 GenericValue (org.apache.ofbiz.entity.GenericValue)356 Delegator (org.apache.ofbiz.entity.Delegator)324 GenericServiceException (org.apache.ofbiz.service.GenericServiceException)321 Locale (java.util.Locale)296 GenericEntityException (org.apache.ofbiz.entity.GenericEntityException)270 HashMap (java.util.HashMap)214 BigDecimal (java.math.BigDecimal)135 GeneralException (org.apache.ofbiz.base.util.GeneralException)87 Timestamp (java.sql.Timestamp)81 LinkedList (java.util.LinkedList)79 IOException (java.io.IOException)59 Map (java.util.Map)51 HttpSession (javax.servlet.http.HttpSession)49 OrderReadHelper (org.apache.ofbiz.order.order.OrderReadHelper)28 ModelService (org.apache.ofbiz.service.ModelService)28 EntityCondition (org.apache.ofbiz.entity.condition.EntityCondition)24 ShoppingCart (org.apache.ofbiz.order.shoppingcart.ShoppingCart)23 Security (org.apache.ofbiz.security.Security)20 ByteBuffer (java.nio.ByteBuffer)19