feat(core-flows,framework,medusa): list shipping options pass in cart as pricing context (#10374)

* feat(core-flows,framework,medusa): list shipping options pass in cart as pricing context

* chore: add test for shipping options returning free shipping
This commit is contained in:
Riqwan Thamir
2024-12-01 20:59:26 +01:00
committed by GitHub
parent eacd691951
commit 11bd556133
12 changed files with 284 additions and 156 deletions
+7
View File
@@ -0,0 +1,7 @@
---
"@medusajs/core-flows": patch
"@medusajs/framework": patch
"@medusajs/medusa": patch
---
feat(core-flows,framework,medusa): list shipping options pass in cart as pricing context
@@ -152,12 +152,12 @@ medusaIntegrationTestRunner({
amount: 500,
rules: [
{
attribute: "cart_total",
attribute: "total",
operator: "gte",
value: 100,
},
{
attribute: "cart_total",
attribute: "total",
operator: "lte",
value: 200,
},
@@ -218,12 +218,12 @@ medusaIntegrationTestRunner({
rules_count: 2,
price_rules: expect.arrayContaining([
expect.objectContaining({
attribute: "cart_total",
attribute: "total",
operator: "gte",
value: "100",
}),
expect.objectContaining({
attribute: "cart_total",
attribute: "total",
operator: "lte",
value: "200",
}),
@@ -327,7 +327,7 @@ medusaIntegrationTestRunner({
amount: 500,
rules: [
{
attribute: "cart_total",
attribute: "total",
operator: "gt",
value: 200,
},
@@ -378,7 +378,7 @@ medusaIntegrationTestRunner({
rules_count: 2,
price_rules: expect.arrayContaining([
expect.objectContaining({
attribute: "cart_total",
attribute: "total",
operator: "gt",
value: "200",
}),
@@ -458,7 +458,7 @@ medusaIntegrationTestRunner({
amount: 500,
rules: [
{
attribute: "cart_total",
attribute: "total",
operator: "not_whitelisted",
value: 100,
},
@@ -496,7 +496,7 @@ medusaIntegrationTestRunner({
amount: 500,
rules: [
{
attribute: "cart_total",
attribute: "total",
operator: "gt",
value: "string",
},
@@ -626,7 +626,7 @@ medusaIntegrationTestRunner({
amount: 5,
rules: [
{
attribute: "cart_total",
attribute: "total",
operator: "gt",
value: 200,
},
@@ -702,7 +702,7 @@ medusaIntegrationTestRunner({
amount: 5,
price_rules: [
expect.objectContaining({
attribute: "cart_total",
attribute: "total",
operator: "gt",
value: "200",
}),
@@ -190,6 +190,17 @@ medusaIntegrationTestRunner({
region_id: region.id,
amount: 1100,
},
{
region_id: region.id,
amount: 0,
rules: [
{
operator: "gt",
attribute: "total",
value: 2000,
},
],
},
{
region_id: regionTwo.id,
amount: 500,
@@ -266,6 +277,83 @@ medusaIntegrationTestRunner({
})
)
})
it("should return prices based on cart total", async () => {
cart = (
await api.post(
`/store/carts`,
{
region_id: region.id,
sales_channel_id: salesChannel.id,
currency_code: "usd",
email: "test@admin.com",
items: [
{
variant_id: product.variants[0].id,
// Adding a quantity of 100 to emulate total being greater than 2000
quantity: 100,
},
],
},
storeHeaders
)
).data.cart
const resp = await api.get(
`/store/shipping-options?cart_id=${cart.id}`,
storeHeaders
)
const shippingOptions = resp.data.shipping_options
expect(shippingOptions).toHaveLength(1)
expect(shippingOptions[0]).toEqual(
expect.objectContaining({
id: shippingOption.id,
name: "Test shipping option",
// Free shipping due to cart total being greater than 2000
amount: 0,
price_type: "flat",
})
)
})
it("should throw when required fields of a cart are not present", async () => {
cart = (
await api.post(
`/store/carts`,
{
region_id: region.id,
currency_code: "usd",
sales_channel_id: null,
email: "test@admin.com",
items: [],
},
storeHeaders
)
).data.cart
const { response } = await api
.get(`/store/shipping-options?cart_id=${cart.id}`, storeHeaders)
.catch((e) => e)
expect(response.data).toEqual({
type: "invalid_data",
message:
"Field(s) are required to have value to continue - sales_channel_id",
})
})
it("should throw error when cart_id is not passed as a parameter", async () => {
const { response } = await api
.get(`/store/shipping-options`, storeHeaders)
.catch((e) => e)
expect(response.data).toEqual({
type: "invalid_data",
message: "Invalid request: Field 'cart_id' is required",
})
})
})
})
},
@@ -13,6 +13,7 @@ import {
updatePaymentCollectionStepId,
updateTaxLinesWorkflow,
} from "@medusajs/core-flows"
import { medusaIntegrationTestRunner } from "@medusajs/test-utils"
import {
ICartModuleService,
ICustomerModuleService,
@@ -30,7 +31,6 @@ import {
Modules,
RuleOperator,
} from "@medusajs/utils"
import { medusaIntegrationTestRunner } from "@medusajs/test-utils"
import {
adminHeaders,
createAdminUser,
@@ -1835,6 +1835,15 @@ medusaIntegrationTestRunner({
})
describe("listShippingOptionsForCartWorkflow", () => {
let region
beforeEach(async () => {
region = await regionModuleService.createRegions({
name: "US",
currency_code: "usd",
})
})
it("should list shipping options for cart", async () => {
const salesChannel = await scModuleService.createSalesChannels({
name: "Webshop",
@@ -1846,6 +1855,7 @@ medusaIntegrationTestRunner({
let cart = await cartModuleService.createCarts({
currency_code: "usd",
region_id: region.id,
sales_channel_id: salesChannel.id,
shipping_address: {
city: "CPH",
@@ -1935,13 +1945,6 @@ medusaIntegrationTestRunner({
).run({
input: {
cart_id: cart.id,
sales_channel_id: salesChannel.id,
currency_code: "usd",
shipping_address: {
city: cart.shipping_address?.city,
province: cart.shipping_address?.province,
country_code: cart.shipping_address?.country_code,
},
},
})
@@ -1965,6 +1968,7 @@ medusaIntegrationTestRunner({
let cart = await cartModuleService.createCarts({
currency_code: "usd",
region_id: region.id,
sales_channel_id: salesChannel.id,
shipping_address: {
city: "CPH",
@@ -2044,16 +2048,7 @@ medusaIntegrationTestRunner({
const { result } = await listShippingOptionsForCartWorkflow(
appContainer
).run({
input: {
cart_id: cart.id,
sales_channel_id: salesChannel.id,
currency_code: "usd",
shipping_address: {
city: cart.shipping_address?.city,
province: cart.shipping_address?.province,
country_code: cart.shipping_address?.country_code,
},
},
input: { cart_id: cart.id },
})
expect(result).toEqual([])
@@ -2070,6 +2065,7 @@ medusaIntegrationTestRunner({
let cart = await cartModuleService.createCarts({
currency_code: "usd",
region_id: region.id,
sales_channel_id: salesChannel.id,
shipping_address: {
city: "CPH",
@@ -2140,16 +2136,7 @@ medusaIntegrationTestRunner({
const { errors } = await listShippingOptionsForCartWorkflow(
appContainer
).run({
input: {
cart_id: cart.id,
sales_channel_id: salesChannel.id,
currency_code: "usd",
shipping_address: {
city: cart.shipping_address?.city,
province: cart.shipping_address?.province,
country_code: cart.shipping_address?.country_code,
},
},
input: { cart_id: cart.id },
throwOnError: false,
})
@@ -1,11 +1,12 @@
import { ListShippingOptionsForCartWorkflowInputDTO } from "@medusajs/framework/types"
import { deepFlatMap, isPresent, MedusaError } from "@medusajs/framework/utils"
import {
createWorkflow,
transform,
when,
WorkflowData,
WorkflowResponse,
} from "@medusajs/framework/workflows-sdk"
import { useQueryGraphStep, validatePresenceOfStep } from "../../common"
import { useRemoteQueryStep } from "../../common/steps/use-remote-query"
export const listShippingOptionsForCartWorkflowId =
@@ -15,26 +16,52 @@ export const listShippingOptionsForCartWorkflowId =
*/
export const listShippingOptionsForCartWorkflow = createWorkflow(
listShippingOptionsForCartWorkflowId,
(input: WorkflowData<ListShippingOptionsForCartWorkflowInputDTO>) => {
const scLocationFulfillmentSets = useRemoteQueryStep({
entry_point: "sales_channels",
(input: WorkflowData<{ cart_id: string; is_return?: boolean }>) => {
const cartQuery = useQueryGraphStep({
entity: "cart",
filters: { id: input.cart_id },
fields: [
"id",
"sales_channel_id",
"currency_code",
"region_id",
"shipping_address.city",
"shipping_address.country_code",
"shipping_address.province",
"total",
],
options: { throwIfKeyNotFound: true },
}).config({ name: "get-cart" })
const cart = transform({ cartQuery }, ({ cartQuery }) => cartQuery.data[0])
validatePresenceOfStep({
entity: cart,
fields: ["sales_channel_id", "region_id", "currency_code"],
})
const scFulfillmentSetQuery = useQueryGraphStep({
entity: "sales_channels",
filters: { id: cart.sales_channel_id },
fields: ["stock_locations.fulfillment_sets.id"],
variables: {
id: input.sales_channel_id,
},
}).config({ name: "sales_channels-fulfillment-query" })
const scFulfillmentSets = transform(
{ scFulfillmentSetQuery },
({ scFulfillmentSetQuery }) => scFulfillmentSetQuery.data[0]
)
const fulfillmentSetIds = transform(
{ options: scLocationFulfillmentSets },
{ options: scFulfillmentSets },
(data) => {
const fulfillmentSetIds = new Set<string>()
deepFlatMap(
data.options,
"stock_locations.fulfillment_sets",
({ fulfillment_sets }) => {
if (fulfillment_sets?.id) {
fulfillmentSetIds.add(fulfillment_sets.id)
({ fulfillment_sets: fulfillmentSet }) => {
if (fulfillmentSet?.id) {
fulfillmentSetIds.add(fulfillmentSet.id)
}
}
)
@@ -43,6 +70,36 @@ export const listShippingOptionsForCartWorkflow = createWorkflow(
}
)
const customerGroupIds = when({ cart }, ({ cart }) => {
return !!cart.id
}).then(() => {
const customerQuery = useQueryGraphStep({
entity: "customer",
filters: { id: cart.customer_id },
fields: ["groups.id"],
}).config({ name: "get-customer" })
return transform({ customerQuery }, ({ customerQuery }) => {
const customer = customerQuery.data[0]
if (!isPresent(customer)) {
return []
}
const { groups = [] } = customer
return groups.map((group) => group.id)
})
})
const pricingContext = transform(
{ cart, customerGroupIds },
({ cart, customerGroupIds }) => ({
...cart,
customer_group_id: customerGroupIds,
})
)
const shippingOptions = useRemoteQueryStep({
entry_point: "shipping_options",
fields: [
@@ -71,61 +128,53 @@ export const listShippingOptionsForCartWorkflow = createWorkflow(
],
variables: {
context: {
is_return: input.is_return,
is_return: !!input.is_return,
enabled_in_store: "true",
},
filters: {
fulfillment_set_id: fulfillmentSetIds,
address: {
city: input.shipping_address?.city,
country_code: input.shipping_address?.country_code,
province_code: input.shipping_address?.province,
city: cart.shipping_address?.city,
country_code: cart.shipping_address?.country_code,
province_code: cart.shipping_address?.province,
},
},
calculated_price: {
context: {
currency_code: input.currency_code,
region_id: input.region_id,
},
context: pricingContext,
},
},
}).config({ name: "shipping-options-query" })
const shippingOptionsWithPrice = transform(
{
shippingOptions,
},
(data) => {
const optionsMissingPrices: string[] = []
const shippingOptionsWithPrice = transform({ shippingOptions }, (data) => {
const optionsMissingPrices: string[] = []
const options = data.shippingOptions.map((shippingOption) => {
const { calculated_price, ...options } = shippingOption ?? {}
const options = data.shippingOptions.map((shippingOption) => {
const { calculated_price, ...options } = shippingOption ?? {}
if (options?.id && !isPresent(calculated_price?.calculated_amount)) {
optionsMissingPrices.push(options.id)
}
return {
...options,
amount: calculated_price?.calculated_amount,
is_tax_inclusive:
!!calculated_price?.is_calculated_price_tax_inclusive,
}
})
if (optionsMissingPrices.length) {
throw new MedusaError(
MedusaError.Types.INVALID_DATA,
`Shipping options with IDs ${optionsMissingPrices.join(
", "
)} do not have a price`
)
if (options?.id && !isPresent(calculated_price?.calculated_amount)) {
optionsMissingPrices.push(options.id)
}
return options
return {
...options,
amount: calculated_price?.calculated_amount,
is_tax_inclusive:
!!calculated_price?.is_calculated_price_tax_inclusive,
}
})
if (optionsMissingPrices.length) {
const ids = optionsMissingPrices.join(", ")
throw new MedusaError(
MedusaError.Types.INVALID_DATA,
`Shipping options with IDs ${ids} do not have a price`
)
}
)
return options
})
return new WorkflowResponse(shippingOptionsWithPrice)
}
+2 -1
View File
@@ -1,10 +1,11 @@
export * from "./steps/create-remote-links"
export * from "./steps/dismiss-remote-links"
export * from "./steps/remove-remote-links"
export * from "./steps/emit-event"
export * from "./steps/remove-remote-links"
export * from "./steps/update-remote-links"
export * from "./steps/use-query-graph"
export * from "./steps/use-remote-query"
export * from "./steps/validate-presence-of"
export * from "./workflows/batch-links"
export * from "./workflows/create-links"
export * from "./workflows/dismiss-links"
@@ -0,0 +1,33 @@
import { isPresent, MedusaError } from "@medusajs/framework/utils"
import { createStep } from "@medusajs/framework/workflows-sdk"
/**
* This step validates the presence of attributes on an object
*/
export const validatePresenceOfStep = createStep(
"validate-presence-of",
async function ({
entity,
fields,
}: {
entity: Record<any, unknown>
fields: string[]
}) {
const invalid: string[] = []
for (const field of fields) {
if (!isPresent(entity[field])) {
invalid.push(field)
}
}
if (invalid.length) {
const invalidFields = invalid.join(", ")
throw new MedusaError(
MedusaError.Types.INVALID_DATA,
`Field(s) are required to have value to continue - ${invalidFields}`
)
}
}
)
+6 -10
View File
@@ -90,16 +90,12 @@ export type GlobalMiddlewareDescriptor = {
config?: MiddlewaresConfig
}
export interface MedusaRequest<Body = unknown>
extends Request<
{
[key: string]: string
},
any,
Body
> {
export interface MedusaRequest<
Body = unknown,
QueryFields = Record<string, unknown>
> extends Request<{ [key: string]: string }, any, Body> {
validatedBody: Body
validatedQuery: RequestQueryFields & Record<string, unknown>
validatedQuery: RequestQueryFields & QueryFields
/**
* TODO: shouldn't this correspond to returnable fields instead of allowed fields? also it is used by the cleanResponseData util
*/
@@ -122,7 +118,7 @@ export interface MedusaRequest<Body = unknown>
/**
* An object containing the fields that are filterable e.g `{ id: Any<String> }`
*/
filterableFields: Record<string, unknown>
filterableFields: QueryFields
includes?: Record<string, boolean>
/**
@@ -86,7 +86,7 @@ export const AdminCreateShippingOptionTypeObject = z
const AdminPriceRules = z.array(
z.object({
attribute: z.literal("cart_total"),
attribute: z.literal("total"),
operator: z.nativeEnum(PricingRuleOperator),
value: z.number(),
})
@@ -1,52 +1,17 @@
import { listShippingOptionsForCartWorkflow } from "@medusajs/core-flows"
import { MedusaRequest, MedusaResponse } from "@medusajs/framework/http"
import { HttpTypes, ICartModuleService } from "@medusajs/framework/types"
import { MedusaError, Modules } from "@medusajs/framework/utils"
import { StoreGetShippingOptionsType } from "./validators"
import { HttpTypes } from "@medusajs/framework/types"
export const GET = async (
req: MedusaRequest<HttpTypes.StoreGetShippingOptionList>,
req: MedusaRequest<{}, HttpTypes.StoreGetShippingOptionList>,
res: MedusaResponse<HttpTypes.StoreShippingOptionListResponse>
) => {
const { cart_id, is_return } =
req.filterableFields as StoreGetShippingOptionsType
const { cart_id, is_return } = req.filterableFields
if (!cart_id) {
throw new MedusaError(
MedusaError.Types.NOT_ALLOWED,
"You must provide the cart_id to list shipping options"
)
}
const cartService = req.scope.resolve<ICartModuleService>(Modules.CART)
const cart = await cartService.retrieveCart(cart_id, {
select: [
"id",
"sales_channel_id",
"currency_code",
"region_id",
"shipping_address.city",
"shipping_address.country_code",
"shipping_address.province",
],
relations: ["shipping_address"],
const workflow = listShippingOptionsForCartWorkflow(req.scope)
const { result: shipping_options } = await workflow.run({
input: { cart_id, is_return: !!is_return },
})
const { result } = await listShippingOptionsForCartWorkflow(req.scope).run({
input: {
cart_id: cart.id,
sales_channel_id: cart.sales_channel_id,
currency_code: cart.currency_code,
region_id: cart.region_id,
is_return: !!is_return,
shipping_address: {
city: cart.shipping_address?.city,
country_code: cart.shipping_address?.country_code,
province: cart.shipping_address?.province,
},
},
})
res.json({ shipping_options: result })
res.json({ shipping_options })
}
@@ -1,11 +1,13 @@
import { z } from "zod"
import { createFindParams } from "../../utils/validators"
import { applyAndAndOrOperators } from "../../utils/common-validators"
import { createFindParams } from "../../utils/validators"
export const StoreGetShippingOptionsFields = z.object({
cart_id: z.string(),
is_return: z.boolean().optional(),
})
export const StoreGetShippingOptionsFields = z
.object({
cart_id: z.string(),
is_return: z.boolean().optional(),
})
.strict()
export type StoreGetShippingOptionsType = z.infer<
typeof StoreGetShippingOptions
@@ -1870,7 +1870,7 @@ moduleIntegrationTestRunner<IPricingModuleService>({
currency_code: "usd",
rules: {
region_id: "de",
cart_total: withOperator("between", 300, 400),
total: withOperator("between", 300, 400),
},
},
{
@@ -1878,7 +1878,7 @@ moduleIntegrationTestRunner<IPricingModuleService>({
currency_code: "usd",
rules: {
region_id: "de",
cart_total: withOperator("betweenEquals", 400, 500),
total: withOperator("betweenEquals", 400, 500),
},
},
{
@@ -1886,7 +1886,7 @@ moduleIntegrationTestRunner<IPricingModuleService>({
currency_code: "usd",
rules: {
region_id: "de",
cart_total: withOperator("excludingMin", 500, 600),
total: withOperator("excludingMin", 500, 600),
},
},
{
@@ -1894,7 +1894,7 @@ moduleIntegrationTestRunner<IPricingModuleService>({
currency_code: "usd",
rules: {
region_id: "de",
cart_total: withOperator("excludingMax", 600, 700),
total: withOperator("excludingMax", 600, 700),
},
},
],
@@ -1906,7 +1906,7 @@ moduleIntegrationTestRunner<IPricingModuleService>({
context: {
currency_code: "usd",
region_id: "de",
cart_total: 350,
total: 350,
},
}
)
@@ -1951,7 +1951,7 @@ moduleIntegrationTestRunner<IPricingModuleService>({
context: {
currency_code: "usd",
region_id: "de",
cart_total: 300,
total: 300,
},
}
)
@@ -1964,7 +1964,7 @@ moduleIntegrationTestRunner<IPricingModuleService>({
context: {
currency_code: "usd",
region_id: "de",
cart_total: 400,
total: 400,
},
}
)
@@ -1979,7 +1979,7 @@ moduleIntegrationTestRunner<IPricingModuleService>({
context: {
currency_code: "usd",
region_id: "de",
cart_total: 500,
total: 500,
},
}
)
@@ -1994,7 +1994,7 @@ moduleIntegrationTestRunner<IPricingModuleService>({
context: {
currency_code: "usd",
region_id: "de",
cart_total: 501,
total: 501,
},
}
)
@@ -2009,7 +2009,7 @@ moduleIntegrationTestRunner<IPricingModuleService>({
context: {
currency_code: "usd",
region_id: "de",
cart_total: 601,
total: 601,
},
}
)
@@ -2024,7 +2024,7 @@ moduleIntegrationTestRunner<IPricingModuleService>({
context: {
currency_code: "usd",
region_id: "de",
cart_total: 900,
total: 900,
},
}
)