@open-mercato/core 0.11.1-develop.8545.1.dd603570fd → 0.11.1-develop.8549.1.bd34c91190

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.
Files changed (70) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/dist/modules/customer_accounts/api/admin/users/[id]/verify-email.js +10 -30
  3. package/dist/modules/customer_accounts/api/admin/users/[id]/verify-email.js.map +2 -2
  4. package/dist/modules/customer_accounts/api/email/verify.js +11 -10
  5. package/dist/modules/customer_accounts/api/email/verify.js.map +2 -2
  6. package/dist/modules/customer_accounts/api/magic-link/verify.js +9 -8
  7. package/dist/modules/customer_accounts/api/magic-link/verify.js.map +2 -2
  8. package/dist/modules/customer_accounts/api/password/reset-confirm.js +13 -16
  9. package/dist/modules/customer_accounts/api/password/reset-confirm.js.map +2 -2
  10. package/dist/modules/customer_accounts/api/signup.js +33 -19
  11. package/dist/modules/customer_accounts/api/signup.js.map +3 -3
  12. package/dist/modules/customer_accounts/data/validators.js +3 -2
  13. package/dist/modules/customer_accounts/data/validators.js.map +2 -2
  14. package/dist/modules/customer_accounts/lib/customerAuth.js +11 -10
  15. package/dist/modules/customer_accounts/lib/customerAuth.js.map +2 -2
  16. package/dist/modules/customer_accounts/lib/customerAuthServer.js +7 -7
  17. package/dist/modules/customer_accounts/lib/customerAuthServer.js.map +2 -2
  18. package/dist/modules/customer_accounts/lib/pendingSignup.js +16 -0
  19. package/dist/modules/customer_accounts/lib/pendingSignup.js.map +7 -0
  20. package/dist/modules/customer_accounts/lib/verifyCustomerEmail.js +50 -0
  21. package/dist/modules/customer_accounts/lib/verifyCustomerEmail.js.map +7 -0
  22. package/dist/modules/customer_accounts/services/customerInvitationService.js +15 -1
  23. package/dist/modules/customer_accounts/services/customerInvitationService.js.map +2 -2
  24. package/dist/modules/customer_accounts/services/customerTokenService.js +13 -13
  25. package/dist/modules/customer_accounts/services/customerTokenService.js.map +2 -2
  26. package/dist/modules/customer_accounts/services/customerUserService.js +1 -1
  27. package/dist/modules/customer_accounts/services/customerUserService.js.map +2 -2
  28. package/dist/modules/customer_accounts/subscribers/autoLinkCrm.js +44 -51
  29. package/dist/modules/customer_accounts/subscribers/autoLinkCrm.js.map +2 -2
  30. package/dist/modules/customer_accounts/subscribers/autoLinkCrmOnVerification.js +12 -0
  31. package/dist/modules/customer_accounts/subscribers/autoLinkCrmOnVerification.js.map +7 -0
  32. package/dist/modules/customer_accounts/subscribers/autoLinkCrmReverse.js +3 -1
  33. package/dist/modules/customer_accounts/subscribers/autoLinkCrmReverse.js.map +2 -2
  34. package/dist/modules/customer_accounts/workers/cleanupExpiredTokens.js +6 -0
  35. package/dist/modules/customer_accounts/workers/cleanupExpiredTokens.js.map +2 -2
  36. package/dist/modules/portal/frontend/[orgSlug]/portal/PasswordForm.js +127 -0
  37. package/dist/modules/portal/frontend/[orgSlug]/portal/PasswordForm.js.map +7 -0
  38. package/dist/modules/portal/frontend/[orgSlug]/portal/reset-password/page.js +10 -122
  39. package/dist/modules/portal/frontend/[orgSlug]/portal/reset-password/page.js.map +2 -2
  40. package/dist/modules/portal/frontend/[orgSlug]/portal/signup/page.js +2 -11
  41. package/dist/modules/portal/frontend/[orgSlug]/portal/signup/page.js.map +2 -2
  42. package/dist/modules/portal/frontend/[orgSlug]/portal/verify/page.js +3 -61
  43. package/dist/modules/portal/frontend/[orgSlug]/portal/verify/page.js.map +2 -2
  44. package/package.json +7 -7
  45. package/src/modules/customer_accounts/api/admin/users/[id]/verify-email.ts +11 -33
  46. package/src/modules/customer_accounts/api/email/verify.ts +15 -11
  47. package/src/modules/customer_accounts/api/magic-link/verify.ts +9 -9
  48. package/src/modules/customer_accounts/api/password/reset-confirm.ts +13 -18
  49. package/src/modules/customer_accounts/api/signup.ts +36 -24
  50. package/src/modules/customer_accounts/data/validators.ts +2 -1
  51. package/src/modules/customer_accounts/lib/customerAuth.ts +12 -10
  52. package/src/modules/customer_accounts/lib/customerAuthServer.ts +7 -7
  53. package/src/modules/customer_accounts/lib/pendingSignup.ts +12 -0
  54. package/src/modules/customer_accounts/lib/verifyCustomerEmail.ts +57 -0
  55. package/src/modules/customer_accounts/services/customerInvitationService.ts +16 -1
  56. package/src/modules/customer_accounts/services/customerTokenService.ts +13 -13
  57. package/src/modules/customer_accounts/services/customerUserService.ts +2 -2
  58. package/src/modules/customer_accounts/subscribers/autoLinkCrm.ts +46 -78
  59. package/src/modules/customer_accounts/subscribers/autoLinkCrmOnVerification.ts +9 -0
  60. package/src/modules/customer_accounts/subscribers/autoLinkCrmReverse.ts +3 -1
  61. package/src/modules/customer_accounts/workers/cleanupExpiredTokens.ts +7 -0
  62. package/src/modules/portal/frontend/[orgSlug]/portal/PasswordForm.tsx +182 -0
  63. package/src/modules/portal/frontend/[orgSlug]/portal/reset-password/page.tsx +9 -165
  64. package/src/modules/portal/frontend/[orgSlug]/portal/signup/page.tsx +2 -12
  65. package/src/modules/portal/frontend/[orgSlug]/portal/verify/page.tsx +3 -89
  66. package/src/modules/portal/i18n/de.json +2 -1
  67. package/src/modules/portal/i18n/en.json +2 -1
  68. package/src/modules/portal/i18n/es.json +2 -1
  69. package/src/modules/portal/i18n/ko.json +2 -1
  70. package/src/modules/portal/i18n/pl.json +2 -1
