Skip to content

armgit / spree

Public Imported from GitHub
0

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.

Build the seller team screen from the operator's staff page

Damian Legawiec46fc0cef4d67
diff --git a/docs/plans/6.0-multi-vendor-marketplace.md b/docs/plans/6.0-multi-vendor-marketplace.md
index 1719ff5470..5969e4b20f 100644
--- a/docs/plans/6.0-multi-vendor-marketplace.md
+++ b/docs/plans/6.0-multi-vendor-marketplace.md
@@ -737,6 +737,7 @@ Even before this lands, work touching adjacent areas should:
- **The shared catalog ships as variant attributes plus one selection service** (RESOLVED 2026-08-16, shipped — Decision 11's Phase 1b). `spree_variants.seller_id` and `spree_variants.delivery_profile_id`, both nullable, and **two modes that never mix**: on an *owned* product (`products.seller_id` set) every variant is that seller's and ships as the product does — no other seller can create a variant there, so the variant's own columns carry no meaning and are kept blank by a normalizer; on a *master* product (`products.seller_id` nil, the shared catalog) each seller's row names its own seller and how it ships, falling back to the master's profile. The resolved answer is a plain read on the model (`resolved_seller`, `resolved_delivery_profile` — product's if owned, else the row's; no memo, no inheritance chain), and the API carries **one field each** (`seller_id`, `delivery_profile_id`), read resolved and written to the column, so a storefront never learns which mode it is in and a read-then-write round trip on an owned product changes nothing (the write is a no-op there). This deliberately departs from `Variant#tax_category`'s override-the-reader shape, and supersedes an earlier cut that modelled the seller as an inheritance-with-override and grew a second `own_*` name on the API to keep the round-trip safe — the domain has no override to model, so it needed neither. `Variant#digital?` moved onto the variant's own profile with it, which is what lets a download and its printed edition sit on one product. Condition is an `OptionType` shipped as **sample data, not a seed** (`db/sample_data/options.rb`, beside color; values new/refurbished/used): nothing in core keys on the word — the buy box groups by whatever option values it is given — so it is a merchant's choice, not an install prerequisite, and a store that sells only new goods never finds it on a fresh install, so it splits a product the way any axis does and the buy box keys on the option combination — a new buy box and a used one, at no extra cost. **The buy box is `Spree::Products::SelectBuyBox`** behind `Spree.product_buy_box_service`: computed on every read and never stored (it turns on price, stock and who is selling today, none of which hold still), ranking first-party ahead of sellers then cheapest, refusing to feature a seller who is suspended, onboarding or away, and still naming a variant when nothing is buyable so the page has a price to render. `purchasable?`/`in_stock?`/`backorderable?` now answer through the winner rather than `variants.any?` — a product is not purchasable because a suspended seller happens to hold stock — and `default_variant` prefers a first-party listing, since the headline price, SKU and the Omnibus `prior_price` are compliance claims about the operator's own pricing. **SKU uniqueness is scoped to the resolved seller** via a hand-written validation rather than a `scope:` option, because Rails' uniqueness validator reads the raw column and would have merged two sellers who each own a whole product into the nil scope. Cross-store binding is refused on the model (`seller`/`delivery_profile` must belong to the product's store), matching the pair already on Product. **Three pre-existing faults were fixed with it, each with a regression spec proven against the old code:** `Product#variants=`'s full-replacement delete was left as-is on the operator's path — the operator writes every seller's variants on a master — and the guard against a seller wiping a rival's rows lives at the seller branch, not the model (see "Writes never destroy another seller's variants" above), `Stock::Splitter::DeliveryProfile` and `Stock::Coordinator` re-keyed their memoisation off `product_id`, and `with_option_value_ids` now requires **one variant** to satisfy every axis (a `HAVING COUNT(DISTINCT option_type_id)` over one grouped subquery) instead of asking the product about each axis separately — "Blue AND XL" had matched a product selling a blue small beside a red XL, a live storefront bug independent of marketplaces. **Both search providers were fixed together**, since a filter's meaning is part of the provider contract and fixing one would have made results change when an operator installs the search gem: the Meilisearch document is per product, so its option values are a union across variants that cannot answer a per-variant question — the presenter now also emits `option_value_combination_ids` (one token per *combination* of values seen on the same variant) and a multi-axis filter asks for a whole combination, with single-axis filters and the disjunctive-facet queries unchanged. Whole combinations rather than pairs, because every pair holding on *some* variant is not the same as one variant holding them all — three variants (blue, XL, used), (blue, S, new) and (red, XL, new) satisfy each pair of "blue AND XL AND new" while none carries all three. Token count is exponential in the axis count, so it is capped (`MAX_COMBINATION_AXES`) and filters naming more axes fall back to the pairwise approximation. **The upgrade needs a reindex** — existing documents lack the field, so a multi-axis filter matches nothing until then; `search_reindex` is in the 5.6→6.0 manifest for exactly this and is a no-op on the database provider.
- **Seller lifecycle → four workflows, never a writable `status`** (RESOLVED 2026-08-16, shipped). `Spree::Sellers::Invite` / `Approve` / `Suspend` / `Reject` (seams `seller_invite_workflow` and siblings), each with `validate` + `after_*` hooks and its own `seller.*` event. The Admin API exposes them as member actions (`POST invite`, `PATCH approve|suspend|reject`) and deliberately omits `status` from `permitted_params` — a PATCH that moved a seller would skip the mail, the payout provisioning and the extension hooks, which is exactly what `6.0-service-workflows.md` keeps out of a column write. Guards admit more than the linear path: `Approve` also lifts a suspension (clearing holiday mode with it) and revives a rejected applicant; `Suspend` is for a seller already on the marketplace while `Reject` is for one that never traded, so rejecting an approved seller is refused. Suspension and rejection reasons live in `metadata` rather than columns — each is a note about one event, and the next one has its own. Creation stays plain CRUD (it is not a lifecycle transition), so the default status is applied in an `after_initialize` on the model, as on `Spree::Fulfillment`.
- **Lifecycle emails are seller-facing, event-driven, and skip the invitation** (RESOLVED 2026-08-16, shipped). `Spree::SellerMailer` (approved/suspended/rejected) in `spree_emails`, fired by `Spree::SellerEmailSubscriber` off the `seller.*` events the workflows already publish — nothing mails from a workflow step, so mail is one listener among several rather than something a transition waits on. Three departures from the legacy module: **no `seller.invited` email** (inviting creates an `Invitation`, which already mails the invitee — a second message would be the same news to the same address), **no marketplace-staff copies** (the legacy module mailed every store admin on approval and onboarding; staff read status in the dashboard, and per-admin fan-out across many sellers is the kind of noise merchants switch off — staff notifications ride the event/webhook surface), and **suspension/rejection reasons never appear in the email** (the operator's note is an internal record; the seller is asked to get in touch). Gated on a new `send_seller_transactional_emails` Store preference rather than the consumer one — sellers are a different audience, and silencing customer receipts must not silence seller mail. Onboarding started/completed emails wait for the onboarding task registry.
+- **Team management mirrors the operator's staff page** (RESOLVED 2026-08-18). Members in a table, pending offers in their own card, one invite dialog — the same layout, components and row actions as Settings → Staff, because it is the same job seen from the other side. Pending invitations were the gap that made the first cut feel broken: inviting someone changed nothing visible, since `team#index` lists accepted members only. A seller now gets `/seller/invitations` (index/destroy + `PATCH resend`), matching the admin surface, and the seller invitation serializer carries `acceptance_url` so a colleague who never got the email can be handed the link. Deliberately a separate controller from `team`: sending an invitation is hiring, chasing or withdrawing one is bookkeeping on the offer. **Roles stay single** — everyone holds the seller's seeded role, so inviting asks only for an address; narrower seller roles need seller-scoped role management first and are a design of their own. One framework lesson: the panel must extend `@spree/dashboard-core/lib/i18n` rather than call `init()` itself, or shared components render raw keys (`admin.row_actions.menu_label`) — a second `init()` wins the race and drops the framework's own copy.
- **An invitation opens the app it is an invitation to** (RESOLVED 2026-08-17). The `admin_invitation_acceptance` route branches on `invitation.resource`: onto a `Spree::Seller` it resolves `Spree::Sellers::PanelUrl` (the `seller_panel_url` preference / SPREE_SELLER_PANEL_URL), everything else keeps the dashboard origin. Not cosmetic — the dashboard's acceptance page authenticates through the Admin API, which no seller may call, so a seller sent there could read the invitation and never accept it. The panel gets its own acceptance page and the seller API its own `auth/invitations/:id/{lookup,accept}`, parallel to the admin pair rather than subclassing it: what differs is the audience issued and the invitations it will touch, and both are the point — accepting a *staff* invitation here is refused as `not_found`, since it carries no seller membership and would mint a seller token for someone who runs no seller. With no panel deployed the link falls back to the dashboard; a marketplace that never onboards sellers by email need configure nothing.
- **The seller panel is its own app and its own SDK** (RESOLVED 2026-08-17). `@spree/seller-sdk` beside `@spree/sdk` and `@spree/admin-sdk`, and `packages/seller-dashboard` (shell) + `packages/seller-dashboard-starter` (host) beside their dashboard counterparts — not a mode of the admin app. The credentials differ in kind, not degree: a seller JWT only (no secret-key equivalent exists), `X-Spree-Seller-Id` rather than `X-Spree-Store-Id` (the store is derived from the seller), and a refresh cookie whose name and path are deliberately not shared. Typing those as optional-but-meaningless on one client is how a panel ends up able to call the wrong API.
**`@spree/dashboard-core` generalizes rather than forks**: it exported an `adminClient` singleton built from `createAdminClient`, so any host reusing the framework got the Admin API — the one thing Decision 10 forbids. Core now takes a registered client (`setApiClient`/`getApiClient`) that each host installs at boot; `adminClient` survives as a deprecated alias. Two further admin assumptions came out with it: the Tailwind source list hardcoded `@spree/dashboard` (so a second panel's own components were never scanned) and the store switcher built a typed `/$storeId` link that cannot compile against a router without that route. `@spree/dashboard-ui` is already headless and needed no change. One framework, two hosts — a fork would mean every registry and provider fix landing twice.
diff --git a/packages/seller-dashboard/src/i18n.ts b/packages/seller-dashboard/src/i18n.ts
index 0ffa85ec65..7d19dfd6ee 100644
--- a/packages/seller-dashboard/src/i18n.ts
+++ b/packages/seller-dashboard/src/i18n.ts
@@ -1,18 +1,22 @@
+// Extends the framework's i18n rather than standing up a second instance.
+//
+// `@spree/dashboard-core/lib/i18n` initialises i18next and registers the
+// framework's own copy — the strings baked into shared components like
+// `RowActions` and the confirm dialog. A panel that called `init()` itself
+// would win the race and leave those components rendering raw keys
+// (`admin.row_actions.menu_label`) wherever they appear.
+import '@spree/dashboard-core/lib/i18n'
import i18n from 'i18next'
-import { initReactI18next } from 'react-i18next'
import en from './locales/en.json'
/**
- * The panel's own copy. Deliberately separate from the admin dashboard's:
- * sellers and marketplace staff read different words for the same records —
- * "your products" rather than "products", "your payouts" rather than a
- * seller's.
+ * The panel's own copy, layered on top.
+ *
+ * Deliberately separate from the admin dashboard's: sellers and marketplace
+ * staff read different words for the same records — "your products" rather
+ * than "products", "your payouts" rather than a seller's. The deep + overwrite
+ * flags merge these in without dropping the framework keys underneath.
*/
-void i18n.use(initReactI18next).init({
- resources: { en: { translation: en } },
- lng: 'en',
- fallbackLng: 'en',
- interpolation: { escapeValue: false },
-})
+i18n.addResourceBundle('en', 'translation', en, true, true)
export default i18n
diff --git a/packages/seller-dashboard/src/locales/en.json b/packages/seller-dashboard/src/locales/en.json
index eba5613930..a949c61c29 100644
--- a/packages/seller-dashboard/src/locales/en.json
+++ b/packages/seller-dashboard/src/locales/en.json
@@ -63,20 +63,46 @@
"team": {
"title": "Your team",
"subtitle": "The people who can sign in and manage this seller.",
- "invite": "Invite someone",
+ "members_section": "Members",
+ "invitations_section": "Pending invitations",
+ "invite_cta": "Invite member",
+ "invite_title": "Invite a colleague",
+ "invite_description": "They will get an email with a link to join this seller.",
"invite_email": "Email",
+ "invite_email_placeholder": "[email protected]",
"invite_submit": "Send invitation",
"invite_sending": "Sending…",
- "invited": "Invitation sent",
- "remove": "Remove",
- "remove_confirm": "Remove {{name}} from the team?",
- "removed": "Member removed",
- "last_member": "A seller needs at least one member. Invite someone else first.",
- "empty": "Nobody else yet."
+ "empty": "Nobody on the team yet",
+ "empty_description": "Invite a colleague and they will appear here once they accept.",
+ "table": {
+ "member": "Member",
+ "email": "Email",
+ "expires": "Expires"
+ },
+ "actions": {
+ "remove": "Remove",
+ "resend": "Resend invitation",
+ "copy_link": "Copy invitation link",
+ "revoke": "Revoke"
+ },
+ "confirm": {
+ "remove_title": "Remove member",
+ "remove_message": "{{name}} will lose access to this seller immediately.",
+ "revoke_title": "Revoke invitation",
+ "revoke_message": "The invitation to {{email}} will stop working."
+ },
+ "messages": {
+ "invited": "Invitation sent",
+ "removed": "Member removed",
+ "resent": "Invitation sent again",
+ "revoked": "Invitation revoked",
+ "link_copied": "Invitation link copied"
+ }
},
"common": {
"loading": "Loading…",
"error": "Something went wrong.",
- "retry": "Try again"
+ "retry": "Try again",
+ "cancel": "Cancel"
}
}
diff --git a/packages/seller-dashboard/src/pages/team.tsx b/packages/seller-dashboard/src/pages/team.tsx
index a0ac0eb0be..95681b467d 100644
--- a/packages/seller-dashboard/src/pages/team.tsx
+++ b/packages/seller-dashboard/src/pages/team.tsx
@@ -1,144 +1,433 @@
+import { getInitials } from '@spree/dashboard-core'
import {
+ Avatar,
+ AvatarFallback,
+ AvatarImage,
Button,
Card,
CardContent,
CardHeader,
CardTitle,
+ Dialog,
+ DialogBody,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ Empty,
+ EmptyDescription,
+ EmptyHeader,
+ EmptyMedia,
+ EmptyTitle,
Field,
- FieldGroup,
+ FieldError,
FieldLabel,
Input,
+ RelativeTime,
+ RowActions,
+ Skeleton,
+ Table,
+ TableBody,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow,
useConfirm,
+ useCopyToClipboard,
} from '@spree/dashboard-ui'
+import type { Invitation, TeamMember } from '@spree/seller-sdk'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { useParams } from '@tanstack/react-router'
+import {
+ ClockIcon,
+ LinkIcon,
+ MailIcon,
+ PlusIcon,
+ SendIcon,
+ UserMinusIcon,
+ UsersRoundIcon,
+ XIcon,
+} from 'lucide-react'
+import { useState } from 'react'
import { useForm } from 'react-hook-form'
import { useTranslation } from 'react-i18next'
import { toast } from 'sonner'
import { sellerClient } from '../api-client'
-import { CenteredMessage } from '../components/centered-message'
/**
- * Who can sign in and manage this seller.
+ * Who can sign in and run this seller.
+ *
+ * Deliberately the same shape as the marketplace operator's staff page —
+ * members in a table, pending offers in their own card — because it is the
+ * same job seen from the other side, and someone who has used one should not
+ * have to learn the other.
*
- * Everyone holds the seller's own role, which carries the whole seller
- * vocabulary — there is no narrower role to choose yet, so inviting asks only
- * for an address.
+ * Everyone holds the seller's own seeded role, which carries the whole seller
+ * vocabulary, so inviting asks only for an address. Narrower seller roles are
+ * a design of their own.
*/
export function TeamPage() {
const { t } = useTranslation()
- const queryClient = useQueryClient()
- const confirm = useConfirm()
const { sellerId } = useParams({ from: '/_authenticated/$sellerId' })
+ const [inviteOpen, setInviteOpen] = useState(false)
- const { data, isLoading, error } = useQuery({
+ const members = useQuery({
queryKey: ['seller', sellerId, 'team'],
queryFn: () => sellerClient().team.list(),
})
- const form = useForm<{ email: string }>({ defaultValues: { email: '' } })
+ const invitations = useQuery({
+ queryKey: ['seller', sellerId, 'invitations'],
+ queryFn: () => sellerClient().invitations.list(),
+ })
- const invalidate = () => queryClient.invalidateQueries({ queryKey: ['seller', sellerId, 'team'] })
+ const pending = invitations.data?.data ?? []
- const invite = useMutation({
- mutationFn: (email: string) => sellerClient().team.invite({ email }),
+ return (
+ <div className="mx-auto flex max-w-3xl flex-col gap-6">
+ <div className="flex items-start justify-between gap-4">
+ <div>
+ <h1 className="font-medium text-2xl">{t('team.title')}</h1>
+ <p className="text-muted-foreground text-sm">{t('team.subtitle')}</p>
+ </div>
+ <Button size="sm" onClick={() => setInviteOpen(true)}>
+ <PlusIcon className="size-4" />
+ {t('team.invite_cta')}
+ </Button>
+ </div>
+
+ <MembersCard members={members.data?.data ?? []} loading={members.isLoading} />
+
+ {/* Hidden entirely when there is nothing outstanding — an empty card
+ would imply something is wrong. */}
+ {(invitations.isLoading || pending.length > 0) && (
+ <PendingInvitationsCard invitations={pending} loading={invitations.isLoading} />
+ )}
+
+ <InviteDialog open={inviteOpen} onOpenChange={setInviteOpen} />
+ </div>
+ )
+}
+
+function MembersCard({ members, loading }: { members: TeamMember[]; loading: boolean }) {
+ const { t } = useTranslation()
+
+ return (
+ <Card>
+ <CardHeader>
+ <CardTitle>{t('team.members_section')}</CardTitle>
+ </CardHeader>
+ <CardContent className="p-0">
+ {loading ? (
+ <div className="flex flex-col gap-3 p-4">
+ <Skeleton className="h-10 w-full" />
+ <Skeleton className="h-10 w-full" />
+ </div>
+ ) : members.length === 0 ? (
+ <Empty>
+ <EmptyHeader>
+ <EmptyMedia variant="icon">
+ <UsersRoundIcon />
+ </EmptyMedia>
+ <EmptyTitle>{t('team.empty')}</EmptyTitle>
+ <EmptyDescription>{t('team.empty_description')}</EmptyDescription>
+ </EmptyHeader>
+ </Empty>
+ ) : (
+ <Table roundedBottom>
+ <TableHeader>
+ <TableRow>
+ <TableHead>{t('team.table.member')}</TableHead>
+ <TableHead className="w-12" />
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {members.map((member) => (
+ <MemberRow key={member.id} member={member} lastOne={members.length === 1} />
+ ))}
+ </TableBody>
+ </Table>
+ )}
+ </CardContent>
+ </Card>
+ )
+}
+
+function MemberRow({ member, lastOne }: { member: TeamMember; lastOne: boolean }) {
+ const { t } = useTranslation()
+ const { sellerId } = useParams({ from: '/_authenticated/$sellerId' })
+ const queryClient = useQueryClient()
+ const confirm = useConfirm()
+
+ const remove = useMutation({
+ mutationFn: (id: string) => sellerClient().team.remove(id),
onSuccess: () => {
- form.reset({ email: '' })
- toast.success(t('team.invited'))
+ toast.success(t('team.messages.removed'))
+ void queryClient.invalidateQueries({ queryKey: ['seller', sellerId, 'team'] })
+ },
+ // Read the server's own message rather than assuming which rule was hit —
+ // "last member" is one refusal among several the API may grow.
+ onError: (err) => toast.error(err instanceof Error ? err.message : t('common.error')),
+ })
+
+ async function handleRemove() {
+ const ok = await confirm({
+ title: t('team.confirm.remove_title'),
+ message: t('team.confirm.remove_message', { name: member.full_name || member.email }),
+ variant: 'destructive',
+ confirmLabel: t('team.actions.remove'),
+ })
+ if (ok) remove.mutate(member.id)
+ }
+
+ return (
+ <TableRow>
+ <TableCell>
+ <div className="flex items-center gap-3">
+ <Avatar className="size-8">
+ {member.avatar_url && <AvatarImage src={member.avatar_url} alt="" />}
+ <AvatarFallback className="bg-muted text-xs">
+ {getInitials(member.full_name, member.email)}
+ </AvatarFallback>
+ </Avatar>
+ <div className="flex flex-col leading-tight">
+ <span className="font-medium text-foreground">{member.full_name || member.email}</span>
+ {member.full_name && (
+ <span className="text-muted-foreground text-xs">{member.email}</span>
+ )}
+ </div>
+ </div>
+ </TableCell>
+ <TableCell className="text-right">
+ <RowActions
+ actions={[
+ {
+ key: 'remove',
+ label: t('team.actions.remove'),
+ icon: <UserMinusIcon className="size-4" />,
+ destructive: true,
+ // A seller nobody can sign in to can only be reopened by the
+ // marketplace operator, so the server refuses this too.
+ disabled: lastOne || remove.isPending,
+ onSelect: handleRemove,
+ },
+ ]}
+ />
+ </TableCell>
+ </TableRow>
+ )
+}
+
+function PendingInvitationsCard({
+ invitations,
+ loading,
+}: {
+ invitations: Invitation[]
+ loading: boolean
+}) {
+ const { t } = useTranslation()
+
+ return (
+ <Card>
+ <CardHeader>
+ <CardTitle>{t('team.invitations_section')}</CardTitle>
+ </CardHeader>
+ <CardContent className="p-0">
+ {loading ? (
+ <div className="p-4">
+ <Skeleton className="h-10 w-full" />
+ </div>
+ ) : (
+ <Table roundedBottom>
+ <TableHeader>
+ <TableRow>
+ <TableHead>{t('team.table.email')}</TableHead>
+ <TableHead>{t('team.table.expires')}</TableHead>
+ <TableHead className="w-12" />
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {invitations.map((invitation) => (
+ <InvitationRow key={invitation.id} invitation={invitation} />
+ ))}
+ </TableBody>
+ </Table>
+ )}
+ </CardContent>
+ </Card>
+ )
+}
+
+function InvitationRow({ invitation }: { invitation: Invitation }) {
+ const { t } = useTranslation()
+ const { sellerId } = useParams({ from: '/_authenticated/$sellerId' })
+ const queryClient = useQueryClient()
+ const confirm = useConfirm()
+ const { copy } = useCopyToClipboard()
+
+ const invalidate = () =>
+ queryClient.invalidateQueries({ queryKey: ['seller', sellerId, 'invitations'] })
+
+ const resend = useMutation({
+ mutationFn: (id: string) => sellerClient().invitations.resend(id),
+ onSuccess: () => {
+ toast.success(t('team.messages.resent'))
void invalidate()
},
- onError: () => toast.error(t('common.error')),
+ onError: (err) => toast.error(err instanceof Error ? err.message : t('common.error')),
})
- const remove = useMutation({
- mutationFn: (id: string) => sellerClient().team.remove(id),
+ const revoke = useMutation({
+ mutationFn: (id: string) => sellerClient().invitations.revoke(id),
onSuccess: () => {
- toast.success(t('team.removed'))
+ toast.success(t('team.messages.revoked'))
void invalidate()
},
- // The server refuses to remove the last member, since emptying a team
- // leaves a seller nobody can sign in to.
- onError: () => toast.error(t('team.last_member')),
+ onError: (err) => toast.error(err instanceof Error ? err.message : t('common.error')),
})
- if (isLoading) return <CenteredMessage>{t('common.loading')}</CenteredMessage>
- if (error) return <CenteredMessage>{t('common.error')}</CenteredMessage>
+ async function handleCopyLink() {
+ // Path-only when no panel origin is configured; resolve against this
+ // panel's own origin, which is where the link would land anyway.
+ const url = invitation.acceptance_url.startsWith('/')
+ ? `${window.location.origin}${invitation.acceptance_url}`
+ : invitation.acceptance_url
+
+ await copy(url)
+ toast.success(t('team.messages.link_copied'))
+ }
- const members = data?.data ?? []
+ async function handleRevoke() {
+ const ok = await confirm({
+ title: t('team.confirm.revoke_title'),
+ message: t('team.confirm.revoke_message', { email: invitation.email }),
+ variant: 'destructive',
+ confirmLabel: t('team.actions.revoke'),
+ })
+ if (ok) revoke.mutate(invitation.id)
+ }
return (
- <div className="mx-auto flex max-w-3xl flex-col gap-6">
- <div>
- <h1 className="font-medium text-2xl">{t('team.title')}</h1>
- <p className="text-muted-foreground text-sm">{t('team.subtitle')}</p>
- </div>
+ <TableRow>
+ <TableCell>
+ <div className="flex items-center gap-2">
+ <MailIcon className="size-4 text-muted-foreground" />
+ <span className="font-medium">{invitation.email}</span>
+ </div>
+ </TableCell>
+ <TableCell className="text-muted-foreground text-sm">
+ {invitation.expires_at ? (
+ <span className="inline-flex items-center gap-1">
+ <ClockIcon className="size-3.5" />
+ <RelativeTime iso={invitation.expires_at} />
+ </span>
+ ) : (
+ '—'
+ )}
+ </TableCell>
+ <TableCell className="text-right">
+ <RowActions
+ actions={[
+ {
+ key: 'resend',
+ label: t('team.actions.resend'),
+ icon: <SendIcon className="size-4" />,
+ disabled: resend.isPending,
+ onSelect: () => resend.mutate(invitation.id),
+ },
+ {
+ key: 'copy',
+ label: t('team.actions.copy_link'),
+ icon: <LinkIcon className="size-4" />,
+ onSelect: handleCopyLink,
+ },
+ {
+ key: 'revoke',
+ label: t('team.actions.revoke'),
+ icon: <XIcon className="size-4" />,
+ destructive: true,
+ disabled: revoke.isPending,
+ onSelect: handleRevoke,
+ },
+ ]}
+ />
+ </TableCell>
+ </TableRow>
+ )
+}
- <Card>
- <CardHeader>
- <CardTitle>{t('team.title')}</CardTitle>
- </CardHeader>
- <CardContent className="flex flex-col">
- {members.length === 0 && (
- <p className="text-muted-foreground text-sm">{t('team.empty')}</p>
- )}
- {members.map((member) => (
- <div
- key={member.id}
- className="flex items-center justify-between border-border border-b py-3 last:border-b-0"
- >
- <div className="flex flex-col">
- <span className="font-medium text-sm">{member.full_name || member.email}</span>
- {member.full_name && (
- <span className="text-muted-foreground text-xs">{member.email}</span>
- )}
- </div>
- <Button
- variant="ghost"
- size="sm"
- disabled={remove.isPending}
- onClick={async () => {
- const ok = await confirm({
- title: t('team.remove'),
- message: t('team.remove_confirm', {
- name: member.full_name || member.email,
- }),
- variant: 'destructive',
- confirmLabel: t('team.remove'),
- })
- if (ok) remove.mutate(member.id)
- }}
- >
- {t('team.remove')}
- </Button>
- </div>
- ))}
- </CardContent>
- </Card>
-
- <Card>
- <CardHeader>
- <CardTitle>{t('team.invite')}</CardTitle>
- </CardHeader>
- <CardContent>
- <form onSubmit={form.handleSubmit((values) => invite.mutate(values.email))}>
- <FieldGroup>
- <Field>
- <FieldLabel htmlFor="invite-email">{t('team.invite_email')}</FieldLabel>
- <Input
- id="invite-email"
- type="email"
- {...form.register('email', { required: true })}
- />
- </Field>
- <div className="flex justify-end">
- <Button type="submit" disabled={invite.isPending}>
- {invite.isPending ? t('team.invite_sending') : t('team.invite_submit')}
- </Button>
- </div>
- </FieldGroup>
- </form>
- </CardContent>
- </Card>
- </div>
+function InviteDialog({
+ open,
+ onOpenChange,
+}: {
+ open: boolean
+ onOpenChange: (open: boolean) => void
+}) {
+ const { t } = useTranslation()
+ const { sellerId } = useParams({ from: '/_authenticated/$sellerId' })
+ const queryClient = useQueryClient()
+ const form = useForm<{ email: string }>({ defaultValues: { email: '' } })
+
+ const invite = useMutation({
+ mutationFn: (email: string) => sellerClient().team.invite({ email }),
+ onSuccess: () => {
+ form.reset({ email: '' })
+ onOpenChange(false)
+ toast.success(t('team.messages.invited'))
+ // The new row lands in pending invitations, not in members — they are
+ // not a member until they accept.
+ void queryClient.invalidateQueries({ queryKey: ['seller', sellerId, 'invitations'] })
+ },
+ onError: (err) => toast.error(err instanceof Error ? err.message : t('common.error')),
+ })
+
+ const { errors } = form.formState
+
+ return (
+ <Dialog
+ open={open}
+ onOpenChange={(next) => {
+ // Clear a half-typed address on dismiss, so reopening starts fresh
+ // rather than showing what was abandoned.
+ if (!next) form.reset({ email: '' })
+ onOpenChange(next)
+ }}
+ >
+ <DialogContent>
+ <DialogHeader>
+ <DialogTitle>{t('team.invite_title')}</DialogTitle>
+ <DialogDescription>{t('team.invite_description')}</DialogDescription>
+ </DialogHeader>
+
+ <form onSubmit={form.handleSubmit((values) => invite.mutate(values.email))}>
+ {/* DialogBody owns the padding and the scroll region; the footer
+ sits outside it so its divider spans the dialog. */}
+ <DialogBody>
+ <Field>
+ <FieldLabel htmlFor="invite-email">{t('team.invite_email')}</FieldLabel>
+ <Input
+ id="invite-email"
+ type="email"
+ autoFocus
+ placeholder={t('team.invite_email_placeholder')}
+ aria-invalid={!!errors.email || undefined}
+ {...form.register('email', { required: true })}
+ />
+ <FieldError errors={[errors.email]} />
+ </Field>
+ </DialogBody>
+
+ <DialogFooter>
+ <Button type="button" variant="outline" onClick={() => onOpenChange(false)}>
+ {t('common.cancel')}
+ </Button>
+ <Button type="submit" disabled={invite.isPending}>
+ {invite.isPending ? t('team.invite_sending') : t('team.invite_submit')}
+ </Button>
+ </DialogFooter>
+ </form>
+ </DialogContent>
+ </Dialog>
)
}
diff --git a/packages/seller-sdk/src/seller-client.ts b/packages/seller-sdk/src/seller-client.ts
index 719fa3d702..7051adff15 100644
--- a/packages/seller-sdk/src/seller-client.ts
+++ b/packages/seller-sdk/src/seller-client.ts
@@ -111,6 +111,26 @@ export class SellerClient {
remove: (id: string, options?: RequestOptions): Promise<void> =>
this.request<void>('DELETE', `/team/${id}`, options),
}
+
+ /**
+ * Offers nobody has accepted yet.
+ *
+ * Sending one lives on `team` — that is hiring — while chasing or
+ * withdrawing one is bookkeeping on the offer itself.
+ */
+ readonly invitations = {
+ /** Pending only; an accepted invitation is a team member. */
+ list: (options?: RequestOptions): Promise<{ data: Invitation[] }> =>
+ this.request<{ data: Invitation[] }>('GET', '/invitations', options),
+
+ /** Sends the email again, for a colleague who never got the first one. */
+ resend: (id: string, options?: RequestOptions): Promise<Invitation> =>
+ this.request<Invitation>('PATCH', `/invitations/${id}/resend`, options),
+
+ /** Withdraws an offer that has not been accepted. */
+ revoke: (id: string, options?: RequestOptions): Promise<void> =>
+ this.request<void>('DELETE', `/invitations/${id}`, options),
+ }
}
/** What `/seller/me` answers. */
diff --git a/packages/seller-sdk/src/types/generated/Invitation.ts b/packages/seller-sdk/src/types/generated/Invitation.ts
index 5e0b57fdfb..3d5c5d9711 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 2f0e6fde2c5925909616a667b6846796
+// Typelizer digest bc9f7c8d41a89f2345c24a7defaddce3
//
// DO NOT MODIFY: This file was automatically generated by Typelizer.
@@ -7,6 +7,7 @@ type Invitation = {
email: string;
created_at: string;
status: string;
+ acceptance_url: string;
expires_at: string | null;
accepted_at: string | null;
}
diff --git a/spree/api/app/controllers/spree/api/v3/seller/invitations_controller.rb b/spree/api/app/controllers/spree/api/v3/seller/invitations_controller.rb
new file mode 100644
index 0000000000..368ecc55c8
--- /dev/null
+++ b/spree/api/app/controllers/spree/api/v3/seller/invitations_controller.rb
@@ -0,0 +1,71 @@
+module Spree
+ module Api
+ module V3
+ module Seller
+ # Invitations this seller has sent that nobody has accepted yet.
+ #
+ # Separate from `TeamController` because they are different things: a
+ # member is a person who can sign in, an invitation is an offer that
+ # may lapse. Creating one still belongs to the team endpoint — hiring
+ # is what the seller is doing — while chasing or withdrawing one is
+ # bookkeeping on the offer itself.
+ #
+ # Rooted at `current_seller.invitations` throughout, so a seller can
+ # neither see nor touch an invitation sent by anyone else.
+ class InvitationsController < Seller::BaseController
+ scoped_resource :seller_profile
+
+ before_action :set_invitation, only: [:destroy, :resend]
+
+ # Pending only: an accepted invitation is a team member, and the
+ # panel already lists those.
+ def index
+ invitations = current_seller.invitations.pending.order(created_at: :desc)
+
+ render json: { data: invitations.map { |invitation| serialize(invitation) } }
+ end
+
+ # Withdraws an offer that has not been accepted.
+ def destroy
+ @invitation.destroy
+ head :no_content
+ end
+
+ # Sends the invitation email again, for a colleague who never got
+ # the first one. The model refuses once the invitation has expired
+ # or been accepted, and says so rather than silently doing nothing.
+ def resend
+ if @invitation.expired?
+ return render_error(
+ code: ErrorHandler::ERROR_CODES[:processing_error],
+ message: Spree.t(:invitation_expired),
+ status: :unprocessable_content
+ )
+ end
+
+ @invitation.resend!
+ render json: serialize(@invitation)
+ end
+
+ protected
+
+ def read_actions
+ %w[index]
+ end
+
+ private
+
+ def set_invitation
+ @invitation = current_seller.invitations.pending.find_by_prefix_id!(params[:id])
+ end
+
+ def serialize(invitation)
+ Spree.api.seller_invitation_serializer.new(
+ invitation, params: { store: current_store }
+ ).to_h
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/spree/api/app/serializers/spree/api/v3/seller/invitation_serializer.rb b/spree/api/app/serializers/spree/api/v3/seller/invitation_serializer.rb
index d338d073fb..f1bb40948c 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
@@ -12,7 +12,8 @@ module Spree
class InvitationSerializer < V3::BaseSerializer
typelize email: :string, status: :string,
expires_at: [:string, nullable: true],
- accepted_at: [:string, nullable: true]
+ accepted_at: [:string, nullable: true],
+ acceptance_url: :string
attributes :email, created_at: :iso8601
@@ -20,6 +21,18 @@ module Spree
invitation.status.to_s
end
+ # So the panel can offer "copy link" for a colleague who never got
+ # the email. Absolute when a panel origin is configured — the route
+ # sends a seller invitation to the seller panel — otherwise the path,
+ # which the panel resolves against its own origin.
+ attribute :acceptance_url do |invitation|
+ if Spree::Config[:seller_panel_url].present? || Spree::Config[:dashboard_url].present?
+ Rails.application.routes.url_helpers.admin_invitation_acceptance_url(invitation)
+ else
+ "/accept-invitation/#{invitation.prefixed_id}?token=#{invitation.token}"
+ end
+ end
+
attribute :expires_at do |invitation|
invitation.expires_at&.iso8601
end
diff --git a/spree/api/config/routes.rb b/spree/api/config/routes.rb
index 4480936087..28a0a342d9 100644
--- a/spree/api/config/routes.rb
+++ b/spree/api/config/routes.rb
@@ -673,6 +673,14 @@ Spree::Core::Engine.add_routes do
# Who runs this seller. Inviting reuses the operator's workflow, so
# there is one invitation rail and one set of hooks.
resources :team, only: [:index, :create, :destroy], controller: 'team'
+
+ # Offers not yet accepted. Creating one is hiring, so it lives on
+ # `team`; chasing or withdrawing one is bookkeeping on the offer.
+ resources :invitations, only: [:index, :destroy], controller: 'invitations' do
+ member do
+ patch :resend
+ end
+ end
end
# Webhooks (outside of store namespace — no API key authentication)
diff --git a/spree/api/spec/controllers/spree/api/v3/seller/invitations_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/seller/invitations_controller_spec.rb
new file mode 100644
index 0000000000..63b7638e78
--- /dev/null
+++ b/spree/api/spec/controllers/spree/api/v3/seller/invitations_controller_spec.rb
@@ -0,0 +1,105 @@
+require 'spec_helper'
+
+RSpec.describe Spree::Api::V3::Seller::InvitationsController, type: :controller do
+ render_views
+
+ include_context 'API v3 Seller'
+
+ let(:seller_user) do
+ create(:admin_user, :without_admin_role).tap { |user| seller.add_user(user) }
+ end
+ let(:token) do
+ Spree::Api::V3::TestingSupport.generate_jwt(
+ seller_user, audience: Spree::Api::V3::JwtAuthentication::JWT_AUDIENCE_SELLER
+ )
+ end
+
+ let!(:invitation) do
+ create(:invitation, resource: seller, inviter: seller_user,
+ email: '[email protected]', role: seller.default_user_role)
+ end
+
+ before do
+ request.headers['Authorization'] = "Bearer #{token}"
+ request.headers['X-Spree-Seller-Id'] = seller.prefixed_id
+ end
+
+ describe 'GET #index' do
+ it 'lists offers nobody has accepted yet' do
+ get :index, as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(json_response['data'].pluck('email')).to include('[email protected]')
+ end
+
+ it 'carries a link the panel can hand to a colleague' do
+ get :index, as: :json
+
+ expect(json_response['data'].first['acceptance_url']).to include(invitation.prefixed_id)
+ end
+
+ # An accepted invitation is a team member, and the panel lists those
+ # separately — showing it here would double-count the person.
+ it 'omits invitations that were accepted' do
+ invitation.invitee = create(:admin_user, email: invitation.email)
+ invitation.accept!
+
+ get :index, as: :json
+
+ expect(json_response['data']).to be_empty
+ end
+
+ it "does not list another seller's invitations" do
+ other = create(:seller, :approved, store: store)
+ create(:invitation, resource: other, inviter: seller_user, email: '[email protected]')
+
+ get :index, as: :json
+
+ expect(json_response['data'].pluck('email')).not_to include('[email protected]')
+ end
+ end
+
+ describe 'PATCH #resend' do
+ it 'sends the offer again' do
+ patch :resend, params: { id: invitation.prefixed_id }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ end
+
+ it 'refuses once the offer has lapsed' do
+ invitation.update_column(:expires_at, 1.day.ago)
+
+ patch :resend, params: { id: invitation.prefixed_id }, as: :json
+
+ expect(response).to have_http_status(:unprocessable_content)
+ end
+
+ it "404s on another seller's invitation" do
+ other = create(:seller, :approved, store: store)
+ theirs = create(:invitation, resource: other, inviter: seller_user)
+
+ patch :resend, params: { id: theirs.prefixed_id }, as: :json
+
+ expect(response).to have_http_status(:not_found)
+ end
+ end
+
+ describe 'DELETE #destroy' do
+ it 'withdraws the offer' do
+ delete :destroy, params: { id: invitation.prefixed_id }, as: :json
+
+ expect(response).to have_http_status(:no_content)
+ expect(seller.reload.invitations.pending).to be_empty
+ end
+
+ it "404s on another seller's invitation" do
+ other = create(:seller, :approved, store: store)
+ theirs = create(:invitation, resource: other, inviter: seller_user)
+
+ delete :destroy, params: { id: theirs.prefixed_id }, as: :json
+
+ expect(response).to have_http_status(:not_found)
+ expect(theirs.reload).to be_present
+ end
+ end
+end
diff --git a/spree/api/spec/requests/seller_team_management_spec.rb b/spree/api/spec/requests/seller_team_management_spec.rb
new file mode 100644
index 0000000000..acc4634af2
--- /dev/null
+++ b/spree/api/spec/requests/seller_team_management_spec.rb
@@ -0,0 +1,59 @@
+require 'spec_helper'
+
+# The team screen's whole loop over HTTP: invite, see it pending, resend,
+# revoke — then invite again and accept, and watch it move from the pending
+# list into the member list.
+RSpec.describe 'seller team management', type: :request do
+ let(:store) { @default_store }
+ let(:seller) { create(:seller, :approved, store: store) }
+ let(:owner) { create(:admin_user, :without_admin_role).tap { |u| seller.add_user(u) } }
+ let(:headers) do
+ {
+ 'Authorization' => "Bearer #{Spree::Api::V3::TestingSupport.generate_jwt(
+ owner, audience: Spree::Api::V3::JwtAuthentication::JWT_AUDIENCE_SELLER
+ )}",
+ 'X-Spree-Seller-Id' => seller.prefixed_id
+ }
+ end
+
+ def json = JSON.parse(response.body)
+
+ it 'runs the loop the team screen drives' do
+ post '/api/v3/seller/team', params: { email: '[email protected]' }, headers: headers
+ expect(response).to have_http_status(:created)
+
+ # The screen reads members and invitations separately: a new hire is not
+ # a member until they accept.
+ get '/api/v3/seller/team', headers: headers
+ expect(json['data'].pluck('email')).not_to include('[email protected]')
+
+ get '/api/v3/seller/invitations', headers: headers
+ pending = json['data'].first
+ expect(pending['email']).to eq('[email protected]')
+ expect(pending['acceptance_url']).to be_present
+
+ patch "/api/v3/seller/invitations/#{pending['id']}/resend", headers: headers
+ expect(response).to have_http_status(:ok)
+
+ delete "/api/v3/seller/invitations/#{pending['id']}", headers: headers
+ expect(response).to have_http_status(:no_content)
+
+ get '/api/v3/seller/invitations', headers: headers
+ expect(json['data']).to be_empty
+ end
+
+ it 'moves an accepted invitation from pending into the team' do
+ post '/api/v3/seller/team', params: { email: '[email protected]' }, headers: headers
+ invitation = Spree::Invitation.find_by(email: '[email protected]')
+
+ post "/api/v3/seller/auth/invitations/#{invitation.prefixed_id}/accept",
+ params: { token: invitation.token, password: 'sekrit123', password_confirmation: 'sekrit123' }
+ expect(response).to have_http_status(:ok)
+
+ get '/api/v3/seller/invitations', headers: headers
+ expect(json['data']).to be_empty
+
+ get '/api/v3/seller/team', headers: headers
+ expect(json['data'].pluck('email')).to include('[email protected]')
+ end
+end
diff --git a/spree/core/config/locales/en.yml b/spree/core/config/locales/en.yml
index caf06302d7..dfb810dca1 100644
--- a/spree/core/config/locales/en.yml
+++ b/spree/core/config/locales/en.yml
@@ -1065,7 +1065,7 @@ en:
inventory: Inventory
invitation_accepted: Invitation accepted!
invitation_already_accepted: This invitation has already been accepted.
- invitation_expired: This invitation has expired.
+ invitation_expired: This invitation has expired. Invite them again to send a new one.
invitation_invitee_missing: This invitation has no invitee.
invitation_mailer:
greeting: Hi %{user_name},