Search in sources :

Example 6 with GenericValue

use of org.apache.ofbiz.entity.GenericValue in project ofbiz-framework by apache.

the class UpsConnectException method upsRateInquire.

public static Map<String, Object> upsRateInquire(DispatchContext dctx, Map<String, ? extends Object> context) {
    Delegator delegator = dctx.getDelegator();
    Locale locale = (Locale) context.get("locale");
    // prepare the data
    String shippingContactMechId = (String) context.get("shippingContactMechId");
    String shippingOriginContactMechId = (String) context.get("shippingOriginContactMechId");
    // obtain the ship-to address
    GenericValue shipToAddress = null;
    if (shippingContactMechId != null) {
        try {
            shipToAddress = EntityQuery.use(delegator).from("PostalAddress").where("contactMechId", shippingContactMechId).queryOne();
        } catch (GenericEntityException e) {
            Debug.logError(e, module);
        }
    }
    if (shipToAddress == null) {
        return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentUnableFoundShipToAddresss", locale));
    }
    // obtain the ship from address if provided
    GenericValue shipFromAddress = null;
    if (shippingOriginContactMechId != null) {
        try {
            shipFromAddress = EntityQuery.use(delegator).from("PostalAddress").where("contactMechId", shippingOriginContactMechId).queryOne();
        } catch (GenericEntityException e) {
            Debug.logError(e, module);
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentUnableFoundShipToAddresssForDropShipping", locale));
        }
    }
    GenericValue destCountryGeo = null;
    try {
        destCountryGeo = shipToAddress.getRelatedOne("CountryGeo", false);
    } catch (GenericEntityException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(e.getMessage());
    }
    if (UtilValidate.isEmpty(destCountryGeo)) {
        return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentUpsShipToAddresssNoDestionationCountry", locale));
    }
    Map<String, Object> cxt = UtilMisc.toMap("serviceConfigProps", context.get("serviceConfigProps"), "upsRateInquireMode", context.get("upsRateInquireMode"), "productStoreId", context.get("productStoreId"), "carrierRoleTypeId", context.get("carrierRoleTypeId"));
    cxt.put("carrierPartyId", context.get("carrierPartyId"));
    cxt.put("shipmentMethodTypeId", context.get("shipmentMethodTypeId"));
    cxt.put("shippingPostalCode", shipToAddress.getString("postalCode"));
    cxt.put("shippingCountryCode", destCountryGeo.getString("geoCode"));
    cxt.put("packageWeights", context.get("packageWeights"));
    cxt.put("shippableItemInfo", context.get("shippableItemInfo"));
    cxt.put("shippableTotal", context.get("shippableTotal"));
    cxt.put("shippableQuantity", context.get("shippableQuantity"));
    cxt.put("shippableWeight", context.get("shippableWeight"));
    cxt.put("isResidentialAddress", context.get("isResidentialAddress"));
    cxt.put("shipFromAddress", shipFromAddress);
    cxt.put("shipmentGatewayConfigId", context.get("shipmentGatewayConfigId"));
    try {
        Map<String, Object> serviceResult = dctx.getDispatcher().runSync("upsRateEstimateByPostalCode", cxt);
        if (ServiceUtil.isError(serviceResult)) {
            return ServiceUtil.returnError(ServiceUtil.getErrorMessage(serviceResult));
        }
        return serviceResult;
    } catch (GenericServiceException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentUpsRateEstimateError", UtilMisc.toMap("errorString", e.getMessage()), locale));
    }
}
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)

Example 7 with GenericValue

use of org.apache.ofbiz.entity.GenericValue in project ofbiz-framework by apache.

the class UpsConnectException method upsRateInquireByPostalCode.

