Search in sources :

Example 6 with GenericServiceException

use of org.apache.ofbiz.service.GenericServiceException 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 GenericServiceException

use of org.apache.ofbiz.service.GenericServiceException 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 GenericServiceException

use of org.apache.ofbiz.service.GenericServiceException 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 GenericServiceException

use of org.apache.ofbiz.service.GenericServiceException 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 GenericServiceException

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

the class InventoryServices method completeInventoryTransfer.

public static Map<String, Object> completeInventoryTransfer(DispatchContext dctx, Map<String, ? extends Object> context) {
    Delegator delegator = dctx.getDelegator();
    String inventoryTransferId = (String) context.get("inventoryTransferId");
    Timestamp receiveDate = (Timestamp) context.get("receiveDate");
    GenericValue inventoryTransfer = null;
    GenericValue inventoryItem = null;
    GenericValue destinationFacility = null;
    GenericValue userLogin = (GenericValue) context.get("userLogin");
    Locale locale = (Locale) context.get("locale");
    try {
        inventoryTransfer = EntityQuery.use(delegator).from("InventoryTransfer").where("inventoryTransferId", inventoryTransferId).queryOne();
        inventoryItem = inventoryTransfer.getRelatedOne("InventoryItem", false);
        destinationFacility = inventoryTransfer.getRelatedOne("ToFacility", false);
    } catch (GenericEntityException e) {
        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ProductInventoryItemLookupProblem", UtilMisc.toMap("errorString", e.getMessage()), locale));
    }
    if (inventoryItem == null) {
        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ProductInventoryItemLookupProblem", UtilMisc.toMap("errorString", ""), locale));
    }
    String inventoryType = inventoryItem.getString("inventoryItemTypeId");
    // set the fields on the transfer record
    if (inventoryTransfer.get("receiveDate") == null) {
        if (receiveDate != null) {
            inventoryTransfer.set("receiveDate", receiveDate);
        } else {
            inventoryTransfer.set("receiveDate", UtilDateTime.nowTimestamp());
        }
    }
    if ("NON_SERIAL_INV_ITEM".equals(inventoryType)) {
        // add an adjusting InventoryItemDetail so set ATP back to QOH: ATP = ATP + (QOH - ATP), diff = QOH - ATP
        BigDecimal atp = inventoryItem.get("availableToPromiseTotal") == null ? BigDecimal.ZERO : inventoryItem.getBigDecimal("availableToPromiseTotal");
        BigDecimal qoh = inventoryItem.get("quantityOnHandTotal") == null ? BigDecimal.ZERO : inventoryItem.getBigDecimal("quantityOnHandTotal");
        Map<String, Object> createDetailMap = UtilMisc.toMap("availableToPromiseDiff", qoh.subtract(atp), "inventoryItemId", inventoryItem.get("inventoryItemId"), "userLogin", userLogin);
        try {
            Map<String, Object> result = dctx.getDispatcher().runSync("createInventoryItemDetail", createDetailMap);
            if (ServiceUtil.isError(result)) {
                return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ProductInventoryItemDetailCreateProblem", UtilMisc.toMap("errorString", ""), locale), null, null, result);
            }
        } catch (GenericServiceException e1) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ProductInventoryItemDetailCreateProblem", UtilMisc.toMap("errorString", e1.getMessage()), locale));
        }
        try {
            inventoryItem.refresh();
        } catch (GenericEntityException e) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ProductInventoryItemRefreshProblem", UtilMisc.toMap("errorString", e.getMessage()), locale));
        }
    }
    // set the fields on the item
    Map<String, Object> updateInventoryItemMap = UtilMisc.toMap("inventoryItemId", inventoryItem.getString("inventoryItemId"), "facilityId", inventoryTransfer.get("facilityIdTo"), "containerId", inventoryTransfer.get("containerIdTo"), "locationSeqId", inventoryTransfer.get("locationSeqIdTo"), "userLogin", userLogin);
    // for serialized items, automatically make them available
    if ("SERIALIZED_INV_ITEM".equals(inventoryType)) {
        updateInventoryItemMap.put("statusId", "INV_AVAILABLE");
    }
    // the inventory item is assigned to the new owner.
    if (destinationFacility != null && destinationFacility.get("ownerPartyId") != null) {
        String fromPartyId = inventoryItem.getString("ownerPartyId");
        String toPartyId = destinationFacility.getString("ownerPartyId");
        if (fromPartyId == null || !fromPartyId.equals(toPartyId)) {
            updateInventoryItemMap.put("ownerPartyId", toPartyId);
        }
    }
    try {
        Map<String, Object> result = dctx.getDispatcher().runSync("updateInventoryItem", updateInventoryItemMap);
        if (ServiceUtil.isError(result)) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ProductInventoryItemStoreProblem", UtilMisc.toMap("errorString", ""), locale), null, null, result);
        }
    } catch (GenericServiceException exc) {
        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ProductInventoryItemStoreProblem", UtilMisc.toMap("errorString", exc.getMessage()), locale));
    }
    // set the inventory transfer record to complete
    inventoryTransfer.set("statusId", "IXF_COMPLETE");
    // store the entities
    try {
        inventoryTransfer.store();
    } catch (GenericEntityException e) {
        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ProductInventoryItemStoreProblem", UtilMisc.toMap("errorString", e.getMessage()), locale));
    }
    return ServiceUtil.returnSuccess();
}
Also used : Locale(java.util.Locale) GenericValue(org.apache.ofbiz.entity.GenericValue) Delegator(org.apache.ofbiz.entity.Delegator) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) Timestamp(java.sql.Timestamp) BigDecimal(java.math.BigDecimal)

Aggregations

GenericServiceException (org.apache.ofbiz.service.GenericServiceException)417 GenericValue (org.apache.ofbiz.entity.GenericValue)339 LocalDispatcher (org.apache.ofbiz.service.LocalDispatcher)303 GenericEntityException (org.apache.ofbiz.entity.GenericEntityException)251 Delegator (org.apache.ofbiz.entity.Delegator)250 Locale (java.util.Locale)246 HashMap (java.util.HashMap)221 BigDecimal (java.math.BigDecimal)139 LinkedList (java.util.LinkedList)79 GeneralException (org.apache.ofbiz.base.util.GeneralException)68 Timestamp (java.sql.Timestamp)66 Map (java.util.Map)54 IOException (java.io.IOException)43 HttpSession (javax.servlet.http.HttpSession)36 ModelService (org.apache.ofbiz.service.ModelService)33 OrderReadHelper (org.apache.ofbiz.order.order.OrderReadHelper)24 EntityCondition (org.apache.ofbiz.entity.condition.EntityCondition)22 ArrayList (java.util.ArrayList)21 LinkedHashMap (java.util.LinkedHashMap)20 List (java.util.List)20