use of org.apache.ofbiz.entity.Delegator 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));
}
}
use of org.apache.ofbiz.entity.Delegator in project ofbiz-framework by apache.
the class UpsConnectException method upsAddressValidation.
public static Map<String, Object> upsAddressValidation(DispatchContext dctx, Map<String, ? extends Object> context) {
Delegator delegator = dctx.getDelegator();
Locale locale = (Locale) context.get("locale");
String city = (String) context.get("city");
String stateProvinceGeoId = (String) context.get("stateProvinceGeoId");
String postalCode = (String) context.get("postalCode");
String shipmentGatewayConfigId = (String) context.get("shipmentGatewayConfigId");
String resource = (String) context.get("serviceConfigProps");
if (UtilValidate.isEmpty(city) && UtilValidate.isEmpty(postalCode)) {
return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentUpsAddressValidationRequireCityOrPostalCode", locale));
}
// prepare the XML Document
Document avRequestDoc = UtilXml.makeEmptyXmlDocument("AddressValidationRequest");
Element avRequestElement = avRequestDoc.getDocumentElement();
avRequestElement.setAttribute("xml:lang", "en-US");
// XML request header
Element requestElement = UtilXml.addChildElement(avRequestElement, "Request", avRequestDoc);
Element transactionReferenceElement = UtilXml.addChildElement(requestElement, "TransactionReference", avRequestDoc);
UtilXml.addChildElementValue(transactionReferenceElement, "CustomerContext", "Rating and Service", avRequestDoc);
UtilXml.addChildElementValue(transactionReferenceElement, "XpciVersion", "1.0001", avRequestDoc);
UtilXml.addChildElementValue(requestElement, "RequestAction", "AV", avRequestDoc);
// Address
Element addressElement = UtilXml.addChildElement(avRequestElement, "Address", avRequestDoc);
if (UtilValidate.isNotEmpty(city)) {
UtilXml.addChildElementValue(addressElement, "City", city, avRequestDoc);
}
if (UtilValidate.isNotEmpty(stateProvinceGeoId)) {
UtilXml.addChildElementValue(addressElement, "StateProvinceCode", stateProvinceGeoId, avRequestDoc);
}
if (UtilValidate.isNotEmpty(postalCode)) {
UtilXml.addChildElementValue(addressElement, "PostalCode", postalCode, avRequestDoc);
}
String avRequestString = null;
try {
avRequestString = UtilXml.writeXmlDocument(avRequestDoc);
} catch (IOException e) {
String ioeErrMsg = "Error writing the AddressValidationRequest XML Document to a String: " + e.toString();
Debug.logError(e, ioeErrMsg, module);
return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentUpsErrorAddressValidationRequestXmlToString", UtilMisc.toMap("errorString", e.toString()), locale));
}
// create AccessRequest XML doc
Document accessRequestDocument = createAccessRequestDocument(delegator, shipmentGatewayConfigId, resource);
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.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentUpsErrorShipmentAcceptRequestXmlToString", UtilMisc.toMap("errorString", e.toString()), locale));
}
// prepare the request string
StringBuilder xmlString = new StringBuilder();
xmlString.append(accessRequestString);
xmlString.append(avRequestString);
Debug.logInfo(xmlString.toString(), module);
// send the request
String avResponseString = null;
try {
avResponseString = sendUpsRequest("AV", xmlString.toString(), shipmentGatewayConfigId, resource, delegator, locale);
} catch (UpsConnectException e) {
String uceErrMsg = "Error sending UPS request: " + e.toString();
Debug.logError(e, uceErrMsg, module);
return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentUpsErrorSendingAddressVerification", UtilMisc.toMap("errorString", e.toString()), locale));
}
Debug.logInfo(avResponseString, module);
Document avResponseDocument = null;
try {
avResponseDocument = UtilXml.readXmlDocument(avResponseString, false);
} catch (SAXException e2) {
String excErrMsg = "Error parsing the UPS response: " + e2.toString();
Debug.logError(e2, excErrMsg, module);
return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentUpsErrorParsingAddressVerificationResponse", UtilMisc.toMap("errorString", e2.toString()), locale));
} catch (ParserConfigurationException e2) {
String excErrMsg = "Error parsing the UPS response: " + e2.toString();
Debug.logError(e2, excErrMsg, module);
return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentUpsErrorParsingAddressVerificationResponse", UtilMisc.toMap("errorString", e2.toString()), locale));
} catch (IOException e2) {
String excErrMsg = "Error parsing the UPS response: " + e2.toString();
Debug.logError(e2, excErrMsg, module);
return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentUpsErrorParsingAddressVerificationResponse", UtilMisc.toMap("errorString", e2.toString()), locale));
}
return handleUpsAddressValidationResponse(avResponseDocument, locale);
}
use of org.apache.ofbiz.entity.Delegator 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);
}
use of org.apache.ofbiz.entity.Delegator in project ofbiz-framework by apache.
the class UspsRequestException method uspsTrackConfirm.
// lifted from UpsServices with no changes - 2004.09.06 JFE
/*
Track/Confirm Samples: (API=TrackV2)
Request:
<TrackRequest USERID="xxxxxxxx" PASSWORD="xxxxxxxx">
<TrackID ID="EJ958083578US"></TrackID>
</TrackRequest>
Response:
<TrackResponse>
<TrackInfo ID="EJ958083578US">
<TrackSummary>Your item was delivered at 8:10 am on June 1 in Wilmington DE 19801.</TrackSummary>
<TrackDetail>May 30 11:07 am NOTICE LEFT WILMINGTON DE 19801.</TrackDetail>
<TrackDetail>May 30 10:08 am ARRIVAL AT UNIT WILMINGTON DE 19850.</TrackDetail>
<TrackDetail>May 29 9:55 am ACCEPT OR PICKUP EDGEWATER NJ 07020.</TrackDetail>
</TrackInfo>
</TrackResponse>
*/
public static Map<String, Object> uspsTrackConfirm(DispatchContext dctx, Map<String, ? extends Object> context) {
Delegator delegator = dctx.getDelegator();
String shipmentGatewayConfigId = (String) context.get("shipmentGatewayConfigId");
String resource = (String) context.get("configProps");
Locale locale = (Locale) context.get("locale");
Document requestDocument = createUspsRequestDocument("TrackRequest", true, delegator, shipmentGatewayConfigId, resource);
Element trackingElement = UtilXml.addChildElement(requestDocument.getDocumentElement(), "TrackID", requestDocument);
trackingElement.setAttribute("ID", (String) context.get("trackingId"));
Document responseDocument = null;
try {
responseDocument = sendUspsRequest("TrackV2", requestDocument, delegator, shipmentGatewayConfigId, resource, locale);
} catch (UspsRequestException e) {
Debug.logInfo(e, module);
return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentUspsTrackingSendingError", UtilMisc.toMap("errorString", e.getMessage()), locale));
}
Element trackInfoElement = UtilXml.firstChildElement(responseDocument.getDocumentElement(), "TrackInfo");
if (trackInfoElement == null) {
return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentUspsTrackingIncompleteResponse", locale));
}
Map<String, Object> result = ServiceUtil.returnSuccess();
result.put("trackingSummary", UtilXml.childElementValue(trackInfoElement, "TrackSummary"));
List<? extends Element> detailElementList = UtilXml.childElementList(trackInfoElement, "TrackDetail");
if (UtilValidate.isNotEmpty(detailElementList)) {
List<String> trackingDetailList = new LinkedList<String>();
for (Element detailElement : detailElementList) {
trackingDetailList.add(UtilXml.elementValue(detailElement));
}
result.put("trackingDetailList", trackingDetailList);
}
return result;
}
use of org.apache.ofbiz.entity.Delegator 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();
}
Aggregations