@pradip1995/segment-jewelry-account-pages 0.1.2 → 0.1.3

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-jewelry-account-pages",
3
- "version": "0.1.2",
3
+ "version": "0.1.3",
4
4
  "license": "MIT",
5
5
  "publishConfig": {
6
6
  "access": "public"
@@ -15,6 +15,10 @@
15
15
  ".": "./src/index.ts",
16
16
  "./manifest": "./src/manifest.ts"
17
17
  },
18
+ "scripts": {
19
+ "typecheck": "tsc --noEmit",
20
+ "lint": "tsc --noEmit"
21
+ },
18
22
  "peerDependencies": {
19
23
  "@pradip1995/commerce-auth": "^4.0.0",
20
24
  "@pradip1995/commerce-core": "^4.0.0",
@@ -27,8 +31,8 @@
27
31
  "@medusajs/types": "^2.8.0",
28
32
  "@pradip1995/commerce-auth": "^4.0.0",
29
33
  "@pradip1995/commerce-core": "^4.0.0",
30
- "@pradip1995/segment-login-template": "^0.5.7",
31
- "@pradip1995/segment-primitives": "^0.4.3",
34
+ "@pradip1995/segment-login-template": "^0.5.13",
35
+ "@pradip1995/segment-primitives": "^0.4.11",
32
36
  "@pradip1995/segment-tokens": "^0.3.7"
33
37
  },
34
38
  "devDependencies": {
@@ -37,10 +41,5 @@
37
41
  "next": ">=15",
38
42
  "react": "19.0.3",
39
43
  "typescript": "^5.7.2"
40
- },
41
- "scripts": {
42
- "typecheck": "tsc --noEmit",
43
- "lint": "tsc --noEmit",
44
- "test": "node --experimental-strip-types --test src/default-address.test.ts"
45
44
  }
46
45
  }
@@ -5,17 +5,9 @@ import type { HttpTypes } from "@medusajs/types"
5
5
  import {
6
6
  addCustomerAddress,
7
7
  deleteCustomerAddress,
8
+ setDefaultAddress,
8
9
  updateCustomerAddress,
9
10
  } from "@pradip1995/commerce-core/data/customer"
10
- import { setExclusiveDefaultAddress } from "./address-actions"
11
- import {
12
- ADDRESS_TYPES,
13
- addressTypeFromMetadata,
14
- isExclusiveDefaultAddress,
15
- resolveAddressType,
16
- resolveDefaultAddressId,
17
- sortAddressesDefaultFirst,
18
- } from "./default-address"
19
11
 
