@pradip1995/segment-primitives 0.4.19 → 0.4.20

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.
@@ -1,184 +1,184 @@
1
- "use client"
2
-
3
- import { useState } from "react"
4
- import { useRouter } from "next/navigation"
5
- import type { HttpTypes } from "@medusajs/types"
6
- import { formatPrice } from "./format-price"
7
- import { couponApplyKind, couponApplyMessage } from "./coupon-apply-result"
8
-
9
- // 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 {
11
- applyPromotions: (codes: string[], cartId: string) => Promise<any>
12
- retrieveCart: (cartId?: string) => Promise<any>
13
- }
14
-
15
- type CouponApplyProps = {
16
- cart: HttpTypes.StoreCart & { promotions?: HttpTypes.StorePromotion[] }
17
- className?: string
18
- }
19
-
20
- function promotionLabel(promotion: any) {
21
- const method = promotion.application_method
22
- if (method?.value == null) return null
23
-
24
- if (method.type === "percentage") {
25
- return `${method.value}% off`
26
- }
27
-
28
- return `${formatPrice(Number(method.value), method.currency_code || "inr")} off`
29
- }
30
-
31
- export default function CouponApply({ cart, className = "" }: CouponApplyProps) {
32
- const router = useRouter()
33
- const [isOpen, setIsOpen] = useState(false)
34
- const [code, setCode] = useState("")
35
- const [isSubmitting, setIsSubmitting] = useState(false)
36
- const [errorMessage, setErrorMessage] = useState("")
37
- const [successMessage, setSuccessMessage] = useState("")
38
-
39
- const promotions = cart.promotions ?? []
40
-
41
- const refreshCart = () => {
42
- router.refresh()
43
- }
44
-
45
- const removePromotionCode = async (promotionCode: string) => {
46
- if (!cart.id) return
47
-
48
- setErrorMessage("")
49
- setSuccessMessage("")
50
- setIsSubmitting(true)
51
-
52
- try {
53
- const remaining = promotions
54
- .filter((promotion) => promotion.code && promotion.code !== promotionCode)
55
- .map((promotion) => promotion.code!)
56
- await applyPromotions(remaining, cart.id)
57
- refreshCart()
58
- } catch {
59
- setErrorMessage("Could not remove coupon. Please try again.")
60
- } finally {
61
- setIsSubmitting(false)
62
- }
63
- }
64
-
65
- const handleApply = async (event: React.FormEvent) => {
66
- event.preventDefault()
67
-
68
- const trimmed = code.trim()
69
- if (!trimmed || !cart.id) return
70
-
71
- setErrorMessage("")
72
- setSuccessMessage("")
73
- setIsSubmitting(true)
74
-
75
- const codes = promotions.filter((p) => p.code).map((p) => p.code!)
76
- if (!codes.includes(trimmed.toUpperCase()) && !codes.includes(trimmed)) {
77
- codes.push(trimmed)
78
- }
79
-
80
- try {
81
- 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)
86
- setCode("")
87
- refreshCart()
88
- } catch {
89
- setErrorMessage("Invalid coupon code. Please check the code and try again.")
90
- } finally {
91
- setIsSubmitting(false)
92
- }
93
- }
94
-
95
- return (
96
- <div className={`coupon-apply ${className}`.trim()}>
97
- <button
98
- type="button"
99
- className="coupon-apply__toggle"
100
- onClick={() => setIsOpen((open) => !open)}
101
- aria-expanded={isOpen}
102
- data-testid="add-discount-button"
103
- >
104
- <span className="coupon-apply__toggle-icon" aria-hidden>
105
- %
106
- </span>
107
- <span className="coupon-apply__toggle-copy">
108
- <span className="coupon-apply__toggle-title">Apply coupon</span>
109
- <span className="coupon-apply__toggle-subtitle">Have a promo code?</span>
110
- </span>
111
- <span className={`coupon-apply__chevron${isOpen ? " coupon-apply__chevron--open" : ""}`} aria-hidden>
112
- ›
113
- </span>
114
- </button>
115
-
116
- {isOpen ? (
117
- <form className="coupon-apply__form" onSubmit={handleApply}>
118
- <input
119
- className="coupon-apply__input"
120
- name="code"
121
- type="text"
122
- value={code}
123
- onChange={(event) => setCode(event.target.value)}
124
- placeholder="Enter coupon code"
125
- autoComplete="off"
126
- data-testid="discount-input"
127
- />
128
- <button
129
- type="submit"
130
- className="coupon-apply__submit"
131
- disabled={isSubmitting || !code.trim()}
132
- data-testid="discount-apply-button"
133
- >
134
- {isSubmitting ? "Applying…" : "Apply"}
135
- </button>
136
- </form>
137
- ) : null}
138
-
139
- {errorMessage ? (
140
- <p className="coupon-apply__message coupon-apply__message--error" data-testid="discount-error-message">
141
- {errorMessage}
142
- </p>
143
- ) : null}
144
-
145
- {successMessage ? (
146
- <p className="coupon-apply__message coupon-apply__message--success" data-testid="discount-success-message">
147
- {successMessage}
148
- </p>
149
- ) : null}
150
-
151
- {promotions.length > 0 ? (
152
- <div className="coupon-apply__applied">
153
- <p className="coupon-apply__applied-title">Applied offers</p>
154
- <ul className="coupon-apply__list">
155
- {promotions.map((promotion) => (
156
- <li key={promotion.id} className="coupon-apply__item" data-testid="discount-row">
157
- <div className="coupon-apply__item-copy">
158
- <span className="coupon-apply__item-code" data-testid="discount-code">
159
- {promotion.is_automatic ? "Automatic offer" : promotion.code}
160
- </span>
161
- {promotionLabel(promotion) ? (
162
- <span className="coupon-apply__item-value">{promotionLabel(promotion)}</span>
163
- ) : null}
164
- </div>
165
- {!promotion.is_automatic && promotion.code ? (
166
- <button
167
- type="button"
168
- className="coupon-apply__remove"
169
- onClick={() => removePromotionCode(promotion.code!)}
170
- disabled={isSubmitting}
171
- aria-label={`Remove coupon ${promotion.code}`}
172
- data-testid="remove-discount-button"
173
- >
174
- Remove
175
- </button>
176
- ) : null}
177
- </li>
178
- ))}
179
- </ul>
180
- </div>
181
- ) : null}
182
- </div>
183
- )
184
- }
1
+ "use client"
2
+
3
+ import { useState } from "react"
4
+ import { useRouter } from "next/navigation"
5
+ import type { HttpTypes } from "@medusajs/types"
6
+ import { formatPrice } from "./format-price"
7
+ import { couponApplyKind, couponApplyMessage } from "./coupon-apply-result"
8
+
9
+ // 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 {
11
+ applyPromotions: (codes: string[], cartId: string) => Promise<any>
12
+ retrieveCart: (cartId?: string) => Promise<any>
13
+ }
14
+
15
+ type CouponApplyProps = {
16
+ cart: HttpTypes.StoreCart & { promotions?: HttpTypes.StorePromotion[] }
17
+ className?: string
18
+ }
19
+
20
+ function promotionLabel(promotion: any) {
21
+ const method = promotion.application_method
22
+ if (method?.value == null) return null
23
+
24
+ if (method.type === "percentage") {
25
+ return `${method.value}% off`
26
+ }
27
+
28
+ return `${formatPrice(Number(method.value), method.currency_code || "inr")} off`
29
+ }
30
+
31
+ export default function CouponApply({ cart, className = "" }: CouponApplyProps) {
32
+ const router = useRouter()
33
+ const [isOpen, setIsOpen] = useState(false)
34
+ const [code, setCode] = useState("")
35
+ const [isSubmitting, setIsSubmitting] = useState(false)
36
+ const [errorMessage, setErrorMessage] = useState("")
37
+ const [successMessage, setSuccessMessage] = useState("")
38
+
39
+ const promotions = cart.promotions ?? []
40
+
41
+ const refreshCart = () => {
42
+ router.refresh()
43
+ }
44
+
45
+ const removePromotionCode = async (promotionCode: string) => {
46
+ if (!cart.id) return
47
+
48
+ setErrorMessage("")
49
+ setSuccessMessage("")
50
+ setIsSubmitting(true)
51
+
52
+ try {
53
+ const remaining = promotions
54
+ .filter((promotion) => promotion.code && promotion.code !== promotionCode)
55
+ .map((promotion) => promotion.code!)
56
+ await applyPromotions(remaining, cart.id)
57
+ refreshCart()
58
+ } catch {
59
+ setErrorMessage("Could not remove coupon. Please try again.")
60
+ } finally {
61
+ setIsSubmitting(false)
62
+ }
63
+ }
64
+
65
+ const handleApply = async (event: React.FormEvent) => {
66
+ event.preventDefault()
67
+
68
+ const trimmed = code.trim()
69
+ if (!trimmed || !cart.id) return
70
+
71
+ setErrorMessage("")
72
+ setSuccessMessage("")
73
+ setIsSubmitting(true)
74
+
75
+ const codes = promotions.filter((p) => p.code).map((p) => p.code!)
76
+ if (!codes.includes(trimmed.toUpperCase()) && !codes.includes(trimmed)) {
77
+ codes.push(trimmed)
78
+ }
79
+
80
+ try {
81
+ 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)
86
+ setCode("")
87
+ refreshCart()
88
+ } catch {
89
+ setErrorMessage("Invalid coupon code. Please check the code and try again.")
90
+ } finally {
91
+ setIsSubmitting(false)
92
+ }
93
+ }
94
+
95
+ return (
96
+ <div className={`coupon-apply ${className}`.trim()}>
97
+ <button
98
+ type="button"
99
+ className="coupon-apply__toggle"
100
+ onClick={() => setIsOpen((open) => !open)}
101
+ aria-expanded={isOpen}
102
+ data-testid="add-discount-button"
103
+ >
104
+ <span className="coupon-apply__toggle-icon" aria-hidden>
105
+ %
106
+ </span>
107
+ <span className="coupon-apply__toggle-copy">
108
+ <span className="coupon-apply__toggle-title">Apply coupon</span>
109
+ <span className="coupon-apply__toggle-subtitle">Have a promo code?</span>
110
+ </span>
111
+ <span className={`coupon-apply__chevron${isOpen ? " coupon-apply__chevron--open" : ""}`} aria-hidden>
112
+ ›
113
+ </span>
114
+ </button>
115
+
116
+ {isOpen ? (
117
+ <form className="coupon-apply__form" onSubmit={handleApply}>
118
+ <input
119
+ className="coupon-apply__input"
120
+ name="code"
121
+ type="text"
122
+ value={code}
123
+ onChange={(event) => setCode(event.target.value)}
124
+ placeholder="Enter coupon code"
125
+ autoComplete="off"
126
+ data-testid="discount-input"
127
+ />
128
+ <button
129
+ type="submit"
130
+ className="coupon-apply__submit"
131
+ disabled={isSubmitting || !code.trim()}
132
+ data-testid="discount-apply-button"
133
+ >
134
+ {isSubmitting ? "Applying…" : "Apply"}
135
+ </button>
136
+ </form>
137
+ ) : null}
138
+
139
+ {errorMessage ? (
140
+ <p className="coupon-apply__message coupon-apply__message--error" data-testid="discount-error-message">
141
+ {errorMessage}
142
+ </p>
143
+ ) : null}
144
+
145
+ {successMessage ? (
146
+ <p className="coupon-apply__message coupon-apply__message--success" data-testid="discount-success-message">
147
+ {successMessage}
148
+ </p>
149
+ ) : null}
150
+
151
+ {promotions.length > 0 ? (
152
+ <div className="coupon-apply__applied">
153
+ <p className="coupon-apply__applied-title">Applied offers</p>
154
+ <ul className="coupon-apply__list">
155
+ {promotions.map((promotion) => (
156
+ <li key={promotion.id} className="coupon-apply__item" data-testid="discount-row">
157
+ <div className="coupon-apply__item-copy">
158
+ <span className="coupon-apply__item-code" data-testid="discount-code">
159
+ {promotion.is_automatic ? "Automatic offer" : promotion.code}
160
+ </span>
161
+ {promotionLabel(promotion) ? (
162
+ <span className="coupon-apply__item-value">{promotionLabel(promotion)}</span>
163
+ ) : null}
164
+ </div>
165
+ {!promotion.is_automatic && promotion.code ? (
166
+ <button
167
+ type="button"
168
+ className="coupon-apply__remove"
169
+ onClick={() => removePromotionCode(promotion.code!)}
170
+ disabled={isSubmitting}
171
+ aria-label={`Remove coupon ${promotion.code}`}
172
+ data-testid="remove-discount-button"
173
+ >
174
+ Remove
175
+ </button>
176
+ ) : null}
177
+ </li>
178
+ ))}
179
+ </ul>
180
+ </div>
181
+ ) : null}
182
+ </div>
183
+ )
184
+ }
@@ -1,12 +1,12 @@
1
- export function formatPrice(
2
- amount: number | undefined | null,
3
- currencyCode = "inr"
4
- ): string {
5
- if (amount == null) return ""
6
- return new Intl.NumberFormat("en-IN", {
7
- style: "currency",
8
- currency: currencyCode.toUpperCase(),
9
- minimumFractionDigits: 0,
10
- maximumFractionDigits: 2,
11
- }).format(amount)
12
- }
1
+ export function formatPrice(
2
+ amount: number | undefined | null,
3
+ currencyCode = "inr"
4
+ ): string {
5
+ if (amount == null) return ""
6
+ return new Intl.NumberFormat("en-IN", {
7
+ style: "currency",
8
+ currency: currencyCode.toUpperCase(),
9
+ minimumFractionDigits: 0,
10
+ maximumFractionDigits: 2,
11
+ }).format(amount)
12
+ }
package/src/index.ts CHANGED
@@ -4,6 +4,7 @@ export { Button } from "./Button"
4
4
  export { Card } from "./Card"
