@pradip1995/segment-primitives 0.4.10 → 0.4.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pradip1995/segment-primitives",
3
- "version": "0.4.10",
3
+ "version": "0.4.11",
4
4
  "license": "MIT",
5
5
  "publishConfig": {
6
6
  "access": "public"
@@ -20,7 +20,13 @@
20
20
  "./section-variants": "./src/section-variants.ts",
21
21
  "./product-variants": "./src/product-variants.ts",
22
22
  "./product-selection-context": "./src/product-selection-context.tsx",
23
- "./is-next-redirect": "./src/is-next-redirect.ts"
23
+ "./is-next-redirect": "./src/is-next-redirect.ts",
24
+ "./order-lines": "./src/order-lines.ts"
25
+ },
26
+ "scripts": {
27
+ "typecheck": "tsc --noEmit",
28
+ "lint": "tsc --noEmit",
29
+ "test": "npx tsx --test src/order-lines.test.ts"
24
30
  },
25
31
  "peerDependencies": {
26
32
  "@medusajs/types": "^2.0.0",
@@ -36,10 +42,5 @@
36
42
  "@types/react": "^19",
37
43
  "react": "19.0.3",
38
44
  "typescript": "^5.7.2"
39
- },
40
- "scripts": {
41
- "typecheck": "tsc --noEmit",
42
- "lint": "tsc --noEmit",
43
- "test": "node --experimental-strip-types --test src/*.test.ts"
44
45
  }
45
- }
46
+ }
@@ -4,12 +4,10 @@ import { useState } from "react"
4
4
  import { useRouter } from "next/navigation"
5
5
  import type { HttpTypes } from "@medusajs/types"
6
6
  import { formatPrice } from "./format-price"
7
- import { couponApplyKind, couponApplyMessage } from "./coupon-apply-result"
8
7
 
9
8
  // Use require to prevent TS from attempting to typecheck the raw .ts files published in commerce-core