20
12
  export default function ModernAccountAddresses({
21
13
  customer,
@@ -24,11 +16,10 @@ export default function ModernAccountAddresses({
24
16
  customer: HttpTypes.StoreCustomer
25
17
  countryCode: string
26
18
  }) {
27
- const addresses = sortAddressesDefaultFirst(customer.addresses ?? [])
19
+ const addresses = customer.addresses ?? []
28
20
  const [editingId, setEditingId] = useState<string | null>(null)
29
21
  const [showAdd, setShowAdd] = useState(false)
30
- const defaultAddressId = resolveDefaultAddressId(addresses)
31
- const hasDefault = Boolean(defaultAddressId)
22
+ const hasDefault = addresses.some((a) => a.is_default_shipping || a.is_default_billing)
32
23
  const editingAddress = addresses.find((address) => address.id === editingId)
33
24
 
34
25
  return (
@@ -63,7 +54,7 @@ export default function ModernAccountAddresses({
63
54
 
64
55
  <div style={{ display: "flex", flexDirection: "column", gap: "1.25rem" }}>
65
56
  {addresses.map((address) => {
66
- const isDefault = isExclusiveDefaultAddress(address, defaultAddressId)
57
+ const isDefault = address.is_default_shipping || address.is_default_billing
67
58
  const name = [address.first_name, address.last_name].filter(Boolean).join(" ")
68
59
  return (
69
60
  <div
@@ -120,7 +111,7 @@ export default function ModernAccountAddresses({
120
111
  color: "var(--lux-onyx)",
121
112
  }}
122
113
  >
123
- {addressTypeFromMetadata(address.metadata)}
114
+ HOME
124
115
  </span>
125
116
  </div>
126
117
  </div>
@@ -231,7 +222,9 @@ export default function ModernAccountAddresses({
231
222
  countryCode={countryCode}
232
223
  address={editingAddress}
233
224
  addressId={editingAddress.id}
234
- defaultChecked={isExclusiveDefaultAddress(editingAddress, defaultAddressId)}
225
+ defaultChecked={
226
+ !!(editingAddress.is_default_shipping || editingAddress.is_default_billing)
227
+ }
235
228
  onDone={() => setEditingId(null)}
236
229
  onCancel={() => setEditingId(null)}
237
230
  />
@@ -316,8 +309,8 @@ function AddressForm({
316
309
  formData
317
310
  )
318
311
  if (result?.success) {
319
- if (addressId && makeDefault) {
320
- const defaultResult = await setExclusiveDefaultAddress(addressId)
312
+ if (addressId && makeDefault && !address?.is_default_shipping) {
313
+ const defaultResult = await setDefaultAddress(addressId)
321
314
  if (!defaultResult?.success) {
322
315
  return {
323
316
  success: false,
@@ -359,8 +352,6 @@ function AddressForm({
359
352
  />
360
353
  <Field label="Phone" name="phone" type="tel" defaultValue={address?.phone || ""} />
361
354
 
362
- <AddressTypeField defaultValue={addressTypeFromMetadata(address?.metadata)} />
363
-
364
355
  <div className="modern-field--full">
365
356
  <label style={{ display: "flex", alignItems: "center", gap: "0.5rem", fontSize: "0.8125rem", cursor: "pointer" }}>
366
357
  <input
@@ -407,15 +398,15 @@ function MakeDefaultButton({ addressId }: { addressId: string }) {
407
398
  setPending(true)
408
399
  setError(null)
409
400
  try {
410
- const result = await setExclusiveDefaultAddress(addressId)
401
+ const result = await setDefaultAddress(addressId)
411
402
  if (!result?.success) {
412
403
  setError(result?.error || "Failed to set default address")
404
+ setPending(false)
413
405
  return
414
406
  }
415
407
  window.location.reload()
416
408
  } catch (err) {
417
409
  setError(err instanceof Error ? err.message : "Failed to set default address")
418
- } finally {
419
410
  setPending(false)
420
411
  }
421
412
  }
@@ -484,29 +475,6 @@ function DeleteAddressButton({ addressId }: { addressId: string }) {
484
475
  )
485
476
  }
486
477
 
487
- function AddressTypeField({ defaultValue }: { defaultValue: string }) {
488
- const selected = resolveAddressType(defaultValue)
489
-
490
- return (
491
- <fieldset className="modern-field modern-field--full modern-address-type" style={{ border: 0, margin: 0, padding: 0 }}>
492
- <legend className="modern-field__label">Address type</legend>
493
- <div className="modern-address-type__options">
494
- {ADDRESS_TYPES.map((type) => (
495
- <label key={type} className="modern-address-type__option">
496
- <input
497
- type="radio"
498
- name="address_type"
499
- value={type}
500
- defaultChecked={selected === type}
501
- />
502
- <span>{type === "HOME" ? "Home" : "Office"}</span>
503
- </label>
504
- ))}
505
- </div>
506
- </fieldset>
507
- )
508
- }
509
-
510
478
  function Field({
511
479
  label,
512
480
  name,
@@ -4,6 +4,7 @@ import Image from "next/image"
4
4
  import type { HttpTypes } from "@medusajs/types"
5
5
  import LocalizedLink from "@pradip1995/segment-primitives/localized-link"
6
6
  import { formatPrice } from "@pradip1995/segment-primitives/format-price"
7
+ import { presentOrderLines } from "@pradip1995/segment-primitives/order-lines"
7
8
 
8
9
  function getStatusDetails(status?: string, fulfillment?: string) {
9
10
  const s = (fulfillment || status || "").toLowerCase()
@@ -87,7 +88,8 @@ export default function ModernAccountOrderCard({
87
88
  }) {
88
89
  const currency = order.currency_code
89
90
  const statusInfo = getStatusDetails(order.status, order.fulfillment_status)
90
- const items = order.items || []
91
+ const presentation = presentOrderLines(order)
92
+ const items = presentation.purchasedItems
91
93
 
92
94
  const dateStr = order.created_at
93
95
  ? new Date(order.created_at).toLocaleDateString("en-US", {
@@ -116,7 +118,7 @@ export default function ModernAccountOrderCard({
116
118
  <div className="modern-order-row__col">
117
119
  <p className="modern-order-row__label">Total amount</p>
118
120
  <p className="modern-order-row__val modern-order-row__val--price">
119
- {formatPrice(order.total, currency)}
121
+ {formatPrice(presentation.paidTotal, currency)}
120
122
  </p>
121
123
  </div>
122
124
 
@@ -204,7 +206,7 @@ export default function ModernAccountOrderCard({
204
206
  <div className="modern-order-card__foot">
205
207
  <div>
206
208
  <span className="modern-order-card__label">Total Amount</span>
207
- <p className="modern-order-card__total-val">{formatPrice(order.total, currency)}</p>
209
+ <p className="modern-order-card__total-val">{formatPrice(presentation.paidTotal, currency)}</p>
208
210
  </div>
209
211
  <LocalizedLink href={`/orders/${order.id}`} className="modern-btn modern-btn--outline">
210
212
  View Order Details →
@@ -3,10 +3,6 @@
3
3
  import { useActionState, useState } from "react"
4
4
  import type { HttpTypes } from "@medusajs/types"
5
5
  import { updateCustomer } from "@pradip1995/commerce-core/data/customer"
6
- import {
7
- isValidIndianPhone,
8
- normalizeIndianPhone,
9
- } from "@pradip1995/commerce-core/util/phone"
10
6
  import {
11
7
  sendRegistrationOtp,
12
8
  verifyRegistrationOtp,
@@ -26,21 +22,6 @@ function getInitials(name: string): string {
26
22
  return name.slice(0, 2).toUpperCase() || "RA"
27
23
  }
28
24
 
29
- function phoneDigits(value: string): string {
30
- return value.replace(/\D/g, "")
31
- }
32
-
33
- function readVerified(
34
- customer: HttpTypes.StoreCustomer,
35
- field: "email_verified" | "phone_verified"
36
- ): boolean {
37
- const direct = (customer as Record<string, unknown>)[field]
38
- if (direct === true || direct === "true") return true
39
- const meta = customer.metadata as Record<string, unknown> | undefined
40
- const fromMeta = meta?.[field]
41
- return fromMeta === true || fromMeta === "true"
42
- }
43
-
44
25
  export default function ModernAccountProfile({
45
26
  customer,
46
27
  countryCode,
@@ -51,8 +32,6 @@ export default function ModernAccountProfile({
51
32
  OtpComponent?: OtpVerificationComponent
52
33
  }) {
53
34
  const [message, setMessage] = useState<string | null>(null)
54
- const [phone, setPhone] = useState(customer.phone || "")
55
- const [phoneError, setPhoneError] = useState<string | null>(null)
56
35
  const [otpOpen, setOtpOpen] = useState(false)
57
36
  const [otp, setOtp] = useState("")
58
37
  const [otpToken, setOtpToken] = useState<string | null>(null)
@@ -61,9 +40,6 @@ export default function ModernAccountProfile({
61
40
  )
62
41
  const [otpError, setOtpError] = useState<string | null>(null)
63
42
  const [otpPending, setOtpPending] = useState(false)
64
- const [phoneVerified, setPhoneVerified] = useState(() =>
65
- readVerified(customer, "phone_verified")
66
- )
67
43
 
68
44
  async function saveProfile(
69
45
  _prev: { ok: boolean; error: string | null },
@@ -72,15 +48,11 @@ export default function ModernAccountProfile({
72
48
  try {
73
49
  const fullName = String(formData.get("full_name") || "").trim()
74
50
  const [first_name, ...rest] = fullName.split(/\s+/)
75
- const e164 = normalizeIndianPhone(phone)
76
51
  await updateCustomer({
77
52
  first_name: first_name || "",
78
53
  last_name: rest.join(" ") || ".",
79
- phone: e164 || undefined,
54
+ phone: String(formData.get("phone") || "").replace(/[^\d+]/g, "") || undefined,
80
55
  })
81
- if (e164 && phoneDigits(e164) !== phoneDigits(customer.phone || "")) {
82
- setPhoneVerified(false)
83
- }
84
56
  return { ok: true, error: null }
85
57
  } catch (err) {
86
58
  if (isNextRedirect(err)) throw err
@@ -96,43 +68,11 @@ export default function ModernAccountProfile({
96
68
  error: null,
97
69
  })
98
70
 
99
- const phoneReady = isValidIndianPhone(phone)
100
- const showVerify = !phoneVerified && phoneReady
101
-
102
- async function ensurePhoneSavedForVerification(): Promise<boolean> {
103
- setPhoneError(null)
104
- if (!phoneReady) {
105
- setPhoneError("Please enter a valid mobile number before verifying.")
106
- return false
107
- }
108
-
109
- const e164 = normalizeIndianPhone(phone)
110
- if (phoneDigits(e164) === phoneDigits(customer.phone || "")) {
111
- return true
112
- }
113
-
114
- try {
115
- await updateCustomer({ phone: e164 })
116
- return true
117
- } catch (err) {
118
- if (isNextRedirect(err)) throw err
119
- setPhoneError(
120
- safeErrorMessage(err, "Failed to save mobile number. Please try again.")
121
- )
122
- return false
123
- }
124
- }
125
-
126
71
  async function sendVerifyOtp(type: "email_verification" | "phone_verification") {
127
72
  setOtpType(type)
128
73
  setOtpPending(true)
129
74
  setOtpError(null)
130
- setPhoneError(null)
131
75
  try {
132
- if (type === "phone_verification") {
133
- const saved = await ensurePhoneSavedForVerification()
134
- if (!saved) return
135
- }
136
76
  const res = await sendRegistrationOtp(customer.id, type)
137
77
  if (!res.success) throw new Error(res.error || "Failed to send code")
138
78
  setOtpToken(res.token ?? null)
@@ -140,9 +80,7 @@ export default function ModernAccountProfile({
140
80
  setOtpOpen(true)
141
81
  } catch (err) {
142
82
  if (isNextRedirect(err)) throw err
143
- const msg = safeErrorMessage(err, "Failed to send code")
144
- setOtpError(msg)
145
- if (type === "phone_verification") setPhoneError(msg)
83
+ setOtpError(safeErrorMessage(err, "Failed to send code"))
146
84
  } finally {
147
85
  setOtpPending(false)
148
86
  }
@@ -161,7 +99,6 @@ export default function ModernAccountProfile({
161
99
  })
162
100
  if (!res.success) throw new Error(res.error || "Invalid code")
163
101
  setOtpOpen(false)
164
- if (otpType === "phone_verification") setPhoneVerified(true)
165
102
  setMessage("Verification successful.")
166
103
  window.location.reload()
167
104
  } catch (err) {
@@ -171,24 +108,17 @@ export default function ModernAccountProfile({
171
108
  }
172
109
  }
173
110
 
174
- function handlePhoneChange(value: string) {
175
- setPhone(value)
176
- setPhoneError(null)
177
- const next = normalizeIndianPhone(value)
178
- if (next && phoneDigits(next) !== phoneDigits(customer.phone || "")) {
179
- setPhoneVerified(false)
180
- }
181
- }
182
-
183
111
  const fullName = [customer.first_name, customer.last_name].filter(Boolean).join(" ")
184
112
  const initials = getInitials(fullName || customer.email)
185
- const emailVerified = readVerified(customer, "email_verified")
186
- const mobileVerified = phoneVerified && Boolean(customer.phone || phoneReady)
113
+ const emailVerified = (customer as { email_verified?: boolean }).email_verified === true
114
+ const phoneVerified = (customer as { phone_verified?: boolean }).phone_verified === true
187
115
 
188
116
  return (
189
117
  <div className="modern-account-page">
118
+ {/* Page Heading */}
190
119
  <h2 className="modern-profile-header-title">ACCOUNT DETAILS</h2>
191
120
 
121
+ {/* Profile Header Banner */}
192
122
  <div className="modern-profile-banner">
193
123
  <div className="modern-profile-banner__avatar-wrap">
194
124
  <div className="modern-profile-banner__avatar">{initials}</div>
@@ -199,9 +129,9 @@ export default function ModernAccountProfile({
199
129
  <p className="modern-profile-banner__email">{customer.email}</p>
200
130
 
201
131
  <div className="modern-profile-banner__pills">
202
- <span className={`modern-status-dot-pill ${mobileVerified ? "is-verified" : "is-unverified"}`}>
132
+ <span className={`modern-status-dot-pill ${phoneVerified && customer.phone ? "is-verified" : "is-unverified"}`}>
203
133
  <span className="modern-status-dot" />
204
- {mobileVerified ? "Mobile Verified" : "Mobile Unverified"}
134
+ {phoneVerified && customer.phone ? "Mobile Verified" : "Mobile Unverified"}
205
135
  </span>
206
136
 
207
137
  <span className={`modern-status-dot-pill ${emailVerified ? "is-verified" : "is-unverified"}`}>
@@ -212,6 +142,7 @@ export default function ModernAccountProfile({
212
142
  </div>
213
143
  </div>
214
144
 
145
+ {/* Personal Information Form Card */}
215
146
  <div className="modern-account-card">
216
147
  <div className="modern-card-sec-head">
217
148
  <h3 className="modern-card-sec-title">Personal Information</h3>
@@ -220,6 +151,7 @@ export default function ModernAccountProfile({
220
151
 
221
152
  <form action={formAction} className="modern-form" style={{ marginTop: "1.25rem" }}>
222
153
  <div className="modern-form-grid-2">
154
+ {/* FULL NAME */}
223
155
  <div className="modern-field">
224
156
  <label className="modern-field__label">FULL NAME*</label>
225
157
  <input
@@ -231,42 +163,31 @@ export default function ModernAccountProfile({
231
163
  />
232
164
  </div>
233
165
 
166
+ {/* MOBILE NUMBER */}
234
167
  <div className="modern-field">
235
- <label className="modern-field__label" htmlFor="account-profile-phone">
236
- MOBILE NUMBER*
237
- </label>
168
+ <label className="modern-field__label">MOBILE NUMBER*</label>
238
169
  <div style={{ display: "flex", gap: "0.5rem", alignItems: "center" }}>
239
170
  <input
240
- id="account-profile-phone"
241
171
  name="phone"
242
172
  type="tel"
243
- value={phone}
244
- onChange={(e) => handlePhoneChange(e.target.value)}
173
+ defaultValue={customer.phone || ""}
245
174
  placeholder="+91 9876543210"
246
175
  className="modern-field__input"
247
176
  style={{ flex: 1 }}
248
- autoComplete="tel"
249
177
  />
250
- {showVerify ? (
178
+ {!phoneVerified && customer.phone ? (
251
179
  <button
252
180
  type="button"
253
181
  onClick={() => sendVerifyOtp("phone_verification")}
254
182
  disabled={otpPending}
255
183
  className="modern-btn modern-btn--primary"
256
184
  style={{ minHeight: "2.85rem", padding: "0 1.15rem", borderRadius: "8px", flexShrink: 0 }}
257
- aria-label="Verify mobile number"
258
185
  >
259
- {otpPending && otpType === "phone_verification" ? "Sending…" : "Verify"}
186
+ Verify
260
187
  </button>
261
- ) : phoneVerified ? (
262
- <span className="modern-verified-pill">✓ Verified</span>
263
188
  ) : null}
264
189
  </div>
265
- {phoneError ? (
266
- <p role="alert" style={{ margin: "0.35rem 0 0", fontSize: "0.75rem", color: "#b91c1c" }}>
267
- {phoneError}
268
- </p>
269
- ) : showVerify ? (
190
+ {!phoneVerified ? (
270
191
  <p style={{ margin: "0.35rem 0 0", fontSize: "0.75rem", color: "#888888" }}>
271
192
  Tap Verify to get an OTP on this number.
272
193
  </p>
@@ -274,6 +195,7 @@ export default function ModernAccountProfile({
274
195
  </div>
275
196
  </div>
276
197
 
198
+ {/* EMAIL */}
277
199
  <div className="modern-field modern-field--full">
278
200
  <label className="modern-field__label">EMAIL</label>
279
201
  <div style={{ display: "flex", gap: "0.75rem", alignItems: "center" }}>
@@ -294,7 +216,9 @@ export default function ModernAccountProfile({
294
216
  Verify Email
295
217
  </button>
296
218
  ) : (
297
- <span className="modern-verified-pill">✓ Verified</span>
219
+ <span className="modern-verified-pill">
220
+ ✓ Verified
221
+ </span>
298
222
  )}
299
223
  </div>
300
224
  </div>
@@ -737,50 +737,6 @@
737
737
  color: #ffffff;
738
738
  }
739
739
 
740
- .modern-address-type__options {
741
- display: flex;
742
- flex-wrap: wrap;
743
- gap: 0.5rem;
744
- }
745
-
746
- .modern-address-type__option {
747
- position: relative;
748
- cursor: pointer;
749
- }
750
-
751
- .modern-address-type__option input {
752
- position: absolute;
753
- opacity: 0;
754
- pointer-events: none;
755
- }
756
-
757
- .modern-address-type__option span {
758
- display: inline-flex;
759
- align-items: center;
760
- justify-content: center;
761
- min-height: 2.4rem;
762
- padding: 0 1.15rem;
763
- border-radius: 999px;
764
- border: 1px solid var(--lux-border);
765
- background: #ffffff;
766
- color: var(--lux-onyx);
767
- font-size: 0.75rem;
768
- font-weight: 700;
769
- letter-spacing: 0.08em;
770
- text-transform: uppercase;
771
- transition: all 0.18s ease;
772
- }
773
-
774
- .modern-address-type__option input:focus-visible + span {
775
- box-shadow: 0 0 0 3px rgba(62, 48, 83, 0.18);
776
- }
777
-
778
- .modern-address-type__option input:checked + span {
779
- background: var(--lux-plum);
780
- border-color: var(--lux-plum);
781
- color: #ffffff;
782
- }
783
-
784
740
  .modern-btn--primary:hover:not(:disabled) {
785
741
  background: #2d223f;
786
742
  }
@@ -1,26 +0,0 @@
1
- "use server"
2
-
3
- import { setDefaultAddress } from "@pradip1995/commerce-core/data/customer"
4
-
5
- /** Sets this address as the default shipping address. Medusa unsets the previous shipping default. */
6
- export async function setExclusiveDefaultAddress(addressId: string) {
7
- if (!addressId) {
8
- return { success: false, error: "Address id is required" }
9
- }
10
-
11
- try {
12
- const result = await setDefaultAddress(addressId)
13
- if (!result?.success) {
14
- return {
15
- success: false,
16
- error: result?.error || "Failed to set default address",
17
- }
18
- }
19
- return { success: true, error: null }
20
- } catch (err) {
21
- return {
22
- success: false,
23
- error: err instanceof Error ? err.message : "Failed to set default address",
24
- }
25
- }
26
- }
@@ -1,186 +0,0 @@
1
- import assert from "node:assert/strict"
2
- import { describe, it } from "node:test"
3
- import {
4
- addressTypeFromMetadata,
5
- isExclusiveDefaultAddress,
6
- resolveAddressType,
7
- resolveDefaultAddressId,
8
- sortAddressesDefaultFirst,
9
- } from "./default-address.ts"
10
-
11
- describe("resolveDefaultAddressId", () => {
12
- const cases: Array<{
13
- name: string
14
- addresses: Parameters<typeof resolveDefaultAddressId>[0]
15
- expected: string | null
16
- }> = [
17
- { name: "empty list", addresses: [], expected: null },
18
- {
19
- name: "no default flags",
20
- addresses: [
21
- { id: "a1" },
22
- { id: "a2", is_default_shipping: false, is_default_billing: false },
23
- ],
24
- expected: null,
25
- },
26
- {
27
- name: "only shipping default",
28
- addresses: [
29
- { id: "a1", is_default_shipping: true },
30
- { id: "a2", is_default_billing: false },
31
- ],
32
- expected: "a1",
33
- },
34
- {
35
- name: "only billing default",
36
- addresses: [
37
- { id: "a1", is_default_billing: true },
38
- { id: "a2" },
39
- ],
40
- expected: "a1",
41
- },
42
- {
43
- name: "shipping wins when both addresses claim default",
44
- addresses: [
45
- { id: "ship", is_default_shipping: true, is_default_billing: false },
46
- { id: "bill", is_default_shipping: false, is_default_billing: true },
47
- ],
48
- expected: "ship",
49
- },
50
- {
51
- name: "same address shipping and billing",
52
- addresses: [
53
- { id: "only", is_default_shipping: true, is_default_billing: true },
54
- { id: "other" },
55
- ],
56
- expected: "only",
57
- },
58
- {
59
- name: "ignores default without id",
60
- addresses: [{ is_default_shipping: true }, { id: "a2", is_default_billing: true }],
61
- expected: "a2",
62
- },
63
- ]
64
-
65
- for (const row of cases) {
66
- it(row.name, () => {
67
- assert.equal(resolveDefaultAddressId(row.addresses), row.expected)
68
- })
69
- }
70
- })
71
-
72
- describe("isExclusiveDefaultAddress", () => {
73
- const cases: Array<{
74
- name: string
75
- address: { id?: string | null }
76
- defaultAddressId: string | null
77
- expected: boolean
78
- }> = [
79
- { name: "match", address: { id: "a1" }, defaultAddressId: "a1", expected: true },
80
- { name: "other address", address: { id: "a2" }, defaultAddressId: "a1", expected: false },
81
- { name: "no default selected", address: { id: "a1" }, defaultAddressId: null, expected: false },
82
- { name: "missing id", address: {}, defaultAddressId: "a1", expected: false },
83
- ]
84
-
85
- for (const row of cases) {
86
- it(row.name, () => {
87
- assert.equal(
88
- isExclusiveDefaultAddress(row.address, row.defaultAddressId),
89
- row.expected
90
- )
91
- })
92
- }
93
- })
94
-
95
- describe("sortAddressesDefaultFirst", () => {
96
- const cases: Array<{
97
- name: string
98
- addresses: Array<{ id: string; is_default_shipping?: boolean; is_default_billing?: boolean }>
99
- expected: string[]
100
- }> = [
101
- {
102
- name: "empty list",
103
- addresses: [],
104
- expected: [],
105
- },
106
- {
107
- name: "no default keeps order",
108
- addresses: [{ id: "a" }, { id: "b" }, { id: "c" }],
109
- expected: ["a", "b", "c"],
110
- },
111
- {
112
- name: "shipping default moves to top",
113
- addresses: [
114
- { id: "a" },
115
- { id: "b", is_default_shipping: true },
116
- { id: "c" },
117
- ],
118
- expected: ["b", "a", "c"],
119
- },
120
- {
121
- name: "billing default used when no shipping default",
122
- addresses: [
123
- { id: "a" },
124
- { id: "b", is_default_billing: true },
125
- ],
126
- expected: ["b", "a"],
127
- },
128
- {
129
- name: "shipping wins if both flags exist on different addresses",
130
- addresses: [
131
- { id: "bill", is_default_billing: true },
132
- { id: "ship", is_default_shipping: true },
133
- ],
134
- expected: ["ship", "bill"],
135
- },
136
- {
137
- name: "already first stays first",
138
- addresses: [{ id: "def", is_default_shipping: true }, { id: "other" }],
139
- expected: ["def", "other"],
140
- },
141
- ]
142
-
143
- for (const row of cases) {
144
- it(row.name, () => {
145
- assert.deepEqual(
146
- sortAddressesDefaultFirst(row.addresses).map((address) => address.id),
147
- row.expected
148
- )
149
- })
150
- }
151
- })
152
-
153
- describe("resolveAddressType", () => {
154
- const cases: Array<{ name: string; value: unknown; expected: "HOME" | "OFFICE" }> = [
155
- { name: "empty string", value: "", expected: "HOME" },
156
- { name: "null", value: null, expected: "HOME" },
157
- { name: "undefined", value: undefined, expected: "HOME" },
158
- { name: "home lowercase", value: "home", expected: "HOME" },
159
- { name: "HOME uppercase", value: "HOME", expected: "HOME" },
160
- { name: "office lowercase", value: "office", expected: "OFFICE" },
161
- { name: "OFFICE uppercase", value: "OFFICE", expected: "OFFICE" },
162
- { name: "Office mixed", value: " Office ", expected: "OFFICE" },
163
- { name: "unknown falls back to home", value: "other", expected: "HOME" },
164
- ]
165
-
166
- for (const row of cases) {
167
- it(row.name, () => {
168
- assert.equal(resolveAddressType(row.value), row.expected)
169
- })
170
- }
171
- })
172
-
173
- describe("addressTypeFromMetadata", () => {
174
- const cases: Array<{ name: string; metadata: unknown; expected: "HOME" | "OFFICE" }> = [
175
- { name: "missing metadata", metadata: null, expected: "HOME" },
176
- { name: "empty object", metadata: {}, expected: "HOME" },
177
- { name: "home type", metadata: { address_type: "HOME" }, expected: "HOME" },
178
- { name: "office type", metadata: { address_type: "office" }, expected: "OFFICE" },
179
- ]
180
-
181
- for (const row of cases) {
182
- it(row.name, () => {
183
- assert.equal(addressTypeFromMetadata(row.metadata), row.expected)
184
- })
185
- }
186
- })
@@ -1,47 +0,0 @@
1
- export type DefaultAddressFlags = {
2
- id?: string | null
3
- is_default_shipping?: boolean | null
4
- is_default_billing?: boolean | null
5
- }
6
-
7
- export const ADDRESS_TYPES = ["HOME", "OFFICE"] as const
8
- export type AddressType = (typeof ADDRESS_TYPES)[number]
9
-
10
- /** One default only: shipping wins, then billing. */
11
- export function resolveDefaultAddressId(
12
- addresses: DefaultAddressFlags[]
13
- ): string | null {
14
- const shipping = addresses.find((address) => address.is_default_shipping && address.id)
15
- if (shipping?.id) return shipping.id
16
- const billing = addresses.find((address) => address.is_default_billing && address.id)
17
- return billing?.id ?? null
18
- }
19
-
20
- export function isExclusiveDefaultAddress(
21
- address: DefaultAddressFlags,
22
- defaultAddressId: string | null
23
- ): boolean {
24
- return Boolean(address.id) && address.id === defaultAddressId
25
- }
26
-
27
- /** Default address first; original order kept for the rest. */
28
- export function sortAddressesDefaultFirst<T extends DefaultAddressFlags>(
29
- addresses: T[]
30
- ): T[] {
31
- const defaultId = resolveDefaultAddressId(addresses)
32
- if (!defaultId) return addresses
33
- return [...addresses].sort((left, right) => {
34
- if (left.id === defaultId) return -1
35
- if (right.id === defaultId) return 1
36
- return 0
37
- })
38
- }
39
-
40
- export function resolveAddressType(value: unknown): AddressType {
41
- return String(value ?? "").trim().toUpperCase() === "OFFICE" ? "OFFICE" : "HOME"
42
- }
43
-
44
- export function addressTypeFromMetadata(metadata: unknown): AddressType {
45
- if (!metadata || typeof metadata !== "object") return "HOME"
46
- return resolveAddressType((metadata as Record<string, unknown>).address_type)
47
- }