Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
Fix: Accepting an invitation while signed in (#15015)
Damian Legawiec29d95e388efb
diff --git a/.changeset/accept-invitation-signed-in.md b/.changeset/accept-invitation-signed-in.mdnew file mode 100644index 0000000000..a2b7a3c99d--- /dev/null+++ b/.changeset/accept-invitation-signed-in.md@@ -0,0 +1,8 @@+---+"@spree/dashboard": patch+"@spree/dashboard-core": patch+"@spree/seller-dashboard": patch+"@spree/seller-sdk": patch+---++Fixed the invitation link redirecting anyone already signed in to the dashboard instead of letting them accept. Someone signed in as the invited account now accepts with one click, and someone signed in as another account is asked to sign out first. The seller panel's acceptance page shares these screens: an existing account confirms its password instead of being asked to set a new one, and the seller invitation lookup now says whether the invitee has an account.diff --git a/docs/api-reference/admin.yaml b/docs/api-reference/admin.yamlindex 68866ed8ad..347a61b199 100644--- a/docs/api-reference/admin.yaml+++ b/docs/api-reference/admin.yaml@@ -289,7 +289,9 @@ paths:`password` is required when no account exists for the invited address,in which case it sets one. When an account already exists, the same- field is how the person proves the account is theirs.+ field is how the person proves the account is theirs — unless the+ request carries that account's own access token, which proves it+ already.x-codeSamples:- lang: javascriptlabel: Spree Admin SDK@@ -81478,8 +81480,9 @@ components:properties:password:type: string- description: 'Required when the invitee has no account yet: it creates one.- An existing account signs in without it.'+ description: Creates the account when the invitee has none yet. An existing+ account confirms it is theirs with it, unless the request is already signed+ in as that account.password_confirmation:type: stringfirst_name:diff --git a/docs/api-reference/seller.yaml b/docs/api-reference/seller.yamlindex 225844880b..178c23f8fa 100644--- a/docs/api-reference/seller.yaml+++ b/docs/api-reference/seller.yaml@@ -289,6 +289,11 @@ paths:expires_at: '2026-01-29T12:00:00.000Z'accepted_at:status: pending+ inviter_email: [email protected]+ invitee_exists: false+ seller:+ id: sel_UkLWZg9DAJ+ name: Seller 72schema:"$ref": "#/components/schemas/Invitation"'404':@@ -323,7 +328,8 @@ paths:`password` is required when no account exists for the invited address, inwhich case it sets one. When an account already exists, the same field is- how the person proves the account is theirs.+ how the person proves the account is theirs — unless the request carries+ that account's own access token, which proves it already.x-codeSamples:- lang: javascriptlabel: Spree Seller SDK@@ -16011,6 +16017,10 @@ paths:expires_at: '2026-01-29T12:00:00.000Z'accepted_at:status: pending+ inviter_email: [email protected]+ seller:+ id: sel_UkLWZg9DAJ+ name: Seller 76schema:type: objectproperties:@@ -16116,6 +16126,10 @@ paths:expires_at: '2026-01-29T12:00:00.000Z'accepted_at:status: pending+ inviter_email: [email protected]+ seller:+ id: sel_UkLWZg9DAJ+ name: Seller 78schema:"$ref": "#/components/schemas/Invitation"'404':@@ -16278,6 +16292,10 @@ paths:expires_at: '2026-01-29T12:00:00.000Z'accepted_at:status: pending+ inviter_email: [email protected]+ seller:+ id: sel_UkLWZg9DAJ+ name: Seller 179schema:"$ref": "#/components/schemas/Invitation"'422':@@ -26634,6 +26652,12 @@ components:- type: stringdescription: The values listed are the built-in ones; extensions may addmore.+ inviter_email:+ type: string+ invitee_exists:+ type: boolean+ seller:+ type: objectrequired:- id@@ -26641,6 +26665,8 @@ components:- expires_at- accepted_at- status+ - inviter_email+ - sellerx-typelizer: trueMedia:type: object@@ -32340,7 +32366,7 @@ components:password:type: stringdescription: Sets the password of a new account, or confirms the password- of an existing one.+ of an existing one, unless the request is already signed in as that account.password_confirmation:type: stringfirst_name:diff --git a/packages/admin-sdk/src/types/params/InvitationAcceptParams.ts b/packages/admin-sdk/src/types/params/InvitationAcceptParams.tsindex 777882deb0..0cafae099f 100644--- a/packages/admin-sdk/src/types/params/InvitationAcceptParams.ts+++ b/packages/admin-sdk/src/types/params/InvitationAcceptParams.ts@@ -2,8 +2,8 @@export type InvitationAcceptParams = {/**- * Required when the invitee has no account yet: it creates one. An existing account signs in- * without it.+ * Creates the account when the invitee has none yet. An existing account confirms it is theirs+ * with it, unless the request is already signed in as that account.*/password?: stringpassword_confirmation?: stringdiff --git a/packages/dashboard-core/src/components/invitation-acceptance.tsx b/packages/dashboard-core/src/components/invitation-acceptance.tsxnew file mode 100644index 0000000000..93477679e6--- /dev/null+++ b/packages/dashboard-core/src/components/invitation-acceptance.tsx@@ -0,0 +1,411 @@+import { zodResolver } from '@hookform/resolvers/zod'+import type { SpreeError } from '@spree/admin-sdk'+import { Button, Input, Label } from '@spree/dashboard-ui'+import { useQuery } from '@tanstack/react-query'+import { useState } from 'react'+import { useForm } from 'react-hook-form'+import { useTranslation } from 'react-i18next'+import { z } from 'zod/v4'+import { useAuth } from '../hooks/use-auth'+import { mapSpreeErrorsToForm } from '../lib/form-errors'+import { i18n } from '../lib/i18n'++/**+ * What the acceptance page needs to know about an invitation, as both the+ * Admin and the Seller API lookups answer it. `target` is what the invitee+ * joins: the store on the operator's dashboard, a seller on the seller panel.+ */+export interface InvitationSummary {+ email: string+ invitee_exists: boolean+ inviter_email?: string | null+ role_name?: string | null+ target: { id: string; name: string }+}++export interface InvitationAcceptanceProps {+ invitationId: string+ /** From the emailed link's query string; the page refuses to go on without it. */+ token?: string+ lookup: (invitationId: string, token: string) => Promise<InvitationSummary>+ /** Runs once the invitee's session is established, to take them into what they joined. */+ onAccepted: (invitation: InvitationSummary) => void | Promise<void>+}++// Lazy message factories: module-scope `i18n.t(...)` would lock the English+// string in at import time, breaking locale switches.+const passwordRequired = () => i18n.t('admin.validation.password_required')+const firstNameRequired = () => i18n.t('admin.validation.first_name_required')+const lastNameRequired = () => i18n.t('admin.validation.last_name_required')+const passwordsDontMatch = () => i18n.t('admin.validation.passwords_dont_match')+const passwordMinLength = () =>+ i18n.t('admin.validation.min_length', { field: i18n.t('admin.fields.password.label'), count: 8 })++/** Existing invitee confirming with their current password. */+const signInSchema = z.object({+ password: z.string().min(1, { error: passwordRequired }),+})+type SignInValues = z.infer<typeof signInSchema>++/** New invitee creating an account inline — mirrors the server's `AdminUser` validations. */+const signUpSchema = z+ .object({+ first_name: z.string().min(1, { error: firstNameRequired }),+ last_name: z.string().min(1, { error: lastNameRequired }),+ password: z.string().min(8, { error: passwordMinLength }),+ password_confirmation: z.string(),+ })+ .refine((data) => data.password === data.password_confirmation, {+ error: passwordsDontMatch,+ path: ['password_confirmation'],+ })+type SignUpValues = z.infer<typeof signUpSchema>++/**+ * The screens behind an invitation link, shared by both panels. The host+ * wraps it in its own page layout and decides where an accepted invitee goes.+ *+ * Someone signed out sets a password (new account) or confirms theirs+ * (existing account). Someone already signed in as the invitee accepts with+ * one click; signed in as anyone else, they are asked to sign out first+ * rather than having their session swapped silently.+ */+export function InvitationAcceptance({+ invitationId,+ token,+ lookup,+ onAccepted,+}: InvitationAcceptanceProps) {+ const { t } = useTranslation()+ const { isInitializing } = useAuth()++ if (!token) {+ return (+ <ErrorCard+ title={t('admin.invitation.missing_token_title')}+ message={t('admin.invitation.missing_token_message')}+ />+ )+ }++ // Waits for the session check: it decides which form fits, and a failed one+ // clears the query cache mid-lookup.+ if (isInitializing) return <Loading />++ return (+ <InvitationLoader+ invitationId={invitationId}+ token={token}+ lookup={lookup}+ onAccepted={onAccepted}+ />+ )+}++type LoadedProps = Required<InvitationAcceptanceProps>++function InvitationLoader({ invitationId, token, lookup, onAccepted }: LoadedProps) {+ const { t } = useTranslation()+ const query = useQuery({+ queryKey: ['invitation-lookup', invitationId, token],+ queryFn: () => lookup(invitationId, token),+ retry: false,+ })++ if (query.isPending) return <Loading />++ if (query.isError) {+ const err = query.error as SpreeError+ return (+ <ErrorCard+ title={+ err.status === 404+ ? t('admin.invitation.not_found_title')+ : t('admin.invitation.generic_error_title')+ }+ message={+ err.status === 404+ ? t('admin.invitation.not_found_message')+ : err.message || t('admin.invitation.generic_error_message')+ }+ />+ )+ }++ return (+ <AcceptForm+ invitationId={invitationId}+ token={token}+ invitation={query.data}+ onAccepted={onAccepted}+ />+ )+}++interface FormProps {+ invitationId: string+ token: string+ invitation: InvitationSummary+ onAccepted: LoadedProps['onAccepted']+}++function AcceptForm(props: FormProps) {+ const { user } = useAuth()+ const { invitation } = props+ // Signing in through a form below sets `user` before the redirect lands;+ // a page opened signed out keeps showing that form until then.+ const [openedSignedOut] = useState(!user)+ if (user && !openedSignedOut) {+ return user.email.toLowerCase() === invitation.email.toLowerCase() ? (+ <AcceptAsSignedIn {...props} />+ ) : (+ <SignedInAsAnotherAccount invitation={invitation} />+ )+ }++ return invitation.invitee_exists ? <SignInForm {...props} /> : <SignUpForm {...props} />+}++function SignInForm({ invitationId, token, invitation, onAccepted }: FormProps) {+ const { t } = useTranslation()+ const { acceptInvitation, isLoading } = useAuth()++ const form = useForm<SignInValues>({+ resolver: zodResolver(signInSchema),+ defaultValues: { password: '' },+ })+ const { errors } = form.formState++ const onSubmit = async (data: SignInValues) => {+ try {+ await acceptInvitation(invitationId, token, { password: data.password })+ } catch (err) {+ const e = err as SpreeError+ if (e?.status === 401) {+ form.setError('root', { message: t('admin.validation.invalid_password') })+ return+ }+ if (!mapSpreeErrorsToForm(err, form.setError)) {+ form.setError('root', { message: e?.message || t('admin.invitation.could_not_accept') })+ }+ return+ }+ await onAccepted(invitation)+ }++ return (+ <>+ <InvitationIntro invitation={invitation} action={t('admin.invitation.sign_in_to_accept')} />+ <form onSubmit={form.handleSubmit(onSubmit)} className="grid gap-6">+ {errors.root && <p className="text-sm text-destructive">{errors.root.message}</p>}+ <div className="grid gap-2">+ <Label htmlFor="invitee-email">{t('admin.fields.email.label')}</Label>+ <Input id="invitee-email" value={invitation.email} disabled />+ </div>+ <div className="grid gap-2">+ <Label htmlFor="password">{t('admin.fields.password.label')}</Label>+ <Input+ id="password"+ type="password"+ autoFocus+ aria-invalid={!!errors.password || undefined}+ {...form.register('password')}+ />+ {errors.password && <p className="text-sm text-destructive">{errors.password.message}</p>}+ </div>+ <Button type="submit" className="w-full" disabled={isLoading}>+ {isLoading ? t('admin.invitation.accepting') : t('admin.invitation.sign_in_and_accept')}+ </Button>+ </form>+ </>+ )+}++function SignUpForm({ invitationId, token, invitation, onAccepted }: FormProps) {+ const { t } = useTranslation()+ const { acceptInvitation, isLoading } = useAuth()++ const form = useForm<SignUpValues>({+ resolver: zodResolver(signUpSchema),+ defaultValues: { first_name: '', last_name: '', password: '', password_confirmation: '' },+ })+ const { errors } = form.formState++ const onSubmit = async (data: SignUpValues) => {+ try {+ await acceptInvitation(invitationId, token, data)+ } catch (err) {+ if (!mapSpreeErrorsToForm(err, form.setError)) {+ const e = err as SpreeError+ form.setError('root', { message: e?.message || t('admin.invitation.could_not_accept') })+ }+ return+ }+ await onAccepted(invitation)+ }++ return (+ <>+ <InvitationIntro invitation={invitation} action={t('admin.invitation.create_to_accept')} />+ <form onSubmit={form.handleSubmit(onSubmit)} className="grid gap-6">+ {errors.root && <p className="text-sm text-destructive">{errors.root.message}</p>}+ <div className="grid gap-2">+ <Label htmlFor="invitee-email">{t('admin.fields.email.label')}</Label>+ <Input id="invitee-email" value={invitation.email} disabled />+ </div>+ <div className="grid grid-cols-2 gap-3">+ <div className="grid gap-2">+ <Label htmlFor="first_name">{t('admin.fields.first_name.label')}</Label>+ <Input+ id="first_name"+ autoFocus+ aria-invalid={!!errors.first_name || undefined}+ {...form.register('first_name')}+ />+ {errors.first_name && (+ <p className="text-sm text-destructive">{errors.first_name.message}</p>+ )}+ </div>+ <div className="grid gap-2">+ <Label htmlFor="last_name">{t('admin.fields.last_name.label')}</Label>+ <Input+ id="last_name"+ aria-invalid={!!errors.last_name || undefined}+ {...form.register('last_name')}+ />+ {errors.last_name && (+ <p className="text-sm text-destructive">{errors.last_name.message}</p>+ )}+ </div>+ </div>+ <div className="grid gap-2">+ <Label htmlFor="password">{t('admin.fields.password.label')}</Label>+ <Input+ id="password"+ type="password"+ aria-invalid={!!errors.password || undefined}+ {...form.register('password')}+ />+ {errors.password && <p className="text-sm text-destructive">{errors.password.message}</p>}+ </div>+ <div className="grid gap-2">+ <Label htmlFor="password_confirmation">+ {t('admin.invitation.password_confirmation')}+ </Label>+ <Input+ id="password_confirmation"+ type="password"+ aria-invalid={!!errors.password_confirmation || undefined}+ {...form.register('password_confirmation')}+ />+ {errors.password_confirmation && (+ <p className="text-sm text-destructive">{errors.password_confirmation.message}</p>+ )}+ </div>+ <Button type="submit" className="w-full" disabled={isLoading}>+ {isLoading ? t('admin.invitation.accepting') : t('admin.invitation.create_and_accept')}+ </Button>+ </form>+ </>+ )+}++function AcceptAsSignedIn({ invitationId, token, invitation, onAccepted }: FormProps) {+ const { t } = useTranslation()+ const { user, acceptInvitation, logout, isLoading } = useAuth()+ const [error, setError] = useState<string | null>(null)++ const onAccept = async () => {+ setError(null)+ try {+ await acceptInvitation(invitationId, token, {})+ } catch (err) {+ const e = err as SpreeError+ // The session lapsed (a laptop that slept, say): signing out brings up+ // the password form instead of an error with no way forward.+ if (e?.status === 401) return logout()+ setError(e?.message || t('admin.invitation.could_not_accept'))+ return+ }+ await onAccepted(invitation)+ }++ return (+ <>+ <InvitationIntro+ invitation={invitation}+ action={t('admin.invitation.signed_in_as_invitee', { email: user?.email })}+ />+ {error && <p className="text-sm text-destructive">{error}</p>}+ <Button className="w-full" disabled={isLoading} onClick={onAccept}>+ {isLoading ? t('admin.invitation.accepting') : t('admin.invitation.accept')}+ </Button>+ </>+ )+}++function SignedInAsAnotherAccount({ invitation }: { invitation: InvitationSummary }) {+ const { t } = useTranslation()+ const { user, logout } = useAuth()++ return (+ <>+ <div className="flex flex-col gap-2">+ <h1 className="text-2xl font-bold">+ {t('admin.invitation.join_store', { store: invitation.target.name })}+ </h1>+ <p className="text-sm text-muted-foreground">+ {t('admin.invitation.signed_in_as_another_account', {+ email: user?.email,+ invitee: invitation.email,+ })}+ </p>+ </div>+ <Button variant="outline" className="w-full" onClick={() => logout()}>+ {t('admin.auth.logout')}+ </Button>+ </>+ )+}++/** "Join <target>" plus one sentence: who invited, as what, and what to do next. */+function InvitationIntro({+ invitation,+ action,+}: {+ invitation: InvitationSummary+ action: string+}) {+ const { t } = useTranslation()+ const invitedPart = invitation.inviter_email+ ? t('admin.invitation.invited_by', { email: invitation.inviter_email })+ : t('admin.invitation.invited_generic')+ const rolePart = invitation.role_name+ ? t('admin.invitation.invited_as_role', { role: invitation.role_name })+ : ''++ return (+ <div className="flex flex-col gap-2">+ <h1 className="text-2xl font-bold">+ {t('admin.invitation.join_store', { store: invitation.target.name })}+ </h1>+ <p className="text-sm text-muted-foreground">{`${invitedPart}${rolePart}${action}`}</p>+ </div>+ )+}++function Loading() {+ const { t } = useTranslation()+ return (+ <div className="py-12 text-center text-muted-foreground">{t('admin.invitation.loading')}</div>+ )+}++function ErrorCard({ title, message }: { title: string; message: string }) {+ return (+ <div className="flex flex-col gap-2">+ <h1 className="text-2xl font-bold">{title}</h1>+ <p className="text-sm text-muted-foreground">{message}</p>+ </div>+ )+}diff --git a/packages/dashboard-core/src/index.ts b/packages/dashboard-core/src/index.tsindex 38bc451835..ccbc713558 100644--- a/packages/dashboard-core/src/index.ts+++ b/packages/dashboard-core/src/index.ts@@ -41,6 +41,7 @@ export * from './components/file-upload-field'export * from './components/image-upload-field'export * from './components/import-button'export * from './components/import-wizard-dialog'+export * from './components/invitation-acceptance'export * from './components/locale-select'export * from './components/market-combobox'export * from './components/media-picker-sheet'diff --git a/packages/dashboard-core/src/locales/ar.json b/packages/dashboard-core/src/locales/ar.jsonindex 1f44ddd6c4..09ab0171b2 100644--- a/packages/dashboard-core/src/locales/ar.json+++ b/packages/dashboard-core/src/locales/ar.json@@ -1043,6 +1043,29 @@},"wizard_title": "الاستيراد"},+ "invitation": {+ "accept": "قبول الدعوة",+ "accepting": "قبول…",+ "could_not_accept": "لا يمكن قبول الدعوة",+ "create_and_accept": "Create account & accept",+ "create_to_accept": ". أنشئ حسابك للقبول.",+ "generic_error_message": "حدث خطأ ما. يرجى المحاولة مرة أخرى.",+ "generic_error_title": "تعذر تحميل الدعوة",+ "invited_as_role": " مثل {{role}}",+ "invited_by": "{{email}} دعوتك",+ "invited_generic": "لقد تمت دعوتك",+ "join_store": "انضم إلى {{store}}",+ "loading": "جارٍ تحميل الدعوة…",+ "missing_token_message": "هذا الرابط يبدو غير مكتمل. اطلب من الشخص الذي دعاك أن يرسلها مرة أخرى.",+ "missing_token_title": "رمز الدعوة مفقود",+ "not_found_message": "انتهت صلاحية هذه الدعوة، أو تم إلغاؤها، أو تم قبولها بالفعل. اطلب من الداعي إرسال واحدة جديدة.",+ "not_found_title": "لم يتم العثور على الدعوة",+ "password_confirmation": "تأكيد كلمة المرور",+ "sign_in_and_accept": "Sign in & accept",+ "sign_in_to_accept": ". قم بتسجيل الدخول للقبول.",+ "signed_in_as_another_account": "أنت مسجّل الدخول باسم {{email}}، لكن هذه الدعوة موجّهة إلى {{invitee}}. سجّل الخروج لقبولها.",+ "signed_in_as_invitee": ". أنت مسجّل الدخول باسم {{email}}."+ },"media_picker": {"confirm": "إضافة المحدد","description": "اختر ملفات موجودة في مكتبتك، أو ارفع ملفات جديدة.",diff --git a/packages/dashboard-core/src/locales/de.json b/packages/dashboard-core/src/locales/de.jsonindex 7fa3d4d708..53049ff3b1 100644--- a/packages/dashboard-core/src/locales/de.json+++ b/packages/dashboard-core/src/locales/de.json@@ -1043,6 +1043,29 @@},"wizard_title": "Import"},+ "invitation": {+ "accept": "Einladung annehmen",+ "accepting": "Wird angenommen…",+ "could_not_accept": "Einladung konnte nicht angenommen werden",+ "create_and_accept": "Konto erstellen & annehmen",+ "create_to_accept": ". Erstellen Sie Ihr Konto, um anzunehmen.",+ "generic_error_message": "Etwas ist schiefgelaufen. Bitte versuchen Sie es erneut.",+ "generic_error_title": "Einladung konnte nicht geladen werden",+ "invited_as_role": " als {{role}}",+ "invited_by": "{{email}} hat Sie eingeladen",+ "invited_generic": "Sie wurden eingeladen",+ "join_store": "{{store}} beitreten",+ "loading": "Einladung wird geladen…",+ "missing_token_message": "Dieser Link scheint unvollständig zu sein. Bitten Sie die Person, die Sie eingeladen hat, ihn erneut zu senden.",+ "missing_token_title": "Einladungs-Token fehlt",+ "not_found_message": "Diese Einladung ist abgelaufen, wurde widerrufen oder bereits angenommen. Bitten Sie die einladende Person, eine neue zu senden.",+ "not_found_title": "Einladung nicht gefunden",+ "password_confirmation": "Passwort bestätigen",+ "sign_in_and_accept": "Anmelden & annehmen",+ "sign_in_to_accept": ". Melden Sie sich an, um anzunehmen.",+ "signed_in_as_another_account": "Sie sind als {{email}} angemeldet, aber diese Einladung gilt für {{invitee}}. Melden Sie sich ab, um sie anzunehmen.",+ "signed_in_as_invitee": ". Sie sind als {{email}} angemeldet."+ },"media_picker": {"confirm": "Auswahl hinzufügen","description": "Wählen Sie Dateien aus Ihrer Bibliothek oder laden Sie neue hoch.",diff --git a/packages/dashboard-core/src/locales/en.json b/packages/dashboard-core/src/locales/en.jsonindex 97d91f2165..e01bac448a 100644--- a/packages/dashboard-core/src/locales/en.json+++ b/packages/dashboard-core/src/locales/en.json@@ -1045,6 +1045,29 @@},"wizard_title": "Import"},+ "invitation": {+ "accept": "Accept invitation",+ "accepting": "Accepting…",+ "could_not_accept": "Could not accept invitation",+ "create_and_accept": "Create account & accept",+ "create_to_accept": ". Create your account to accept.",+ "generic_error_message": "Something went wrong. Please try again.",+ "generic_error_title": "Could not load invitation",+ "invited_as_role": " as {{role}}",+ "invited_by": "{{email}} invited you",+ "invited_generic": "You have been invited",+ "join_store": "Join {{store}}",+ "loading": "Loading invitation…",+ "missing_token_message": "This link looks incomplete. Ask whoever invited you to send it again.",+ "missing_token_title": "Missing invitation token",+ "not_found_message": "This invitation has expired, been revoked, or already been accepted. Ask the inviter to send a new one.",+ "not_found_title": "Invitation not found",+ "password_confirmation": "Confirm password",+ "sign_in_and_accept": "Sign in & accept",+ "sign_in_to_accept": ". Sign in to accept.",+ "signed_in_as_another_account": "You are signed in as {{email}}, but this invitation is for {{invitee}}. Sign out to accept it.",+ "signed_in_as_invitee": ". You are signed in as {{email}}."+ },"media_picker": {"confirm": "Add selected","description": "Pick files already in your library, or upload new ones.",diff --git a/packages/dashboard-core/src/locales/es.json b/packages/dashboard-core/src/locales/es.jsonindex 293daa87ff..bd5a2377bc 100644--- a/packages/dashboard-core/src/locales/es.json+++ b/packages/dashboard-core/src/locales/es.json@@ -1506,6 +1506,29 @@},"wizard_title": "Importar"},+ "invitation": {+ "accept": "Aceptar invitación",+ "accepting": "Aceptando…",+ "could_not_accept": "No se pudo aceptar la invitación",+ "create_and_accept": "Crear cuenta y aceptar",+ "create_to_accept": ". Creá tu cuenta para aceptar.",+ "generic_error_message": "Algo salió mal. Intentá de nuevo.",+ "generic_error_title": "No se pudo cargar la invitación",+ "invited_as_role": " como {{role}}",+ "invited_by": "{{email}} te invitó",+ "invited_generic": "Fuiste invitado",+ "join_store": "Sumarte a {{store}}",+ "loading": "Cargando invitación…",+ "missing_token_message": "Este enlace parece incompleto. Pedile a quien te invitó que lo vuelva a enviar.",+ "missing_token_title": "Falta el token de invitación",+ "not_found_message": "Esta invitación venció, fue revocada o ya fue aceptada. Pedile al que invita que envíe una nueva.",+ "not_found_title": "Invitación no encontrada",+ "password_confirmation": "Confirmar contraseña",+ "sign_in_and_accept": "Iniciar sesión y aceptar",+ "sign_in_to_accept": ". Iniciá sesión para aceptar.",+ "signed_in_as_another_account": "Iniciaste sesión como {{email}}, pero esta invitación es para {{invitee}}. Cerrá sesión para aceptarla.",+ "signed_in_as_invitee": ". Iniciaste sesión como {{email}}."+ },"actions": {"actions_menu": "Acciones","add": "Agregar",diff --git a/packages/dashboard-core/src/locales/fr.json b/packages/dashboard-core/src/locales/fr.jsonindex 9a224bb5ef..12fad668e2 100644--- a/packages/dashboard-core/src/locales/fr.json+++ b/packages/dashboard-core/src/locales/fr.json@@ -1043,6 +1043,29 @@},"wizard_title": "Import"},+ "invitation": {+ "accept": "Accepter l’invitation",+ "accepting": "Acceptation…",+ "could_not_accept": "Impossible d'accepter l'invitation",+ "create_and_accept": "Créer un compte et accepter",+ "create_to_accept": ". Créez votre compte pour accepter.",+ "generic_error_message": "Une erreur s'est produite. Veuillez réessayer.",+ "generic_error_title": "Impossible de charger l'invitation",+ "invited_as_role": " en tant que {{role}}",+ "invited_by": "{{email}} vous a invité",+ "invited_generic": "Vous avez été invité",+ "join_store": "Rejoindre {{store}}",+ "loading": "Chargement de l'invitation…",+ "missing_token_message": "Ce lien semble incomplet. Demandez à la personne qui vous a invité de vous le renvoyer.",+ "missing_token_title": "Jeton d'invitation manquant",+ "not_found_message": "Cette invitation a expiré, a été révoquée ou a déjà été acceptée. Demandez à la personne qui vous a invité de vous en envoyer une nouvelle.",+ "not_found_title": "Invitation introuvable",+ "password_confirmation": "Confirmer le mot de passe",+ "sign_in_and_accept": "Se connecter et accepter",+ "sign_in_to_accept": ". Connectez-vous pour accepter.",+ "signed_in_as_another_account": "Vous êtes connecté en tant que {{email}}, mais cette invitation est destinée à {{invitee}}. Déconnectez-vous pour l’accepter.",+ "signed_in_as_invitee": ". Vous êtes connecté en tant que {{email}}."+ },"media_picker": {"confirm": "Ajouter la sélection","description": "Choisissez des fichiers déjà dans votre médiathèque, ou importez-en de nouveaux.",diff --git a/packages/dashboard-core/src/locales/ja.json b/packages/dashboard-core/src/locales/ja.jsonindex 4a69a40e6b..6016973388 100644--- a/packages/dashboard-core/src/locales/ja.json+++ b/packages/dashboard-core/src/locales/ja.json@@ -1045,6 +1045,29 @@},"wizard_title": "インポート"},+ "invitation": {+ "accept": "招待を承諾",+ "accepting": "承諾中…",+ "could_not_accept": "招待を承諾できませんでした",+ "create_and_accept": "アカウントを作成して承諾",+ "create_to_accept": "。承諾するにはアカウントを作成してください。",+ "generic_error_message": "問題が起きました。もう一度お試しください。",+ "generic_error_title": "招待を読み込めませんでした",+ "invited_as_role": "({{role}}として)",+ "invited_by": "{{email}}から招待が届いています",+ "invited_generic": "招待されています",+ "join_store": "{{store}}に参加",+ "loading": "招待を読み込み中…",+ "missing_token_message": "このリンクは不完全なようです。招待した人にもう一度送ってもらってください。",+ "missing_token_title": "招待のトークンがありません",+ "not_found_message": "この招待は期限切れか、取り消されたか、すでに承諾されています。招待した人に新しく送ってもらってください。",+ "not_found_title": "招待が見つかりません",+ "password_confirmation": "パスワード(確認)",+ "sign_in_and_accept": "ログインして承諾",+ "sign_in_to_accept": "。承諾するにはログインしてください。",+ "signed_in_as_another_account": "{{email}}でログイン中ですが、この招待は{{invitee}}宛てです。承諾するにはログアウトしてください。",+ "signed_in_as_invitee": "。{{email}}でログイン中です。"+ },"media_picker": {"confirm": "選んだものを追加","description": "ライブラリにあるファイルを選ぶか、新しくアップロードしてください。",diff --git a/packages/dashboard-core/src/locales/pl.json b/packages/dashboard-core/src/locales/pl.jsonindex 819e645f74..07da3652b2 100644--- a/packages/dashboard-core/src/locales/pl.json+++ b/packages/dashboard-core/src/locales/pl.json@@ -1044,6 +1044,29 @@},"wizard_title": "Import"},+ "invitation": {+ "accept": "Zaakceptuj zaproszenie",+ "accepting": "Akceptowanie…",+ "could_not_accept": "Nie udało się zaakceptować zaproszenia",+ "create_and_accept": "Utwórz konto i zaakceptuj",+ "create_to_accept": ". Utwórz konto, aby zaakceptować.",+ "generic_error_message": "Coś poszło nie tak. Spróbuj ponownie.",+ "generic_error_title": "Nie udało się wczytać zaproszenia",+ "invited_as_role": " jako {{role}}",+ "invited_by": "{{email}} zaprosił(a) Cię",+ "invited_generic": "Zostałeś(-aś) zaproszony(-a)",+ "join_store": "Dołącz do {{store}}",+ "loading": "Wczytywanie zaproszenia…",+ "missing_token_message": "Ten link wygląda na niekompletny. Poproś osobę, która Cię zaprosiła, o ponowne przesłanie go.",+ "missing_token_title": "Brak tokenu zaproszenia",+ "not_found_message": "To zaproszenie wygasło, zostało unieważnione lub już je zaakceptowano. Poproś osobę zapraszającą o wysłanie nowego.",+ "not_found_title": "Nie znaleziono zaproszenia",+ "password_confirmation": "Potwierdź hasło",+ "sign_in_and_accept": "Zaloguj się i zaakceptuj",+ "sign_in_to_accept": ". Zaloguj się, aby zaakceptować.",+ "signed_in_as_another_account": "Zalogowano jako {{email}}, ale to zaproszenie jest dla {{invitee}}. Wyloguj się, aby je zaakceptować.",+ "signed_in_as_invitee": ". Zalogowano jako {{email}}."+ },"media_picker": {"confirm": "Dodaj wybrane","description": "Wybierz pliki z biblioteki lub prześlij nowe.",diff --git a/packages/dashboard-core/src/locales/zh-CN.json b/packages/dashboard-core/src/locales/zh-CN.jsonindex 4343e1134c..2ec548b85e 100644--- a/packages/dashboard-core/src/locales/zh-CN.json+++ b/packages/dashboard-core/src/locales/zh-CN.json@@ -1043,6 +1043,29 @@},"wizard_title": "导入"},+ "invitation": {+ "accept": "接受邀请",+ "accepting": "正在接受…",+ "could_not_accept": "无法接受邀请",+ "create_and_accept": "创建账户并接受",+ "create_to_accept": "。创建账户以接受。",+ "generic_error_message": "出现了一些问题。请重试。",+ "generic_error_title": "无法加载邀请",+ "invited_as_role": ",担任 {{role}}",+ "invited_by": "{{email}} 邀请了你",+ "invited_generic": "你已被邀请",+ "join_store": "加入 {{store}}",+ "loading": "正在加载邀请…",+ "missing_token_message": "此链接似乎不完整。请让邀请你的人重新发送一次。",+ "missing_token_title": "缺少邀请令牌",+ "not_found_message": "此邀请已过期、被撤销或已被接受。请让邀请人发送一个新的邀请。",+ "not_found_title": "未找到邀请",+ "password_confirmation": "确认密码",+ "sign_in_and_accept": "登录并接受",+ "sign_in_to_accept": "。登录以接受。",+ "signed_in_as_another_account": "你当前以 {{email}} 登录,但此邀请发送给 {{invitee}}。请退出登录后再接受。",+ "signed_in_as_invitee": "。你当前以 {{email}} 登录。"+ },"media_picker": {"confirm": "添加所选","description": "从媒体库中选择文件,或上传新文件。",diff --git a/packages/dashboard/e2e/invitation-acceptance.spec.ts b/packages/dashboard/e2e/invitation-acceptance.spec.tsindex c4b9b72b8a..be532c525e 100644--- a/packages/dashboard/e2e/invitation-acceptance.spec.ts+++ b/packages/dashboard/e2e/invitation-acceptance.spec.ts@@ -1,5 +1,11 @@import { expect, test } from '@playwright/test'-import { invitationAcceptancePath, login } from './helpers'+import {+ adminApiSession,+ adminRequest,+ escapeRegex,+ invitationAcceptancePath,+ login,+} from './helpers'test.describe('invitation lifecycle', () => {test('admin invites a teammate and the invitee signs up via the link', async ({@@ -67,6 +73,97 @@ test.describe('invitation lifecycle', () => {}})+ test('someone signed in as another account is asked to sign out instead of being redirected', async ({+ page,+ }) => {+ const session = await login(page)+ const inviteeEmail = `e2e-invitee-${Date.now()}@example.com`+ const roles = await adminRequest<{ data: { id: string }[] }>(page, session, 'get', '/roles')+ const invitation = await adminRequest<{ id: string }>(page, session, 'post', '/invitations', {+ email: inviteeEmail,+ role_id: roles.data[0].id,+ })+ const acceptancePath = await invitationAcceptancePath(+ page,+ session,+ `/api/v3/admin/invitations/${invitation.id}`,+ )++ await page.goto(acceptancePath)+ await expect(+ page.getByText(new RegExp(`signed in as ${escapeRegex(session.admin_email)}`, 'i')),+ ).toBeVisible({+ timeout: 15_000,+ })+ await expect(page).toHaveURL(/\/accept-invitation\//)++ await page.getByRole('button', { name: /sign out/i }).click()+ await expect(page.getByLabel(/email/i)).toHaveValue(inviteeEmail, { timeout: 15_000 })+ await expect(page.getByRole('button', { name: /create account & accept/i })).toBeVisible()++ await adminRequest(page, await adminApiSession(page), 'delete', `/invitations/${invitation.id}`)+ })++ test('someone signed in as the invited account accepts with one click', async ({+ page,+ browser,+ }) => {+ const session = await login(page)+ const email = `e2e-returning-${Date.now()}@example.com`+ const roles = await adminRequest<{ data: { id: string }[] }>(page, session, 'get', '/roles')+ const invite = async () => {+ const invitation = await adminRequest<{ id: string }>(page, session, 'post', '/invitations', {+ email,+ role_id: roles.data[0].id,+ })+ const path = await invitationAcceptancePath(+ page,+ session,+ `/api/v3/admin/invitations/${invitation.id}`,+ )+ return { id: invitation.id, path }+ }++ const inviteeContext = await browser.newContext()+ const inviteePage = await inviteeContext.newPage()+ try {+ // An account that left the store: it exists and is signed in, but holds+ // no role here. Accepting through the API plants its session cookie.+ const first = await invite()+ const accepted = await inviteePage.request.post(+ `/api/v3/admin/auth/invitations/${first.id}/accept`,+ {+ data: {+ token: new URL(first.path, 'http://localhost').searchParams.get('token'),+ password: 'e2e-password-123',+ password_confirmation: 'e2e-password-123',+ },+ },+ )+ expect(accepted.ok(), await accepted.text()).toBeTruthy()+ const { user } = (await accepted.json()) as { user: { id: string } }+ await adminRequest(page, session, 'delete', `/admin_users/${user.id}`)++ const second = await invite()+ await inviteePage.goto(second.path)+ await expect(+ inviteePage.getByText(new RegExp(`signed in as ${escapeRegex(email)}`, 'i')),+ ).toBeVisible({+ timeout: 15_000,+ })+ await expect(inviteePage.getByLabel(/password/i)).toHaveCount(0)++ await inviteePage.getByRole('button', { name: /^accept invitation$/i }).click()+ await expect(inviteePage).toHaveURL(new RegExp(`/${session.store_id}`), { timeout: 15_000 })+ // Permissions fetched before the role existed would leave the sidebar bare.+ await expect(inviteePage.getByRole('link', { name: /^products$/i })).toBeVisible({+ timeout: 15_000,+ })+ } finally {+ await inviteeContext.close()+ }+ })+test('shows an error for an invalid token', async ({ page }) => {await page.goto('/accept-invitation/inv_doesnotexist?token=bogus-token-here')await expect(page.getByText(/invitation not found/i)).toBeVisible({ timeout: 15_000 })diff --git a/packages/dashboard/e2e/seller-invitation-acceptance.spec.ts b/packages/dashboard/e2e/seller-invitation-acceptance.spec.tsindex d6aee6ae09..a01f3a55bd 100644--- a/packages/dashboard/e2e/seller-invitation-acceptance.spec.ts+++ b/packages/dashboard/e2e/seller-invitation-acceptance.spec.ts@@ -1,11 +1,113 @@-import { expect, test } from '@playwright/test'-import { invitationAcceptancePath, login, SELLER_PANEL } from './helpers'+import { expect, type Page, test } from '@playwright/test'+import {+ adminRequest,+ deleteSeededRecords,+ type E2ELoginSession,+ escapeRegex,+ FIXTURE_SELLER_USER_EMAIL,+ invitationAcceptancePath,+ login,+ SELLER_PANEL,+ seedRecord,+ sellerLogin,+} from './helpers'// The seller panel is its own app on its own origin (see playwright.config.ts),// so this spec drives two: the operator's dashboard through `baseURL`, and the// panel by absolute URL.+/** A new seller with one pending invitation, and the panel link that accepts it. */+async function inviteToNewSeller(page: Page, session: E2ELoginSession, email: string) {+ const seller = await seedRecord(page, session, '/sellers', {+ name: `E2E Seller ${Date.now()}-${Math.random().toString(36).slice(2, 6)}`,+ })+ await adminRequest(page, session, 'post', `/sellers/${seller.id}/invite`, { email })+ const { data } = await adminRequest<{ data: { id: string }[] }>(+ page,+ session,+ 'get',+ `/sellers/${seller.id}/invitations`,+ )+ const path = await invitationAcceptancePath(+ page,+ session,+ `/api/v3/admin/sellers/${seller.id}/invitations/${data[0].id}`,+ )+ return { seller, invitationId: data[0].id, url: `${SELLER_PANEL}${path}` }+}+test.describe('seller invitation lifecycle', () => {+ test.afterEach(async ({ page }) => {+ await deleteSeededRecords(page)+ })++ test('someone signed in as another seller account is asked to sign out', async ({+ page,+ browser,+ }) => {+ const session = await login(page)+ const inviteeEmail = `e2e-seller-invitee-${Date.now()}@example.com`+ const { url } = await inviteToNewSeller(page, session, inviteeEmail)++ const panelContext = await browser.newContext()+ const panel = await panelContext.newPage()+ try {+ await sellerLogin(panel)+ await panel.goto(url)+ await expect(+ panel.getByText(new RegExp(`signed in as ${escapeRegex(FIXTURE_SELLER_USER_EMAIL)}`, 'i')),+ ).toBeVisible({ timeout: 20_000 })++ await panel.getByRole('button', { name: /sign out/i }).click()+ await expect(panel.getByLabel(/email/i)).toHaveValue(inviteeEmail, { timeout: 20_000 })+ await expect(panel.getByRole('button', { name: /create account & accept/i })).toBeVisible()+ } finally {+ await panelContext.close()+ }+ })++ test('someone signed in as the invited account accepts with one click', async ({+ page,+ browser,+ }) => {+ const session = await login(page)+ const email = `e2e-seller-returning-${Date.now()}@example.com`+ const first = await inviteToNewSeller(page, session, email)++ const panelContext = await browser.newContext()+ const panel = await panelContext.newPage()+ try {+ // An account that already runs one seller, signed in to the panel:+ // accepting through the API plants its session cookie.+ const accepted = await panel.request.post(+ `${SELLER_PANEL}/api/v3/seller/auth/invitations/${first.invitationId}/accept`,+ {+ data: {+ token: new URL(first.url).searchParams.get('token'),+ password: 'e2e-password-123',+ password_confirmation: 'e2e-password-123',+ first_name: 'Robin',+ last_name: 'Returning',+ },+ },+ )+ expect(accepted.ok(), await accepted.text()).toBeTruthy()++ const second = await inviteToNewSeller(page, session, email)+ await panel.goto(second.url)+ await expect(+ panel.getByText(new RegExp(`signed in as ${escapeRegex(email)}`, 'i')),+ ).toBeVisible({ timeout: 20_000 })+ await expect(panel.getByLabel(/password/i)).toHaveCount(0)++ await panel.getByRole('button', { name: /^accept invitation$/i }).click()+ await expect(panel).toHaveURL(new RegExp(`/${second.seller.id}$`), { timeout: 20_000 })+ await expect(panel.getByText(/selling/i).first()).toBeVisible({ timeout: 20_000 })+ } finally {+ await panelContext.close()+ }+ })+test('an invited seller accepts and lands in their own panel', async ({ page, browser }) => {const creds = await login(page)const suffix = Date.now()diff --git a/packages/dashboard/src/locales/ar.json b/packages/dashboard/src/locales/ar.jsonindex e1ffec3379..83fff64c27 100644--- a/packages/dashboard/src/locales/ar.json+++ b/packages/dashboard/src/locales/ar.json@@ -1593,14 +1593,6 @@"label": "الكمية"}},- "invitation_acceptance": {- "password": {- "label": "كلمة المرور"- },- "password_confirmation": {- "label": "تأكيد كلمة المرور"- }- },"issued_at": {"label": "تاريخ الإصدار"},@@ -2732,25 +2724,6 @@"toggle_label": "تشغيل {{name}} أو إيقافه","view_cta": "عرض"},- "invitation": {- "accepting": "قبول…",- "could_not_accept": "لا يمكن قبول الدعوة",- "create_and_accept": "Create account & accept",- "create_to_accept": ". أنشئ حسابك للقبول.",- "generic_error_message": "حدث خطأ ما. يرجى المحاولة مرة أخرى.",- "generic_error_title": "تعذر تحميل الدعوة",- "invited_as_role": "مثل {{role}}",- "invited_by": "{{email}} دعوتك",- "invited_generic": "لقد تمت دعوتك",- "join_store": "انضم إلى {{store}}",- "loading": "جارٍ تحميل الدعوة…",- "missing_token_message": "هذا الرابط يبدو غير مكتمل. اطلب من الشخص الذي دعاك أن يرسلها مرة أخرى.",- "missing_token_title": "رمز الدعوة مفقود",- "not_found_message": "انتهت صلاحية هذه الدعوة، أو تم إلغاؤها، أو تم قبولها بالفعل. اطلب من الداعي إرسال واحدة جديدة.",- "not_found_title": "لم يتم العثور على الدعوة",- "sign_in_and_accept": "Sign in & accept",- "sign_in_to_accept": ". قم بتسجيل الدخول للقبول."- },"jurisdiction": {"everywhere": "كل المناطق"},diff --git a/packages/dashboard/src/locales/de.json b/packages/dashboard/src/locales/de.jsonindex b3119ac9a5..d77621624f 100644--- a/packages/dashboard/src/locales/de.json+++ b/packages/dashboard/src/locales/de.json@@ -1575,14 +1575,6 @@"label": "Menge"}},- "invitation_acceptance": {- "password": {- "label": "Passwort"- },- "password_confirmation": {- "label": "Passwort bestätigen"- }- },"issued_at": {"label": "Ausgestellt am"},@@ -2714,25 +2706,6 @@"toggle_label": "{{name}} ein- oder ausschalten","view_cta": "Ansehen"},- "invitation": {- "accepting": "Wird angenommen…",- "could_not_accept": "Einladung konnte nicht angenommen werden",- "create_and_accept": "Konto erstellen & annehmen",- "create_to_accept": ". Erstellen Sie Ihr Konto, um anzunehmen.",- "generic_error_message": "Etwas ist schiefgelaufen. Bitte versuchen Sie es erneut.",- "generic_error_title": "Einladung konnte nicht geladen werden",- "invited_as_role": " als {{role}}",- "invited_by": "{{email}} hat Sie eingeladen",- "invited_generic": "Sie wurden eingeladen",- "join_store": "{{store}} beitreten",- "loading": "Einladung wird geladen…",- "missing_token_message": "Dieser Link scheint unvollständig zu sein. Bitten Sie die Person, die Sie eingeladen hat, ihn erneut zu senden.",- "missing_token_title": "Einladungs-Token fehlt",- "not_found_message": "Diese Einladung ist abgelaufen, wurde widerrufen oder bereits angenommen. Bitten Sie die einladende Person, eine neue zu senden.",- "not_found_title": "Einladung nicht gefunden",- "sign_in_and_accept": "Anmelden & annehmen",- "sign_in_to_accept": ". Melden Sie sich an, um anzunehmen."- },"jurisdiction": {"everywhere": "Überall"},diff --git a/packages/dashboard/src/locales/en.json b/packages/dashboard/src/locales/en.jsonindex a79e035382..3597489aca 100644--- a/packages/dashboard/src/locales/en.json+++ b/packages/dashboard/src/locales/en.json@@ -1575,14 +1575,6 @@"label": "Quantity"}},- "invitation_acceptance": {- "password": {- "label": "Password"- },- "password_confirmation": {- "label": "Confirm password"- }- },"issued_at": {"label": "Issued on"},@@ -2714,25 +2706,6 @@"toggle_label": "Turn {{name}} on or off","view_cta": "View"},- "invitation": {- "accepting": "Accepting…",- "could_not_accept": "Could not accept invitation",- "create_and_accept": "Create account & accept",- "create_to_accept": ". Create your account to accept.",- "generic_error_message": "Something went wrong. Please try again.",- "generic_error_title": "Could not load invitation",- "invited_as_role": " as {{role}}",- "invited_by": "{{email}} invited you",- "invited_generic": "You have been invited",- "join_store": "Join {{store}}",- "loading": "Loading invitation…",- "missing_token_message": "This link looks incomplete. Ask whoever invited you to send it again.",- "missing_token_title": "Missing invitation token",- "not_found_message": "This invitation has expired, been revoked, or already been accepted. Ask the inviter to send a new one.",- "not_found_title": "Invitation not found",- "sign_in_and_accept": "Sign in & accept",- "sign_in_to_accept": ". Sign in to accept."- },"jurisdiction": {"everywhere": "Everywhere"},diff --git a/packages/dashboard/src/locales/es.json b/packages/dashboard/src/locales/es.jsonindex 96fb36b816..fcb7e73501 100644--- a/packages/dashboard/src/locales/es.json+++ b/packages/dashboard/src/locales/es.json@@ -1599,14 +1599,6 @@"label": "Cantidad"}},- "invitation_acceptance": {- "password": {- "label": "Contraseña"- },- "password_confirmation": {- "label": "Confirmar contraseña"- }- },"issued_at": {"label": "Emitido el"},@@ -5914,25 +5906,6 @@},"table_title": "Definiciones de campos personalizados"},- "invitation": {- "accepting": "Aceptando…",- "could_not_accept": "No se pudo aceptar la invitación",- "create_and_accept": "Crear cuenta y aceptar",- "create_to_accept": ". Creá tu cuenta para aceptar.",- "generic_error_message": "Algo salió mal. Intentá de nuevo.",- "generic_error_title": "No se pudo cargar la invitación",- "invited_as_role": " como {{role}}",- "invited_by": "{{email}} te invitó",- "invited_generic": "Fuiste invitado",- "join_store": "Sumarte a {{store}}",- "loading": "Cargando invitación…",- "missing_token_message": "Este enlace parece incompleto. Pedile a quien te invitó que lo vuelva a enviar.",- "missing_token_title": "Falta el token de invitación",- "not_found_message": "Esta invitación venció, fue revocada o ya fue aceptada. Pedile al que invita que envíe una nueva.",- "not_found_title": "Invitación no encontrada",- "sign_in_and_accept": "Iniciar sesión y aceptar",- "sign_in_to_accept": ". Iniciá sesión para aceptar."- },"markets": {"add_cta": "Agregar mercado","columns": {diff --git a/packages/dashboard/src/locales/fr.json b/packages/dashboard/src/locales/fr.jsonindex c000b34187..167f5249d4 100644--- a/packages/dashboard/src/locales/fr.json+++ b/packages/dashboard/src/locales/fr.json@@ -1575,14 +1575,6 @@"label": "Quantité"}},- "invitation_acceptance": {- "password": {- "label": "Mot de passe"- },- "password_confirmation": {- "label": "Confirmer le mot de passe"- }- },"issued_at": {"label": "Délivrée le"},@@ -2714,25 +2706,6 @@"toggle_label": "Activer ou désactiver {{name}}","view_cta": "Voir"},- "invitation": {- "accepting": "Acceptation…",- "could_not_accept": "Impossible d'accepter l'invitation",- "create_and_accept": "Créer un compte et accepter",- "create_to_accept": ". Créez votre compte pour accepter.",- "generic_error_message": "Une erreur s'est produite. Veuillez réessayer.",- "generic_error_title": "Impossible de charger l'invitation",- "invited_as_role": " en tant que {{role}}",- "invited_by": "{{email}} vous a invité",- "invited_generic": "Vous avez été invité",- "join_store": "Rejoindre {{store}}",- "loading": "Chargement de l'invitation…",- "missing_token_message": "Ce lien semble incomplet. Demandez à la personne qui vous a invité de vous le renvoyer.",- "missing_token_title": "Jeton d'invitation manquant",- "not_found_message": "Cette invitation a expiré, a été révoquée ou a déjà été acceptée. Demandez à la personne qui vous a invité de vous en envoyer une nouvelle.",- "not_found_title": "Invitation introuvable",- "sign_in_and_accept": "Se connecter et accepter",- "sign_in_to_accept": ". Connectez-vous pour accepter."- },"jurisdiction": {"everywhere": "Partout"},diff --git a/packages/dashboard/src/locales/ja.json b/packages/dashboard/src/locales/ja.jsonindex 0fd664f824..3469b1b382 100644--- a/packages/dashboard/src/locales/ja.json+++ b/packages/dashboard/src/locales/ja.json@@ -1575,14 +1575,6 @@"label": "数量"}},- "invitation_acceptance": {- "password": {- "label": "パスワード"- },- "password_confirmation": {- "label": "パスワード(確認)"- }- },"issued_at": {"label": "発行日"},@@ -2714,25 +2706,6 @@"toggle_label": "{{name}}のオン・オフを切り替え","view_cta": "表示"},- "invitation": {- "accepting": "承諾中…",- "could_not_accept": "招待を承諾できませんでした",- "create_and_accept": "アカウントを作成して承諾",- "create_to_accept": "。承諾するにはアカウントを作成してください。",- "generic_error_message": "問題が起きました。もう一度お試しください。",- "generic_error_title": "招待を読み込めませんでした",- "invited_as_role": "({{role}}として)",- "invited_by": "{{email}}から招待が届いています",- "invited_generic": "招待されています",- "join_store": "{{store}}に参加",- "loading": "招待を読み込み中…",- "missing_token_message": "このリンクは不完全なようです。招待した人にもう一度送ってもらってください。",- "missing_token_title": "招待のトークンがありません",- "not_found_message": "この招待は期限切れか、取り消されたか、すでに承諾されています。招待した人に新しく送ってもらってください。",- "not_found_title": "招待が見つかりません",- "sign_in_and_accept": "ログインして承諾",- "sign_in_to_accept": "。承諾するにはログインしてください。"- },"jurisdiction": {"everywhere": "すべての地域"},diff --git a/packages/dashboard/src/locales/pl.json b/packages/dashboard/src/locales/pl.jsonindex 265ce42cc0..363830617b 100644--- a/packages/dashboard/src/locales/pl.json+++ b/packages/dashboard/src/locales/pl.json@@ -1593,14 +1593,6 @@"label": "Ilość"}},- "invitation_acceptance": {- "password": {- "label": "Hasło"- },- "password_confirmation": {- "label": "Potwierdź hasło"- }- },"issued_at": {"label": "Data wydania"},@@ -2732,25 +2724,6 @@"toggle_label": "Włącz lub wyłącz {{name}}","view_cta": "Zobacz"},- "invitation": {- "accepting": "Akceptowanie…",- "could_not_accept": "Nie udało się zaakceptować zaproszenia",- "create_and_accept": "Utwórz konto i zaakceptuj",- "create_to_accept": ". Utwórz konto, aby zaakceptować.",- "generic_error_message": "Coś poszło nie tak. Spróbuj ponownie.",- "generic_error_title": "Nie udało się wczytać zaproszenia",- "invited_as_role": " jako {{role}}",- "invited_by": "{{email}} zaprosił(a) Cię",- "invited_generic": "Zostałeś(-aś) zaproszony(-a)",- "join_store": "Dołącz do {{store}}",- "loading": "Wczytywanie zaproszenia…",- "missing_token_message": "Ten link wygląda na niekompletny. Poproś osobę, która Cię zaprosiła, o ponowne przesłanie go.",- "missing_token_title": "Brak tokenu zaproszenia",- "not_found_message": "To zaproszenie wygasło, zostało unieważnione lub już je zaakceptowano. Poproś osobę zapraszającą o wysłanie nowego.",- "not_found_title": "Nie znaleziono zaproszenia",- "sign_in_and_accept": "Zaloguj się i zaakceptuj",- "sign_in_to_accept": ". Zaloguj się, aby zaakceptować."- },"jurisdiction": {"everywhere": "Wszędzie"},diff --git a/packages/dashboard/src/locales/zh-CN.json b/packages/dashboard/src/locales/zh-CN.jsonindex da34e8f455..b78a8b2488 100644--- a/packages/dashboard/src/locales/zh-CN.json+++ b/packages/dashboard/src/locales/zh-CN.json@@ -1570,14 +1570,6 @@"label": "数量"}},- "invitation_acceptance": {- "password": {- "label": "密码"- },- "password_confirmation": {- "label": "确认密码"- }- },"issued_at": {"label": "签发日期"},@@ -2709,25 +2701,6 @@"toggle_label": "开启或关闭 {{name}}","view_cta": "查看"},- "invitation": {- "accepting": "正在接受…",- "could_not_accept": "无法接受邀请",- "create_and_accept": "创建账户并接受",- "create_to_accept": "。创建账户以接受。",- "generic_error_message": "出现了一些问题。请重试。",- "generic_error_title": "无法加载邀请",- "invited_as_role": ",担任 {{role}}",- "invited_by": "{{email}} 邀请了你",- "invited_generic": "你已被邀请",- "join_store": "加入 {{store}}",- "loading": "正在加载邀请…",- "missing_token_message": "此链接似乎不完整。请让邀请你的人重新发送一次。",- "missing_token_title": "缺少邀请令牌",- "not_found_message": "此邀请已过期、被撤销或已被接受。请让邀请人发送一个新的邀请。",- "not_found_title": "未找到邀请",- "sign_in_and_accept": "登录并接受",- "sign_in_to_accept": "。登录以接受。"- },"jurisdiction": {"everywhere": "所有地区"},diff --git a/packages/dashboard/src/routes/accept-invitation.$invitationId.tsx b/packages/dashboard/src/routes/accept-invitation.$invitationId.tsxindex 70d2c24e0b..235aaceac3 100644--- a/packages/dashboard/src/routes/accept-invitation.$invitationId.tsx+++ b/packages/dashboard/src/routes/accept-invitation.$invitationId.tsx@@ -1,19 +1,7 @@-import { zodResolver } from '@hookform/resolvers/zod'-import type { Invitation, SpreeError } from '@spree/admin-sdk'-import { adminClient, mapSpreeErrorsToForm, useAuth } from '@spree/dashboard-core'-import { Button, Input, Label } from '@spree/dashboard-ui'-import { useQuery } from '@tanstack/react-query'-import { createFileRoute, Navigate, useNavigate } from '@tanstack/react-router'-import { useForm } from 'react-hook-form'-import { useTranslation } from 'react-i18next'+import { adminClient, InvitationAcceptance, usePermissions } from '@spree/dashboard-core'+import { createFileRoute, useNavigate } from '@tanstack/react-router'import { z } from 'zod/v4'import { AuthShell } from '../components/spree/auth-shell'-import {- type AcceptInvitationSignInFormValues,- type AcceptInvitationSignUpFormValues,- acceptInvitationSignInFormSchema,- acceptInvitationSignUpFormSchema,-} from '../schemas/auth'const acceptSearchSchema = z.object({token: z.string().min(1).optional(),@@ -25,273 +13,31 @@ export const Route = createFileRoute('/accept-invitation/$invitationId')({})function AcceptInvitationPage() {- const { t } = useTranslation()const { invitationId } = Route.useParams()const { token } = Route.useSearch()- const { isAuthenticated } = useAuth()-- if (isAuthenticated) return <Navigate to="/" replace />-- if (!token) {- return (- <AuthShell>- <ErrorCard- title={t('admin.invitation.missing_token_title')}- message={t('admin.invitation.missing_token_message')}- />- </AuthShell>- )- }+ const navigate = useNavigate()+ const { refresh: refreshPermissions } = usePermissions()return (<AuthShell>- <InvitationLoader invitationId={invitationId} token={token} />- </AuthShell>- )-}--function InvitationLoader({ invitationId, token }: { invitationId: string; token: string }) {- const { t } = useTranslation()- const lookup = useQuery({- queryKey: ['invitation-lookup', invitationId, token],- queryFn: () => adminClient.auth.lookupInvitation(invitationId, token),- retry: false,- })-- if (lookup.isPending) {- return (- <div className="py-12 text-center text-muted-foreground">{t('admin.invitation.loading')}</div>- )- }-- if (lookup.isError) {- const err = lookup.error as SpreeError- return (- <ErrorCard- title={- err.status === 404- ? t('admin.invitation.not_found_title')- : t('admin.invitation.generic_error_title')- }- message={- err.status === 404- ? t('admin.invitation.not_found_message')- : err.message || t('admin.invitation.generic_error_message')- }+ <InvitationAcceptance+ invitationId={invitationId}+ token={token}+ lookup={async (id, token) => {+ const invitation = await adminClient.auth.lookupInvitation(id, token)+ return { ...invitation, target: invitation.store }+ }}+ onAccepted={async (invitation) => {+ await navigate({+ to: '/$storeId',+ params: { storeId: invitation.target.id },+ replace: true,+ })+ // The session's permissions were loaded before it held a role here.+ // Refreshed once the store is entered, so they are fetched for it.+ await refreshPermissions()+ }}/>- )- }-- return <AcceptForm invitationId={invitationId} token={token} invitation={lookup.data} />-}--function AcceptForm({- invitationId,- token,- invitation,-}: {- invitationId: string- token: string- invitation: Invitation-}) {- return invitation.invitee_exists ? (- <SignInForm invitationId={invitationId} token={token} invitation={invitation} />- ) : (- <SignUpForm invitationId={invitationId} token={token} invitation={invitation} />- )-}--function SignInForm({- invitationId,- token,- invitation,-}: {- invitationId: string- token: string- invitation: Invitation-}) {- const { t } = useTranslation()- const { acceptInvitation, isLoading } = useAuth()- const navigate = useNavigate()-- const form = useForm<AcceptInvitationSignInFormValues>({- resolver: zodResolver(acceptInvitationSignInFormSchema),- defaultValues: { password: '' },- })- const { errors } = form.formState-- const onSubmit = async (data: AcceptInvitationSignInFormValues) => {- try {- await acceptInvitation(invitationId, token, { password: data.password })- navigate({ to: '/', replace: true })- } catch (err) {- const e = err as SpreeError- if (e?.status === 401) {- form.setError('root', { message: t('admin.validation.invalid_password') })- return- }- if (!mapSpreeErrorsToForm(err, form.setError)) {- form.setError('root', { message: e?.message || t('admin.invitation.could_not_accept') })- }- }- }-- const invitedPart = invitation.inviter_email- ? t('admin.invitation.invited_by', { email: invitation.inviter_email })- : t('admin.invitation.invited_generic')- const rolePart = invitation.role_name- ? t('admin.invitation.invited_as_role', { role: invitation.role_name })- : ''- const actionPart = t('admin.invitation.sign_in_to_accept')-- return (- <>- <div className="flex flex-col gap-2">- <h1 className="text-2xl font-bold">- {t('admin.invitation.join_store', { store: invitation.store.name })}- </h1>- <p className="text-sm text-muted-foreground">{`${invitedPart}${rolePart}${actionPart}`}</p>- </div>- <form onSubmit={form.handleSubmit(onSubmit)} className="grid gap-6">- {errors.root && <p className="text-sm text-destructive">{errors.root.message}</p>}- <div className="grid gap-2">- <Label htmlFor="invitee-email">{t('admin.fields.email.label')}</Label>- <Input id="invitee-email" value={invitation.email} disabled />- </div>- <div className="grid gap-2">- <Label htmlFor="password">{t('admin.fields.invitation_acceptance.password.label')}</Label>- <Input- id="password"- type="password"- autoFocus- aria-invalid={!!errors.password || undefined}- {...form.register('password')}- />- {errors.password && <p className="text-sm text-destructive">{errors.password.message}</p>}- </div>- <Button type="submit" className="w-full" disabled={isLoading}>- {isLoading ? t('admin.invitation.accepting') : t('admin.invitation.sign_in_and_accept')}- </Button>- </form>- </>- )-}--function SignUpForm({- invitationId,- token,- invitation,-}: {- invitationId: string- token: string- invitation: Invitation-}) {- const { t } = useTranslation()- const { acceptInvitation, isLoading } = useAuth()- const navigate = useNavigate()-- const form = useForm<AcceptInvitationSignUpFormValues>({- resolver: zodResolver(acceptInvitationSignUpFormSchema),- defaultValues: { first_name: '', last_name: '', password: '', password_confirmation: '' },- })- const { errors } = form.formState-- const onSubmit = async (data: AcceptInvitationSignUpFormValues) => {- try {- await acceptInvitation(invitationId, token, data)- navigate({ to: '/', replace: true })- } catch (err) {- if (!mapSpreeErrorsToForm(err, form.setError)) {- const e = err as SpreeError- form.setError('root', { message: e?.message || t('admin.invitation.could_not_accept') })- }- }- }-- const invitedPart = invitation.inviter_email- ? t('admin.invitation.invited_by', { email: invitation.inviter_email })- : t('admin.invitation.invited_generic')- const rolePart = invitation.role_name- ? t('admin.invitation.invited_as_role', { role: invitation.role_name })- : ''- const actionPart = t('admin.invitation.create_to_accept')-- return (- <>- <div className="flex flex-col gap-2">- <h1 className="text-2xl font-bold">- {t('admin.invitation.join_store', { store: invitation.store.name })}- </h1>- <p className="text-sm text-muted-foreground">{`${invitedPart}${rolePart}${actionPart}`}</p>- </div>- <form onSubmit={form.handleSubmit(onSubmit)} className="grid gap-6">- {errors.root && <p className="text-sm text-destructive">{errors.root.message}</p>}- <div className="grid gap-2">- <Label htmlFor="invitee-email">{t('admin.fields.email.label')}</Label>- <Input id="invitee-email" value={invitation.email} disabled />- </div>- <div className="grid grid-cols-2 gap-3">- <div className="grid gap-2">- <Label htmlFor="first_name">{t('admin.fields.first_name.label')}</Label>- <Input- id="first_name"- autoFocus- aria-invalid={!!errors.first_name || undefined}- {...form.register('first_name')}- />- {errors.first_name && (- <p className="text-sm text-destructive">{errors.first_name.message}</p>- )}- </div>- <div className="grid gap-2">- <Label htmlFor="last_name">{t('admin.fields.last_name.label')}</Label>- <Input- id="last_name"- aria-invalid={!!errors.last_name || undefined}- {...form.register('last_name')}- />- {errors.last_name && (- <p className="text-sm text-destructive">{errors.last_name.message}</p>- )}- </div>- </div>- <div className="grid gap-2">- <Label htmlFor="password">{t('admin.fields.invitation_acceptance.password.label')}</Label>- <Input- id="password"- type="password"- aria-invalid={!!errors.password || undefined}- {...form.register('password')}- />- {errors.password && <p className="text-sm text-destructive">{errors.password.message}</p>}- </div>- <div className="grid gap-2">- <Label htmlFor="password_confirmation">- {t('admin.fields.invitation_acceptance.password_confirmation.label')}- </Label>- <Input- id="password_confirmation"- type="password"- aria-invalid={!!errors.password_confirmation || undefined}- {...form.register('password_confirmation')}- />- {errors.password_confirmation && (- <p className="text-sm text-destructive">{errors.password_confirmation.message}</p>- )}- </div>- <Button type="submit" className="w-full" disabled={isLoading}>- {isLoading ? t('admin.invitation.accepting') : t('admin.invitation.create_and_accept')}- </Button>- </form>- </>- )-}--function ErrorCard({ title, message }: { title: string; message: string }) {- return (- <div className="flex flex-col gap-2">- <h1 className="text-2xl font-bold">{title}</h1>- <p className="text-sm text-muted-foreground">{message}</p>- </div>+ </AuthShell>)}diff --git a/packages/dashboard/src/schemas/auth.ts b/packages/dashboard/src/schemas/auth.tsindex e2018383e4..031e288f7d 100644--- a/packages/dashboard/src/schemas/auth.ts+++ b/packages/dashboard/src/schemas/auth.ts@@ -27,12 +27,6 @@ export const loginFormSchema = z.object({})export type LoginFormValues = z.infer<typeof loginFormSchema>-/** Existing invitee confirming with their current password. */-export const acceptInvitationSignInFormSchema = z.object({- password: z.string().min(1, { error: passwordRequired }),-})-export type AcceptInvitationSignInFormValues = z.infer<typeof acceptInvitationSignInFormSchema>-/** Forgot-password request — just the email; the server never reveals whether it matched. */export const forgotPasswordFormSchema = z.object({email: z.email(),@@ -51,20 +45,6 @@ export const resetPasswordFormSchema = z})export type ResetPasswordFormValues = z.infer<typeof resetPasswordFormSchema>-/** New invitee creating an account inline — mirrors the server's `AdminUser` validations. */-export const acceptInvitationSignUpFormSchema = z- .object({- first_name: z.string().min(1, { error: firstNameRequired }),- last_name: z.string().min(1, { error: lastNameRequired }),- password: z.string().min(8, { error: passwordMinLength }),- password_confirmation: z.string(),- })- .refine((data) => data.password === data.password_confirmation, {- error: passwordsDontMatch,- path: ['password_confirmation'],- })-export type AcceptInvitationSignUpFormValues = z.infer<typeof acceptInvitationSignUpFormSchema>-/** First-run setup — the first admin account plus the store's name. */export const setupFormSchema = z.object({diff --git a/packages/seller-dashboard/src/locales/ar.json b/packages/seller-dashboard/src/locales/ar.jsonindex 0907489c4e..3f7d21fdfb 100644--- a/packages/seller-dashboard/src/locales/ar.json+++ b/packages/seller-dashboard/src/locales/ar.json@@ -1,17 +1,4 @@{- "accept_invitation": {- "failed": "تعذَّر قبول هذه الدعوة. ربما انتهت صلاحيتها أو كانت كلمة المرور خاطئة.",- "first_name": "الاسم الأول",- "invalid_link": "هذا الرابط ينقصه الرمز. افتح الرابط من رسالة الدعوة.",- "last_name": "اسم العائلة",- "not_found": "لم تعد هذه الدعوة صالحة. اطلب ممن دعاك إرسال دعوة جديدة.",- "password": "كلمة المرور",- "password_confirmation": "تأكيد كلمة المرور",- "submit": "قبول الدعوة",- "submitting": "جارٍ القبول…",- "subtitle": "تمت دعوتك بالبريد {{email}}. عيّن كلمة مرور لإتمام التسجيل.",- "title": "انضم إلى الفريق"- },"account": {"avatar": "الصورة","avatar_help": "تظهر بجوار اسمك في جميع أنحاء اللوحة. الصور المربعة تبدو أفضل.",diff --git a/packages/seller-dashboard/src/locales/de.json b/packages/seller-dashboard/src/locales/de.jsonindex 9b79b6b4b9..82ea451125 100644--- a/packages/seller-dashboard/src/locales/de.json+++ b/packages/seller-dashboard/src/locales/de.json@@ -1,17 +1,4 @@{- "accept_invitation": {- "failed": "Diese Einladung konnte nicht angenommen werden. Möglicherweise ist sie abgelaufen oder das Passwort war falsch.",- "first_name": "Vorname",- "invalid_link": "Diesem Link fehlt sein Token. Öffnen Sie den Link aus Ihrer Einladungs-E-Mail.",- "last_name": "Nachname",- "not_found": "Diese Einladung ist nicht mehr gültig. Bitten Sie die Person, die Sie eingeladen hat, um eine neue.",- "password": "Passwort",- "password_confirmation": "Passwort bestätigen",- "submit": "Einladung annehmen",- "submitting": "Wird angenommen…",- "subtitle": "Sie wurden als {{email}} eingeladen. Legen Sie ein Passwort fest, um abzuschließen.",- "title": "Team beitreten"- },"account": {"avatar": "Foto","avatar_help": "Wird im gesamten Panel neben Ihrem Namen angezeigt. Quadratische Bilder sehen am besten aus.",diff --git a/packages/seller-dashboard/src/locales/en.json b/packages/seller-dashboard/src/locales/en.jsonindex 6b6c392797..6cb261de1b 100644--- a/packages/seller-dashboard/src/locales/en.json+++ b/packages/seller-dashboard/src/locales/en.json@@ -1,17 +1,4 @@{- "accept_invitation": {- "failed": "That invitation could not be accepted. It may have expired, or the password was wrong.",- "first_name": "First name",- "invalid_link": "This link is missing its token. Open the link from your invitation email.",- "last_name": "Last name",- "not_found": "This invitation is no longer valid. Ask whoever invited you to send a new one.",- "password": "Password",- "password_confirmation": "Confirm password",- "submit": "Accept invitation",- "submitting": "Accepting…",- "subtitle": "You were invited as {{email}}. Set a password to finish.",- "title": "Join the team"- },"account": {"avatar": "Photo","avatar_help": "Shown next to your name across the panel. Square images look best.",diff --git a/packages/seller-dashboard/src/locales/fr.json b/packages/seller-dashboard/src/locales/fr.jsonindex ac781fd851..939bb8b15c 100644--- a/packages/seller-dashboard/src/locales/fr.json+++ b/packages/seller-dashboard/src/locales/fr.json@@ -1,17 +1,4 @@{- "accept_invitation": {- "failed": "Cette invitation n’a pas pu être acceptée. Elle a peut-être expiré, ou le mot de passe était incorrect.",- "first_name": "Prénom",- "invalid_link": "Il manque le jeton dans ce lien. Ouvrez le lien depuis votre e-mail d’invitation.",- "last_name": "Nom",- "not_found": "Cette invitation n’est plus valable. Demandez à la personne qui vous a invité de vous en envoyer une nouvelle.",- "password": "Mot de passe",- "password_confirmation": "Confirmer le mot de passe",- "submit": "Accepter l’invitation",- "submitting": "Acceptation…",- "subtitle": "Vous avez été invité en tant que {{email}}. Choisissez un mot de passe pour terminer.",- "title": "Rejoindre l’équipe"- },"account": {"avatar": "Photo","avatar_help": "Affichée à côté de votre nom dans tout le panneau. Les images carrées sont recommandées.",diff --git a/packages/seller-dashboard/src/locales/ja.json b/packages/seller-dashboard/src/locales/ja.jsonindex 52a231d7a6..f208345f6e 100644--- a/packages/seller-dashboard/src/locales/ja.json+++ b/packages/seller-dashboard/src/locales/ja.json@@ -1,17 +1,4 @@{- "accept_invitation": {- "failed": "招待を承諾できませんでした。期限が切れているか、パスワードが正しくない可能性があります。",- "first_name": "名",- "invalid_link": "このリンクにはトークンがありません。招待メールのリンクから開いてください。",- "last_name": "姓",- "not_found": "この招待はもう有効ではありません。招待した人に新しい招待を送ってもらってください。",- "password": "パスワード",- "password_confirmation": "パスワード(確認)",- "submit": "招待を承諾",- "submitting": "承諾中…",- "subtitle": "{{email}} として招待されました。パスワードを設定して完了してください。",- "title": "チームに参加"- },"account": {"avatar": "写真","avatar_help": "パネル内であなたの名前の横に表示されます。正方形の画像がきれいに表示されます。",diff --git a/packages/seller-dashboard/src/locales/pl.json b/packages/seller-dashboard/src/locales/pl.jsonindex a80f1f2973..dae31ba68a 100644--- a/packages/seller-dashboard/src/locales/pl.json+++ b/packages/seller-dashboard/src/locales/pl.json@@ -1,17 +1,4 @@{- "accept_invitation": {- "failed": "Nie udało się przyjąć tego zaproszenia. Mogło wygasnąć lub hasło było nieprawidłowe.",- "first_name": "Imię",- "invalid_link": "W tym linku brakuje tokenu. Otwórz link z wiadomości z zaproszeniem.",- "last_name": "Nazwisko",- "not_found": "To zaproszenie jest już nieważne. Poproś osobę, która Cię zaprosiła, o nowe.",- "password": "Hasło",- "password_confirmation": "Potwierdź hasło",- "submit": "Przyjmij zaproszenie",- "submitting": "Przyjmowanie…",- "subtitle": "Zaproszenie otrzymał adres {{email}}. Ustaw hasło, aby zakończyć.",- "title": "Dołącz do zespołu"- },"account": {"avatar": "Zdjęcie","avatar_help": "Wyświetlane obok Twojego imienia w całym panelu. Najlepiej wyglądają zdjęcia kwadratowe.",diff --git a/packages/seller-dashboard/src/locales/zh-CN.json b/packages/seller-dashboard/src/locales/zh-CN.jsonindex 9bdc353cff..b384203d59 100644--- a/packages/seller-dashboard/src/locales/zh-CN.json+++ b/packages/seller-dashboard/src/locales/zh-CN.json@@ -1,17 +1,4 @@{- "accept_invitation": {- "failed": "无法接受该邀请。邀请可能已过期,或密码有误。",- "first_name": "名字",- "invalid_link": "此链接缺少令牌。请从邀请邮件中打开链接。",- "last_name": "姓氏",- "not_found": "此邀请已失效。请让邀请你的人重新发送一份。",- "password": "密码",- "password_confirmation": "确认密码",- "submit": "接受邀请",- "submitting": "正在接受…",- "subtitle": "你以 {{email}} 的身份受邀。设置密码即可完成。",- "title": "加入团队"- },"account": {"avatar": "照片","avatar_help": "在面板中显示在您的姓名旁边。方形图片效果最佳。",diff --git a/packages/seller-dashboard/src/pages/accept-invitation.tsx b/packages/seller-dashboard/src/pages/accept-invitation.tsxindex 8186d32596..df125cc8e4 100644--- a/packages/seller-dashboard/src/pages/accept-invitation.tsx+++ b/packages/seller-dashboard/src/pages/accept-invitation.tsx@@ -1,26 +1,14 @@-import { useAuth } from '@spree/dashboard-core'-import { Button, Field, FieldError, FieldGroup, FieldLabel, Input } from '@spree/dashboard-ui'-import { useQuery } from '@tanstack/react-query'+import { InvitationAcceptance } from '@spree/dashboard-core'import { useNavigate } from '@tanstack/react-router'-import { useState } from 'react'-import { useForm } from 'react-hook-form'-import { useTranslation } from 'react-i18next'import { sellerClient } from '../api-client'-import { CenteredMessage } from '../components/centered-message'--interface AcceptValues {- password: string- password_confirmation: string- first_name: string- last_name: string-}/*** Joining a seller's team from the emailed link.*- * The invitation id and token in the URL are the whole credential — nobody is- * signed in yet. Accepting returns a seller session, so the new member lands- * in the panel rather than being bounced to a login form.+ * The screens are the framework's, shared with the operator's dashboard; what+ * is the panel's own is which API answers the lookup and where an accepted+ * member lands. That is the seller they joined: the layout under that route+ * loads the member's permissions for it.*/export function AcceptInvitationPage({invitationId,@@ -29,98 +17,31 @@ export function AcceptInvitationPage({invitationId: stringtoken?: string}) {- const { t } = useTranslation()- const { acceptInvitation } = useAuth()const navigate = useNavigate()- const [error, setError] = useState<string | null>(null)-- const {- data: invitation,- isLoading,- error: lookupError,- } = useQuery({- queryKey: ['seller', 'invitation', invitationId],- queryFn: () => sellerClient().auth.lookupInvitation(invitationId, token ?? ''),- enabled: Boolean(token),- retry: false,- })-- const form = useForm<AcceptValues>({- defaultValues: { password: '', password_confirmation: '', first_name: '', last_name: '' },- })-- if (!token) return <CenteredMessage>{t('accept_invitation.invalid_link')}</CenteredMessage>- if (isLoading) return <CenteredMessage>{t('common.loading')}</CenteredMessage>- if (lookupError || !invitation) {- return <CenteredMessage>{t('accept_invitation.not_found')}</CenteredMessage>- }-- async function onSubmit(values: AcceptValues) {- setError(null)- try {- await acceptInvitation(invitationId, token ?? '', values)- // The index route decides where to go from there — it already knows how- // to skip the picker for someone who runs exactly one seller. Without- // this the form simply sits there after a successful accept, and the- // obvious next move is to submit again, against an invitation that has- // now been consumed.- navigate({ to: '/', replace: true })- } catch {- setError(t('accept_invitation.failed'))- }- }-- const { errors, isSubmitting } = form.formStatereturn (<div className="flex min-h-screen items-center justify-center p-6">- <div className="w-full max-w-sm">- <h1 className="font-medium text-xl">{t('accept_invitation.title')}</h1>- <p className="mt-1 mb-6 text-muted-foreground text-sm">- {t('accept_invitation.subtitle', { email: invitation.email })}- </p>-- <form onSubmit={form.handleSubmit(onSubmit)}>- <FieldGroup>- <Field>- <FieldLabel htmlFor="first_name">{t('accept_invitation.first_name')}</FieldLabel>- <Input id="first_name" {...form.register('first_name')} />- </Field>-- <Field>- <FieldLabel htmlFor="last_name">{t('accept_invitation.last_name')}</FieldLabel>- <Input id="last_name" {...form.register('last_name')} />- </Field>-- <Field>- <FieldLabel htmlFor="password">{t('accept_invitation.password')}</FieldLabel>- <Input- id="password"- type="password"- aria-invalid={!!errors.password || undefined}- {...form.register('password', { required: true })}- />- <FieldError errors={[errors.password]} />- </Field>-- <Field>- <FieldLabel htmlFor="password_confirmation">- {t('accept_invitation.password_confirmation')}- </FieldLabel>- <Input- id="password_confirmation"- type="password"- {...form.register('password_confirmation')}- />- </Field>-- {error && <p className="text-destructive text-sm">{error}</p>}-- <Button type="submit" disabled={isSubmitting}>- {isSubmitting ? t('accept_invitation.submitting') : t('accept_invitation.submit')}- </Button>- </FieldGroup>- </form>+ <div className="flex w-full max-w-sm flex-col gap-6">+ <InvitationAcceptance+ invitationId={invitationId}+ token={token}+ lookup={async (id, token) => {+ const invitation = await sellerClient().auth.lookupInvitation(id, token)+ // Carried by the lookup alone; the team listings leave it out.+ return {+ ...invitation,+ invitee_exists: invitation.invitee_exists ?? false,+ target: invitation.seller,+ }+ }}+ onAccepted={(invitation) =>+ navigate({+ to: '/$sellerId',+ params: { sellerId: invitation.target.id },+ replace: true,+ })+ }+ /></div></div>)diff --git a/packages/seller-sdk/src/types/generated/Invitation.ts b/packages/seller-sdk/src/types/generated/Invitation.tsindex dbb56a4f52..00c6d11bdc 100644--- a/packages/seller-sdk/src/types/generated/Invitation.ts+++ b/packages/seller-sdk/src/types/generated/Invitation.ts@@ -1,4 +1,4 @@-// Typelizer digest d19765a6d7e7e17a401825da307ac6db+// Typelizer digest 319090087edde10a92755c600387bd94//// DO NOT MODIFY: This file was automatically generated by Typelizer.import type {InvitationStatus} from '@/types'@@ -10,6 +10,9 @@ type Invitation = {expires_at: string | null;accepted_at: string | null;status: InvitationStatus;+ inviter_email: string;+ invitee_exists?: boolean;+ seller: { id: string; name: string };}export default Invitation;diff --git a/packages/seller-sdk/src/types/params/InvitationAcceptParams.ts b/packages/seller-sdk/src/types/params/InvitationAcceptParams.tsindex 973c397dc8..e113189b60 100644--- a/packages/seller-sdk/src/types/params/InvitationAcceptParams.ts+++ b/packages/seller-sdk/src/types/params/InvitationAcceptParams.ts@@ -1,7 +1,10 @@// This file is auto-generated from the request schemas in docs/api-reference by `pnpm generate:params`. Do not edit directly.export type InvitationAcceptParams = {- /** Sets the password of a new account, or confirms the password of an existing one. */+ /**+ * Sets the password of a new account, or confirms the password of an existing one, unless the+ * request is already signed in as that account.+ */password?: stringpassword_confirmation?: string/** Used only when the invitation creates a new account. */diff --git a/packages/seller-sdk/src/zod/generated/Invitation.ts b/packages/seller-sdk/src/zod/generated/Invitation.tsindex e1650a2246..ee704cd948 100644--- a/packages/seller-sdk/src/zod/generated/Invitation.ts+++ b/packages/seller-sdk/src/zod/generated/Invitation.ts@@ -8,6 +8,9 @@ export const InvitationSchema = z.object({expires_at: z.string().nullable(),accepted_at: z.string().nullable(),status: z.string(),+ inviter_email: z.string(),+ invitee_exists: z.boolean().optional(),+ seller: z.object({ id: z.string(), name: z.string() }),});export type Invitation = z.infer<typeof InvitationSchema>;diff --git a/spree/api/app/controllers/spree/api/v3/admin/invitation_acceptances_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/invitation_acceptances_controller.rbindex 120c82d1ae..66924a8071 100644--- a/spree/api/app/controllers/spree/api/v3/admin/invitation_acceptances_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/admin/invitation_acceptances_controller.rb@@ -12,7 +12,7 @@ module Spreerequest_params 'InvitationAcceptParams', action: :accept do |body|body.attribute :password, :string,- description: 'Required when the invitee has no account yet: it creates one. An existing account signs in without it.'+ description: 'Creates the account when the invitee has none yet. An existing account confirms it is theirs with it, unless the request is already signed in as that account.'body.attribute :password_confirmation, :stringbody.attribute :first_name, :stringbody.attribute :last_name, :string@@ -74,10 +74,14 @@ module Spree# implicit: we look the user up by `invitation.email`, never by a# client-supplied email. The token is the credential.def resolve_or_create_invitee(invitation)- existing = Spree.admin_user_class.find_by(email: invitation.email)- return authenticate_existing(existing) if existing+ existing = invitation.invitee_account+ return create_new_invitee(invitation) unless existing- create_new_invitee(invitation)+ # Someone already signed in as the invitee has proven who they are.+ authenticate_user+ return existing if current_user == existing++ authenticate_existing(existing)enddef authenticate_existing(user)diff --git a/spree/api/app/controllers/spree/api/v3/seller/invitation_acceptances_controller.rb b/spree/api/app/controllers/spree/api/v3/seller/invitation_acceptances_controller.rbindex 3af5d8b2c1..f369b320b9 100644--- a/spree/api/app/controllers/spree/api/v3/seller/invitation_acceptances_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/seller/invitation_acceptances_controller.rb@@ -24,7 +24,7 @@ module Spreerequest_params 'InvitationAcceptParams', action: :accept do |body|body.attribute :password, :string,- description: 'Sets the password of a new account, or confirms the password of an existing one.'+ description: 'Sets the password of a new account, or confirms the password of an existing one, unless the request is already signed in as that account.'body.attribute :password_confirmation, :stringbody.attribute :first_name, :string, description: 'Used only when the invitation creates a new account.'body.attribute :last_name, :string, description: 'Used only when the invitation creates a new account.'@@ -35,7 +35,7 @@ module Spreereturn unless load_invitationrender json: Spree.api.seller_invitation_serializer.new(- @invitation, params: { store: @invitation.store }+ @invitation, params: { store: @invitation.store, acceptance: true }).serializable_hashend@@ -97,10 +97,14 @@ module Spree# implicit: we look the user up by `invitation.email`, never by a# client-supplied email. The token is the credential.def resolve_or_create_invitee(invitation)- existing = Spree.admin_user_class.find_by(email: invitation.email)- return authenticate_existing(existing) if existing+ existing = invitation.invitee_account+ return create_new_invitee(invitation) unless existing- create_new_invitee(invitation)+ # Someone already signed in as the invitee has proven who they are.+ authenticate_user+ return existing if current_user == existing++ authenticate_existing(existing)enddef authenticate_existing(user)@@ -151,6 +155,12 @@ module Spreeuser.sellers.map { |seller| { id: seller.prefixed_id, name: seller.name, status: seller.status } }end+ # The plain v3 base expects a storefront token; the session this+ # page may carry is a seller panel one.+ def expected_audience+ Spree::Api::V3::JwtAuthentication::JWT_AUDIENCE_SELLER+ end+def request_env_for_token{ ip_address: request.remote_ip, user_agent: request.user_agent&.truncate(255) }enddiff --git a/spree/api/app/serializers/spree/api/v3/admin/invitation_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/invitation_serializer.rbindex 2a3a999c0a..e4aa1ea8fd 100644--- a/spree/api/app/serializers/spree/api/v3/admin/invitation_serializer.rb+++ b/spree/api/app/serializers/spree/api/v3/admin/invitation_serializer.rb@@ -37,7 +37,7 @@ module Spree# Looked up by email so an admin who's already on another store sees# the password prompt, not a fresh account form.attribute :invitee_exists do |invitation|- Spree.admin_user_class.exists?(email: invitation.email)+ invitation.invitee_account.present?end# Minimal store identity for the unauthenticated acceptance page'sdiff --git a/spree/api/app/serializers/spree/api/v3/seller/invitation_serializer.rb b/spree/api/app/serializers/spree/api/v3/seller/invitation_serializer.rbindex e01360dc83..51b85e6b26 100644--- a/spree/api/app/serializers/spree/api/v3/seller/invitation_serializer.rb+++ b/spree/api/app/serializers/spree/api/v3/seller/invitation_serializer.rb@@ -5,12 +5,33 @@ module Spreeclass InvitationSerializer < V3::BaseSerializertypelize email: :string, status: [:string, enum: Spree::Invitation.statuses, enum_type_name: 'InvitationStatus'],expires_at: [:string, nullable: true],- accepted_at: [:string, nullable: true]+ accepted_at: [:string, nullable: true],+ inviter_email: :string,+ invitee_exists: [:boolean, optional: true],+ seller: '{ id: string; name: string }'attributes :email,created_at: :iso8601, expires_at: :iso8601, accepted_at: :iso8601attributes status: :string++ attribute :inviter_email do |invitation|+ invitation.inviter.email+ end++ # Drives the acceptance page's sign-in vs sign-up branch, so only the+ # public lookup carries it: whoever holds the emailed link already+ # knows the address. A seller's team screen does not get to learn+ # which addresses hold accounts elsewhere on the marketplace.+ attribute :invitee_exists, if: proc { params[:acceptance] } do |invitation|+ invitation.invitee_account.present?+ end++ # The smallest shape the acceptance page's title ("Join <seller>")+ # needs; the page is public, so nothing more of the seller goes out.+ attribute :seller do |invitation|+ { id: invitation.resource.prefixed_id, name: invitation.resource.name }+ endendendenddiff --git a/spree/api/spec/integration/spree/api/v3/admin/invitations_spec.rb b/spree/api/spec/integration/spree/api/v3/admin/invitations_spec.rbindex 4f92824a71..b13b904f9d 100644--- a/spree/api/spec/integration/spree/api/v3/admin/invitations_spec.rb+++ b/spree/api/spec/integration/spree/api/v3/admin/invitations_spec.rb@@ -162,7 +162,9 @@ RSpec.describe 'Admin Invitations API', type: :request, swagger_doc: 'api-refere`password` is required when no account exists for the invited address,in which case it sets one. When an account already exists, the same- field is how the person proves the account is theirs.+ field is how the person proves the account is theirs — unless the+ request carries that account's own access token, which proves it+ already.DESCadmin_sdk_example 'auth/accept-invitation'diff --git a/spree/api/spec/integration/spree/api/v3/seller/invitation_acceptances_spec.rb b/spree/api/spec/integration/spree/api/v3/seller/invitation_acceptances_spec.rbindex 20d60b5a16..f87a134d7e 100644--- a/spree/api/spec/integration/spree/api/v3/seller/invitation_acceptances_spec.rb+++ b/spree/api/spec/integration/spree/api/v3/seller/invitation_acceptances_spec.rb@@ -73,7 +73,8 @@ RSpec.describe 'Seller Invitation Acceptance API', type: :request, swagger_doc:`password` is required when no account exists for the invited address, inwhich case it sets one. When an account already exists, the same field is- how the person proves the account is theirs.+ how the person proves the account is theirs — unless the request carries+ that account's own access token, which proves it already.DESCseller_sdk_example 'auth/accept-invitation', as: :guestdiff --git a/spree/api/spec/requests/spree/api/v3/admin/invitation_acceptances_spec.rb b/spree/api/spec/requests/spree/api/v3/admin/invitation_acceptances_spec.rbnew file mode 100644index 0000000000..42ee3c2687--- /dev/null+++ b/spree/api/spec/requests/spree/api/v3/admin/invitation_acceptances_spec.rb@@ -0,0 +1,61 @@+require 'spec_helper'++RSpec.describe 'Accepting a staff invitation on the Admin API', type: :request do+ include_context 'API v3 Admin'++ let(:password) { 'password123' }+ # Staff of another store, invited to this one.+ let(:invitee) { create(:admin_user, :without_admin_role, password: password, password_confirmation: password) }+ let!(:invitation) { create(:invitation, resource: store, email: invitee.email) }++ def accept(params = {}, headers: {})+ post "/api/v3/admin/auth/invitations/#{invitation.prefixed_id}/accept",+ params: { token: invitation.token }.merge(params), headers: headers+ end++ def bearer(user)+ { 'Authorization' => "Bearer #{Spree::Api::V3::TestingSupport.generate_jwt(user, audience: Spree::Api::V3::JwtAuthentication::JWT_AUDIENCE_ADMIN)}" }+ end++ it 'accepts without a password when signed in as the invitee' do+ expect { accept(headers: bearer(invitee)) }.to change(Spree::RoleUser, :count).by(1)++ expect(response).to have_http_status(:ok)+ expect(JSON.parse(response.body)['user']['email']).to eq(invitee.email)+ expect(invitation.reload.status).to eq('accepted')+ end++ it 'matches the signed-in account to the invited address regardless of case' do+ invitation.update_column(:email, invitee.email.upcase)++ accept(headers: bearer(invitee))++ expect(response).to have_http_status(:ok)+ expect(invitation.reload.status).to eq('accepted')+ end++ it 'still asks for the password when signed in as another account' do+ other_account = bearer(create(:admin_user))++ expect { accept(headers: other_account) }.not_to change(Spree::RoleUser, :count)++ expect(response).to have_http_status(:unauthorized)+ expect(Spree::Invitation.pending.exists?(invitation.id)).to be(true)+ end++ it 'finds the account for a differently cased address on the password path too' do+ invitation.update_column(:email, invitee.email.upcase)++ expect { accept({ password: password }) }.to change(Spree::RoleUser, :count).by(1)++ expect(response).to have_http_status(:ok)+ expect(JSON.parse(response.body)['user']['email']).to eq(invitee.email)+ end++ it 'accepts a signed-out invitee who gives the password' do+ accept({ password: password })++ expect(response).to have_http_status(:ok)+ expect(invitation.reload.status).to eq('accepted')+ end+enddiff --git a/spree/api/spec/requests/spree/api/v3/seller/invitation_acceptances_spec.rb b/spree/api/spec/requests/spree/api/v3/seller/invitation_acceptances_spec.rbnew file mode 100644index 0000000000..b4c2872f4d--- /dev/null+++ b/spree/api/spec/requests/spree/api/v3/seller/invitation_acceptances_spec.rb@@ -0,0 +1,89 @@+require 'spec_helper'++RSpec.describe 'Accepting a seller invitation on the Seller API', type: :request do+ include_context 'API v3 Seller'++ let(:password) { 'password123' }+ # Staff of another seller, invited to this one.+ let(:invitee) { create(:admin_user, :without_admin_role, password: password, password_confirmation: password) }+ let!(:invitation) do+ create(:invitation, resource: seller, inviter: seller_user, email: invitee.email, role: seller.default_user_role)+ end++ def accept(params = {}, headers: {})+ post "/api/v3/seller/auth/invitations/#{invitation.prefixed_id}/accept",+ params: { token: invitation.token }.merge(params), headers: headers+ end++ def bearer(user)+ token = Spree::Api::V3::TestingSupport.generate_jwt(+ user, audience: Spree::Api::V3::JwtAuthentication::JWT_AUDIENCE_SELLER+ )+ { 'Authorization' => "Bearer #{token}" }+ end++ it 'accepts without a password when signed in as the invitee' do+ expect { accept(headers: bearer(invitee)) }.to change(Spree::RoleUser, :count).by(1)++ expect(response).to have_http_status(:ok)+ expect(JSON.parse(response.body)['user']['email']).to eq(invitee.email)+ expect(invitation.reload.status).to eq('accepted')+ end++ it 'matches the signed-in account to the invited address regardless of case' do+ invitation.update_column(:email, invitee.email.upcase)++ accept(headers: bearer(invitee))++ expect(response).to have_http_status(:ok)+ expect(invitation.reload.status).to eq('accepted')+ end++ it 'still asks for the password when signed in as another account' do+ other_account = bearer(seller_user)++ expect { accept(headers: other_account) }.not_to change(Spree::RoleUser, :count)++ expect(response).to have_http_status(:unauthorized)+ expect(Spree::Invitation.pending.exists?(invitation.id)).to be(true)+ end++ it 'ignores an admin panel token, which was not issued for this API' do+ token = Spree::Api::V3::TestingSupport.generate_jwt(+ invitee, audience: Spree::Api::V3::JwtAuthentication::JWT_AUDIENCE_ADMIN+ )++ accept(headers: { 'Authorization' => "Bearer #{token}" })++ expect(response).to have_http_status(:unauthorized)+ end++ it 'finds the account for a differently cased address on the password path too' do+ invitation.update_column(:email, invitee.email.upcase)++ expect { accept({ password: password }) }.to change(Spree::RoleUser, :count).by(1)++ expect(response).to have_http_status(:ok)+ end++ it 'reports whether the invitee already has an account' do+ get "/api/v3/seller/auth/invitations/#{invitation.prefixed_id}/lookup", params: { token: invitation.token }++ body = JSON.parse(response.body)+ expect(body['invitee_exists']).to be(true)+ expect(body['seller']).to eq('id' => seller.prefixed_id, 'name' => seller.name)+ end++ # Whether an address holds an account anywhere on the marketplace is for the+ # link's holder, who already knows the address — not for a seller's team.+ it 'leaves that out of the team listing' do+ seller_role.update!(permissions: %w[read_seller_profile])++ get '/api/v3/seller/invitations', headers: seller_headers++ expect(response).to have_http_status(:ok)+ listed = JSON.parse(response.body)['data'].find { |row| row['id'] == invitation.prefixed_id }+ expect(listed).to be_present+ expect(listed).not_to have_key('invitee_exists')+ end+enddiff --git a/spree/core/app/models/spree/invitation.rb b/spree/core/app/models/spree/invitation.rbindex b60ec30903..38ff4c71ce 100644--- a/spree/core/app/models/spree/invitation.rb+++ b/spree/core/app/models/spree/invitation.rb@@ -116,6 +116,15 @@ module Spreepublish_event('invitation.resent')end+ # The staff account holding the invited address, if one exists. Matched+ # the way the account's email uniqueness is, case-insensitively, so an+ # address typed in another case still finds the one account it can belong+ # to. Resolved by record rather than by comparing strings in Ruby, whose+ # case folding is wider than the database's.+ def invitee_account+ Spree.admin_user_class.where('LOWER(email) = LOWER(?)', email).first+ end+privatedef publish_invitation_created_event@@ -161,7 +170,7 @@ module Spreereturn if resource.blank?# Check role_users directly for better performance and to avoid potential source_type issues- user_to_check = invitee || Spree.admin_user_class.find_by(email: email)+ user_to_check = invitee || invitee_accountreturn if user_to_check.blank?if resource.role_users.exists?(user: user_to_check)@@ -172,7 +181,7 @@ module Spreedef set_invitee_from_emailreturn if invitee.present?- self.invitee = Spree.admin_user_class.find_by(email: email)+ self.invitee = invitee_accountendendenddiff --git a/spree/core/spec/models/spree/invitation_spec.rb b/spree/core/spec/models/spree/invitation_spec.rbindex 54355764ce..a3e9160395 100644--- a/spree/core/spec/models/spree/invitation_spec.rb+++ b/spree/core/spec/models/spree/invitation_spec.rb@@ -136,4 +136,18 @@ RSpec.describe Spree::Invitation, type: :model doexpect(invitation.acceptance_url).to include("/accept-invitation/#{invitation.prefixed_id}?token=#{invitation.token}")endend++ describe '#invitee_account' do+ let!(:account) { create(:admin_user, email: '[email protected]') }++ it 'finds the account for a differently cased address' do+ invitation = build(:invitation, email: '[email protected]')++ expect(invitation.invitee_account).to eq(account)+ end++ it 'is nil when no account holds the address' do+ expect(build(:invitation, email: '[email protected]').invitee_account).to be_nil+ end+ endend