Skip to content

The complete open source platform to run your entire marketplace. Storefront, vendor panel, admin console, and integrations in one enterprise-grade platform you own.

fix(cart): allocate cart credit lines across split orders (#1728)

Viktor Holik2b06829294c6
diff --git a/integration-tests/helpers/split-order-checkout.ts b/integration-tests/helpers/split-order-checkout.ts
index a1e7f2669..33f9fc54e 100644
--- a/integration-tests/helpers/split-order-checkout.ts
+++ b/integration-tests/helpers/split-order-checkout.ts
@@ -1,5 +1,6 @@
import { MedusaContainer } from "@medusajs/framework/types"
import { ContainerRegistrationKeys } from "@medusajs/framework/utils"
+import { createCartCreditLinesWorkflow } from "@medusajs/medusa/core-flows"
import { MercurModules, SellerStatus } from "@mercurjs/types"
import { createVendorProduct } from "./create-product"
@@ -169,7 +170,16 @@ export const completeSplitOrderCheckout = async (
/** Checks out one cart holding every given offer; resolves to its split orders. */
export const completeSplitOrderGroupCheckout = async (
- opts: SplitOrderCheckoutOptions & { offerIds: string[] }
+ opts: SplitOrderCheckoutOptions & {
+ offerIds: string[]
+ creditLines?: {
+ amount: number
+ reference: string
+ reference_id: string
+ }[]
+ /** A cart fully covered by credit lines completes without a payment. */
+ skipPayment?: boolean
+ }
): Promise<{ id: string }[]> => {
const { container, api, storeHeaders } = opts
@@ -227,18 +237,30 @@ export const completeSplitOrderGroupCheckout = async (
)
}
- const paymentCollection = (
+ if (opts.creditLines?.length) {
+ await createCartCreditLinesWorkflow(container).run({
+ input: opts.creditLines.map((creditLine) => ({
+ ...creditLine,
+ cart_id: cart.id,
+ metadata: null,
+ })),
+ })
+ }
+
+ if (!opts.skipPayment) {
+ const paymentCollection = (
+ await api.post(
+ `/store/payment-collections`,
+ { cart_id: cart.id },
+ storeHeaders
+ )
+ ).data.payment_collection
await api.post(
- `/store/payment-collections`,
- { cart_id: cart.id },
+ `/store/payment-collections/${paymentCollection.id}/payment-sessions`,
+ { provider_id: "pp_system_default" },
storeHeaders
)
- ).data.payment_collection
- await api.post(
- `/store/payment-collections/${paymentCollection.id}/payment-sessions`,
- { provider_id: "pp_system_default" },
- storeHeaders
- )
+ }
const completeResp = await api.post(
`/store/carts/${cart.id}/complete`,
diff --git a/integration-tests/http/order/store/split-order-credit-lines.spec.ts b/integration-tests/http/order/store/split-order-credit-lines.spec.ts
new file mode 100644
index 000000000..22d353e13
--- /dev/null
+++ b/integration-tests/http/order/store/split-order-credit-lines.spec.ts
@@ -0,0 +1,272 @@
+import { medusaIntegrationTestRunner } from "@medusajs/test-utils"
+import {
+ IRegionModuleService,
+ ISalesChannelModuleService,
+ MedusaContainer,
+} from "@medusajs/framework/types"
+import { ContainerRegistrationKeys, Modules } from "@medusajs/framework/utils"
+import { createCustomerUser } from "../../../helpers/create-customer-user"
+import {
+ adminHeaders,
+ createAdminUser,
+ generatePublishableKey,
+ generateStoreHeaders,
+} from "../../../helpers/create-admin-user"
+import {
+ completeSplitOrderGroupCheckout,
+ seedSellerOfferWithShipping,
+} from "../../../helpers/split-order-checkout"
+
+jest.setTimeout(180000)
+
+const SELLER_A_TOTAL = 3000
+const SELLER_B_TOTAL = 4500
+
+medusaIntegrationTestRunner({
+ testSuite: ({ getContainer, api, dbConnection }) => {
+ describe("Split order credit lines", () => {
+ let appContainer: MedusaContainer
+ let sellerA: any
+ let sellerB: any
+ let storeHeaders: any
+ let customerEmail: string
+ let region: any
+ let salesChannel: any
+
+ beforeAll(async () => {
+ appContainer = getContainer()
+ })
+
+ beforeEach(async () => {
+ await createAdminUser(dbConnection, adminHeaders, appContainer)
+
+ const customerResult = await createCustomerUser(appContainer, {
+ email: "[email protected]",
+ first_name: "Credit",
+ last_name: "Buyer",
+ })
+ customerEmail = customerResult.customer.email!
+ const apiKey = await generatePublishableKey(appContainer)
+ storeHeaders = {
+ headers: {
+ ...generateStoreHeaders({ publishableKey: apiKey }).headers,
+ ...customerResult.headers.headers,
+ },
+ }
+
+ salesChannel = await appContainer
+ .resolve<ISalesChannelModuleService>(Modules.SALES_CHANNEL)
+ .createSalesChannels({ name: "Credit Channel" })
+
+ region = await appContainer
+ .resolve<IRegionModuleService>(Modules.REGION)
+ .createRegions({
+ name: "Credit Region",
+ currency_code: "usd",
+ countries: ["us"],
+ })
+
+ await appContainer
+ .resolve(ContainerRegistrationKeys.LINK)
+ .create({
+ [Modules.REGION]: { region_id: region.id },
+ [Modules.PAYMENT]: {
+ payment_provider_id: "pp_system_default",
+ },
+ })
+
+ sellerA = await seedSellerOfferWithShipping({
+ container: appContainer,
+ api,
+ salesChannelId: salesChannel.id,
+ email: "[email protected]",
+ name: "CreditA",
+ stocked: 20,
+ offerPrice: 2500,
+ })
+ sellerB = await seedSellerOfferWithShipping({
+ container: appContainer,
+ api,
+ salesChannelId: salesChannel.id,
+ email: "[email protected]",
+ name: "CreditB",
+ stocked: 20,
+ offerPrice: 4000,
+ })
+ })
+
+ const query = () =>
+ appContainer.resolve(ContainerRegistrationKeys.QUERY)
+
+ const getOrder = async (orderId: string) => {
+ const {
+ data: [order],
+ } = await query().graph({
+ entity: "order",
+ filters: { id: orderId },
+ fields: [
+ "id",
+ "total",
+ "credit_line_total",
+ "summary",
+ "credit_lines.amount",
+ "credit_lines.reference",
+ "credit_lines.reference_id",
+ "credit_lines.metadata",
+ "payment_collections.payments.captures.amount",
+ "cart.total",
+ "cart.credit_lines.id",
+ "cart.payment_collection.amount",
+ "cart.payment_collection.payments.id",
+ ],
+ })
+ return order as any
+ }
+
+ const checkout = async (
+ creditLines: { amount: number; reference_id: string }[],
+ options: { pay: boolean }
+ ) => {
+ const orders = await completeSplitOrderGroupCheckout({
+ container: appContainer,
+ api,
+ storeHeaders,
+ regionId: region.id,
+ salesChannelId: salesChannel.id,
+ offerIds: [sellerA.offer.id, sellerB.offer.id],
+ email: customerEmail,
+ creditLines: creditLines.map((line) => ({
+ ...line,
+ reference: "store_credit",
+ })),
+ skipPayment: !options.pay,
+ })
+
+ const { data: links } = await query().graph({
+ entity: "order_seller",
+ filters: { order_id: orders.map((o) => o.id) },
+ fields: ["order_id", "seller_id"],
+ })
+ const orderIdOf = (sellerId: string) =>
+ links.find((l: any) => l.seller_id === sellerId)
+ ?.order_id as string
+
+ return {
+ orderA: await getOrder(orderIdOf(sellerA.sellerId)),
+ orderB: await getOrder(orderIdOf(sellerB.sellerId)),
+ }
+ }
+
+ const creditAmount = (line: any) => Number(line.amount)
+
+ const eventually = async (assertion: () => Promise<void>) => {
+ const deadline = Date.now() + 15000
+ for (;;) {
+ try {
+ return await assertion()
+ } catch (error) {
+ if (Date.now() > deadline) {
+ throw error
+ }
+ await new Promise((r) => setTimeout(r, 250))
+ }
+ }
+ }
+
+ it("gives each order its share of a partial credit", async () => {
+ const { orderA, orderB } = await checkout(
+ [{ amount: 750, reference_id: "credit_1" }],
+ { pay: true }
+ )
+
+ expect(orderA.credit_lines.map(creditAmount)).toEqual([300])
+ expect(orderB.credit_lines.map(creditAmount)).toEqual([450])
+ expect(orderA.credit_lines).toEqual([
+ expect.objectContaining({
+ reference: "store_credit",
+ reference_id: "credit_1",
+ metadata: {
+ cart_credit_line_id: orderA.cart.credit_lines[0].id,
+ },
+ }),
+ ])
+ expect(orderB.credit_lines).toEqual([
+ expect.objectContaining({
+ reference: "store_credit",
+ reference_id: "credit_1",
+ }),
+ ])
+
+ expect(Number(orderA.total)).toEqual(SELLER_A_TOTAL - 300)
+ expect(Number(orderB.total)).toEqual(SELLER_B_TOTAL - 450)
+
+ const cartCollection = orderA.cart.payment_collection
+ expect(Number(orderA.total) + Number(orderB.total)).toEqual(
+ Number(cartCollection.amount)
+ )
+ })
+
+ it("settles both orders when the partial credit's payment is captured", async () => {
+ const { orderA, orderB } = await checkout(
+ [{ amount: 750, reference_id: "credit_1" }],
+ { pay: true }
+ )
+
+ await api.post(
+ `/admin/payments/${orderA.cart.payment_collection.payments[0].id}/capture`,
+ {},
+ adminHeaders
+ )
+
+ await eventually(async () => {
+ const paidA = await getOrder(orderA.id)
+ const paidB = await getOrder(orderB.id)
+
+ expect(
+ Number(paidA.payment_collections[0].payments[0].captures[0].amount)
+ ).toEqual(SELLER_A_TOTAL - 300)
+ expect(
+ Number(paidB.payment_collections[0].payments[0].captures[0].amount)
+ ).toEqual(SELLER_B_TOTAL - 450)
+ expect(Number(paidA.summary.pending_difference)).toEqual(0)
+ expect(Number(paidB.summary.pending_difference)).toEqual(0)
+ })
+ })
+
+ it("settles both orders with their credit lines when credit covers the whole cart", async () => {
+ const { orderA, orderB } = await checkout(
+ [{ amount: SELLER_A_TOTAL + SELLER_B_TOTAL, reference_id: "credit_1" }],
+ { pay: false }
+ )
+
+ expect(Number(orderA.credit_line_total)).toEqual(SELLER_A_TOTAL)
+ expect(Number(orderB.credit_line_total)).toEqual(SELLER_B_TOTAL)
+ expect(Number(orderA.total)).toEqual(0)
+ expect(Number(orderB.total)).toEqual(0)
+ expect(Number(orderA.summary.pending_difference)).toEqual(0)
+ expect(Number(orderB.summary.pending_difference)).toEqual(0)
+ })
+
+ it("splits every credit line of a cart that has several", async () => {
+ const { orderA, orderB } = await checkout(
+ [
+ { amount: 100, reference_id: "credit_1" },
+ { amount: 200, reference_id: "credit_2" },
+ ],
+ { pay: true }
+ )
+
+ const byReference = (order: any) =>
+ Object.fromEntries(
+ order.credit_lines.map((line: any) => [
+ line.reference_id,
+ creditAmount(line),
+ ])
+ )
+
+ expect(byReference(orderA)).toEqual({ credit_1: 40, credit_2: 80 })
+ expect(byReference(orderB)).toEqual({ credit_1: 60, credit_2: 120 })
+ })
+ })
+ },
+})
diff --git a/packages/core/src/workflows/cart/utils/__tests__/allocate-credit-lines.unit.spec.ts b/packages/core/src/workflows/cart/utils/__tests__/allocate-credit-lines.unit.spec.ts
new file mode 100644
index 000000000..0f4ba0811
--- /dev/null
+++ b/packages/core/src/workflows/cart/utils/__tests__/allocate-credit-lines.unit.spec.ts
@@ -0,0 +1,116 @@
+import { MathBN } from "@medusajs/framework/utils"
+
+import { allocateCreditLines } from "../allocate-credit-lines"
+
+const creditLine = (id: string, amount: number) => ({
+ id,
+ amount,
+ reference: "store_credit",
+ reference_id: `ref_${id}`,
+ metadata: { source: "loyalty" },
+})
+
+const amounts = (lines: { amount: unknown }[]) =>
+ lines.map((line) => MathBN.convert(line.amount as number).toNumber())
+
+const totalOf = (lines: { amount: unknown }[]) =>
+ amounts(lines).reduce((acc, amount) => acc + amount, 0)
+
+describe("allocateCreditLines", () => {
+ it("splits a credit line by each order's share of the total", () => {
+ const [a, b] = allocateCreditLines({
+ credit_lines: [creditLine("cl_1", 10)],
+ order_totals: [40, 60],
+ currency_code: "eur",
+ })
+
+ expect(amounts(a)).toEqual([4])
+ expect(amounts(b)).toEqual([6])
+ })
+
+ it("keeps the source of the credit on every share", () => {
+ const [a, b] = allocateCreditLines({
+ credit_lines: [creditLine("cl_1", 10)],
+ order_totals: [40, 60],
+ currency_code: "eur",
+ })
+
+ for (const [line] of [a, b]) {
+ expect(line).toEqual(
+ expect.objectContaining({
+ reference: "store_credit",
+ reference_id: "ref_cl_1",
+ metadata: { source: "loyalty", cart_credit_line_id: "cl_1" },
+ })
+ )
+ }
+ })
+
+ it("rounds to the currency precision and adds up to the credit line", () => {
+ const shares = allocateCreditLines({
+ credit_lines: [creditLine("cl_1", 10)],
+ order_totals: [1, 1, 1],
+ currency_code: "eur",
+ })
+
+ expect(shares.map(amounts)).toEqual([[3.34], [3.33], [3.33]])
+ })
+
+ it("respects currencies without minor units", () => {
+ const shares = allocateCreditLines({
+ credit_lines: [creditLine("cl_1", 100)],
+ order_totals: [1, 2],
+ currency_code: "jpy",
+ })
+
+ expect(shares.map(amounts)).toEqual([[33], [67]])
+ })
+
+ it("settles every order when several lines cover the whole cart", () => {
+ const totals = [33.33, 33.33, 33.34]
+ const shares = allocateCreditLines({
+ credit_lines: [
+ creditLine("cl_1", 0.01),
+ creditLine("cl_2", 0.02),
+ creditLine("cl_3", 99.97),
+ ],
+ order_totals: totals,
+ currency_code: "usd",
+ })
+
+ shares.forEach((lines, index) => {
+ expect(totalOf(lines)).toBeCloseTo(totals[index], 10)
+ })
+ })
+
+ it("gives a single order the credit line unchanged", () => {
+ const [only] = allocateCreditLines({
+ credit_lines: [creditLine("cl_1", 12.34)],
+ order_totals: [100],
+ currency_code: "usd",
+ })
+
+ expect(amounts(only)).toEqual([12.34])
+ })
+
+ it("leaves out a share that rounds to nothing", () => {
+ const [a, b] = allocateCreditLines({
+ credit_lines: [creditLine("cl_1", 10)],
+ order_totals: [0, 100],
+ currency_code: "usd",
+ })
+
+ expect(a).toEqual([])
+ expect(amounts(b)).toEqual([10])
+ })
+
+ it("allocates nothing for a cart without credit lines", () => {
+ expect(
+ allocateCreditLines({
+ credit_lines: [],
+ order_totals: [40, 60],
+ currency_code: "usd",
+ })
+ ).toEqual([[], []])
+ })
+})
diff --git a/packages/core/src/workflows/cart/utils/allocate-credit-lines.ts b/packages/core/src/workflows/cart/utils/allocate-credit-lines.ts
new file mode 100644
index 000000000..e71788f37
--- /dev/null
+++ b/packages/core/src/workflows/cart/utils/allocate-credit-lines.ts
@@ -0,0 +1,71 @@
+import { BigNumberInput } from "@medusajs/framework/types"
+import { MathBN } from "@medusajs/framework/utils"
+
+import {
+ allocateProportionally,
+ getCurrencyDecimalDigits,
+} from "../../payment/utils/split-order-payment"
+
+type CartCreditLine = {
+ id: string
+ amount: BigNumberInput
+ raw_amount?: BigNumberInput | null
+ reference?: string | null
+ reference_id?: string | null
+ metadata?: Record<string, unknown> | null
+}
+
+export type AllocatedCreditLine = {
+ amount: BigNumberInput
+ reference?: string | null
+ reference_id?: string | null
+ metadata: Record<string, unknown>
+}
+
+/**
+ * Splits a cart's credit lines across its orders by their totals before credit.
+ * Each line is weighted by what the earlier lines left of each order, so lines
+ * that together cover the cart settle every order rather than leaving rounding
+ * behind on one and overpaying another.
+ */
+export const allocateCreditLines = ({
+ credit_lines,
+ order_totals,
+ currency_code,
+}: {
+ credit_lines: CartCreditLine[]
+ order_totals: BigNumberInput[]
+ currency_code?: string | null
+}): AllocatedCreditLine[][] => {
+ const decimalDigits = getCurrencyDecimalDigits(currency_code)
+ const remaining = [...order_totals]
+ const allocated: AllocatedCreditLine[][] = order_totals.map(() => [])
+
+ for (const creditLine of credit_lines) {
+ const shares = allocateProportionally({
+ amount: creditLine.raw_amount ?? creditLine.amount,
+ weights: remaining,
+ decimalDigits,
+ })
+
+ shares.forEach((share, index) => {
+ remaining[index] = MathBN.sub(remaining[index], share)
+
+ if (MathBN.eq(share, 0)) {
+ return
+ }
+
+ allocated[index].push({
+ amount: share,
+ reference: creditLine.reference,
+ reference_id: creditLine.reference_id,
+ metadata: {
+ ...creditLine.metadata,
+ cart_credit_line_id: creditLine.id,
+ },
+ })
+ })
+ }
+
+ return allocated
+}
diff --git a/packages/core/src/workflows/cart/utils/index.ts b/packages/core/src/workflows/cart/utils/index.ts
index 54d485aa8..00481dc38 100644
--- a/packages/core/src/workflows/cart/utils/index.ts
+++ b/packages/core/src/workflows/cart/utils/index.ts
@@ -1,3 +1,4 @@
+export * from './allocate-credit-lines'
export * from './fields'
export * from './prepare-line-item-data'
export * from './schemas'
diff --git a/packages/core/src/workflows/cart/workflows/complete-cart-with-split-orders.ts b/packages/core/src/workflows/cart/workflows/complete-cart-with-split-orders.ts
index c3f524411..d49d94297 100644
--- a/packages/core/src/workflows/cart/workflows/complete-cart-with-split-orders.ts
+++ b/packages/core/src/workflows/cart/workflows/complete-cart-with-split-orders.ts
@@ -1,4 +1,5 @@
import {
+ BigNumberInput,
CartWorkflowDTO,
CreateOrderDTO,
LinkDefinition,
@@ -8,6 +9,7 @@ import {
} from "@medusajs/framework/types"
import {
generateEntityId,
+ MathBN,
Modules,
OrderStatus,
OrderWorkflowEvents,
@@ -42,6 +44,7 @@ import {
validateSellerCartShippingStep,
} from "../steps"
import {
+ allocateCreditLines,
completeCartFields,
isAdjustmentInSellerScope,
prepareAdjustmentsData,
@@ -261,12 +264,30 @@ export const completeCartWithSplitOrdersWorkflow = createWorkflow(
const ordersToCreate: (CreateOrderDTO & { id: string })[] = []
const offerIdsByOrderId: Record<string, (string | null)[]> = {}
- Array.from(cartSellerIds).map((sellerId) => {
- const sellerCartItems = (cart.items ?? []).filter(
+ const sellerIds = Array.from(cartSellerIds)
+ const itemsOfSeller = (sellerId: string) =>
+ (cart.items ?? []).filter(
(item: any) => item.offer?.seller_id === sellerId
)
+ const shippingMethodsOfSeller = (sellerId: string) => {
const sellerShippingOptions = sellerShippingOptionsMap.get(sellerId) ?? []
- const sellerCartShippingMethods = (cart.shipping_methods ?? []).filter((sm) => sellerShippingOptions.some((so) => so.id === sm.shipping_option_id))
+ return (cart.shipping_methods ?? []).filter((sm) => sellerShippingOptions.some((so) => so.id === sm.shipping_option_id))
+ }
+
+ const sellerCreditLines = allocateCreditLines({
+ credit_lines: cart.credit_lines ?? [],
+ order_totals: sellerIds.map((sellerId) =>
+ [...itemsOfSeller(sellerId), ...shippingMethodsOfSeller(sellerId)].reduce<BigNumberInput>(
+ (acc, line) => MathBN.add(acc, line.raw_total ?? line.total),
+ 0
+ )
+ ),
+ currency_code: cart.currency_code,
+ })
+
+ sellerIds.forEach((sellerId, sellerIndex) => {
+ const sellerCartItems = itemsOfSeller(sellerId)
+ const sellerCartShippingMethods = shippingMethodsOfSeller(sellerId)
const allItems = sellerCartItems.map((item) => {
const offerShippingProfileId = (
@@ -317,19 +338,6 @@ export const completeCartWithSplitOrdersWorkflow = createWorkflow(
}
})
- // todo: add credit lines support for child orders
- // const creditLines = (cart.credit_lines ?? []).map(
- // (creditLine: CartCreditLineDTO) => {
- // return {
- // amount: creditLine.amount,
- // raw_amount: creditLine.raw_amount,
- // reference: creditLine.reference,
- // reference_id: creditLine.reference_id,
- // metadata: creditLine.metadata,
- // }
- // }
- // )
-
const itemAdjustments = allItems
.map((item) => item.adjustments ?? [])
.flat(1)
@@ -378,8 +386,10 @@ export const completeCartWithSplitOrdersWorkflow = createWorkflow(
shipping_methods: shippingMethods,
metadata: cart.metadata,
promo_codes: promoCodes,
- // todo: add credit lines support for child orders
- credit_lines: [],
+ credit_lines: sellerCreditLines[sellerIndex].map((creditLine) => ({
+ ...creditLine,
+ order_id: orderId,
+ })),
})
sellerOrdersMap[sellerId] = orderId