@pradip1995/segment-primitives 0.4.11 → 0.4.13

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.11",
3
+ "version": "0.4.13",
4
4
  "license": "MIT",
5
5
  "publishConfig": {
6
6
  "access": "public"
@@ -21,12 +21,11 @@
21
21
  "./product-variants": "./src/product-variants.ts",
22
22
  "./product-selection-context": "./src/product-selection-context.tsx",
23
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
+ "./order-lines": "./src/order-lines.ts",
25
+ "./wishlist-count": "./src/wishlist-count.ts",
26
+ "./use-wishlist-count": "./src/use-wishlist-count.ts",
27
+ "./notify-wishlist": "./src/notify-wishlist.ts",
28
+ "./revalidate-wishlist": "./src/revalidate-wishlist.ts"
30
29
  },
31
30
  "peerDependencies": {
32
31
  "@medusajs/types": "^2.0.0",
@@ -40,7 +39,13 @@
40
39
  "@medusajs/types": "^2.0.0",
41
40
  "@pradip1995/plugin-sdk": "^0.2.0",
42
41
  "@types/react": "^19",
42
+ "next": ">=15",
43
43
  "react": "19.0.3",
44
44
  "typescript": "^5.7.2"
45
+ },
46
+ "scripts": {
47
+ "typecheck": "tsc --noEmit",
48
+ "lint": "tsc --noEmit",
49
+ "test": "node --experimental-strip-types --test src/*.test.ts"
45
50
  }
46
- }
51
+ }
@@ -0,0 +1,73 @@
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
+ })
@@ -0,0 +1,41 @@
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
+ }
@@ -4,10 +4,12 @@ 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"
7
8
 
8
9
  // Use require to prevent TS from attempting to typecheck the raw .ts files published in commerce-core