public static Map<String, Object> upsRateInquireByPostalCode(DispatchContext dctx, Map<String, ? extends Object> context) {
    Delegator delegator = dctx.getDelegator();
    Locale locale = (Locale) context.get("locale");
    // prepare the data
    String serviceConfigProps = (String) context.get("serviceConfigProps");
    String shipmentGatewayConfigId = (String) context.get("shipmentGatewayConfigId");
    String upsRateInquireMode = (String) context.get("upsRateInquireMode");
    String productStoreId = (String) context.get("productStoreId");
    String carrierRoleTypeId = (String) context.get("carrierRoleTypeId");
    String carrierPartyId = (String) context.get("carrierPartyId");
    String shipmentMethodTypeId = (String) context.get("shipmentMethodTypeId");
    String shippingPostalCode = (String) context.get("shippingPostalCode");
    String shippingCountryCode = (String) context.get("shippingCountryCode");
    List<BigDecimal> packageWeights = UtilGenerics.checkList(context.get("packageWeights"));
    List<Map<String, Object>> shippableItemInfo = UtilGenerics.checkList(context.get("shippableItemInfo"));
    String isResidentialAddress = (String) context.get("isResidentialAddress");
    // Important: DO NOT returnError here or you could trigger a transaction rollback and break other services.
    if (UtilValidate.isEmpty(shippingPostalCode)) {
        return ServiceUtil.returnFailure(UtilProperties.getMessage(resourceError, "FacilityShipmentUpsCannotRateEstimatePostalCodeMissing", locale));
    }
    if (serviceConfigProps == null) {
        serviceConfigProps = "shipment.properties";
    }
    if (upsRateInquireMode == null || !"Shop".equals(upsRateInquireMode)) {
        // can be either Rate || Shop
        Debug.logWarning("No upsRateInquireMode set, defaulting to 'Rate'", module);
        upsRateInquireMode = "Rate";
    }
    // grab the pickup type; if none is defined we will assume daily pickup
    String pickupType = getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "shipperPickupType", serviceConfigProps, "shipment.ups.shipper.pickup.type", "01");
    // if we're drop shipping from a supplier, then the address is given to us
    GenericValue shipFromAddress = (GenericValue) context.get("shipFromAddress");
    if (shipFromAddress == null) {
        // locate the ship-from address based on the product store's default facility
        GenericValue productStore = ProductStoreWorker.getProductStore(productStoreId, delegator);
        if (productStore != null && productStore.get("inventoryFacilityId") != null) {
            GenericValue facilityContactMech = ContactMechWorker.getFacilityContactMechByPurpose(delegator, productStore.getString("inventoryFacilityId"), UtilMisc.toList("SHIP_ORIG_LOCATION", "PRIMARY_LOCATION"));
            if (facilityContactMech != null) {
                try {
                    shipFromAddress = EntityQuery.use(delegator).from("PostalAddress").where("contactMechId", facilityContactMech.getString("contactMechId")).queryOne();
                } catch (GenericEntityException e) {
                    Debug.logError(e, module);
                }
            }
        }
    }
    if (shipFromAddress == null) {
        return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentUnableFoundShipToAddresss", locale));
    }
    // locate the service code
    String serviceCode = null;
    if (!"Shop".equals(upsRateInquireMode)) {
        // locate the CarrierShipmentMethod record
        GenericValue carrierShipmentMethod = null;
        try {
            carrierShipmentMethod = EntityQuery.use(delegator).from("CarrierShipmentMethod").where("shipmentMethodTypeId", shipmentMethodTypeId, "partyId", carrierPartyId, "roleTypeId", carrierRoleTypeId).queryOne();
        } catch (GenericEntityException e) {
            Debug.logError(e, module);
        }
        if (carrierShipmentMethod == null) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentUpsUnableToLocateShippingMethodRequested", locale));
        }
        // service code is 'carrierServiceCode'
        serviceCode = carrierShipmentMethod.getString("carrierServiceCode");
    }
    // prepare the XML Document
    Document rateRequestDoc = UtilXml.makeEmptyXmlDocument("RatingServiceSelectionRequest");
    Element rateRequestElement = rateRequestDoc.getDocumentElement();
    rateRequestElement.setAttribute("xml:lang", "en-US");
    // XML request header
    Element requestElement = UtilXml.addChildElement(rateRequestElement, "Request", rateRequestDoc);
    Element transactionReferenceElement = UtilXml.addChildElement(requestElement, "TransactionReference", rateRequestDoc);
    UtilXml.addChildElementValue(transactionReferenceElement, "CustomerContext", "Rating and Service", rateRequestDoc);
    UtilXml.addChildElementValue(transactionReferenceElement, "XpciVersion", "1.0001", rateRequestDoc);
    // RequestAction is always Rate, but RequestOption can be Rate to get a single rate or Shop for all shipping methods
    UtilXml.addChildElementValue(requestElement, "RequestAction", "Rate", rateRequestDoc);
    UtilXml.addChildElementValue(requestElement, "RequestOption", upsRateInquireMode, rateRequestDoc);
    // set the pickup type
    Element pickupElement = UtilXml.addChildElement(rateRequestElement, "PickupType", rateRequestDoc);
    UtilXml.addChildElementValue(pickupElement, "Code", pickupType, rateRequestDoc);
    // shipment info
    Element shipmentElement = UtilXml.addChildElement(rateRequestElement, "Shipment", rateRequestDoc);
    // shipper info - (sub of shipment)
    Element shipperElement = UtilXml.addChildElement(shipmentElement, "Shipper", rateRequestDoc);
    Element shipperAddrElement = UtilXml.addChildElement(shipperElement, "Address", rateRequestDoc);
    UtilXml.addChildElementValue(shipperAddrElement, "PostalCode", shipFromAddress.getString("postalCode"), rateRequestDoc);
    try {
        // If the warehouse you are shipping from its located in a country other than US, you need to supply its country code to UPS
        UtilXml.addChildElementValue(shipperAddrElement, "CountryCode", shipFromAddress.getRelatedOne("CountryGeo", true).getString("geoCode"), rateRequestDoc);
    } catch (GenericEntityException e) {
        return ServiceUtil.returnError(e.getMessage());
    }
    // ship-to info - (sub of shipment)
    Element shiptoElement = UtilXml.addChildElement(shipmentElement, "ShipTo", rateRequestDoc);
    Element shiptoAddrElement = UtilXml.addChildElement(shiptoElement, "Address", rateRequestDoc);
    UtilXml.addChildElementValue(shiptoAddrElement, "PostalCode", shippingPostalCode, rateRequestDoc);
    if (shippingCountryCode != null && !shippingCountryCode.equals("")) {
        UtilXml.addChildElementValue(shiptoAddrElement, "CountryCode", shippingCountryCode, rateRequestDoc);
    }
    if (isResidentialAddress != null && "Y".equals(isResidentialAddress)) {
        UtilXml.addChildElement(shiptoAddrElement, "ResidentialAddress", rateRequestDoc);
    }
    // requested service (code) - not used when in Shop mode
    if (serviceCode != null) {
        Element serviceElement = UtilXml.addChildElement(shipmentElement, "Service", rateRequestDoc);
        UtilXml.addChildElementValue(serviceElement, "Code", serviceCode, rateRequestDoc);
    }
    // package info
    String maxWeightStr = getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "maxEstimateWeight", serviceConfigProps, "shipment.ups.max.estimate.weight", "99");
    BigDecimal maxWeight;
    try {
        maxWeight = new BigDecimal(maxWeightStr);
    } catch (NumberFormatException e) {
        maxWeight = new BigDecimal("99");
    }
    String minWeightStr = getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "minEstimateWeight", serviceConfigProps, "shipment.ups.min.estimate.weight", ".1");
    BigDecimal minWeight;
    try {
        minWeight = new BigDecimal(minWeightStr);
    } catch (NumberFormatException e) {
        minWeight = new BigDecimal("0.1");
    }
    // Passing in a list of package weights overrides the calculation of same via shippableItemInfo
    if (UtilValidate.isEmpty(packageWeights)) {
        String totalWeightStr = getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "minEstimateWeight", serviceConfigProps, "shipment.ups.min.estimate.weight", "1");
        splitEstimatePackages(dctx, rateRequestDoc, shipmentElement, shippableItemInfo, maxWeight, minWeight, totalWeightStr);
    } else {
        for (BigDecimal packageWeight : packageWeights) {
            addPackageElement(rateRequestDoc, shipmentElement, packageWeight);
        }
    }
    // service options
    UtilXml.addChildElement(shipmentElement, "ShipmentServiceOptions", rateRequestDoc);
    String rateRequestString = null;
    try {
        rateRequestString = UtilXml.writeXmlDocument(rateRequestDoc);
    } catch (IOException e) {
        String ioeErrMsg = "Error writing the RatingServiceSelectionRequest XML Document to a String: " + e.toString();
        Debug.logError(e, ioeErrMsg, module);
        return ServiceUtil.returnFailure(UtilProperties.getMessage(resourceError, "FacilityShipmentUpsErrorRatingServiceSelectionRequestXmlToString", UtilMisc.toMap("errorString", e.toString()), locale));
    }
    // create AccessRequest XML doc
    Document accessRequestDocument = createAccessRequestDocument(delegator, shipmentGatewayConfigId, serviceConfigProps);
    String accessRequestString = null;
    try {
        accessRequestString = UtilXml.writeXmlDocument(accessRequestDocument);
    } catch (IOException e) {
        String ioeErrMsg = "Error writing the AccessRequest XML Document to a String: " + e.toString();
        Debug.logError(e, ioeErrMsg, module);
        return ServiceUtil.returnFailure(UtilProperties.getMessage(resourceError, "FacilityShipmentUpsErrorAccessRequestXmlToString", UtilMisc.toMap("errorString", e.toString()), locale));
    }
    // prepare the access/inquire request string
    StringBuilder xmlString = new StringBuilder();
    xmlString.append(accessRequestString);
    xmlString.append(rateRequestString);
    if (Debug.verboseOn())
        Debug.logVerbose(xmlString.toString(), module);
    // send the request
    String rateResponseString = null;
    try {
        rateResponseString = sendUpsRequest("Rate", xmlString.toString(), shipmentGatewayConfigId, serviceConfigProps, delegator, locale);
    } catch (UpsConnectException e) {
        String uceErrMsg = "Error sending UPS request for UPS Service Rate: " + e.toString();
        Debug.logError(e, uceErrMsg, module);
        return ServiceUtil.returnFailure(UtilProperties.getMessage(resourceError, "FacilityShipmentUpsErrorSendingRate", UtilMisc.toMap("errorString", e.toString()), locale));
    }
    Debug.logVerbose(rateResponseString, module);
    Document rateResponseDocument = null;
    try {
        rateResponseDocument = UtilXml.readXmlDocument(rateResponseString, false);
    } catch (SAXException e2) {
        String excErrMsg = "Error parsing the RatingServiceSelectionResponse: " + e2.toString();
        Debug.logError(e2, excErrMsg, module);
        return ServiceUtil.returnFailure(UtilProperties.getMessage(resourceError, "FacilityShipmentUpsErrorParsingRatingServiceSelectionResponse", UtilMisc.toMap("errorString", e2.toString()), locale));
    } catch (ParserConfigurationException e2) {
        String excErrMsg = "Error parsing the RatingServiceSelectionResponse: " + e2.toString();
        Debug.logError(e2, excErrMsg, module);
        return ServiceUtil.returnFailure(UtilProperties.getMessage(resourceError, "FacilityShipmentUpsErrorParsingRatingServiceSelectionResponse", UtilMisc.toMap("errorString", e2.toString()), locale));
    } catch (IOException e2) {
        String excErrMsg = "Error parsing the RatingServiceSelectionResponse: " + e2.toString();
        Debug.logError(e2, excErrMsg, module);
        return ServiceUtil.returnFailure(UtilProperties.getMessage(resourceError, "FacilityShipmentUpsErrorParsingRatingServiceSelectionResponse", UtilMisc.toMap("errorString", e2.toString()), locale));
    }
    return handleUpsRateInquireResponse(rateResponseDocument, locale);
}
Also used : Locale(java.util.Locale) GenericValue(org.apache.ofbiz.entity.GenericValue) Element(org.w3c.dom.Element) IOException(java.io.IOException) Document(org.w3c.dom.Document) BigDecimal(java.math.BigDecimal) SAXException(org.xml.sax.SAXException) Delegator(org.apache.ofbiz.entity.Delegator) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) Map(java.util.Map) HashMap(java.util.HashMap)

