@pradip1995/segment-jewelry-account-pages 0.1.5 → 0.1.7

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.5",
3
+ "version": "0.1.7",
4
4
  "license": "MIT",
5
5
  "publishConfig": {
6
6
  "access": "public"
@@ -8,7 +8,9 @@ import {
8
8
  normalizeIndianPhone,
9
9
  } from "@pradip1995/commerce-core/util/phone"
10
10
  import {
11
+ requestContactChange,
11
12
  sendRegistrationOtp,
13
+ verifyContactChange,
12
14
  verifyRegistrationOtp,
13
15
  } from "@pradip1995/segment-login-template/auth-server"
14
16
  import type { OtpVerificationComponent } from "@pradip1995/segment-login-template/otp-component"
@@ -17,6 +19,17 @@ import {
17
19
  isNextRedirect,
18
20
  safeErrorMessage,
19
21
  } from "@pradip1995/segment-primitives/is-next-redirect"
22
+ import {
23
+ EMAIL_OTP_ERRORS,
24
+ PHONE_OTP_ERRORS,
25
+ isValidEmail,
26
+ isContactStatusVerified,
27
+ resolveEmailOtpFlow,
28
+ resolvePhoneOtpFlow,
29
+ verifiedFieldAction,
30
+ type ContactOtpFlow,
31
+ type VerifiedFieldAction,
32
+ } from "./profile-contact-field"
20
33
 
21
34
  function getInitials(name: string): string {
22
35
  const parts = name.trim().split(/\s+/)
@@ -26,21 +39,77 @@ function getInitials(name: string): string {
26
39
  return name.slice(0, 2).toUpperCase() || "RA"
27
40
  }
28
41
 
29
- function phoneDigits(value: string): string {
30
- return value.replace(/\D/g, "")
31
- }
32
-
33
42
  function readVerified(
34
43
  customer: HttpTypes.StoreCustomer,
35
44
  field: "email_verified" | "phone_verified"
36
45
  ): boolean {
37
- const direct = (customer as Record<string, unknown>)[field]
46
+ const direct = (customer as unknown as Record<string, unknown>)[field]
38
47
  if (direct === true || direct === "true") return true
39
48
  const meta = customer.metadata as Record<string, unknown> | undefined
40
49
  const fromMeta = meta?.[field]
41
50
  return fromMeta === true || fromMeta === "true"
42
51
  }
43
52
 
53
+ const COMPACT_BTN_STYLE = {
54
+ minHeight: "2.85rem",
55
+ padding: "0 1.15rem",
56
+ borderRadius: "8px",
57
+ flexShrink: 0,
58
+ } as const
59
+
60
+ function ContactActions({
61
+ action,
62
+ verifyPending,
63
+ verifyLabel,
64
+ verifyAriaLabel,
65
+ editAriaLabel,
66
+ onVerify,
67
+ onEdit,
68
+ }: {
69
+ action: VerifiedFieldAction
70
+ verifyPending: boolean
71
+ verifyLabel: string
72
+ verifyAriaLabel: string
73
+ editAriaLabel: string
74
+ onVerify: () => void
75
+ onEdit: () => void
76
+ }) {
77
+ if (action === "edit") {
78
+ return (
79
+ <>
80
+ <span className="modern-verified-pill">✓ Verified</span>
81
+ <button
82
+ type="button"
83
+ onClick={onEdit}
84
+ className="modern-btn modern-btn--outline"
85
+ style={COMPACT_BTN_STYLE}
86
+ aria-label={editAriaLabel}
87
+ >
88
+ Edit
89
+ </button>
90
+ </>
91
+ )
92
+ }
93
+ if (action === "verified") {
94
+ return <span className="modern-verified-pill">✓ Verified</span>
95
+ }
96
+ if (action === "verify") {
97
+ return (
98
+ <button
99
+ type="button"
100
+ onClick={onVerify}
101
+ disabled={verifyPending}
102
+ className="modern-btn modern-btn--primary"
103
+ style={COMPACT_BTN_STYLE}
104
+ aria-label={verifyAriaLabel}
105
+ >
106
+ {verifyPending ? "Sending…" : verifyLabel}
107
+ </button>
108
+ )
109
+ }
110
+ return null
111
+ }
112
+
44
113
  export default function ModernAccountProfile({
45
114
  customer,
46
115
  countryCode,
@@ -53,17 +122,25 @@ export default function ModernAccountProfile({
53
122
  const [message, setMessage] = useState<string | null>(null)
54
123
  const [phone, setPhone] = useState(customer.phone || "")
55
124
  const [phoneError, setPhoneError] = useState<string | null>(null)
125
+ const [editingPhone, setEditingPhone] = useState(false)
126
+ const [email, setEmail] = useState(customer.email || "")
127
+ const [emailError, setEmailError] = useState<string | null>(null)
128
+ const [editingEmail, setEditingEmail] = useState(false)
56
129
  const [otpOpen, setOtpOpen] = useState(false)
57
130
  const [otp, setOtp] = useState("")
58
131
  const [otpToken, setOtpToken] = useState<string | null>(null)
59
132
  const [otpType, setOtpType] = useState<"email_verification" | "phone_verification">(
60
133
  "email_verification"
61
134
  )
135
+ const [otpFlow, setOtpFlow] = useState<ContactOtpFlow>("verify_existing")
62
136
  const [otpError, setOtpError] = useState<string | null>(null)
63
137
  const [otpPending, setOtpPending] = useState(false)
64
138
  const [phoneVerified, setPhoneVerified] = useState(() =>
65
139
  readVerified(customer, "phone_verified")
66
140
  )
141
+ const [emailVerified, setEmailVerified] = useState(() =>
142
+ readVerified(customer, "email_verified")
143
+ )
67
144
 
68
145
  async function saveProfile(
69
146
  _prev: { ok: boolean; error: string | null },
@@ -72,15 +149,11 @@ export default function ModernAccountProfile({
72
149
  try {
73
150
  const fullName = String(formData.get("full_name") || "").trim()
74
151
  const [first_name, ...rest] = fullName.split(/\s+/)
75
- const e164 = normalizeIndianPhone(phone)
152
+ // Phone/email only change via OTP contact endpoints — never PATCH them here.
76
153
  await updateCustomer({
77
154
  first_name: first_name || "",
78
155
  last_name: rest.join(" ") || ".",
79
- phone: e164 || undefined,
80
156
  })
81
- if (e164 && phoneDigits(e164) !== phoneDigits(customer.phone || "")) {
82
- setPhoneVerified(false)
83
- }
84
157
  return { ok: true, error: null }
85
158
  } catch (err) {
86
159
  if (isNextRedirect(err)) throw err
@@ -97,44 +170,62 @@ export default function ModernAccountProfile({
97
170
  })
98
171
 
99
172
  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
- }
173
+ const emailReady = isValidEmail(email)
174
+ const phoneLocked = phoneVerified && !editingPhone
175
+ const emailLocked = emailVerified && !editingEmail
176
+ const phoneAction = verifiedFieldAction({
177
+ verified: phoneVerified,
178
+ editing: editingPhone,
179
+ ready: phoneReady,
180
+ })
181
+ const emailAction = verifiedFieldAction({
182
+ verified: emailVerified,
183
+ editing: editingEmail,
184
+ ready: emailReady,
185
+ })
125
186
 
126
187
  async function sendVerifyOtp(type: "email_verification" | "phone_verification") {
127
188
  setOtpType(type)
128
189
  setOtpPending(true)
129
190
  setOtpError(null)
130
191
  setPhoneError(null)
192
+ setEmailError(null)
131
193
  try {
132
194
  if (type === "phone_verification") {
133
- const saved = await ensurePhoneSavedForVerification()
134
- if (!saved) return
195
+ const resolved = resolvePhoneOtpFlow({
196
+ currentPhone: customer.phone,
197
+ draftE164: normalizeIndianPhone(phone),
198
+ })
199
+ if (!resolved.ok) {
200
+ setPhoneError(PHONE_OTP_ERRORS[resolved.reason])
201
+ return
202
+ }
203
+ setOtpFlow(resolved.flow)
204
+ const res =
205
+ resolved.flow === "change_contact"
206
+ ? await requestContactChange({ phone: resolved.phone })
207
+ : await sendRegistrationOtp(customer.id, type)
208
+ if (!res.success) throw new Error(res.error || "Failed to send code")
209
+ setOtpToken(res.token ?? null)
210
+ setOtp("")
211
+ setOtpOpen(true)
212
+ return
213
+ }
214
+
215
+ const resolved = resolveEmailOtpFlow({
216
+ currentEmail: customer.email,
217
+ draftEmail: email,
218
+ })
219
+ if (!resolved.ok) {
220
+ setEmailError(EMAIL_OTP_ERRORS[resolved.reason])
221
+ return
135
222
  }
136
- const res = await sendRegistrationOtp(customer.id, type)
137
- if (!res.success) throw new Error(res.error || "Failed to send code")
223
+ setOtpFlow(resolved.flow)
224
+ const res =
225
+ resolved.flow === "change_contact"
226
+ ? await requestContactChange({ email: resolved.email })
227
+ : await sendRegistrationOtp(customer.id, type)
228
+ if (!res?.success) throw new Error(res?.error || "Failed to send code")
138
229
  setOtpToken(res.token ?? null)
139
230
  setOtp("")
140
231
  setOtpOpen(true)
@@ -143,6 +234,7 @@ export default function ModernAccountProfile({
143
234
  const msg = safeErrorMessage(err, "Failed to send code")
144
235
  setOtpError(msg)
145
236
  if (type === "phone_verification") setPhoneError(msg)
237
+ if (type === "email_verification") setEmailError(msg)
146
238
  } finally {
147
239
  setOtpPending(false)
148
240
  }
@@ -153,15 +245,30 @@ export default function ModernAccountProfile({
153
245
  setOtpPending(true)
154
246
  setOtpError(null)
155
247
  try {
156
- const res = await verifyRegistrationOtp({
157
- otpToken: otpToken || "",
158
- code: otp,
159
- countryCode,
160
- skipRedirect: true,
161
- })
162
- if (!res.success) throw new Error(res.error || "Invalid code")
248
+ if (otpFlow === "change_contact") {
249
+ const res = await verifyContactChange({
250
+ otpToken: otpToken || "",
251
+ code: otp,
252
+ })
253
+ if (!res.success) throw new Error(res.error || "Invalid code")
254
+ } else {
255
+ const res = await verifyRegistrationOtp({
256
+ otpToken: otpToken || "",
257
+ code: otp,
258
+ countryCode,
259
+ skipRedirect: true,
260
+ })
261
+ if (!res.success) throw new Error(res.error || "Invalid code")
262
+ }
263
+ if (otpType === "phone_verification") {
264
+ setPhoneVerified(true)
265
+ setEditingPhone(false)
266
+ }
267
+ if (otpType === "email_verification") {
268
+ setEmailVerified(true)
269
+ setEditingEmail(false)
270
+ }
163
271
  setOtpOpen(false)
164
- if (otpType === "phone_verification") setPhoneVerified(true)
165
272
  setMessage("Verification successful.")
166
273
  window.location.reload()
167
274
  } catch (err) {
@@ -174,16 +281,40 @@ export default function ModernAccountProfile({
174
281
  function handlePhoneChange(value: string) {
175
282
  setPhone(value)
176
283
  setPhoneError(null)
177
- const next = normalizeIndianPhone(value)
178
- if (next && phoneDigits(next) !== phoneDigits(customer.phone || "")) {
179
- setPhoneVerified(false)
180
- }
284
+ // Any edit clears verified UI until OTP succeeds — never restore from server mid-edit.
285
+ setPhoneVerified(false)
286
+ }
287
+
288
+ function handleEmailChange(value: string) {
289
+ setEmail(value)
290
+ setEmailError(null)
291
+ setEmailVerified(false)
292
+ }
293
+
294
+ function startEditingPhone() {
295
+ setEditingPhone(true)
296
+ setPhoneVerified(false)
297
+ setPhoneError(null)
298
+ }
299
+
300
+ function startEditingEmail() {
301
+ setEditingEmail(true)
302
+ setEmailVerified(false)
303
+ setEmailError(null)
181
304
  }
182
305
 
183
306
  const fullName = [customer.first_name, customer.last_name].filter(Boolean).join(" ")
184
307
  const initials = getInitials(fullName || customer.email)
185
- const emailVerified = readVerified(customer, "email_verified")
186
- const mobileVerified = phoneVerified && Boolean(customer.phone || phoneReady)
308
+ const mobileVerified = isContactStatusVerified({
309
+ verified: phoneVerified && Boolean(customer.phone || phoneReady),
310
+ editing: editingPhone,
311
+ })
312
+ const emailStatusVerified = isContactStatusVerified({
313
+ verified: emailVerified,
314
+ editing: editingEmail,
315
+ })
316
+ const otpTarget =
317
+ otpType === "email_verification" ? email || "email" : phone || "phone"
187
318
 
188
319
  return (
189
320
  <div className="modern-account-page">
@@ -204,9 +335,9 @@ export default function ModernAccountProfile({
204
335
  {mobileVerified ? "Mobile Verified" : "Mobile Unverified"}
205
336
  </span>
206
337
 
207
- <span className={`modern-status-dot-pill ${emailVerified ? "is-verified" : "is-unverified"}`}>
338
+ <span className={`modern-status-dot-pill ${emailStatusVerified ? "is-verified" : "is-unverified"}`}>
208
339
  <span className="modern-status-dot" />
209
- {emailVerified ? "Email Verified" : "Email Unverified"}
340
+ {emailStatusVerified ? "Email Verified" : "Email Unverified"}
210
341
  </span>
211
342
  </div>
212
343
  </div>
@@ -235,7 +366,7 @@ export default function ModernAccountProfile({
235
366
  <label className="modern-field__label" htmlFor="account-profile-phone">
236
367
  MOBILE NUMBER*
237
368
  </label>
238
- <div style={{ display: "flex", gap: "0.5rem", alignItems: "center" }}>
369
+ <div className="modern-field-row">
239
370
  <input
240
371
  id="account-profile-phone"
241
372
  name="phone"
@@ -244,59 +375,72 @@ export default function ModernAccountProfile({
244
375
  onChange={(e) => handlePhoneChange(e.target.value)}
245
376
  placeholder="+91 9876543210"
246
377
  className="modern-field__input"
247
- style={{ flex: 1 }}
248
378
  autoComplete="tel"
379
+ readOnly={phoneLocked}
380
+ aria-readonly={phoneLocked || undefined}
381
+ />
382
+ <ContactActions
383
+ action={phoneAction}
384
+ verifyPending={otpPending && otpType === "phone_verification"}
385
+ verifyLabel="Verify"
386
+ verifyAriaLabel="Verify mobile number"
387
+ editAriaLabel="Edit mobile number"
388
+ onVerify={() => sendVerifyOtp("phone_verification")}
389
+ onEdit={startEditingPhone}
249
390
  />
250
- {showVerify ? (
251
- <button
252
- type="button"
253
- onClick={() => sendVerifyOtp("phone_verification")}
254
- disabled={otpPending}
255
- className="modern-btn modern-btn--primary"
256
- style={{ minHeight: "2.85rem", padding: "0 1.15rem", borderRadius: "8px", flexShrink: 0 }}
257
- aria-label="Verify mobile number"
258
- >
259
- {otpPending && otpType === "phone_verification" ? "Sending…" : "Verify"}
260
- </button>
261
- ) : phoneVerified ? (
262
- <span className="modern-verified-pill">✓ Verified</span>
263
- ) : null}
264
391
  </div>
265
392
  {phoneError ? (
266
- <p role="alert" style={{ margin: "0.35rem 0 0", fontSize: "0.75rem", color: "#b91c1c" }}>
393
+ <p role="alert" className="modern-field-hint modern-field-hint--error">
267
394
  {phoneError}
268
395
  </p>
269
- ) : showVerify ? (
270
- <p style={{ margin: "0.35rem 0 0", fontSize: "0.75rem", color: "#888888" }}>
271
- Tap Verify to get an OTP on this number.
272
- </p>
396
+ ) : phoneAction === "edit" ? (
397
+ <p className="modern-field-hint">Tap Edit to change this number, then verify it again.</p>
398
+ ) : phoneAction === "verify" ? (
399
+ <p className="modern-field-hint">Tap Verify to get an OTP on this number.</p>
400
+ ) : editingPhone ? (
401
+ <p className="modern-field-hint">Enter a new number, then tap Verify.</p>
273
402
  ) : null}
274
403
  </div>
275
404
  </div>
276
405
 
277
406
  <div className="modern-field modern-field--full">
278
- <label className="modern-field__label">EMAIL</label>
279
- <div style={{ display: "flex", gap: "0.75rem", alignItems: "center" }}>
407
+ <label className="modern-field__label" htmlFor="account-profile-email">
408
+ EMAIL
409
+ </label>
410
+ <div className="modern-field-row">
280
411
  <input
281
- value={customer.email}
282
- readOnly
412
+ id="account-profile-email"
413
+ name="email"
414
+ type="email"
415
+ value={email}
416
+ onChange={(e) => handleEmailChange(e.target.value)}
417
+ readOnly={emailLocked}
418
+ aria-readonly={emailLocked || undefined}
419
+ placeholder="Enter your email"
420
+ autoComplete="email"
283
421
  className="modern-field__input"
284
- style={{ flex: 1 }}
285
422
  />
286
- {!emailVerified ? (
287
- <button
288
- type="button"
289
- onClick={() => sendVerifyOtp("email_verification")}
290
- disabled={otpPending}
291
- className="modern-btn modern-btn--outline"
292
- style={{ flexShrink: 0 }}
293
- >
294
- Verify Email
295
- </button>
296
- ) : (
297
- <span className="modern-verified-pill">✓ Verified</span>
298
- )}
423
+ <ContactActions
424
+ action={emailAction}
425
+ verifyPending={otpPending && otpType === "email_verification"}
426
+ verifyLabel="Verify Email"
427
+ verifyAriaLabel="Verify email"
428
+ editAriaLabel="Edit email"
429
+ onVerify={() => sendVerifyOtp("email_verification")}
430
+ onEdit={startEditingEmail}
431
+ />
299
432
  </div>
433
+ {emailError ? (
434
+ <p role="alert" className="modern-field-hint modern-field-hint--error">
435
+ {emailError}
436
+ </p>
437
+ ) : emailAction === "edit" ? (
438
+ <p className="modern-field-hint">Tap Edit to change this email, then verify it again.</p>
439
+ ) : emailAction === "verify" ? (
440
+ <p className="modern-field-hint">Tap Verify to get an OTP at this address.</p>
441
+ ) : editingEmail ? (
442
+ <p className="modern-field-hint">Enter a new email, then tap Verify.</p>
443
+ ) : null}
300
444
  </div>
301
445
 
302
446
  {state.error || message ? (
@@ -329,7 +473,7 @@ export default function ModernAccountProfile({
329
473
  <OtpComponent
330
474
  open={otpOpen}
331
475
  title={otpType === "email_verification" ? "Verify Email" : "Verify Phone"}
332
- description={`Enter verification code sent to your ${otpType === "email_verification" ? "email" : "phone"}.`}
476
+ description={`Enter verification code sent to ${otpTarget}.`}
333
477
  otp={otp}
334
478
  onOtpChange={setOtp}
335
479
  error={otpError}
@@ -718,6 +718,28 @@
718
718
  cursor: not-allowed;
719
719
  }
720
720
 
721
+ .modern-field-row {
722
+ display: flex;
723
+ gap: 0.5rem;
724
+ align-items: center;
725
+ flex-wrap: wrap;
726
+ }
727
+
728
+ .modern-field-row .modern-field__input {
729
+ flex: 1;
730
+ min-width: 12rem;
731
+ }
732
+
733
+ .modern-field-hint {
734
+ margin: 0.35rem 0 0;
735
+ font-size: 0.75rem;
736
+ color: #888888;
737
+ }
738
+
739
+ .modern-field-hint--error {
740
+ color: #b91c1c;
741
+ }
742
+
721
743
  /* Buttons */
722
744
  .modern-btn {
723
745
  display: inline-flex;
@@ -0,0 +1,259 @@
1
+ import assert from "node:assert/strict"
2
+ import { describe, it } from "node:test"
3
+ import {
4
+ EMAIL_OTP_ERRORS,
5
+ PHONE_OTP_ERRORS,
6
+ isValidEmail,
7
+ isVerifiedFieldLocked,
8
+ isContactStatusVerified,
9
+ normalizeEmail,
10
+ phoneDigits,
11
+ resolveEmailOtpFlow,
12
+ resolvePhoneOtpFlow,
13
+ verifiedFieldAction,
14
+ type ContactOtpFlow,
15
+ type ResolveEmailOtpFlowResult,
16
+ type ResolvePhoneOtpFlowResult,
17
+ type VerifiedFieldAction,
18
+ } from "./profile-contact-field.ts"
19
+
20
+ describe("phoneDigits", () => {
21
+ const cases: Array<{ name: string; value: string; want: string }> = [
22
+ { name: "strips spaces and plus", value: "+91 87800 50157", want: "918780050157" },
23
+ { name: "keeps digits only", value: "878-005-0157", want: "8780050157" },
24
+ { name: "empty stays empty", value: "", want: "" },
25
+ ]
26
+ for (const tc of cases) {
27
+ it(tc.name, () => {
28
+ assert.equal(phoneDigits(tc.value), tc.want)
29
+ })
30
+ }
31
+ })
32
+
33
+ describe("isVerifiedFieldLocked", () => {
34
+ const cases: Array<{
35
+ name: string
36
+ verified: boolean
37
+ editing: boolean
38
+ want: boolean
39
+ }> = [
40
+ { name: "verified and not editing is locked", verified: true, editing: false, want: true },
41
+ { name: "verified while editing is unlocked", verified: true, editing: true, want: false },
42
+ { name: "unverified is never locked", verified: false, editing: false, want: false },
43
+ { name: "unverified stays unlocked even if editing", verified: false, editing: true, want: false },
44
+ ]
45
+ for (const tc of cases) {
46
+ it(tc.name, () => {
47
+ assert.equal(
48
+ isVerifiedFieldLocked({ verified: tc.verified, editing: tc.editing }),
49
+ tc.want
50
+ )
51
+ })
52
+ }
53
+ })
54
+
55
+ describe("verifiedFieldAction", () => {
56
+ const cases: Array<{
57
+ name: string
58
+ verified: boolean
59
+ editing: boolean
60
+ ready: boolean
61
+ want: VerifiedFieldAction
62
+ }> = [
63
+ {
64
+ name: "verified contact shows edit",
65
+ verified: true,
66
+ editing: false,
67
+ ready: true,
68
+ want: "edit",
69
+ },
70
+ {
71
+ name: "editing a previously verified contact requires verify again",
72
+ verified: true,
73
+ editing: true,
74
+ ready: true,
75
+ want: "verify",
76
+ },
77
+ {
78
+ name: "editing with incomplete draft shows no action yet",
79
+ verified: true,
80
+ editing: true,
81
+ ready: false,
82
+ want: "none",
83
+ },
84
+ {
85
+ name: "typed valid unverified contact shows verify",
86
+ verified: false,
87
+ editing: false,
88
+ ready: true,
89
+ want: "verify",
90
+ },
91
+ {
92
+ name: "empty unverified contact shows no action yet",
93
+ verified: false,
94
+ editing: false,
95
+ ready: false,
96
+ want: "none",
97
+ },
98
+ ]
99
+ for (const tc of cases) {
100
+ it(tc.name, () => {
101
+ assert.equal(
102
+ verifiedFieldAction({
103
+ verified: tc.verified,
104
+ editing: tc.editing,
105
+ ready: tc.ready,
106
+ }),
107
+ tc.want
108
+ )
109
+ })
110
+ }
111
+ })
112
+
113
+ describe("isContactStatusVerified", () => {
114
+ const cases: Array<{
115
+ name: string
116
+ verified: boolean
117
+ editing: boolean
118
+ want: boolean
119
+ }> = [
120
+ { name: "verified and not editing is verified", verified: true, editing: false, want: true },
121
+ { name: "verified while editing is not verified", verified: true, editing: true, want: false },
122
+ { name: "unverified is never verified", verified: false, editing: false, want: false },
123
+ ]
124
+ for (const tc of cases) {
125
+ it(tc.name, () => {
126
+ assert.equal(
127
+ isContactStatusVerified({ verified: tc.verified, editing: tc.editing }),
128
+ tc.want
129
+ )
130
+ })
131
+ }
132
+ })
133
+
134
+ describe("normalizeEmail", () => {
135
+ const cases: Array<{ name: string; value: string | null | undefined; want: string }> = [
136
+ { name: "trims and lowercases", value: " Jay@Empire.COM ", want: "jay@empire.com" },
137
+ { name: "empty stays empty", value: "", want: "" },
138
+ { name: "null becomes empty", value: null, want: "" },
139
+ ]
140
+ for (const tc of cases) {
141
+ it(tc.name, () => {
142
+ assert.equal(normalizeEmail(tc.value), tc.want)
143
+ })
144
+ }
145
+ })
146
+
147
+ describe("isValidEmail", () => {
148
+ const cases: Array<{ name: string; value: string | null | undefined; want: boolean }> = [
149
+ { name: "accepts a normal email", value: "jay@empire.com", want: true },
150
+ { name: "rejects empty", value: "", want: false },
151
+ { name: "rejects missing at-sign", value: "jayempire.com", want: false },
152
+ ]
153
+ for (const tc of cases) {
154
+ it(tc.name, () => {
155
+ assert.equal(isValidEmail(tc.value), tc.want)
156
+ })
157
+ }
158
+ })
159
+
160
+ describe("resolveEmailOtpFlow", () => {
161
+ const cases: Array<{
162
+ name: string
163
+ currentEmail: string | null | undefined
164
+ draftEmail: string
165
+ want: ResolveEmailOtpFlowResult
166
+ }> = [
167
+ {
168
+ name: "same email verifies the existing address",
169
+ currentEmail: "jay@empire.com",
170
+ draftEmail: "Jay@Empire.com",
171
+ want: { ok: true, flow: "verify_existing", email: "jay@empire.com" },
172
+ },
173
+ {
174
+ name: "changing to a different email uses contact change",
175
+ currentEmail: "old@empire.com",
176
+ draftEmail: "new@empire.com",
177
+ want: { ok: true, flow: "change_contact", email: "new@empire.com" },
178
+ },
179
+ {
180
+ name: "empty draft is empty",
181
+ currentEmail: "jay@empire.com",
182
+ draftEmail: " ",
183
+ want: { ok: false, reason: "empty" },
184
+ },
185
+ {
186
+ name: "malformed draft is invalid",
187
+ currentEmail: "jay@empire.com",
188
+ draftEmail: "not-an-email",
189
+ want: { ok: false, reason: "invalid" },
190
+ },
191
+ ]
192
+ for (const tc of cases) {
193
+ it(tc.name, () => {
194
+ assert.deepEqual(
195
+ resolveEmailOtpFlow({ currentEmail: tc.currentEmail, draftEmail: tc.draftEmail }),
196
+ tc.want
197
+ )
198
+ })
199
+ }
200
+ })
201
+
202
+ describe("resolvePhoneOtpFlow", () => {
203
+ const cases: Array<{
204
+ name: string
205
+ currentPhone: string | null | undefined
206
+ draftE164: string
207
+ want: ResolvePhoneOtpFlowResult
208
+ }> = [
209
+ {
210
+ name: "same number verifies the existing phone",
211
+ currentPhone: "+918780050157",
212
+ draftE164: "+918780050157",
213
+ want: { ok: true, flow: "verify_existing" as ContactOtpFlow, phone: "+918780050157" },
214
+ },
215
+ {
216
+ name: "same digits with different formatting still verifies existing",
217
+ currentPhone: "+91 87800 50157",
218
+ draftE164: "+918780050157",
219
+ want: { ok: true, flow: "verify_existing", phone: "+918780050157" },
220
+ },
221
+ {
222
+ name: "a new number uses contact change",
223
+ currentPhone: "+918780050157",
224
+ draftE164: "+919876543210",
225
+ want: { ok: true, flow: "change_contact", phone: "+919876543210" },
226
+ },
227
+ {
228
+ name: "empty draft is empty",
229
+ currentPhone: "+918780050157",
230
+ draftE164: "",
231
+ want: { ok: false, reason: "empty" },
232
+ },
233
+ ]
234
+ for (const tc of cases) {
235
+ it(tc.name, () => {
236
+ assert.deepEqual(
237
+ resolvePhoneOtpFlow({ currentPhone: tc.currentPhone, draftE164: tc.draftE164 }),
238
+ tc.want
239
+ )
240
+ })
241
+ }
242
+ })
243
+
244
+ describe("otp error copy", () => {
245
+ const cases = [
246
+ { name: "empty email", actual: EMAIL_OTP_ERRORS.empty, want: "Please enter an email address before verifying." },
247
+ { name: "invalid email", actual: EMAIL_OTP_ERRORS.invalid, want: "Please enter a valid email address." },
248
+ {
249
+ name: "empty phone",
250
+ actual: PHONE_OTP_ERRORS.empty,
251
+ want: "Please enter a valid mobile number before verifying.",
252
+ },
253
+ ]
254
+ for (const tc of cases) {
255
+ it(tc.name, () => {
256
+ assert.equal(tc.actual, tc.want)
257
+ })
258
+ }
259
+ })
@@ -0,0 +1,91 @@
1
+ export type VerifiedFieldAction = "verify" | "edit" | "verified" | "none"
2
+
3
+ export type ContactOtpFlow = "verify_existing" | "change_contact"
4
+
5
+ export const EMAIL_REGEX = /^\S+@\S+\.\S+$/
6
+
7
+ export const EMAIL_OTP_ERRORS = {
8
+ empty: "Please enter an email address before verifying.",
9
+ invalid: "Please enter a valid email address.",
10
+ } as const
11
+
12
+ export const PHONE_OTP_ERRORS = {
13
+ empty: "Please enter a valid mobile number before verifying.",
14
+ } as const
15
+
16
+ export function phoneDigits(value: string): string {
17
+ return value.replace(/\D/g, "")
18
+ }
19
+
20
+ export function isVerifiedFieldLocked(input: {
21
+ verified: boolean
22
+ editing: boolean
23
+ }): boolean {
24
+ return input.verified && !input.editing
25
+ }
26
+
27
+ export function verifiedFieldAction(input: {
28
+ verified: boolean
29
+ editing: boolean
30
+ ready: boolean
31
+ }): VerifiedFieldAction {
32
+ // Locked verified contact: show Edit. Once editing starts, never show
33
+ // Verified again until OTP succeeds — draft changes must re-verify.
34
+ if (isVerifiedFieldLocked(input)) return "edit"
35
+ if (input.editing) return input.ready ? "verify" : "none"
36
+ if (input.verified) return "verified"
37
+ if (input.ready) return "verify"
38
+ return "none"
39
+ }
40
+
41
+ /** True only when server says verified and the user is not mid-edit. */
42
+ export function isContactStatusVerified(input: {
43
+ verified: boolean
44
+ editing: boolean
45
+ }): boolean {
46
+ return input.verified && !input.editing
47
+ }
48
+
49
+ export function normalizeEmail(value: string | null | undefined): string {
50
+ return (value || "").trim().toLowerCase()
51
+ }
52
+
53
+ export function isValidEmail(value: string | null | undefined): boolean {
54
+ return EMAIL_REGEX.test(normalizeEmail(value))
55
+ }
56
+
57
+ export type ResolveEmailOtpFlowResult =
58
+ | { ok: true; flow: ContactOtpFlow; email: string }
59
+ | { ok: false; reason: "empty" | "invalid" }
60
+
61
+ export function resolveEmailOtpFlow(input: {
62
+ currentEmail: string | null | undefined
63
+ draftEmail: string | null | undefined
64
+ }): ResolveEmailOtpFlowResult {
65
+ const email = normalizeEmail(input.draftEmail)
66
+ if (!email) return { ok: false, reason: "empty" }
67
+ if (!isValidEmail(email)) return { ok: false, reason: "invalid" }
68
+ const current = normalizeEmail(input.currentEmail)
69
+ if (current && email === current) {
70
+ return { ok: true, flow: "verify_existing", email }
71
+ }
72
+ return { ok: true, flow: "change_contact", email }
73
+ }
74
+
75
+ export type ResolvePhoneOtpFlowResult =
76
+ | { ok: true; flow: ContactOtpFlow; phone: string }
77
+ | { ok: false; reason: "empty" }
78
+
79
+ export function resolvePhoneOtpFlow(input: {
80
+ currentPhone: string | null | undefined
81
+ draftE164: string
82
+ }): ResolvePhoneOtpFlowResult {
83
+ const phone = input.draftE164
84
+ if (!phone) return { ok: false, reason: "empty" }
85
+ const current = phoneDigits(input.currentPhone || "")
86
+ const draft = phoneDigits(phone)
87
+ if (current && current === draft) {
88
+ return { ok: true, flow: "verify_existing", phone }
89
+ }
90
+ return { ok: true, flow: "change_contact", phone }
91
+ }