Search in sources :

Example 16 with GenericEntityException

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

the class ShipmentEvents method viewShipmentPackageRouteSegLabelImage.

public static String viewShipmentPackageRouteSegLabelImage(HttpServletRequest request, HttpServletResponse response) {
    Delegator delegator = (Delegator) request.getAttribute("delegator");
    String shipmentId = request.getParameter("shipmentId");
    String shipmentRouteSegmentId = request.getParameter("shipmentRouteSegmentId");
    String shipmentPackageSeqId = request.getParameter("shipmentPackageSeqId");
    GenericValue shipmentPackageRouteSeg = null;
    try {
        shipmentPackageRouteSeg = EntityQuery.use(delegator).from("ShipmentPackageRouteSeg").where("shipmentId", shipmentId, "shipmentRouteSegmentId", shipmentRouteSegmentId, "shipmentPackageSeqId", shipmentPackageSeqId).queryOne();
    } catch (GenericEntityException e) {
        String errorMsg = "Error looking up ShipmentPackageRouteSeg: " + e.toString();
        Debug.logError(e, errorMsg, module);
        request.setAttribute("_ERROR_MESSAGE_", errorMsg);
        return "error";
    }
    if (shipmentPackageRouteSeg == null) {
        request.setAttribute("_ERROR_MESSAGE_", "Could not find ShipmentPackageRouteSeg where shipmentId=[" + shipmentId + "], shipmentRouteSegmentId=[" + shipmentRouteSegmentId + "], shipmentPackageSeqId=[" + shipmentPackageSeqId + "]");
        return "error";
    }
    byte[] bytes = shipmentPackageRouteSeg.getBytes("labelImage");
    if (bytes == null || bytes.length == 0) {
        request.setAttribute("_ERROR_MESSAGE_", "The ShipmentPackageRouteSeg was found where shipmentId=[" + shipmentId + "], shipmentRouteSegmentId=[" + shipmentRouteSegmentId + "], shipmentPackageSeqId=[" + shipmentPackageSeqId + "], but there was no labelImage on the value.");
        return "error";
    }
    // It would be nice to store the actual type of the image alongside the image data.
    try {
        UtilHttp.streamContentToBrowser(response, bytes, "image/gif");
    } catch (IOException e1) {
        try {
            UtilHttp.streamContentToBrowser(response, bytes, "image/png");
        } catch (IOException e2) {
            String errorMsg = "Error writing labelImage to OutputStream: " + e2.toString();
            Debug.logError(e2, errorMsg, module);
            request.setAttribute("_ERROR_MESSAGE_", errorMsg);
            return "error";
        }
    }
    return "success";
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) Delegator(org.apache.ofbiz.entity.Delegator) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) IOException(java.io.IOException)

Example 17 with GenericEntityException

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

the class ShipmentWorker method getShipmentPackageContentValue.

/*
     * Returns the value of a given ShipmentPackageContent record.  Calculated by working out the total value (from the OrderItems) of all ItemIssuances
     * for the ShipmentItem then dividing that by the total quantity issued for the same to get an average item value then multiplying that by the package
     * content quantity.
     * Note: No rounding of the calculation is performed so you will need to round it to the accuracy that you require
     */
public static BigDecimal getShipmentPackageContentValue(GenericValue shipmentPackageContent) {
    BigDecimal quantity = shipmentPackageContent.getBigDecimal("quantity");
    BigDecimal value;
    // lookup the issuance to find the order
    List<GenericValue> issuances = null;
    try {
        GenericValue shipmentItem = shipmentPackageContent.getRelatedOne("ShipmentItem", false);
        issuances = shipmentItem.getRelated("ItemIssuance", null, null, false);
    } catch (GenericEntityException e) {
        Debug.logError(e, module);
    }
    BigDecimal totalIssued = BigDecimal.ZERO;
    BigDecimal totalValue = BigDecimal.ZERO;
    if (UtilValidate.isNotEmpty(issuances)) {
        for (GenericValue issuance : issuances) {
            // we only need one
            BigDecimal issuanceQuantity = issuance.getBigDecimal("quantity");
            BigDecimal issuanceCancelQuantity = issuance.getBigDecimal("cancelQuantity");
            if (issuanceCancelQuantity != null) {
                issuanceQuantity = issuanceQuantity.subtract(issuanceCancelQuantity);
            }
            // get the order item
            GenericValue orderItem = null;
            try {
                orderItem = issuance.getRelatedOne("OrderItem", false);
            } catch (GenericEntityException e) {
                Debug.logError(e, module);
            }
            if (orderItem != null) {
                // get the value per unit - (base price * amount)
                BigDecimal selectedAmount = orderItem.getBigDecimal("selectedAmount");
                if (selectedAmount == null || selectedAmount.compareTo(BigDecimal.ZERO) <= 0) {
                    selectedAmount = BigDecimal.ONE;
                }
                BigDecimal unitPrice = orderItem.getBigDecimal("unitPrice");
                BigDecimal itemValue = unitPrice.multiply(selectedAmount);
                // total value for package (per unit * quantity)
                totalIssued = totalIssued.add(issuanceQuantity);
                totalValue = totalValue.add(itemValue.multiply(issuanceQuantity));
            }
        }
    }
    // take the average value of the issuances and multiply it by the shipment package content quantity
    value = totalValue.divide(totalIssued, 10, RoundingMode.HALF_EVEN).multiply(quantity);
    return value;
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) BigDecimal(java.math.BigDecimal)