Example 8 with GenericValue

use of org.apache.ofbiz.entity.GenericValue in project ofbiz-framework by apache.

the class UspsRequestException method uspsUpdateShipmentRateInfo.

// Warning: I don't think the following 2 services were completed or fully tested - 2004.09.06 JFE
/* --- ShipmentRouteSegment services --------------------------------------------------------------------------- */
public static Map<String, Object> uspsUpdateShipmentRateInfo(DispatchContext dctx, Map<String, ? extends Object> context) {
    Delegator delegator = dctx.getDelegator();
    LocalDispatcher dispatcher = dctx.getDispatcher();
    String shipmentId = (String) context.get("shipmentId");
    String shipmentRouteSegmentId = (String) context.get("shipmentRouteSegmentId");
    Locale locale = (Locale) context.get("locale");
    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, "FacilityShipmentUspsGatewayNotAvailable", locale));
    }
    try {
        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));
        }
        // ensure the carrier is USPS
        if (!"USPS".equals(shipmentRouteSegment.getString("carrierPartyId"))) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentUspsNotRouteSegmentCarrier", UtilMisc.toMap("shipmentRouteSegmentId", shipmentRouteSegmentId, "shipmentId", shipmentId), locale));
        }
        // get the origin address
        GenericValue originAddress = shipmentRouteSegment.getRelatedOne("OriginPostalAddress", false);
        if (originAddress == null) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentRouteSegmentOriginPostalAddressNotFound", UtilMisc.toMap("shipmentId", shipmentId, "shipmentRouteSegmentId", shipmentRouteSegmentId), locale));
        }
        if (!"USA".equals(originAddress.getString("countryGeoId"))) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentUspsRouteSegmentOriginCountryGeoNotInUsa", UtilMisc.toMap("shipmentId", shipmentId, "shipmentRouteSegmentId", shipmentRouteSegmentId), locale));
        }
        String originZip = originAddress.getString("postalCode");
        if (UtilValidate.isEmpty(originZip)) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentUspsRouteSegmentOriginZipCodeMissing", UtilMisc.toMap("contactMechId", originAddress.getString("contactMechId")), locale));
        }
        // get the destination address
        GenericValue destinationAddress = shipmentRouteSegment.getRelatedOne("DestPostalAddress", false);
        if (destinationAddress == null) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentRouteSegmentDestPostalAddressNotFound", UtilMisc.toMap("shipmentId", shipmentId, "shipmentRouteSegmentId", shipmentRouteSegmentId), locale));
        }
        if (!"USA".equals(destinationAddress.getString("countryGeoId"))) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentUspsRouteSegmentOriginCountryGeoNotInUsa", UtilMisc.toMap("shipmentId", shipmentId, "shipmentRouteSegmentId", shipmentRouteSegmentId), locale));
        }
        String destinationZip = destinationAddress.getString("postalCode");
        if (UtilValidate.isEmpty(destinationZip)) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentUspsRouteSegmentDestinationZipCodeMissing", UtilMisc.toMap("contactMechId", destinationAddress.getString("contactMechId")), locale));
        }
        // get the service type from the CarrierShipmentMethod
        String shipmentMethodTypeId = shipmentRouteSegment.getString("shipmentMethodTypeId");
        String partyId = shipmentRouteSegment.getString("carrierPartyId");
        GenericValue carrierShipmentMethod = EntityQuery.use(delegator).from("CarrierShipmentMethod").where("partyId", partyId, "roleTypeId", "CARRIER", "shipmentMethodTypeId", shipmentMethodTypeId).queryOne();
        if (carrierShipmentMethod == null) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentUspsNoCarrierShipmentMethod", UtilMisc.toMap("carrierPartyId", partyId, "shipmentMethodTypeId", shipmentMethodTypeId), locale));
        }
        String serviceType = carrierShipmentMethod.getString("carrierServiceCode");
        if (UtilValidate.isEmpty(serviceType)) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentUspsNoCarrierServiceCodeFound", UtilMisc.toMap("carrierPartyId", partyId, "shipmentMethodTypeId", shipmentMethodTypeId), locale));
        }
        // get the packages for this shipment route segment
        List<GenericValue> shipmentPackageRouteSegList = shipmentRouteSegment.getRelated("ShipmentPackageRouteSeg", null, UtilMisc.toList("+shipmentPackageSeqId"), false);
        if (UtilValidate.isEmpty(shipmentPackageRouteSegList)) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentPackageRouteSegsNotFound", UtilMisc.toMap("shipmentId", shipmentId, "shipmentRouteSegmentId", shipmentRouteSegmentId), locale));
        }
        BigDecimal actualTransportCost = BigDecimal.ZERO;
        String carrierDeliveryZone = null;
        String carrierRestrictionCodes = null;
        String carrierRestrictionDesc = null;
        // send a new request for each package
        for (Iterator<GenericValue> i = shipmentPackageRouteSegList.iterator(); i.hasNext(); ) {
            GenericValue shipmentPackageRouteSeg = i.next();
            Document requestDocument = createUspsRequestDocument("RateRequest", true, delegator, shipmentGatewayConfigId, resource);
            Element packageElement = UtilXml.addChildElement(requestDocument.getDocumentElement(), "Package", requestDocument);
            packageElement.setAttribute("ID", "0");
            UtilXml.addChildElementValue(packageElement, "Service", serviceType, requestDocument);
            UtilXml.addChildElementValue(packageElement, "ZipOrigination", originZip, requestDocument);
            UtilXml.addChildElementValue(packageElement, "ZipDestination", destinationZip, requestDocument);
            GenericValue shipmentPackage = null;
            shipmentPackage = shipmentPackageRouteSeg.getRelatedOne("ShipmentPackage", false);
            // weight elements - Pounds, Ounces
            String weightStr = shipmentPackage.getString("weight");
            if (UtilValidate.isEmpty(weightStr)) {
                return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentUspsWeightNotFound", UtilMisc.toMap("shipmentId", shipmentPackage.getString("shipmentId"), "shipmentPackageSeqId", shipmentPackage.getString("shipmentPackageSeqId")), locale));
            }
            BigDecimal weight = BigDecimal.ZERO;
            try {
                weight = new BigDecimal(weightStr);
            } catch (NumberFormatException nfe) {
                // TODO: handle exception
                Debug.logError(nfe, module);
            }
            String weightUomId = shipmentPackage.getString("weightUomId");
            if (UtilValidate.isEmpty(weightUomId)) {
                // assume weight is in pounds
                weightUomId = "WT_lb";
            }
            if (!"WT_lb".equals(weightUomId)) {
                // attempt a conversion to pounds
                Map<String, Object> result;
                try {
                    result = dispatcher.runSync("convertUom", UtilMisc.<String, Object>toMap("uomId", weightUomId, "uomIdTo", "WT_lb", "originalValue", weight));
                    if (ServiceUtil.isError(result)) {
                        return ServiceUtil.returnError(ServiceUtil.getErrorMessage(result));
                    }
                } catch (GenericServiceException ex) {
                    return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentUspsWeightConversionError", UtilMisc.toMap("errorString", ex.getMessage()), locale));
                }
                if (result.get(ModelService.RESPONSE_MESSAGE).equals(ModelService.RESPOND_SUCCESS) && result.get("convertedValue") != null) {
                    weight = weight.multiply((BigDecimal) result.get("convertedValue"));
                } else {
                    return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentUspsWeightUnsupported", UtilMisc.toMap("weightUomId", weightUomId, "shipmentId", shipmentPackage.getString("shipmentId"), "shipmentPackageSeqId", shipmentPackage.getString("shipmentPackageSeqId"), "weightUom", "WT_lb"), locale));
                }
            }
            BigDecimal weightPounds = weight.setScale(0, RoundingMode.FLOOR);
            BigDecimal weightOunces = weight.multiply(new BigDecimal("16")).remainder(new BigDecimal("16")).setScale(0, RoundingMode.CEILING);
            DecimalFormat df = new DecimalFormat("#");
            UtilXml.addChildElementValue(packageElement, "Pounds", df.format(weightPounds), requestDocument);
            UtilXml.addChildElementValue(packageElement, "Ounces", df.format(weightOunces), requestDocument);
            // Container element
            GenericValue carrierShipmentBoxType = null;
            List<GenericValue> carrierShipmentBoxTypes = null;
            carrierShipmentBoxTypes = shipmentPackage.getRelated("CarrierShipmentBoxType", UtilMisc.toMap("partyId", "USPS"), null, false);
            if (carrierShipmentBoxTypes.size() > 0) {
                carrierShipmentBoxType = carrierShipmentBoxTypes.get(0);
            }
            if (carrierShipmentBoxType != null && UtilValidate.isNotEmpty(carrierShipmentBoxType.getString("packagingTypeCode"))) {
                UtilXml.addChildElementValue(packageElement, "Container", carrierShipmentBoxType.getString("packagingTypeCode"), requestDocument);
            } else {
                // default to "None", for customers using their own package
                UtilXml.addChildElementValue(packageElement, "Container", "None", requestDocument);
            }
            // Size element
            if (carrierShipmentBoxType != null && UtilValidate.isNotEmpty("oversizeCode")) {
                UtilXml.addChildElementValue(packageElement, "Size", carrierShipmentBoxType.getString("oversizeCode"), requestDocument);
            } else {
                // default to "Regular", length + girth measurement <= 84 inches
                UtilXml.addChildElementValue(packageElement, "Size", "Regular", requestDocument);
            }
            // Although only applicable for Parcel Post, this tag is required for all requests
            UtilXml.addChildElementValue(packageElement, "Machinable", "False", requestDocument);
            Document responseDocument = null;
            try {
                responseDocument = sendUspsRequest("Rate", requestDocument, delegator, shipmentGatewayConfigId, resource, locale);
            } catch (UspsRequestException e) {
                Debug.logInfo(e, module);
                return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentUspsRateDomesticSendingError", UtilMisc.toMap("errorString", e.getMessage()), locale));
            }
            Element respPackageElement = UtilXml.firstChildElement(responseDocument.getDocumentElement(), "Package");
            if (respPackageElement == null) {
                return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentUspsRateDomesticResponseIncompleteElementPackage", locale));
            }
            Element respErrorElement = UtilXml.firstChildElement(respPackageElement, "Error");
            if (respErrorElement != null) {
                return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentUspsRateDomesticResponseError", UtilMisc.toMap("errorString", UtilXml.childElementValue(respErrorElement, "Description")), locale));
            }
            // update the ShipmentPackageRouteSeg
            String postageString = UtilXml.childElementValue(respPackageElement, "Postage");
            if (UtilValidate.isEmpty(postageString)) {
                return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentUspsRateDomesticResponseIncompleteElementPostage", locale));
            }
            BigDecimal postage = BigDecimal.ZERO;
            try {
                postage = new BigDecimal(postageString);
            } catch (NumberFormatException nfe) {
                // TODO: handle exception
                Debug.logError(nfe, module);
            }
            actualTransportCost = actualTransportCost.add(postage);
            shipmentPackageRouteSeg.setString("packageTransportCost", postageString);
            shipmentPackageRouteSeg.store();
            // if this is the last package, get the zone and APO/FPO restrictions for the ShipmentRouteSegment
            if (!i.hasNext()) {
                carrierDeliveryZone = UtilXml.childElementValue(respPackageElement, "Zone");
                carrierRestrictionCodes = UtilXml.childElementValue(respPackageElement, "RestrictionCodes");
                carrierRestrictionDesc = UtilXml.childElementValue(respPackageElement, "RestrictionDescription");
            }
        }
        // update the ShipmentRouteSegment
        shipmentRouteSegment.set("carrierDeliveryZone", carrierDeliveryZone);
        shipmentRouteSegment.set("carrierRestrictionCodes", carrierRestrictionCodes);
        shipmentRouteSegment.set("carrierRestrictionDesc", carrierRestrictionDesc);
        shipmentRouteSegment.setString("actualTransportCost", String.valueOf(actualTransportCost));
        shipmentRouteSegment.store();
    } catch (GenericEntityException gee) {
        Debug.logInfo(gee, module);
        return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentUspsRateDomesticReadingError", UtilMisc.toMap("errorString", gee.getMessage()), locale));
    }
    return ServiceUtil.returnSuccess();
}
Also used : Locale(java.util.Locale) GenericValue(org.apache.ofbiz.entity.GenericValue) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) Element(org.w3c.dom.Element) DecimalFormat(java.text.DecimalFormat) Document(org.w3c.dom.Document) BigDecimal(java.math.BigDecimal) Delegator(org.apache.ofbiz.entity.Delegator) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) GenericServiceException(org.apache.ofbiz.service.GenericServiceException)