9
- const { applyPromotions } = require("@pradip1995/commerce-core/client/actions/cart") as {
10
+ const { applyPromotions, retrieveCart } = require("@pradip1995/commerce-core/client/actions/cart") as {
10
11
  applyPromotions: (codes: string[], cartId: string) => Promise<any>
12
+ retrieveCart: (cartId?: string) => Promise<any>
11
13
  }
12
14
 
13
15
  type CouponApplyProps = {
@@ -77,13 +79,10 @@ export default function CouponApply({ cart, className = "" }: CouponApplyProps)
77
79
 
78
80
  try {
79
81
  const updatedCart = await applyPromotions(codes, cart.id)
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
- }
82
+ const freshCart = (await retrieveCart(cart.id).catch(() => null)) ?? updatedCart
83
+ const { error, success } = couponApplyMessage(couponApplyKind(freshCart))
84
+ setErrorMessage(error)
85
+ setSuccessMessage(success)
87
86
  setCode("")
88
87
  refreshCart()
89
88
  } catch {
package/src/index.ts CHANGED
@@ -2,8 +2,3 @@ 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,9 @@
1
+ "use client"
2
+
3
+ import { revalidateWishlistCache } from "./revalidate-wishlist"
4
+ import { dispatchWishlistUpdated, type WishlistUpdatedDetail } from "./wishlist-count"
5
+
6
+ export async function notifyWishlistChanged(detail: WishlistUpdatedDetail) {
7
+ dispatchWishlistUpdated(detail)
8
+ await revalidateWishlistCache()
9
+ }
@@ -1,8 +1,13 @@
1
1
  import assert from "node:assert/strict"
2
- import test from "node:test"
3
- import { outboundExchangeItemIds, presentOrderLines } from "./order-lines"
2
+ import { describe, it } from "node:test"
3
+ import {
4
+ outboundExchangeItemIds,
5
+ presentOrderLines,
6
+ type OrderExchangeLike,
7
+ type OrderLineLike,
8
+ } from "./order-lines.ts"
4
9
 
5
- const originalRing = {
10
+ const originalRing: OrderLineLike = {
6
11
  id: "ordli_ring_8",
7
12
  product_id: "prod_ring",
8
13
  variant_id: "var_8",
@@ -17,7 +22,7 @@ const originalRing = {
17
22
  },
18
23
  }
19
24
 
20
- const pendant = {
25
+ const pendant: OrderLineLike = {
21
26
  id: "ordli_pendant",
22
27
  product_id: "prod_pendant",
23
28
  variant_id: "var_default",
@@ -32,7 +37,7 @@ const pendant = {
32
37
  },
33
38
  }
34
39
 
35
- const replacementRing = {
40
+ const replacementRing: OrderLineLike = {
36
41
  id: "ordli_ring_7",
37
42
  product_id: "prod_ring",
38
43
  variant_id: "var_7",
@@ -47,53 +52,195 @@ const replacementRing = {
47
52
  },
48
53
  }
49
54
 
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
- })
55
+ const originalSize7: OrderLineLike = {
56
+ ...replacementRing,
57
+ id: "ordli_ring_7_original",
58
+ created_at: originalRing.created_at,
59
+ detail: {
60
+ fulfilled_quantity: 1,
61
+ delivered_quantity: 1,
62
+ return_requested_quantity: 0,
63
+ returned_quantity: 0,
64
+ },
65
+ }
56
66
 
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
- })
67
+ const PRESENT_CASES: {
68
+ name: string
69
+ order: {
70
+ items?: OrderLineLike[] | null
71
+ shipping_total?: number | null
72
+ exchanges?: OrderExchangeLike[] | null
73
+ }
74
+ want: {
75
+ purchasedIds: string[]
76
+ outboundIds: string[]
77
+ inboundIds: string[]
78
+ paidSubtotal: number
79
+ paidTotal: number
80
+ hasActiveExchange: boolean
81
+ originalFulfillmentIsComplete: boolean
82
+ reorderIds: string[]
83
+ }
84
+ }[] = [
85
+ {
86
+ name: "hides the exchange replacement from purchased items and paid total",
87
+ order: {
88
+ items: [originalRing, pendant, replacementRing],
89
+ shipping_total: 0,
90
+ },
91
+ want: {
92
+ purchasedIds: ["ordli_ring_8", "ordli_pendant"],
93
+ outboundIds: ["ordli_ring_7"],
94
+ inboundIds: ["ordli_ring_8"],
95
+ paidSubtotal: 969,
96
+ paidTotal: 969,
97
+ hasActiveExchange: true,
98
+ originalFulfillmentIsComplete: true,
99
+ reorderIds: ["ordli_ring_8", "ordli_pendant"],
100
+ },
101
+ },
102
+ {
103
+ name: "does not treat a second original size of the same product as the replacement",
104
+ order: {
105
+ items: [originalRing, originalSize7],
106
+ shipping_total: 0,
107
+ },
108
+ want: {
109
+ purchasedIds: ["ordli_ring_8", "ordli_ring_7_original"],
110
+ outboundIds: [],
111
+ inboundIds: ["ordli_ring_8"],
112
+ paidSubtotal: 200,
113
+ paidTotal: 200,
114
+ hasActiveExchange: true,
115
+ originalFulfillmentIsComplete: true,
116
+ reorderIds: ["ordli_ring_8", "ordli_ring_7_original"],
117
+ },
118
+ },
119
+ {
120
+ name: "empty order has zero totals and no lines",
121
+ order: { items: [], shipping_total: 40 },
122
+ want: {
123
+ purchasedIds: [],
124
+ outboundIds: [],
125
+ inboundIds: [],
126
+ paidSubtotal: 0,
127
+ paidTotal: 40,
128
+ hasActiveExchange: false,
129
+ originalFulfillmentIsComplete: false,
130
+ reorderIds: [],
131
+ },
132
+ },
133
+ {
134
+ name: "adds shipping to paid total",
135
+ order: {
136
+ items: [pendant],
137
+ shipping_total: 49,
138
+ },
139
+ want: {
140
+ purchasedIds: ["ordli_pendant"],
141
+ outboundIds: [],
142
+ inboundIds: [],
143
+ paidSubtotal: 869,
144
+ paidTotal: 918,
145
+ hasActiveExchange: false,
146
+ originalFulfillmentIsComplete: true,
147
+ reorderIds: ["ordli_pendant"],
148
+ },
149
+ },
150
+ {
151
+ name: "falls back to unit_price times quantity when total is missing",
152
+ order: {
153
+ items: [
154
+ {
155
+ id: "ordli_loose",
156
+ quantity: 2,
157
+ unit_price: 50,
158
+ },
159
+ ],
160
+ shipping_total: 10,
161
+ },
162
+ want: {
163
+ purchasedIds: ["ordli_loose"],
164
+ outboundIds: [],
165
+ inboundIds: [],
166
+ paidSubtotal: 100,
167
+ paidTotal: 110,
168
+ hasActiveExchange: false,
169
+ originalFulfillmentIsComplete: false,
170
+ reorderIds: ["ordli_loose"],
171
+ },
172
+ },
173
+ ]
69
174
 
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"])
175
+ const OUTBOUND_CASES: {
176
+ name: string
177
+ items: OrderLineLike[]
178
+ exchanges?: OrderExchangeLike[] | null
179
+ want: string[]
180
+ }[] = [
181
+ {
182
+ name: "uses exchange additional_items when present",
183
+ items: [originalRing, pendant, replacementRing],
184
+ exchanges: [{ additional_items: [{ item_id: "ordli_ring_7" }] }],
185
+ want: ["ordli_ring_7"],
186
+ },
187
+ {
188
+ name: "ignores canceled exchange additional_items and infers replacement",
189
+ items: [originalRing, pendant, replacementRing],
190
+ exchanges: [
191
+ {
192
+ canceled_at: "2026-08-27T12:50:00.000Z",
193
+ additional_items: [{ item_id: "ordli_ring_7" }],
194
+ },
195
+ ],
196
+ want: ["ordli_ring_7"],
197
+ },
198
+ {
199
+ name: "returns empty when there is no inbound exchange item",
200
+ items: [pendant],
201
+ exchanges: [],
202
+ want: [],
203
+ },
204
+ ]
205
+
206
+ describe("presentOrderLines", () => {
207
+ for (const tc of PRESENT_CASES) {
208
+ it(tc.name, () => {
209
+ const view = presentOrderLines(tc.order)
210
+ assert.deepEqual(
211
+ view.purchasedItems.map((item) => item.id),
212
+ tc.want.purchasedIds
213
+ )
214
+ assert.deepEqual(
215
+ view.outboundItems.map((item) => item.id),
216
+ tc.want.outboundIds
217
+ )
218
+ assert.deepEqual(
219
+ view.inboundItems.map((item) => item.id),
220
+ tc.want.inboundIds
221
+ )
222
+ assert.deepEqual(
223
+ view.reorderItems.map((item) => item.id),
224
+ tc.want.reorderIds
225
+ )
226
+ assert.equal(view.paidSubtotal, tc.want.paidSubtotal)
227
+ assert.equal(view.paidTotal, tc.want.paidTotal)
228
+ assert.equal(view.hasActiveExchange, tc.want.hasActiveExchange)
229
+ assert.equal(
230
+ view.originalFulfillmentIsComplete,
231
+ tc.want.originalFulfillmentIsComplete
232
+ )
233
+ })
234
+ }
76
235
  })
77
236
 
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
- },
237
+ describe("outboundExchangeItemIds", () => {
238
+ for (const tc of OUTBOUND_CASES) {
239
+ it(tc.name, () => {
240
+ assert.deepEqual(
241
+ [...outboundExchangeItemIds(tc.items, tc.exchanges)],
242
+ tc.want
243
+ )
244
+ })
89
245
  }
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
246
  })