10
- const { applyPromotions, retrieveCart } = require("@pradip1995/commerce-core/client/actions/cart") as {
9
+ const { applyPromotions } = require("@pradip1995/commerce-core/client/actions/cart") as {
11
10
  applyPromotions: (codes: string[], cartId: string) => Promise<any>
12
- retrieveCart: (cartId?: string) => Promise<any>
13
11
  }
14
12
 
15
13
  type CouponApplyProps = {
@@ -79,10 +77,13 @@ export default function CouponApply({ cart, className = "" }: CouponApplyProps)
79
77
 
80
78
  try {
81
79
  const updatedCart = await applyPromotions(codes, cart.id)
82
- const freshCart = (await retrieveCart(cart.id).catch(() => null)) ?? updatedCart
83
- const { error, success } = couponApplyMessage(couponApplyKind(freshCart))
84
- setErrorMessage(error)
85
- setSuccessMessage(success)
80
+ const hasDiscount = (updatedCart?.discount_total ?? 0) > 0
81
+
82
+ if (hasDiscount) {
83
+ setSuccessMessage("Coupon applied successfully!")
84
+ } else {
85
+ setErrorMessage("Coupon added, but it doesn't apply to the items in your bag.")
86
+ }
86
87
  setCode("")
87
88
  refreshCart()
88
89
  } catch {
package/src/index.ts CHANGED
@@ -2,3 +2,8 @@ export { default as LocalizedLink } from "./localized-link"
2
2
  export { default as CouponApply } from "./coupon-apply"
3
3
  export { Button } from "./Button"
4
4
  export { Card } from "./Card"
5
+ export {
6
+ isInboundExchangeItem,
7
+ outboundExchangeItemIds,
8
+ presentOrderLines,
9
+ } from "./order-lines"
@@ -0,0 +1,99 @@
1
+ import assert from "node:assert/strict"
2
+ import test from "node:test"
3
+ import { outboundExchangeItemIds, presentOrderLines } from "./order-lines"
4
+
5
+ const originalRing = {
6
+ id: "ordli_ring_8",
7
+ product_id: "prod_ring",
8
+ variant_id: "var_8",
9
+ quantity: 1,
10
+ total: 100,
11
+ created_at: "2026-08-27T12:39:21.453Z",
12
+ detail: {
13
+ fulfilled_quantity: 1,
14
+ delivered_quantity: 1,
15
+ return_requested_quantity: 1,
16
+ returned_quantity: 0,
17
+ },
18
+ }
19
+
20
+ const pendant = {
21
+ id: "ordli_pendant",
22
+ product_id: "prod_pendant",
23
+ variant_id: "var_default",
24
+ quantity: 1,
25
+ total: 869,
26
+ created_at: "2026-08-27T12:39:21.453Z",
27
+ detail: {
28
+ fulfilled_quantity: 1,
29
+ delivered_quantity: 1,
30
+ return_requested_quantity: 0,
31
+ returned_quantity: 0,
32
+ },
33
+ }
34
+
35
+ const replacementRing = {
36
+ id: "ordli_ring_7",
37
+ product_id: "prod_ring",
38
+ variant_id: "var_7",
39
+ quantity: 1,
40
+ total: 100,
41
+ created_at: "2026-08-27T12:41:36.022Z",
42
+ detail: {
43
+ fulfilled_quantity: 0,
44
+ delivered_quantity: 0,
45
+ return_requested_quantity: 0,
46
+ returned_quantity: 0,
47
+ },
48
+ }
49
+
50
+ test("hides the exchange replacement from purchased items and paid total", () => {
51
+ const view = presentOrderLines({
52
+ items: [originalRing, pendant, replacementRing],
53
+ shipping_total: 0,
54
+ total: 1069,
55
+ })
56
+
57
+ assert.deepEqual(
58
+ view.purchasedItems.map((item) => item.id),
59
+ ["ordli_ring_8", "ordli_pendant"]
60
+ )
61
+ assert.deepEqual(
62
+ view.outboundItems.map((item) => item.id),
63
+ ["ordli_ring_7"]
64
+ )
65
+ assert.equal(view.paidTotal, 969)
66
+ assert.equal(view.hasActiveExchange, true)
67
+ assert.equal(view.reorderItems.length, 2)
68
+ })
69
+
70
+ test("uses exchange additional_items when present", () => {
71
+ const ids = outboundExchangeItemIds(
72
+ [originalRing, pendant, replacementRing],
73
+ [{ additional_items: [{ item_id: "ordli_ring_7" }] }]
74
+ )
75
+ assert.deepEqual([...ids], ["ordli_ring_7"])
76
+ })
77
+
78
+ test("does not treat a second original size of the same product as the replacement", () => {
79
+ const originalSize7 = {
80
+ ...replacementRing,
81
+ id: "ordli_ring_7_original",
82
+ created_at: originalRing.created_at,
83
+ detail: {
84
+ fulfilled_quantity: 1,
85
+ delivered_quantity: 1,
86
+ return_requested_quantity: 0,
87
+ returned_quantity: 0,
88
+ },
89
+ }
90
+ const view = presentOrderLines({
91
+ items: [originalRing, originalSize7],
92
+ shipping_total: 0,
93
+ })
94
+ assert.deepEqual(
95
+ view.purchasedItems.map((item) => item.id),
96
+ ["ordli_ring_8", "ordli_ring_7_original"]
97
+ )
98
+ assert.equal(view.outboundItems.length, 0)
99
+ })
@@ -0,0 +1,151 @@
1
+ export type OrderLineQuantities = {
2
+ fulfilled_quantity?: number | null
3
+ delivered_quantity?: number | null
4
+ return_requested_quantity?: number | null
5
+ returned_quantity?: number | null
6
+ }
7
+
8
+ export type OrderLineLike = {
9
+ id: string
10
+ product_id?: string | null
11
+ variant_id?: string | null
12
+ quantity?: number | null
13
+ total?: number | null
14
+ unit_price?: number | null
15
+ created_at?: string | Date | null
16
+ detail?: OrderLineQuantities | null
17
+ } & OrderLineQuantities
18
+
19
+ export type OrderExchangeLike = {
20
+ canceled_at?: string | Date | null
21
+ additional_items?: Array<{ id?: string | null; item_id?: string | null }> | null
22
+ }
23
+
24
+ export type OrderLike = {
25
+ items?: OrderLineLike[] | null
26
+ shipping_total?: number | null
27
+ total?: number | null
28
+ exchanges?: OrderExchangeLike[] | null
29
+ }
30
+
31
+ function qty(value?: number | null): number {
32
+ const n = Number(value)
33
+ return Number.isFinite(n) ? n : 0
34
+ }
35
+
36
+ function lineQty(item: OrderLineLike, key: keyof OrderLineQuantities): number {
37
+ return qty(item.detail?.[key] ?? item[key])
38
+ }
39
+
40
+ function itemCreatedAt(item: OrderLineLike): number {
41
+ if (!item.created_at) return 0
42
+ const t = new Date(item.created_at).getTime()
43
+ return Number.isFinite(t) ? t : 0
44
+ }
45
+
46
+ function isCanceled(value?: string | Date | null): boolean {
47
+ return Boolean(value)
48
+ }
49
+
50
+ export function isInboundExchangeItem(item: OrderLineLike): boolean {
51
+ return (
52
+ lineQty(item, "return_requested_quantity") > 0 ||
53
+ lineQty(item, "returned_quantity") > 0
54
+ )
55
+ }
56
+
57
+ export function outboundExchangeItemIds(
58
+ items: OrderLineLike[],
59
+ exchanges?: OrderExchangeLike[] | null
60
+ ): Set<string> {
61
+ const ids = new Set<string>()
62
+ for (const exchange of exchanges || []) {
63
+ if (isCanceled(exchange.canceled_at)) continue
64
+ for (const extra of exchange.additional_items || []) {
65
+ const id = extra.item_id || extra.id
66
+ if (id) ids.add(id)
67
+ }
68
+ }
69
+ if (ids.size > 0) return ids
70
+
71
+ const inbound = items.filter(isInboundExchangeItem)
72
+ if (!inbound.length) return ids
73
+
74
+ const inboundIds = new Set(inbound.map((item) => item.id))
75
+ const inboundByProduct = new Map<string, OrderLineLike[]>()
76
+ for (const item of inbound) {
77
+ if (!item.product_id) continue
78
+ const list = inboundByProduct.get(item.product_id) || []
79
+ list.push(item)
80
+ inboundByProduct.set(item.product_id, list)
81
+ }
82
+
83
+ for (const item of items) {
84
+ if (inboundIds.has(item.id) || !item.product_id) continue
85
+ const matches = inboundByProduct.get(item.product_id)
86
+ if (!matches?.length) continue
87
+
88
+ const laterThanInbound = matches.some((origin) => {
89
+ const originAt = itemCreatedAt(origin)
90
+ const candidateAt = itemCreatedAt(item)
91
+ return originAt > 0 && candidateAt > originAt + 1000
92
+ })
93
+ const pendingReplacement =
94
+ lineQty(item, "fulfilled_quantity") === 0 &&
95
+ lineQty(item, "delivered_quantity") === 0
96
+
97
+ if (laterThanInbound || pendingReplacement) {
98
+ ids.add(item.id)
99
+ }
100
+ }
101
+
102
+ return ids
103
+ }
104
+
105
+ export function presentOrderLines<T extends OrderLineLike>(order: {
106
+ items?: T[] | null
107
+ shipping_total?: number | null
108
+ total?: number | null
109
+ exchanges?: OrderExchangeLike[] | null
110
+ }): {
111
+ purchasedItems: T[]
112
+ outboundItems: T[]
113
+ inboundItems: T[]
114
+ reorderItems: T[]
115
+ paidSubtotal: number
116
+ paidTotal: number
117
+ hasActiveExchange: boolean
118
+ originalFulfillmentIsComplete: boolean
119
+ } {
120
+ const items = (order.items || []) as T[]
121
+ const outboundIds = outboundExchangeItemIds(items, order.exchanges)
122
+ const outboundItems = items.filter((item) => outboundIds.has(item.id))
123
+ const purchasedItems = items.filter((item) => !outboundIds.has(item.id))
124
+ const inboundItems = purchasedItems.filter(isInboundExchangeItem)
125
+ const paidSubtotal = purchasedItems.reduce((sum, item) => {
126
+ if (typeof item.total === "number") return sum + item.total
127
+ return sum + qty(item.unit_price) * qty(item.quantity)
128
+ }, 0)
129
+ const shipping = qty(order.shipping_total)
130
+ const hasActiveExchange = inboundItems.some(
131
+ (item) => lineQty(item, "return_requested_quantity") > 0
132
+ )
133
+ const originalFulfillmentIsComplete =
134
+ purchasedItems.length > 0 &&
135
+ purchasedItems.every(
136
+ (item) =>
137
+ lineQty(item, "delivered_quantity") > 0 ||
138
+ lineQty(item, "fulfilled_quantity") > 0
139
+ )
140
+
141
+ return {
142
+ purchasedItems,
143
+ outboundItems,
144
+ inboundItems,
145
+ reorderItems: purchasedItems,
146
+ paidSubtotal,
147
+ paidTotal: paidSubtotal + shipping,
148
+ hasActiveExchange,
149
+ originalFulfillmentIsComplete,
150
+ }
151
+ }
@@ -1,73 +0,0 @@
1
- import { describe, it } from "node:test"
2
- import assert from "node:assert/strict"
3
- import {
4
- COUPON_APPLY_NO_ITEM_MATCH,
5
- COUPON_APPLY_SUCCESS,
6
- couponApplyKind,
7
- couponApplyMessage,
8
- type CouponApplyCart,
9
- type CouponApplyKind,
10
- } from "./coupon-apply-result.ts"
11
-
12
- const KIND_CASES: { name: string; cart: CouponApplyCart; want: CouponApplyKind }[] = [
13
- {
14
- name: "positive discount_total is success",
15
- cart: { discount_total: 86 },
16
- want: "success",
17
- },
18
- {
19
- name: "explicit zero discount_total means the code did not hit bag items",
20
- cart: { discount_total: 0, promotions: [{ code: "WELCOME10" }] },
21
- want: "no-item-match",
22
- },
23
- {
24
- name: "missing discount_total after a successful apply is not a false error",
25
- cart: { promotions: [{ code: "WELCOME10" }] },
26
- want: "success",
27
- },
28
- {
29
- name: "null discount_total after a successful apply is not a false error",
30
- cart: { discount_total: null },
31
- want: "success",
32
- },
33
- {
34
- name: "retrieve failure after a successful apply is not a false error",
35
- cart: null,
36
- want: "success",
37
- },
38
- ]
39
-
40
- const MESSAGE_CASES: { name: string; kind: CouponApplyKind; wantError: string; wantSuccess: string }[] =
41
- [
42
- {
43
- name: "success copy",
44
- kind: "success",
45
- wantError: "",
46
- wantSuccess: COUPON_APPLY_SUCCESS,
47
- },
48
- {
49
- name: "no-item-match copy",
50
- kind: "no-item-match",
51
- wantError: COUPON_APPLY_NO_ITEM_MATCH,
52
- wantSuccess: "",
53
- },
54
- ]
55
-
56
- describe("couponApplyKind", () => {
57
- for (const tc of KIND_CASES) {
58
- it(tc.name, () => {
59
- assert.equal(couponApplyKind(tc.cart), tc.want)
60
- })
61
- }
62
- })
63
-
64
- describe("couponApplyMessage", () => {
65
- for (const tc of MESSAGE_CASES) {
66
- it(tc.name, () => {
67
- assert.deepEqual(couponApplyMessage(tc.kind), {
68
- error: tc.wantError,
69
- success: tc.wantSuccess,
70
- })
71
- })
72
- }
73
- })
@@ -1,41 +0,0 @@
1
- export type CouponApplyKind = "success" | "no-item-match"
2
-
3
- export type CouponApplyCart = {
4
- discount_total?: number | null
5
- promotions?: { code?: string | null }[] | null
6
- } | null
7
-
8
- export const COUPON_APPLY_SUCCESS = "Coupon applied successfully!"
9
- export const COUPON_APPLY_NO_ITEM_MATCH =
10
- "Coupon added, but it doesn't apply to the items in your bag."
11
-
12
- /**
13
- * `applyPromotions` already succeeded. Decide checkout copy from the cart
14
- * fetched afterwards — missing `discount_total` must not look like a failed coupon.
15
- */
16
- export function couponApplyKind(cart: CouponApplyCart): CouponApplyKind {
17
- if (cart == null) {
18
- return "success"
19
- }
20
-
21
- if (cart.discount_total != null && Number(cart.discount_total) === 0) {
22
- return "no-item-match"
23
- }
24
-
25
- if (Number(cart.discount_total ?? 0) > 0) {
26
- return "success"
27
- }
28
-
29
- return "success"
30
- }
31
-
32
- export function couponApplyMessage(kind: CouponApplyKind): {
33
- error: string
34
- success: string
35
- } {
36
- if (kind === "success") {
37
- return { error: "", success: COUPON_APPLY_SUCCESS }
38
- }
39
-
40
- return { error: COUPON_APPLY_NO_ITEM_MATCH, success: "" }
41
- }