Example 9 with GenericValue

use of org.apache.ofbiz.entity.GenericValue in project ofbiz-framework by apache.

the class VerifyPickSessionRow method issueItemToShipment.

protected void issueItemToShipment(String shipmentId, String picklistBinId, GenericValue userLogin, BigDecimal quantity, LocalDispatcher dispatcher, Locale locale) throws GeneralException {
    if (quantity == null) {
        quantity = this.getReadyToVerifyQty();
    }
    Map<String, Object> issueOrderItemMap = new HashMap<String, Object>();
    issueOrderItemMap.put("shipmentId", shipmentId);
    issueOrderItemMap.put("orderId", this.getOrderId());
    issueOrderItemMap.put("orderItemSeqId", this.getOrderItemSeqId());
    issueOrderItemMap.put("shipGroupSeqId", this.getShipGroupSeqId());
    issueOrderItemMap.put("inventoryItemId", this.getInventoryItemId());
    issueOrderItemMap.put("quantity", quantity);
    issueOrderItemMap.put("userLogin", userLogin);
    Map<String, Object> issueOrderItemResp = dispatcher.runSync("issueOrderItemShipGrpInvResToShipment", issueOrderItemMap);
    if (ServiceUtil.isError(issueOrderItemResp)) {
        throw new GeneralException(ServiceUtil.getErrorMessage(issueOrderItemResp));
    }
    String shipmentItemSeqId = (String) issueOrderItemResp.get("shipmentItemSeqId");
    if (shipmentItemSeqId == null) {
        throw new GeneralException(UtilProperties.getMessage("ProductErrorUiLabels", "ProductErrorIssueItemDidNotReturnAValidShipmentItemSeqId", locale));
    } else {
        this.setShipmentItemSeqId(shipmentItemSeqId);
    }
    if (picklistBinId != null) {
        // find the pick list item
        Delegator delegator = dispatcher.getDelegator();
        Map<String, Object> picklistItemMap = new HashMap<String, Object>();
        picklistItemMap.put("picklistBinId", picklistBinId);
        picklistItemMap.put("orderId", this.getOrderId());
        picklistItemMap.put("orderItemSeqId", this.getOrderItemSeqId());
        picklistItemMap.put("shipGroupSeqId", this.getShipGroupSeqId());
        picklistItemMap.put("inventoryItemId", this.getInventoryItemId());
        GenericValue picklistItem = EntityQuery.use(delegator).from("PicklistItem").where(picklistItemMap).cache(true).queryOne();
        if (UtilValidate.isNotEmpty(picklistItem)) {
            BigDecimal itemQty = picklistItem.getBigDecimal("quantity");
            if (itemQty.compareTo(quantity) == 0) {
                // set to complete
                picklistItemMap.put("itemStatusId", "PICKITEM_COMPLETED");
            } else {
                picklistItemMap.put("itemStatusId", "PICKITEM_CANCELLED");
            }
            picklistItemMap.put("userLogin", userLogin);
            Map<String, Object> picklistItemResp = dispatcher.runSync("updatePicklistItem", picklistItemMap);
            if (ServiceUtil.isError(picklistItemResp)) {
                throw new GeneralException(ServiceUtil.getErrorMessage(picklistItemResp));
            }
        }
    }
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) GeneralException(org.apache.ofbiz.base.util.GeneralException) Delegator(org.apache.ofbiz.entity.Delegator) HashMap(java.util.HashMap) BigDecimal(java.math.BigDecimal)