5
5
  export {
6
6
  isInboundExchangeItem,
7
+ isReceivedOutboundItem,
7
8
  outboundExchangeItemIds,
8
9
  presentOrderLines,
9
10
  } from "./order-lines"
@@ -1,86 +1,86 @@
1
- /**
2
- * Next.js `redirect()` / `notFound()` throw special control-flow errors.
3
- * Catch blocks must rethrow these — never render `err.message` ("NEXT_REDIRECT").
4
- */
5
-
6
- const CONTROL_FLOW_RE = /NEXT_REDIRECT|NEXT_REDIRECTION|NEXT_NOT_FOUND|NEXT_HTTP_ERROR_FALLBACK/i
7
-
8
- function textLooksLikeControlFlow(value: string): boolean {
9
- return CONTROL_FLOW_RE.test(value)
10
- }
11
-
12
- export function isNextRedirect(err: unknown): boolean {
13
- if (err == null) return false
14
-
15
- if (typeof err === "string") {
16
- return textLooksLikeControlFlow(err)
17
- }
18
-
19
- if (typeof err !== "object") {
20
- return textLooksLikeControlFlow(String(err))
21
- }
22
-
23
- const digest =
24
- "digest" in err ? String((err as { digest?: unknown }).digest ?? "") : ""
25
- if (textLooksLikeControlFlow(digest)) {
26
- return true
27
- }
28
-
29
- const message =
30
- err instanceof Error
31
- ? err.message
32
- : "message" in err
33
- ? String((err as { message?: unknown }).message ?? "")
34
- : ""
35
-
36
- if (textLooksLikeControlFlow(message)) {
37
- return true
38
- }
39
-
40
- // Some runtimes stringify the redirect error oddly.
41
- try {
42
- return textLooksLikeControlFlow(String(err))
43
- } catch {
44
- return false
45
- }
46
- }
47
-
48
- /** Never return a Next.js control-flow token as a user-facing error. */
49
- export function safeErrorMessage(err: unknown, fallback: string): string {
50
- if (isNextRedirect(err)) return fallback
51
- if (err instanceof Error) {
52
- const msg = err.message?.trim()
53
- if (!msg || textLooksLikeControlFlow(msg)) return fallback
54
- return msg
55
- }
56
- if (typeof err === "string") {
57
- const msg = err.trim()
58
- if (!msg || textLooksLikeControlFlow(msg)) return fallback
59
- return msg
60
- }
61
- return fallback
62
- }
63
-
64
- export function isNextRedirectMessage(value: unknown): boolean {
65
- return typeof value === "string" && textLooksLikeControlFlow(value)
66
- }
67
-
68
- const SHIPPING_PROFILE_RE = /shipping profiles that are not satisfied/i
69
- const RSC_DIGEST_RE =
70
- /Server Components render|digest property is included on this error/i
71
-
72
- /**
73
- * Maps checkout/payment failures to an actionable message.
74
- * Production Next.js often replaces the Medusa shipping-profile error with an RSC digest.
75
- */
76
- export function checkoutPaymentErrorMessage(err: unknown): string {
77
- const fallback = "Payment could not be started."
78
- const msg = safeErrorMessage(err, fallback)
79
- if (SHIPPING_PROFILE_RE.test(msg)) {
80
- return "This product has no shipping profile, so checkout cannot complete. In Medusa Admin, open the product and assign the Default shipping profile (the same one used by Express/Standard shipping)."
81
- }
82
- if (RSC_DIGEST_RE.test(msg)) {
83
- return "Checkout could not complete. If this happens only for one product, assign it a shipping profile in Medusa Admin (same profile as your shipping methods) and try again."
84
- }
85
- return msg
86
- }
1
+ /**
2
+ * Next.js `redirect()` / `notFound()` throw special control-flow errors.
3
+ * Catch blocks must rethrow these — never render `err.message` ("NEXT_REDIRECT").
4
+ */
5
+
6
+ const CONTROL_FLOW_RE = /NEXT_REDIRECT|NEXT_REDIRECTION|NEXT_NOT_FOUND|NEXT_HTTP_ERROR_FALLBACK/i
7
+
8
+ function textLooksLikeControlFlow(value: string): boolean {
9
+ return CONTROL_FLOW_RE.test(value)
10
+ }
11
+
12
+ export function isNextRedirect(err: unknown): boolean {
13
+ if (err == null) return false
14
+
15
+ if (typeof err === "string") {
16
+ return textLooksLikeControlFlow(err)
17
+ }
18
+
19
+ if (typeof err !== "object") {
20
+ return textLooksLikeControlFlow(String(err))
21
+ }
22
+
23
+ const digest =
24
+ "digest" in err ? String((err as { digest?: unknown }).digest ?? "") : ""
25
+ if (textLooksLikeControlFlow(digest)) {
26
+ return true
27
+ }
28
+
29
+ const message =
30
+ err instanceof Error
31
+ ? err.message
32
+ : "message" in err
33
+ ? String((err as { message?: unknown }).message ?? "")
34
+ : ""
35
+
36
+ if (textLooksLikeControlFlow(message)) {
37
+ return true
38
+ }
39
+
40
+ // Some runtimes stringify the redirect error oddly.
41
+ try {
42
+ return textLooksLikeControlFlow(String(err))
43
+ } catch {
44
+ return false
45
+ }
46
+ }
47
+
48
+ /** Never return a Next.js control-flow token as a user-facing error. */
49
+ export function safeErrorMessage(err: unknown, fallback: string): string {
50
+ if (isNextRedirect(err)) return fallback
51
+ if (err instanceof Error) {
52
+ const msg = err.message?.trim()
53
+ if (!msg || textLooksLikeControlFlow(msg)) return fallback
54
+ return msg
55
+ }
56
+ if (typeof err === "string") {
57
+ const msg = err.trim()
58
+ if (!msg || textLooksLikeControlFlow(msg)) return fallback
59
+ return msg
60
+ }
61
+ return fallback
62
+ }
63
+
64
+ export function isNextRedirectMessage(value: unknown): boolean {
65
+ return typeof value === "string" && textLooksLikeControlFlow(value)
66
+ }
67
+
68
+ const SHIPPING_PROFILE_RE = /shipping profiles that are not satisfied/i
69
+ const RSC_DIGEST_RE =
70
+ /Server Components render|digest property is included on this error/i
71
+
72
+ /**
73
+ * Maps checkout/payment failures to an actionable message.
74
+ * Production Next.js often replaces the Medusa shipping-profile error with an RSC digest.
75
+ */
76
+ export function checkoutPaymentErrorMessage(err: unknown): string {
77
+ const fallback = "Payment could not be started."
78
+ const msg = safeErrorMessage(err, fallback)
79
+ if (SHIPPING_PROFILE_RE.test(msg)) {
80
+ return "This product has no shipping profile, so checkout cannot complete. In Medusa Admin, open the product and assign the Default shipping profile (the same one used by Express/Standard shipping)."
81
+ }
82
+ if (RSC_DIGEST_RE.test(msg)) {
83
+ return "Checkout could not complete. If this happens only for one product, assign it a shipping profile in Medusa Admin (same profile as your shipping methods) and try again."
84
+ }
85
+ return msg
86
+ }
@@ -1,37 +1,37 @@
1
- "use client"
2
-
3
- import Link from "next/link"
4
- import type { ComponentProps } from "react"
5
-
6
- type Props = ComponentProps<typeof Link> & {
7
- href: string
8
- /** Region prefix (e.g. `in`). Prefer passing from layout data for stable SSR. */
9
- countryCode?: string
10
- }
11
-
12
- const DEFAULT_REGION = "in"
13
-
14
- export default function LocalizedLink({
15
- href,
16
- children,
17
- countryCode,
18
- ...rest
19
- }: Props) {
20
- const region = (countryCode || DEFAULT_REGION).toLowerCase()
21
-
22
- if (!href.startsWith("/")) {
23
- return (
24
- <Link href={href} {...rest}>
25
- {children}
26
- </Link>
27
- )
28
- }
29
-
30
- const localizedHref = href === "/" ? `/${region}` : `/${region}${href}`
31
-
32
- return (
33
- <Link href={localizedHref} {...rest}>
34
- {children}
35
- </Link>
36
- )
37
- }
1
+ "use client"
2
+
3
+ import Link from "next/link"
4
+ import type { ComponentProps } from "react"
5
+
6
+ type Props = ComponentProps<typeof Link> & {
7
+ href: string
8
+ /** Region prefix (e.g. `in`). Prefer passing from layout data for stable SSR. */
9
+ countryCode?: string
10
+ }
11
+
12
+ const DEFAULT_REGION = "in"
13
+
14
+ export default function LocalizedLink({
15
+ href,
16
+ children,
17
+ countryCode,
18
+ ...rest
19
+ }: Props) {
20
+ const region = (countryCode || DEFAULT_REGION).toLowerCase()
21
+
22
+ if (!href.startsWith("/")) {
23
+ return (
24
+ <Link href={href} {...rest}>
25
+ {children}
26
+ </Link>
27
+ )
28
+ }
29
+
30
+ const localizedHref = href === "/" ? `/${region}` : `/${region}${href}`
31
+
32
+ return (
33
+ <Link href={localizedHref} {...rest}>
34
+ {children}
35
+ </Link>
36
+ )
37
+ }