Example 18 with GenericEntityException

use of org.apache.ofbiz.entity.GenericEntityException 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 19 with GenericEntityException

use of org.apache.ofbiz.entity.GenericEntityException 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)

Example 20 with GenericEntityException

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

the class InventoryServices method prepareInventoryTransfer.

public static Map<String, Object> prepareInventoryTransfer(DispatchContext dctx, Map<String, ? extends Object> context) {
    Delegator delegator = dctx.getDelegator();
    String inventoryItemId = (String) context.get("inventoryItemId");
    BigDecimal xferQty = (BigDecimal) context.get("xferQty");
    GenericValue inventoryItem = null;
    GenericValue newItem = null;
    GenericValue userLogin = (GenericValue) context.get("userLogin");
    Locale locale = (Locale) context.get("locale");
    try {
        inventoryItem = EntityQuery.use(delegator).from("InventoryItem").where("inventoryItemId", inventoryItemId).queryOne();
    } catch (GenericEntityException e) {
        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ProductNotFindInventoryItemWithId", locale) + inventoryItemId);
    }
    if (inventoryItem == null) {
        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ProductNotFindInventoryItemWithId", locale) + inventoryItemId);
    }
    try {
        Map<String, Object> results = ServiceUtil.returnSuccess();
        String inventoryType = inventoryItem.getString("inventoryItemTypeId");
        if ("NON_SERIAL_INV_ITEM".equals(inventoryType)) {
            BigDecimal atp = inventoryItem.getBigDecimal("availableToPromiseTotal");
            BigDecimal qoh = inventoryItem.getBigDecimal("quantityOnHandTotal");
            if (atp == null) {
                return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ProductInventoryItemATPNotAvailable", UtilMisc.toMap("inventoryItemId", inventoryItem.getString("inventoryItemId")), locale));
            }
            if (qoh == null) {
                qoh = atp;
            }
            // first make sure we have enough to cover the request transfer amount
            if (xferQty.compareTo(atp) > 0) {
                return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ProductInventoryItemATPIsNotSufficient", UtilMisc.toMap("inventoryItemId", inventoryItem.getString("inventoryItemId"), "atp", atp, "xferQty", xferQty), locale));
            }
            // however, if atp < qoh && atp == xferQty, then we still need to split; oh, but no need to check atp == xferQty in the second part because if it isn't greater and isn't less, then it is equal
            if (xferQty.compareTo(atp) < 0 || atp.compareTo(qoh) < 0) {
                BigDecimal negXferQty = xferQty.negate();
                // NOTE: new inventory items should always be created calling the
                // createInventoryItem service because in this way we are sure
                // that all the relevant fields are filled with default values.
                // However, the code here should work fine because all the values
                // for the new inventory item are inerited from the existing item.
                newItem = GenericValue.create(inventoryItem);
                newItem.set("availableToPromiseTotal", BigDecimal.ZERO);
                newItem.set("quantityOnHandTotal", BigDecimal.ZERO);
                delegator.createSetNextSeqId(newItem);
                results.put("inventoryItemId", newItem.get("inventoryItemId"));
                // TODO: how do we get this here: "inventoryTransferId", inventoryTransferId
                Map<String, Object> createNewDetailMap = UtilMisc.toMap("availableToPromiseDiff", xferQty, "quantityOnHandDiff", xferQty, "accountingQuantityDiff", xferQty, "inventoryItemId", newItem.get("inventoryItemId"), "userLogin", userLogin);
                Map<String, Object> createUpdateDetailMap = UtilMisc.toMap("availableToPromiseDiff", negXferQty, "quantityOnHandDiff", negXferQty, "accountingQuantityDiff", negXferQty, "inventoryItemId", inventoryItem.get("inventoryItemId"), "userLogin", userLogin);
                try {
                    Map<String, Object> resultNew = dctx.getDispatcher().runSync("createInventoryItemDetail", createNewDetailMap);
                    if (ServiceUtil.isError(resultNew)) {
                        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ProductInventoryItemDetailCreateProblem", UtilMisc.toMap("errorString", ""), locale), null, null, resultNew);
                    }
                    Map<String, Object> resultUpdate = dctx.getDispatcher().runSync("createInventoryItemDetail", createUpdateDetailMap);
                    if (ServiceUtil.isError(resultUpdate)) {
                        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ProductInventoryItemDetailCreateProblem", UtilMisc.toMap("errorString", ""), locale), null, null, resultUpdate);
                    }
                } catch (GenericServiceException e1) {
                    return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ProductInventoryItemDetailCreateProblem", UtilMisc.toMap("errorString", e1.getMessage()), locale));
                }
            } else {
                results.put("inventoryItemId", inventoryItem.get("inventoryItemId"));
            }
        } else if ("SERIALIZED_INV_ITEM".equals(inventoryType)) {
            if (!"INV_AVAILABLE".equals(inventoryItem.getString("statusId"))) {
                return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ProductSerializedInventoryNotAvailable", locale));
            }
        }
        // if newItem is not null, it is the item to be moved, otherwise the original inventoryItem is the one to be moved
        if ("NON_SERIAL_INV_ITEM".equals(inventoryType)) {
            // set the transfered inventory item's atp to 0 and the qoh to the xferQty; at this point atp and qoh will always be the same, so we can safely zero the atp for now
            GenericValue inventoryItemToClear = newItem == null ? inventoryItem : newItem;
            inventoryItemToClear.refresh();
            BigDecimal atp = inventoryItemToClear.get("availableToPromiseTotal") == null ? BigDecimal.ZERO : inventoryItemToClear.getBigDecimal("availableToPromiseTotal");
            if (atp.compareTo(BigDecimal.ZERO) != 0) {
                Map<String, Object> createDetailMap = UtilMisc.toMap("availableToPromiseDiff", atp.negate(), "inventoryItemId", inventoryItemToClear.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));
                }
            }
        } else if ("SERIALIZED_INV_ITEM".equals(inventoryType)) {
            // set the status to avoid re-moving or something
            if (newItem != null) {
                newItem.refresh();
                newItem.set("statusId", "INV_BEING_TRANSFERED");
                newItem.store();
                results.put("inventoryItemId", newItem.get("inventoryItemId"));
            } else {
                inventoryItem.refresh();
                inventoryItem.set("statusId", "INV_BEING_TRANSFERED");
                inventoryItem.store();
                results.put("inventoryItemId", inventoryItem.get("inventoryItemId"));
            }
        }
        return results;
    } catch (GenericEntityException e) {
        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ProductInventoryItemStoreProblem", 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) BigDecimal(java.math.BigDecimal)

Aggregations

GenericEntityException (org.apache.ofbiz.entity.GenericEntityException)913 GenericValue (org.apache.ofbiz.entity.GenericValue)847 Delegator (org.apache.ofbiz.entity.Delegator)599 Locale (java.util.Locale)384 HashMap (java.util.HashMap)336 GenericServiceException (org.apache.ofbiz.service.GenericServiceException)270 LocalDispatcher (org.apache.ofbiz.service.LocalDispatcher)259 LinkedList (java.util.LinkedList)231 BigDecimal (java.math.BigDecimal)213 Timestamp (java.sql.Timestamp)171 Map (java.util.Map)109 GeneralException (org.apache.ofbiz.base.util.GeneralException)95 EntityCondition (org.apache.ofbiz.entity.condition.EntityCondition)78 IOException (java.io.IOException)75 EntityListIterator (org.apache.ofbiz.entity.util.EntityListIterator)57 Security (org.apache.ofbiz.security.Security)54 ArrayList (java.util.ArrayList)48 EntityExpr (org.apache.ofbiz.entity.condition.EntityExpr)47 GenericTransactionException (org.apache.ofbiz.entity.transaction.GenericTransactionException)39 LinkedHashMap (java.util.LinkedHashMap)37