UNPKG

@medusajs/core-flows

Version:

Set of workflow definitions for Medusa

61 lines 2.74 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.validateShippingStep = exports.validateShippingStepId = void 0; const utils_1 = require("@medusajs/framework/utils"); const workflows_sdk_1 = require("@medusajs/workflows-sdk"); exports.validateShippingStepId = "validate-shipping"; /** * This step validates shipping data when cart is completed. * * It ensures that a shipping method is selected if there is an item in the cart that requires shipping. * It also ensures that product's shipping profile mathes the selected shipping options. If the * conditions are not met, an error is thrown. * * :::note * * You can retrieve cart or shipping option's details using [Query](https://docs.medusajs.com/learn/fundamentals/module-links/query), * or [useQueryGraphStep](https://docs.medusajs.com/resources/references/medusa-workflows/steps/useQueryGraphStep). * * ::: * * @example * validateShippingStep({ * cart: { * id: "cart_123", * items: [ * { * id: "item_123", * variant: { * id: "variant_123", * // other item details... * }, * } * ], * // other cart details... * }, * shippingOptions: [ * { * id: "option_123", * shipping_profile_id: "sp_123", * // other option details... * } * ] * }) */ exports.validateShippingStep = (0, workflows_sdk_1.createStep)(exports.validateShippingStepId, async (data) => { const { cart, shippingOptions } = data; const optionProfileMap = new Map(shippingOptions.map((option) => [option.id, option.shipping_profile_id])); const cartItemsWithShipping = cart.items?.filter((item) => item.requires_shipping) || []; const cartShippingMethods = cart.shipping_methods || []; if (cartItemsWithShipping.length > 0 && cartShippingMethods.length === 0) { throw new utils_1.MedusaError(utils_1.MedusaError.Types.INVALID_DATA, "No shipping method selected but the cart contains items that require shipping."); } const requiredShippingPorfiles = cartItemsWithShipping.map((item) => item.variant.product?.shipping_profile?.id); const availableShippingPorfiles = cartShippingMethods.map((method) => optionProfileMap.get(method.shipping_option_id)); const missingShippingPorfiles = requiredShippingPorfiles.filter((profile) => !availableShippingPorfiles.includes(profile)); if (missingShippingPorfiles.length > 0) { throw new utils_1.MedusaError(utils_1.MedusaError.Types.INVALID_DATA, "The cart items require shipping profiles that are not satisfied by the current shipping methods"); } return new workflows_sdk_1.StepResponse(void 0); }); //# sourceMappingURL=validate-shipping.js.map