@@ -0,0 +1,8 @@
1
+ "use server"
2
+
3
+ import { revalidatePath } from "next/cache"
4
+
5
+ export async function revalidateWishlistCache() {
6
+ revalidatePath("/", "layout")
7
+ revalidatePath("/wishlist")
8
+ }
@@ -0,0 +1,32 @@
1
+ "use client"
2
+
3
+ import { useEffect, useRef, useState } from "react"
4
+ import {
5
+ WISHLIST_UPDATED_EVENT,
6
+ nextWishlistCount,
7
+ type WishlistUpdatedDetail,
8
+ } from "./wishlist-count"
9
+
10
+ export function useWishlistCount(serverCount: number) {
11
+ const initial = nextWishlistCount(serverCount)
12
+ const [count, setCount] = useState(initial)
13
+ const lastServerCount = useRef(initial)
14
+
15
+ useEffect(() => {
16
+ const next = nextWishlistCount(serverCount)
17
+ if (next === lastServerCount.current) return
18
+ lastServerCount.current = next
19
+ setCount(next)
20
+ }, [serverCount])
21
+
22
+ useEffect(() => {
23
+ const onUpdate = (event: Event) => {
24
+ const detail = (event as CustomEvent<WishlistUpdatedDetail>).detail
25
+ setCount((current) => nextWishlistCount(current, detail))
26
+ }
27
+ window.addEventListener(WISHLIST_UPDATED_EVENT, onUpdate)
28
+ return () => window.removeEventListener(WISHLIST_UPDATED_EVENT, onUpdate)
29
+ }, [])
30
+
31
+ return count
32
+ }
@@ -0,0 +1,96 @@
1
+ import assert from "node:assert/strict"
2
+ import { describe, it } from "node:test"
3
+ import { nextWishlistCount, type WishlistUpdatedDetail } from "./wishlist-count.ts"
4
+
5
+ const CASES: Array<{
6
+ name: string
7
+ current: number
8
+ detail?: WishlistUpdatedDetail | null
9
+ want: number
10
+ }> = [
11
+ {
12
+ name: "removing one item decrements the navbar badge",
13
+ current: 2,
14
+ detail: { delta: -1 },
15
+ want: 1,
16
+ },
17
+ {
18
+ name: "removing the last item clears the badge",
19
+ current: 1,
20
+ detail: { delta: -1 },
21
+ want: 0,
22
+ },
23
+ {
24
+ name: "removing from an empty wishlist stays at zero",
25
+ current: 0,
26
+ detail: { delta: -1 },
27
+ want: 0,
28
+ },
29
+ {
30
+ name: "adding an item increments the badge",
31
+ current: 0,
32
+ detail: { delta: 1 },
33
+ want: 1,
34
+ },
35
+ {
36
+ name: "adding onto an existing count increments the badge",
37
+ current: 2,
38
+ detail: { delta: 1 },
39
+ want: 3,
40
+ },
41
+ {
42
+ name: "an explicit count replaces the current badge",
43
+ current: 4,
44
+ detail: { count: 1 },
45
+ want: 1,
46
+ },
47
+ {
48
+ name: "an explicit count wins when delta is also present",
49
+ current: 4,
50
+ detail: { count: 0, delta: 2 },
51
+ want: 0,
52
+ },
53
+ {
54
+ name: "missing detail keeps the current badge",
55
+ current: 3,
56
+ want: 3,
57
+ },
58
+ {
59
+ name: "null detail keeps the current badge",
60
+ current: 3,
61
+ detail: null,
62
+ want: 3,
63
+ },
64
+ {
65
+ name: "empty detail keeps the current badge",
66
+ current: 3,
67
+ detail: {},
68
+ want: 3,
69
+ },
70
+ {
71
+ name: "non-finite current is treated as zero before applying delta",
72
+ current: Number.NaN,
73
+ detail: { delta: 2 },
74
+ want: 2,
75
+ },
76
+ {
77
+ name: "non-finite delta is ignored",
78
+ current: 5,
79
+ detail: { delta: Number.NaN },
80
+ want: 5,
81
+ },
82
+ {
83
+ name: "fractional values are truncated",
84
+ current: 2.9,
85
+ detail: { delta: -1.8 },
86
+ want: 1,
87
+ },
88
+ ]
89
+
90
+ describe("nextWishlistCount", () => {
91
+ for (const row of CASES) {
92
+ it(row.name, () => {
93
+ assert.equal(nextWishlistCount(row.current, row.detail), row.want)
94
+ })
95
+ }
96
+ })
@@ -0,0 +1,26 @@
1
+ export const WISHLIST_UPDATED_EVENT = "wishlist:updated"
2
+
3
+ export type WishlistUpdatedDetail = {
4
+ delta?: number
5
+ count?: number
6
+ }
7
+
8
+ export function nextWishlistCount(
9
+ current: number,
10
+ detail?: WishlistUpdatedDetail | null
11
+ ): number {
12
+ const base = Number.isFinite(current) ? Math.max(0, Math.trunc(current)) : 0
13
+ if (!detail) return base
14
+ if (typeof detail.count === "number" && Number.isFinite(detail.count)) {
15
+ return Math.max(0, Math.trunc(detail.count))
16
+ }
17
+ if (typeof detail.delta === "number" && Number.isFinite(detail.delta)) {
18
+ return Math.max(0, base + Math.trunc(detail.delta))
19
+ }
20
+ return base
21
+ }
22
+
23
+ export function dispatchWishlistUpdated(detail: WishlistUpdatedDetail) {
24
+ if (typeof window === "undefined") return
25
+ window.dispatchEvent(new CustomEvent(WISHLIST_UPDATED_EVENT, { detail }))
26
+ }