@@ -3,6 +3,7 @@ import { CustomerUser } from '@open-mercato/core/modules/customer_accounts/data/
3
3
  import { findWithDecryption, findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'
4
4
  import { resolveOwnedCompanyForPerson } from '@open-mercato/core/modules/customer_accounts/lib/customerEntityOwnership'
5
5
  import { createLogger } from '@open-mercato/shared/lib/logger'
6
+ import { getTelemetryRuntime } from '@open-mercato/shared/lib/telemetry/runtime'
6
7
 
7
8
  const logger = createLogger('customer_accounts').child({ component: 'auto-link-crm' })
8
9
 
@@ -17,7 +18,7 @@ export default async function handle(
17
18
  ctx: { resolve: <T = unknown>(name: string) => T; eventName?: string },
18
19
  ): Promise<void> {
19
20
  const data = payload as Record<string, unknown>
20
- const userId = data?.id as string
21
+ const userId = (data?.userId ?? data?.id) as string
21
22
  const tenantId = data?.tenantId as string
22
23
  const organizationId = data?.organizationId as string | undefined
23
24
  if (!userId || !tenantId) return
@@ -25,8 +26,14 @@ export default async function handle(
25
26
  const em = ctx.resolve<EntityManager>('em')
26
27
 
27
28
  try {
28
- const user = await findOneWithDecryption(em, CustomerUser, { id: userId, tenantId, deletedAt: null }, undefined, { tenantId, organizationId })
29
+ const user = await findOneWithDecryption(em, CustomerUser, {
30
+ id: userId,
31
+ tenantId,
32
+ ...(organizationId ? { organizationId } : {}),
33
+ deletedAt: null,
34
+ }, undefined, { tenantId, organizationId })
29
35
  if (!user) return
36
+ if (!user.emailVerifiedAt || !user.isActive) return
30
37
 
31
38
  const { CustomerEntity } = await import('@open-mercato/core/modules/customers/data/entities')
32
39
 
@@ -36,95 +43,56 @@ export default async function handle(
36
43
  // widen the user's portal access instead of repairing it.
37
44
  const ownScope = { tenantId, organizationId: user.organizationId }
38
45
 
39
- // Defensive normalization for NEW users only — this subscriber runs on
40
- // `customer_accounts.user.created`, which is never re-emitted for an existing
41
- // row. customerEntityId is the CRM company FK, and earlier invite flows (#4362)
42
- // could poison it with a person entity id, which then breaks every later user
43
- // edit ("Company not found"). If the linked entity is a person (not a company)
44
- // or sits outside the user's org, drop it — or recover the person's real company
45
- // from their profile. Correct company links are left untouched. Rows created
46
- // before this change keep their bad FK; see #4473 for the backfill.
47
- if (user.customerEntityId) {
46
+ let personEntityId = user.personEntityId ?? null
47
+ let customerEntityId = user.customerEntityId ?? null
48
+ if (customerEntityId) {
48
49
  const linked = await findOneWithDecryption(
49
50
  em,
50
51
  CustomerEntity,
51
- { id: user.customerEntityId, tenantId, organizationId: user.organizationId, deletedAt: null } as any,
52
+ { id: customerEntityId, ...ownScope, deletedAt: null },
52
53
  undefined,
53
- { tenantId, organizationId },
54
- ) as any
55
- if (!linked) {
56
- // Not resolvable inside the user's own org — a cross-org (or deleted)
57
- // entity. Clear it rather than leave it: this FK is the portal scope key.
58
- await em.nativeUpdate(
59
- CustomerUser,
60
- { id: userId, tenantId, organizationId: user.organizationId },
61
- { customerEntityId: null },
62
- )
63
- user.customerEntityId = null
64
- } else if (linked.kind === 'person') {
65
- // Only adopt a recovered company that is itself in the user's org.
66
- const replacement = await resolveOwnedCompanyForPerson(em, user.customerEntityId, ownScope)
67
- await em.nativeUpdate(
68
- CustomerUser,
69
- { id: userId, tenantId, organizationId: user.organizationId },
70
- { customerEntityId: replacement },
71
- )
72
- user.customerEntityId = replacement
54
+ ownScope,
55
+ )
56
+ if (!linked) customerEntityId = null
57
+ else if (linked.kind === 'person') {
58
+ customerEntityId = await resolveOwnedCompanyForPerson(em, linked.id, ownScope)
73
59
  }
74
60
  }
75
61
 
76
- // A user invited from a CRM person card arrives with personEntityId already
77
- // set, so the email-matching path below never runs for it. Derive the company
78
- // FK from that person's own profile instead of leaving it null forever — the
79
- // portal Users page, portal invitations, and the company detail "Portal users"
80
- // group all key off customerEntityId (#4362).
81
- if (user.personEntityId) {
82
- if (user.customerEntityId) return
83
- const recovered = await resolveOwnedCompanyForPerson(em, user.personEntityId, ownScope)
84
- if (recovered) {
85
- await em.nativeUpdate(
86
- CustomerUser,
87
- { id: userId, tenantId, organizationId: user.organizationId },
88
- { customerEntityId: recovered },
62
+ if (!personEntityId) {
63
+ const email = user.email?.toLowerCase().trim()
64
+ if (email) {
65
+ const personEntities = await findWithDecryption(
66
+ em,
67
+ CustomerEntity,
68
+ { ...ownScope, kind: 'person', deletedAt: null },
69
+ { limit: 500 },
70
+ ownScope,
89
71
  )
72
+ personEntityId = personEntities.find((person) => person.primaryEmail?.toLowerCase().trim() === email)?.id ?? null
90
73
  }
91
- return
92
74
  }
93
-
94
- const email = (data?.email ? (data.email as string) : user.email)?.toLowerCase().trim()
95
- if (!email) return
96
-
97
- // Scope the candidate lookup to the user's own org. The fifth argument is a
98
- // decryption scope, not a filter, so without organizationId in the `where`
99
- // this matches people across every org in the tenant and writes a cross-org
100
- // link that the normalization block above just cleared.
101
- const personEntities = await findWithDecryption(
102
- em,
103
- CustomerEntity,
104
- { tenantId, organizationId: user.organizationId, kind: 'person', deletedAt: null } as any,
105
- { limit: 500 } as any,
106
- { tenantId, organizationId },
107
- )
108
-
109
- const matchingEntity = personEntities.find(
110
- (e: any) => e.primaryEmail && e.primaryEmail.toLowerCase().trim() === email,
111
- ) as any
112
-
113
- if (!matchingEntity) return
114
-
115
- const companyEntityId = await resolveOwnedCompanyForPerson(em, matchingEntity.id, ownScope)
116
-
117
- const updates: Record<string, unknown> = { personEntityId: matchingEntity.id }
118
- if (companyEntityId) {
119
- updates.customerEntityId = companyEntityId
75
+ if (personEntityId && !customerEntityId) {
76
+ customerEntityId = await resolveOwnedCompanyForPerson(em, personEntityId, ownScope)
120
77
  }
121
78
 
122
- await em.nativeUpdate(
123
- CustomerUser,
124
- { id: userId, tenantId, organizationId: user.organizationId },
125
- updates,
126
- )
79
+ const updates: Partial<CustomerUser> = {}
80
+ if (personEntityId !== (user.personEntityId ?? null)) updates.personEntityId = personEntityId
81
+ if (customerEntityId !== (user.customerEntityId ?? null)) updates.customerEntityId = customerEntityId
82
+ if (!Object.keys(updates).length) return
83
+
84
+ await em.nativeUpdate(CustomerUser, {
85
+ id: userId,
86
+ ...ownScope,
87
+ emailHash: user.emailHash,
88
+ emailVerifiedAt: { $ne: null },
89
+ deletedAt: null,
90
+ isActive: true,
91
+ personEntityId: user.personEntityId ?? null,
92
+ customerEntityId: user.customerEntityId ?? null,
93
+ }, updates)
127
94
  } catch (err) {
128
95
  logger.error('Failed to link customer user to CRM person', { err })
96
+ getTelemetryRuntime()?.reportError(err, { module: 'customer_accounts', code: 'customer_accounts.crm_link_failed' })
129
97
  }
130
98
  }
@@ -0,0 +1,9 @@
1
+ import autoLinkCrm from './autoLinkCrm'
2
+
3
+ export const metadata = {
4
+ event: 'customer_accounts.email.verified',
5
+ persistent: true,
6
+ id: 'customer_accounts:auto-link-crm-on-verification',
7
+ }
8
+
9
+ export default autoLinkCrm
@@ -72,11 +72,13 @@ export default async function handle(
72
72
  emailHash: { $in: emailHashes },
73
73
  ...ownScope,
74
74
  deletedAt: null,
75
+ emailVerifiedAt: { $ne: null },
76
+ isActive: true,
75
77
  personEntityId: null,
76
78
  }
77
79
  const customerUser = await findOneWithDecryption(em, CustomerUser, userWhere, undefined, ownScope)
78
80
 
79
- if (customerUser) {
81
+ if (customerUser?.emailVerifiedAt && customerUser.isActive) {
80
82
  const updates: Partial<CustomerUser> = { personEntityId: entity.id, updatedAt: new Date() }
81
83
  if (!customerUser.customerEntityId) {
82
84
  const companyEntityId = await resolveOwnedCompanyForPerson(em, entity.id, ownScope)
@@ -1,10 +1,12 @@
1
1
  import type { JobContext, QueuedJob, WorkerMeta } from '@open-mercato/queue'
2
2
  import type { EntityManager } from '@mikro-orm/postgresql'
3
3
  import {
4
+ CustomerUser,
4
5
  CustomerUserEmailVerification,
5
6
  CustomerUserPasswordReset,
6
7
  CustomerUserInvitation,
7
8
  } from '@open-mercato/core/modules/customer_accounts/data/entities'
9
+ import { pendingSignup, signupExpiryCutoff } from '../lib/pendingSignup'
8
10
 
9
11
  export const metadata: WorkerMeta = {
10
12
  queue: 'customer-accounts-cleanup-tokens',
@@ -20,6 +22,11 @@ export default async function handle(job: QueuedJob, ctx: HandlerContext): Promi
20
22
  const em = ctx.resolve<EntityManager>('em')
21
23
  const now = new Date()
22
24
 
25
+ await em.nativeUpdate(CustomerUser, {
26
+ ...pendingSignup,
27
+ createdAt: { $lte: signupExpiryCutoff(now) },
28
+ }, { deletedAt: now, isActive: false, passwordHash: null, sessionsRevokedAt: now })
29
+
23
30
  // Cleanup expired email verifications
24
31
  await em.nativeDelete(CustomerUserEmailVerification, {
25
32
  $or: [
@@ -0,0 +1,182 @@
1
+ "use client"
2
+ import { useCallback, useState, useEffect, type ReactNode } from 'react'
3
+ import { useSearchParams } from 'next/navigation'
4
+ import Link from 'next/link'
5
+ import { useT } from '@open-mercato/shared/lib/i18n/context'
6
+ import { PasswordInput } from '@open-mercato/ui/primitives/password-input'
7
+ import { Label } from '@open-mercato/ui/primitives/label'
8
+ import { Button } from '@open-mercato/ui/primitives/button'
9
+ import { Alert, AlertDescription } from '@open-mercato/ui/primitives/alert'
10
+ import { EmptyState } from '@open-mercato/ui/primitives/empty-state'
11
+ import { SearchX } from 'lucide-react'
12
+ import { Spinner } from '@open-mercato/ui/primitives/spinner'
13
+ import { apiCall } from '@open-mercato/ui/backend/utils/apiCall'
14
+ import { usePortalContext } from '@open-mercato/ui/portal/PortalContext'
15
+
16
+ type Props = {
17
+ params: { orgSlug: string }
18
+ verify?: boolean
19
+ beforeForm?: ReactNode
20
+ afterForm?: ReactNode
21
+ }
22
+
23
+ export function PortalPasswordForm({ params, verify = false, beforeForm, afterForm }: Props) {
24
+ const t = useT()
25
+ const orgSlug = params.orgSlug
26
+ const { tenant } = usePortalContext()
27
+ const searchParams = useSearchParams()
28
+
29
+ const [password, setPassword] = useState('')
30
+ const [confirmPassword, setConfirmPassword] = useState('')
31
+ const [error, setError] = useState<string | null>(null)
32
+ const [success, setSuccess] = useState(false)
33
+ const [submitting, setSubmitting] = useState(false)
34
+ const token = searchParams.get('token')
35
+ const noTokenMessage = verify
36
+ ? t('portal.verify.error.invalidToken', 'Verification token is missing.')
37
+ : t('portal.resetPassword.error.noToken', 'Invalid or missing reset token.')
38
+
39
+ useEffect(() => {
40
+ if (!token) setError(noTokenMessage)
41
+ }, [token, noTokenMessage])
42
+
43
+ const handleSubmit = useCallback(
44
+ async (event: React.FormEvent) => {
45
+ event.preventDefault()
46
+ setError(null)
47
+
48
+ if (!token) {
49
+ setError(noTokenMessage)
50
+ return
51
+ }
52
+
53
+ if (password !== confirmPassword) {
54
+ setError(t('portal.resetPassword.error.passwordMismatch', 'Passwords do not match.'))
55
+ return
56
+ }
57
+
58
+ if (password.length < 8) {
59
+ setError(t('portal.resetPassword.error.passwordTooShort', 'Password must be at least 8 characters long.'))
60
+ return
61
+ }
62
+
63
+ setSubmitting(true)
64
+ try {
65
+ const endpoint = verify ? '/api/customer_accounts/email/verify' : '/api/customer_accounts/password/reset-confirm'
66
+ const result = await apiCall<{ ok: boolean; error?: string }>(endpoint, {
67
+ method: 'POST',
68
+ headers: { 'Content-Type': 'application/json' },
69
+ body: JSON.stringify({ token, password }),
70
+ })
71
+
72
+ if (result.ok && result.result?.ok) {
73
+ setSuccess(true)
74
+ return
75
+ }
76
+
77
+ if (verify) {
78
+ setError(t('portal.verify.error.generic', 'Email verification failed. Please try again.'))
79
+ } else if (result.status === 400) {
80
+ setError(t('portal.resetPassword.error.invalidToken', 'Invalid or expired reset token.'))
81
+ } else {
82
+ setError(result.result?.error || t('portal.resetPassword.error.generic', 'Password reset failed. Please try again.'))
83
+ }
84
+ } catch {
85
+ setError(verify
86
+ ? t('portal.verify.error.generic', 'Email verification failed. Please try again.')
87
+ : t('portal.resetPassword.error.generic', 'Password reset failed. Please try again.'))
88
+ } finally {
89
+ setSubmitting(false)
90
+ }
91
+ },
92
+ [token, password, confirmPassword, t, verify, noTokenMessage],
93
+ )
94
+
95
+ if (tenant.loading) {
96
+ return <div className="flex items-center justify-center py-20"><Spinner /></div>
97
+ }
98
+
99
+ if (tenant.error) {
100
+ return (
101
+ <div className="mx-auto w-full max-w-md py-12">
102
+ <EmptyState
103
+ variant="subtle"
104
+ size="lg"
105
+ icon={<SearchX className="h-6 w-6" aria-hidden />}
106
+ title={t('portal.org.invalid', 'Organization not found.')}
107
+ />
108
+ </div>
109
+ )
110
+ }
111
+
112
+ if (success) {
113
+ return (
114
+ <div className="mx-auto w-full max-w-sm">
115
+ <div className="mb-8 text-center">
116
+ <h1 className="text-2xl font-bold tracking-tight">{verify
117
+ ? t('portal.verify.success.title', 'Email verified')
118
+ : t('portal.resetPassword.success.title', 'Password Reset Complete')}</h1>
119
+ <p className="mt-1.5 text-sm text-muted-foreground">{verify
120
+ ? t('portal.verify.success.description', 'Your email has been verified. You can now sign in to the portal.')
121
+ : t('portal.resetPassword.success.description', 'Your password has been successfully reset.')}</p>
122
+ </div>
123
+
124
+ <Alert>
125
+ <AlertDescription>{t('portal.resetPassword.success.message', 'You can now sign in with your new password.')}</AlertDescription>
126
+ </Alert>
127
+
128
+ <div className="mt-6 text-center">
129
+ <Link href={`/${orgSlug}/portal/login`} className="font-medium text-foreground underline underline-offset-4 hover:opacity-80">
130
+ {t('portal.resetPassword.success.loginLink', 'Go to Sign In')}
131
+ </Link>
132
+ </div>
133
+ </div>
134
+ )
135
+ }
136
+
137
+ return (
138
+ <div className="mx-auto w-full max-w-sm">
139
+ <div className="mb-8 text-center">
140
+ <h1 className="text-2xl font-bold tracking-tight">{verify
141
+ ? t('portal.verify.title', 'Verify email')
142
+ : t('portal.resetPassword.title', 'Reset Password')}</h1>
143
+ <p className="mt-1.5 text-sm text-muted-foreground">{t('portal.resetPassword.description', 'Enter your new password below.')}</p>
144
+ </div>
145
+
146
+ {beforeForm}
147
+
148
+ <form onSubmit={handleSubmit} className="flex flex-col gap-4">
149
+ {error ? (
150
+ <Alert status="error">
151
+ <AlertDescription>{error}</AlertDescription>
152
+ </Alert>
153
+ ) : null}
154
+
155
+ <div className="flex flex-col gap-1.5">
156
+ <Label htmlFor="reset-password" className="text-overline font-semibold uppercase tracking-wider text-muted-foreground/70">{t('portal.resetPassword.password', 'New Password')}</Label>
157
+ <PasswordInput id="reset-password" autoComplete="new-password" required placeholder={t('portal.resetPassword.password.placeholder', '••••••••')} value={password} onChange={(e) => setPassword(e.target.value)} disabled={submitting || !token} className="rounded-lg" />
158
+ </div>
159
+
160
+ <div className="flex flex-col gap-1.5">
161
+ <Label htmlFor="confirm-password" className="text-overline font-semibold uppercase tracking-wider text-muted-foreground/70">{t('portal.resetPassword.confirmPassword', 'Confirm New Password')}</Label>
162
+ <PasswordInput id="confirm-password" autoComplete="new-password" required placeholder={t('portal.resetPassword.confirmPassword.placeholder', '••••••••')} value={confirmPassword} onChange={(e) => setConfirmPassword(e.target.value)} disabled={submitting || !token} className="rounded-lg" />
163
+ </div>
164
+
165
+ <Button type="submit" disabled={submitting || !token} className="mt-1 w-full rounded-lg">
166
+ {verify
167
+ ? t('portal.verify.submit', 'Verify email and set password')
168
+ : submitting ? t('portal.resetPassword.submitting', 'Resetting password...') : t('portal.resetPassword.submit', 'Reset Password')}
169
+ </Button>
170
+
171
+ <p className="text-center text-sm text-muted-foreground">
172
+ {verify ? null : t('portal.resetPassword.backToLogin', 'Remember your password?')}{' '}
173
+ <Link href={`/${orgSlug}/portal/login`} className="font-medium text-foreground underline underline-offset-4 hover:opacity-80">
174
+ {t('portal.resetPassword.loginLink', 'Sign in')}
175
+ </Link>
176
+ </p>
177
+ </form>
178
+
179
+ {afterForm}
180
+ </div>
181
+ )
182
+ }
@@ -1,173 +1,17 @@
1
1
  "use client"
2
- import { useCallback, useMemo, useState, useEffect } from 'react'
2
+ import { useMemo } from 'react'
3
3
  import { extensionPoints } from '@open-mercato/core/modules/portal/extension-points'
4
- import { useSearchParams } from 'next/navigation'
5
- import Link from 'next/link'
6
- import { useT } from '@open-mercato/shared/lib/i18n/context'
7
- import { PasswordInput } from '@open-mercato/ui/primitives/password-input'
8
- import { Label } from '@open-mercato/ui/primitives/label'
9
- import { Button } from '@open-mercato/ui/primitives/button'
10
- import { Alert, AlertDescription } from '@open-mercato/ui/primitives/alert'
11
- import { EmptyState } from '@open-mercato/ui/primitives/empty-state'
12
- import { SearchX } from 'lucide-react'
13
- import { Spinner } from '@open-mercato/ui/primitives/spinner'
14
- import { apiCall } from '@open-mercato/ui/backend/utils/apiCall'
15
- import { usePortalContext } from '@open-mercato/ui/portal/PortalContext'
16
4
  import { InjectionSpot } from '@open-mercato/ui/backend/injection/InjectionSpot'
5
+ import { PortalPasswordForm } from '../PasswordForm'
17
6
 
18
- type Props = { params: { orgSlug: string } }
19
-
20
- export default function PortalResetPasswordPage({ params }: Props) {
21
- const t = useT()
7
+ export default function PortalResetPasswordPage({ params }: { params: { orgSlug: string } }) {
22
8
  const orgSlug = params.orgSlug
23
- const { tenant } = usePortalContext()
24
- const searchParams = useSearchParams()
25
-
26
- const [password, setPassword] = useState('')
27
- const [confirmPassword, setConfirmPassword] = useState('')
28
- const [error, setError] = useState<string | null>(null)
29
- const [success, setSuccess] = useState(false)
30
- const [submitting, setSubmitting] = useState(false)
31
- const [token, setToken] = useState<string | null>(null)
32
-
33
- useEffect(() => {
34
- const tokenParam = searchParams.get('token')
35
- if (!tokenParam) {
36
- setError(t('portal.resetPassword.error.noToken', 'Invalid or missing reset token.'))
37
- } else {
38
- setToken(tokenParam)
39
- }
40
- }, [searchParams, t])
41
-
42
- const handleSubmit = useCallback(
43
- async (event: React.FormEvent) => {
44
- event.preventDefault()
45
- setError(null)
46
-
47
- if (!token) {
48
- setError(t('portal.resetPassword.error.noToken', 'Invalid or missing reset token.'))
49
- return
50
- }
51
-
52
- if (password !== confirmPassword) {
53
- setError(t('portal.resetPassword.error.passwordMismatch', 'Passwords do not match.'))
54
- return
55
- }
56
-
57
- if (password.length < 8) {
58
- setError(t('portal.resetPassword.error.passwordTooShort', 'Password must be at least 8 characters long.'))
59
- return
60
- }
61
-
62
- setSubmitting(true)
63
- try {
64
- const result = await apiCall<{ ok: boolean; error?: string }>('/api/customer_accounts/password/reset-confirm', {
65
- method: 'POST',
66
- headers: { 'Content-Type': 'application/json' },
67
- body: JSON.stringify({ token, password }),
68
- })
69
-
70
- if (result.ok && result.result?.ok) {
71
- setSuccess(true)
72
- return
73
- }
74
-
75
- if (result.status === 400) {
76
- setError(t('portal.resetPassword.error.invalidToken', 'Invalid or expired reset token.'))
77
- } else {
78
- setError(result.result?.error || t('portal.resetPassword.error.generic', 'Password reset failed. Please try again.'))
79
- }
80
- } catch {
81
- setError(t('portal.resetPassword.error.generic', 'Password reset failed. Please try again.'))
82
- } finally {
83
- setSubmitting(false)
84
- }
85
- },
86
- [token, password, confirmPassword, t],
87
- )
88
-
89
- const injectionContext = useMemo(
90
- () => ({ orgSlug }),
91
- [orgSlug],
92
- )
93
-
94
- if (tenant.loading) {
95
- return <div className="flex items-center justify-center py-20"><Spinner /></div>
96
- }
97
-
98
- if (tenant.error) {
99
- return (
100
- <div className="mx-auto w-full max-w-md py-12">
101
- <EmptyState
102
- variant="subtle"
103
- size="lg"
104
- icon={<SearchX className="h-6 w-6" aria-hidden />}
105
- title={t('portal.org.invalid', 'Organization not found.')}
106
- />
107
- </div>
108
- )
109
- }
110
-
111
- if (success) {
112
- return (
113
- <div className="mx-auto w-full max-w-sm">
114
- <div className="mb-8 text-center">
115
- <h1 className="text-2xl font-bold tracking-tight">{t('portal.resetPassword.success.title', 'Password Reset Complete')}</h1>
116
- <p className="mt-1.5 text-sm text-muted-foreground">{t('portal.resetPassword.success.description', 'Your password has been successfully reset.')}</p>
117
- </div>
118
-
119
- <Alert>
120
- <AlertDescription>{t('portal.resetPassword.success.message', 'You can now sign in with your new password.')}</AlertDescription>
121
- </Alert>
122
-
123
- <div className="mt-6 text-center">
124
- <Link href={`/${orgSlug}/portal/login`} className="font-medium text-foreground underline underline-offset-4 hover:opacity-80">
125
- {t('portal.resetPassword.success.loginLink', 'Go to Sign In')}
126
- </Link>
127
- </div>
128
- </div>
129
- )
130
- }
131
-
9
+ const injectionContext = useMemo(() => ({ orgSlug }), [orgSlug])
132
10
  return (
133
- <div className="mx-auto w-full max-w-sm">
134
- <div className="mb-8 text-center">
135
- <h1 className="text-2xl font-bold tracking-tight">{t('portal.resetPassword.title', 'Reset Password')}</h1>
136
- <p className="mt-1.5 text-sm text-muted-foreground">{t('portal.resetPassword.description', 'Enter your new password below.')}</p>
137
- </div>
138
-
139
- <InjectionSpot spotId={extensionPoints.hosts.resetPasswordBefore.spotId} context={injectionContext} />
140
-
141
- <form onSubmit={handleSubmit} className="flex flex-col gap-4">
142
- {error ? (
143
- <Alert status="error">
144
- <AlertDescription>{error}</AlertDescription>
145
- </Alert>
146
- ) : null}
147
-
148
- <div className="flex flex-col gap-1.5">
149
- <Label htmlFor="reset-password" className="text-overline font-semibold uppercase tracking-wider text-muted-foreground/70">{t('portal.resetPassword.password', 'New Password')}</Label>
150
- <PasswordInput id="reset-password" autoComplete="new-password" required placeholder={t('portal.resetPassword.password.placeholder', '••••••••')} value={password} onChange={(e) => setPassword(e.target.value)} disabled={submitting || !token} className="rounded-lg" />
151
- </div>
152
-
153
- <div className="flex flex-col gap-1.5">
154
- <Label htmlFor="confirm-password" className="text-overline font-semibold uppercase tracking-wider text-muted-foreground/70">{t('portal.resetPassword.confirmPassword', 'Confirm New Password')}</Label>
155
- <PasswordInput id="confirm-password" autoComplete="new-password" required placeholder={t('portal.resetPassword.confirmPassword.placeholder', '••••••••')} value={confirmPassword} onChange={(e) => setConfirmPassword(e.target.value)} disabled={submitting || !token} className="rounded-lg" />
156
- </div>
157
-
158
- <Button type="submit" disabled={submitting || !token} className="mt-1 w-full rounded-lg">
159
- {submitting ? t('portal.resetPassword.submitting', 'Resetting password...') : t('portal.resetPassword.submit', 'Reset Password')}
160
- </Button>
161
-
162
- <p className="text-center text-sm text-muted-foreground">
163
- {t('portal.resetPassword.backToLogin', 'Remember your password?')}{' '}
164
- <Link href={`/${orgSlug}/portal/login`} className="font-medium text-foreground underline underline-offset-4 hover:opacity-80">
165
- {t('portal.resetPassword.loginLink', 'Sign in')}
166
- </Link>
167
- </p>
168
- </form>
169
-
170
- <InjectionSpot spotId={extensionPoints.hosts.resetPasswordAfter.spotId} context={injectionContext} />
171
- </div>
11
+ <PortalPasswordForm
12
+ params={params}
13
+ beforeForm={<InjectionSpot spotId={extensionPoints.hosts.resetPasswordBefore.spotId} context={injectionContext} />}
14
+ afterForm={<InjectionSpot spotId={extensionPoints.hosts.resetPasswordAfter.spotId} context={injectionContext} />}
15
+ />
172
16
  )
173
17
  }
@@ -5,7 +5,6 @@ import Link from 'next/link'
5
5
  import { useT } from '@open-mercato/shared/lib/i18n/context'
6
6
  import { Input } from '@open-mercato/ui/primitives/input'
7
7
  import { EmailInput } from '@open-mercato/ui/primitives/email-input'
8
- import { PasswordInput } from '@open-mercato/ui/primitives/password-input'
9
8
  import { Label } from '@open-mercato/ui/primitives/label'
10
9
  import { Button } from '@open-mercato/ui/primitives/button'
11
10
  import { Alert, AlertDescription } from '@open-mercato/ui/primitives/alert'
@@ -26,7 +25,6 @@ export default function PortalSignupPage({ params }: Props) {
26
25
 
27
26
  const [displayName, setDisplayName] = useState('')
28
27
  const [email, setEmail] = useState('')
29
- const [password, setPassword] = useState('')
30
28
  const [error, setError] = useState<string | null>(null)
31
29
  const [fieldErrors, setFieldErrors] = useState<Record<string, string>>({})
32
30
  const [success, setSuccess] = useState(false)
@@ -48,7 +46,7 @@ export default function PortalSignupPage({ params }: Props) {
48
46
  const result = await apiCall<SignupResponse>('/api/customer_accounts/signup', {
49
47
  method: 'POST',
50
48
  headers: { 'Content-Type': 'application/json' },
51
- body: JSON.stringify({ email, password, displayName, organizationId: tenant.organizationId }),
49
+ body: JSON.stringify({ email, displayName, organizationId: tenant.organizationId }),
52
50
  })
53
51
 
54
52
  if (result.status === 202 && result.result?.ok) {
@@ -66,8 +64,6 @@ export default function PortalSignupPage({ params }: Props) {
66
64
  mapped.displayName = t('portal.signup.error.displayName.required', 'Full name is required.')
67
65
  } else if (fieldKey === 'email') {
68
66
  mapped.email = t('portal.signup.error.email.invalid', 'Please enter a valid email address.')
69
- } else if (fieldKey === 'password') {
70
- mapped.password = t('portal.signup.error.password.minLength', 'Password must be at least 8 characters.')
71
67
  }
72
68
  }
73
69
  const hasUnmappedField = detailEntries.some(([fieldKey]) => !(fieldKey in mapped))
@@ -84,7 +80,7 @@ export default function PortalSignupPage({ params }: Props) {
84
80
  setSubmitting(false)
85
81
  }
86
82
  },
87
- [displayName, email, password, tenant.organizationId, t],
83
+ [displayName, email, tenant.organizationId, t],
88
84
  )
89
85
 
90
86
  const injectionContext = useMemo(
@@ -155,12 +151,6 @@ export default function PortalSignupPage({ params }: Props) {
155
151
  {fieldErrors.email && <p id="signup-email-error" role="alert" className="text-sm text-destructive">{fieldErrors.email}</p>}
156
152
  </div>
157
153
 
158
- <div className="flex flex-col gap-1.5">
159
- <Label htmlFor="signup-password" className="text-overline font-semibold uppercase tracking-wider text-muted-foreground/70">{t('portal.signup.password', 'Password')}</Label>
160
- <PasswordInput id="signup-password" autoComplete="new-password" required placeholder={t('portal.signup.password.placeholder', '\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022')} value={password} onChange={(e) => setPassword(e.target.value)} disabled={submitting} aria-invalid={fieldErrors.password ? true : undefined} aria-describedby={fieldErrors.password ? 'signup-password-error' : undefined} className="rounded-lg" />
161
- {fieldErrors.password && <p id="signup-password-error" role="alert" className="text-sm text-destructive">{fieldErrors.password}</p>}
162
- </div>
163
-
164
154
  <Button type="submit" disabled={submitting} className="mt-1 w-full rounded-lg">
165
155
  {submitting ? t('portal.signup.submitting', 'Creating account...') : t('portal.signup.submit', 'Create Account')}
166
156
  </Button>