Example 10 with GenericValue

use of org.apache.ofbiz.entity.GenericValue in project ofbiz-framework by apache.

the class WeightPackageSession method upsShipmentConfirm.

protected BigDecimal upsShipmentConfirm() throws GeneralException {
    Delegator delegator = this.getDelegator();
    BigDecimal actualCost = BigDecimal.ZERO;
    List<GenericValue> shipmentRouteSegments = EntityQuery.use(delegator).from("ShipmentRouteSegment").where("shipmentId", shipmentId).queryList();
    if (UtilValidate.isNotEmpty(shipmentRouteSegments)) {
        for (GenericValue shipmentRouteSegment : shipmentRouteSegments) {
            Map<String, Object> shipmentRouteSegmentMap = new HashMap<String, Object>();
            shipmentRouteSegmentMap.put("shipmentId", shipmentId);
            shipmentRouteSegmentMap.put("shipmentRouteSegmentId", shipmentRouteSegment.getString("shipmentRouteSegmentId"));
            shipmentRouteSegmentMap.put("userLogin", userLogin);
            Map<String, Object> shipmentRouteSegmentResult = this.getDispatcher().runSync("upsShipmentConfirm", shipmentRouteSegmentMap);
            if (ServiceUtil.isError(shipmentRouteSegmentResult)) {
                throw new GeneralException(ServiceUtil.getErrorMessage(shipmentRouteSegmentResult));
            }
            GenericValue shipRouteSeg = EntityQuery.use(delegator).from("ShipmentRouteSegment").where("shipmentId", shipmentId, "shipmentRouteSegmentId", shipmentRouteSegment.getString("shipmentRouteSegmentId")).queryOne();
            actualCost = actualCost.add(shipRouteSeg.getBigDecimal("actualCost"));
        }
    }
    return actualCost;
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) GeneralException(org.apache.ofbiz.base.util.GeneralException) Delegator(org.apache.ofbiz.entity.Delegator) HashMap(java.util.HashMap) BigDecimal(java.math.BigDecimal)

Aggregations

GenericValue (org.apache.ofbiz.entity.GenericValue)1422 GenericEntityException (org.apache.ofbiz.entity.GenericEntityException)871 Delegator (org.apache.ofbiz.entity.Delegator)721 Locale (java.util.Locale)505 HashMap (java.util.HashMap)463 GenericServiceException (org.apache.ofbiz.service.GenericServiceException)370 LocalDispatcher (org.apache.ofbiz.service.LocalDispatcher)356 BigDecimal (java.math.BigDecimal)338 LinkedList (java.util.LinkedList)312 Timestamp (java.sql.Timestamp)202 GeneralException (org.apache.ofbiz.base.util.GeneralException)168 Map (java.util.Map)155 IOException (java.io.IOException)116 EntityCondition (org.apache.ofbiz.entity.condition.EntityCondition)97 HttpSession (javax.servlet.http.HttpSession)89 ArrayList (java.util.ArrayList)69 Security (org.apache.ofbiz.security.Security)69 EntityListIterator (org.apache.ofbiz.entity.util.EntityListIterator)59 List (java.util.List)56 EntityExpr (org.apache.ofbiz.entity.condition.EntityExpr)52