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.

Let a seller work through their own onboarding checklist

Damian Legawiec1a0467d77867
diff --git a/docs/plans/6.0-multi-vendor-marketplace.md b/docs/plans/6.0-multi-vendor-marketplace.md
index 745e48121c..6146fd7bee 100644
--- a/docs/plans/6.0-multi-vendor-marketplace.md
+++ b/docs/plans/6.0-multi-vendor-marketplace.md
@@ -739,6 +739,7 @@ Even before this lands, work touching adjacent areas should:
- **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.
- **The seller panel is a path, not a subdomain** (RESOLVED 2026-08-18). Served at `/sellers` by `spree_dashboard`, exactly as the operator's dashboard is served at `/dashboard` — same engine, same SPA controller (generalised to `Spree::Dashboard::SpaController`, which a subclass points at a bundle), `SPREE_SELLER_PANEL_DIST_PATH` beside `SPREE_DASHBOARD_DIST_PATH`. Nothing forced a second hostname: the two panels' refresh cookies are already isolated by name and path (`/api/v3/admin/auth` vs `/api/v3/seller/auth`), so sharing an origin costs nothing in isolation and saves every deployment a hostname, a certificate and a CORS allowlist entry. `SPREE_SELLER_PANEL_URL` remains for marketplaces that do want sellers on their own domain, and `Sellers::PanelUrl` now resolves the `/sellers` mount before falling back to the dashboard. The dev-time `sellers.<branch>` host stays — two Vite servers cannot share an origin root, which is why `admin.<branch>` exists too. **Constraint:** a link the panel builds from a path must resolve against `BASE_URL`, never `window.location.origin` alone, or it misses the mount.
- **The seller panel is customisable the way the dashboard is — same registries, same facade** (RESOLVED 2026-08-18). Reversing the first cut's "reference/throwaway, no extension points": the seller panel is the part of a marketplace most often shaped to fit, and shaping it should mean adding and removing, not rewriting. `@spree/seller-dashboard` re-exports `@spree/dashboard-core/plugin`, so one `defineDashboardPlugin({ nav, slots, tables })` extends either panel; the built-in sidebar entries register into the shared nav registry (a marketplace `nav.remove('team')`s the built-in), and the built-in screens expose named slots (`seller.team.actions`, `seller.team.after`). Two core changes made this a reuse rather than a fork: `useNavItems(tenantId)` lifts the sidebar's registry composition (tenant prefixing + `if` gates + permission filtering) out of `AppSidebar` so a panel scoped by seller id composes the same registry, and `useOptionalStore()` lets shared code run in a panel that mounts no `StoreProvider`. The chrome moved onto the real `Sidebar`/`NavMain` primitives with it. **Two more things a second consumer surfaced:** the seller `/me` sent only permission keys, so `<Can>` — which reads CanCanCan rules — answered false for everything on the panel, silently (fixed: `PermissionSerialization` concern shared by both `/me`s); and `Seller::ResourceController` had no subclass and no spec — `Seller::ProductsController` is now its first consumer, with the tenancy proofs (another seller's id 404s on show/update/destroy, `seller_id` in a create payload is ignored, a member without `write_products` gets 403). The seller product serializer extends the **store** one, not admin's, so nested variants/media inherit no operator data; the seller SDK writer emits the store-level types a seller serializer nests rather than an empty twin per type.
+- **A seller sees their own checklist, one page, no wizard** (RESOLVED 2026-08-20). The seller-facing half of `6.0-seller-onboarding-requirements.md`: `GET /seller/onboarding` answers `{status, progress, requirements}` off the same `Spree::Sellers::Requirements` evaluator the operator reads, so the two can never disagree about what is outstanding; submitting for review and submitting against one requirement are the existing workflows, called rather than reimplemented. Accepting terms is a **profile write** (`accept_terms: true`) rather than an endpoint of its own, and is one-way — the stamp records that it happened. **One page, not a wizard:** the checklist is not ordered by dependency, a seller does these in any order, and several mean going away and coming back (a document to find, an account to open) — a wizard would trap them at step two. The legacy extension's shape carries over: progress bar, accordion, first outstanding line open. **Kind → panel route is a map in the panel, not `action_url`:** the server has no idea how this panel routes, and a kind it does not recognise still renders its name, description and any `action_url` — which is what makes a provider gem's kind (Stripe payouts, Phase 3b) useful before the panel knows it exists. Submission downloads are served per request through the seller's own scope, never a storage URL: these are identity documents.
- **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.
diff --git a/docs/plans/6.0-seller-onboarding-requirements.md b/docs/plans/6.0-seller-onboarding-requirements.md
index 09964488f4..49387d5f18 100644
--- a/docs/plans/6.0-seller-onboarding-requirements.md
+++ b/docs/plans/6.0-seller-onboarding-requirements.md
@@ -1,6 +1,6 @@
# Seller Onboarding Requirements
-**Status:** Phase 1-3 implemented (2026-08-18) — core models, kinds, evaluator, workflows, Admin API + SDK, and the operator dashboard. Remaining: the seller-facing `/api/v3/seller` endpoints (ride with the marketplace plan's seller branch), the payout-account kind (Phase 3b), the `DeliveryMethod` kind (Phase 3), and the developer guide
+**Status:** Phase 1-3 implemented (2026-08-18) — core models, kinds, evaluator, workflows, Admin API + SDK, and the operator dashboard. **Seller-facing surface implemented (2026-08-20)** — `GET /seller/onboarding`, `POST /seller/onboarding/submit_for_review`, `POST /seller/requirements/:id/submissions` (+ a seller-scoped submission download), `accept_terms` on the profile write, the `@spree/seller-sdk` resources, and the panel's checklist page. Remaining: the payout-account kind (Phase 3b), the `DeliveryMethod` kind (Phase 3), and the developer guide
**Target:** Spree 6.0
**Depends on:** `6.0-multi-vendor-marketplace.md` (Phase 1 — `Spree::Seller`, lifecycle workflows, the `/api/v3/seller` branch), `6.0-service-workflows.md`, `6.0-admin-rbac.md`, `6.0-integrations-admin.md` (the `PreferenceSchema` types-discovery pattern)
**Author:** Damian Legawiec
diff --git a/packages/seller-dashboard-starter/src/routeTree.gen.ts b/packages/seller-dashboard-starter/src/routeTree.gen.ts
index 3ba9e3c8b1..cd105dc73a 100644
--- a/packages/seller-dashboard-starter/src/routeTree.gen.ts
+++ b/packages/seller-dashboard-starter/src/routeTree.gen.ts
@@ -16,6 +16,7 @@ import { Route as acceptInvitationDotinvitationIdRouteImport } from './../../sel
import { Route as authenticatedSellerIdRouteImport } from './../../seller-dashboard/src/routes/_authenticated/$sellerId'
import { Route as IndexRouteImport } from './../../seller-dashboard/src/routes/_authenticated/$sellerId/index'
import { Route as TeamRouteImport } from './../../seller-dashboard/src/routes/_authenticated/$sellerId/team'
+import { Route as OnboardingRouteImport } from './../../seller-dashboard/src/routes/_authenticated/$sellerId/onboarding'
const loginRoute = loginRouteImport.update({
id: '/login',
@@ -52,12 +53,18 @@ const TeamRoute = TeamRouteImport.update({
path: '/team',
getParentRoute: () => authenticatedSellerIdRoute,
} as any)
+const OnboardingRoute = OnboardingRouteImport.update({
+ id: '/onboarding',
+ path: '/onboarding',
+ getParentRoute: () => authenticatedSellerIdRoute,
+} as any)
export interface FileRoutesByFullPath {
'/': typeof authenticatedIndexRoute
'/login': typeof loginRoute
'/$sellerId': typeof authenticatedSellerIdRouteWithChildren
'/accept-invitation/$invitationId': typeof acceptInvitationDotinvitationIdRoute
+ '/$sellerId/onboarding': typeof OnboardingRoute
'/$sellerId/team': typeof TeamRoute
'/$sellerId/': typeof IndexRoute
}
@@ -65,6 +72,7 @@ export interface FileRoutesByTo {
'/login': typeof loginRoute
'/accept-invitation/$invitationId': typeof acceptInvitationDotinvitationIdRoute
'/': typeof authenticatedIndexRoute
+ '/$sellerId/onboarding': typeof OnboardingRoute
'/$sellerId/team': typeof TeamRoute
'/$sellerId': typeof IndexRoute
}
@@ -75,6 +83,7 @@ export interface FileRoutesById {
'/_authenticated/$sellerId': typeof authenticatedSellerIdRouteWithChildren
'/accept-invitation/$invitationId': typeof acceptInvitationDotinvitationIdRoute
'/_authenticated/': typeof authenticatedIndexRoute
+ '/_authenticated/$sellerId/onboarding': typeof OnboardingRoute
'/_authenticated/$sellerId/team': typeof TeamRoute
'/_authenticated/$sellerId/': typeof IndexRoute
}
@@ -85,6 +94,7 @@ export interface FileRouteTypes {
| '/login'
| '/$sellerId'
| '/accept-invitation/$invitationId'
+ | '/$sellerId/onboarding'
| '/$sellerId/team'
| '/$sellerId/'
fileRoutesByTo: FileRoutesByTo
@@ -92,6 +102,7 @@ export interface FileRouteTypes {
| '/login'
| '/accept-invitation/$invitationId'
| '/'
+ | '/$sellerId/onboarding'
| '/$sellerId/team'
| '/$sellerId'
id:
@@ -101,6 +112,7 @@ export interface FileRouteTypes {
| '/_authenticated/$sellerId'
| '/accept-invitation/$invitationId'
| '/_authenticated/'
+ | '/_authenticated/$sellerId/onboarding'
| '/_authenticated/$sellerId/team'
| '/_authenticated/$sellerId/'
fileRoutesById: FileRoutesById
@@ -162,15 +174,24 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof TeamRouteImport
parentRoute: typeof authenticatedSellerIdRoute
}
+ '/_authenticated/$sellerId/onboarding': {
+ id: '/_authenticated/$sellerId/onboarding'
+ path: '/onboarding'
+ fullPath: '/$sellerId/onboarding'
+ preLoaderRoute: typeof OnboardingRouteImport
+ parentRoute: typeof authenticatedSellerIdRoute
+ }
}
}
interface authenticatedSellerIdRouteChildren {
+ OnboardingRoute: typeof OnboardingRoute
TeamRoute: typeof TeamRoute
IndexRoute: typeof IndexRoute
}
const authenticatedSellerIdRouteChildren: authenticatedSellerIdRouteChildren = {
+ OnboardingRoute: OnboardingRoute,
TeamRoute: TeamRoute,
IndexRoute: IndexRoute,
}
diff --git a/packages/seller-dashboard/src/components/onboarding-nav-badge.tsx b/packages/seller-dashboard/src/components/onboarding-nav-badge.tsx
new file mode 100644
index 0000000000..850de8c87e
--- /dev/null
+++ b/packages/seller-dashboard/src/components/onboarding-nav-badge.tsx
@@ -0,0 +1,38 @@
+import { Badge } from '@spree/dashboard-ui'
+import { useQuery } from '@tanstack/react-query'
+import { useParams } from '@tanstack/react-router'
+import { sellerClient } from '../api-client'
+
+/**
+ * Progress counter beside the onboarding nav entry, mirroring the operator's
+ * Getting Started badge — a seller can see how far along they are without
+ * opening the page.
+ *
+ * Shares the onboarding query key with the page itself, so the two read one
+ * cache entry: the badge updates the moment a task completes, and visiting
+ * the page costs no extra request.
+ *
+ * Hidden once everything is done, like its operator twin — a badge that
+ * always reads `4/4` is noise.
+ */
+export function OnboardingNavBadge() {
+ // `strict: false`: the badge renders inside the sidebar, which the seller
+ // picker also mounts — there is no `$sellerId` in scope there.
+ const { sellerId } = useParams({ strict: false }) as { sellerId?: string }
+
+ const { data } = useQuery({
+ queryKey: ['seller', sellerId, 'onboarding'],
+ queryFn: () => sellerClient().onboarding.get(),
+ enabled: Boolean(sellerId),
+ })
+
+ const progress = data?.progress
+ if (!progress || progress.total === 0 || progress.done === progress.total) return null
+
+ return (
+ <Badge variant="outline" className="mr-1 flex items-center gap-0 rounded-lg">
+ <span>{progress.done}</span>
+ <span className="opacity-50">/{progress.total}</span>
+ </Badge>
+ )
+}
diff --git a/packages/seller-dashboard/src/locales/en.json b/packages/seller-dashboard/src/locales/en.json
index a949c61c29..355f5e9958 100644
--- a/packages/seller-dashboard/src/locales/en.json
+++ b/packages/seller-dashboard/src/locales/en.json
@@ -33,7 +33,35 @@
"nav": {
"profile": "Profile",
"team": "Team",
- "sign_out": "Sign out"
+ "sign_out": "Sign out",
+ "onboarding": "Getting set up"
+ },
+ "onboarding": {
+ "title": "Getting set up",
+ "subtitle": "What this marketplace asks for before you can start selling.",
+ "progress_title": "Your progress",
+ "progress_count": "{{done}} of {{total}} done",
+ "remaining_one": "{{count}} thing still to do before you can submit",
+ "remaining_other": "{{count}} things still to do before you can submit",
+ "ready": "Everything required is done.",
+ "submit": "Submit for review",
+ "submitting": "Submitting…",
+ "submitted": "Sent for review",
+ "under_review": "The marketplace is reviewing your application. We will email you when there is news.",
+ "optional": "Optional",
+ "done": "This one is done.",
+ "awaiting_review": "Waiting for the marketplace to review this.",
+ "accept_terms": "Accept the terms",
+ "terms_accepted": "Terms accepted",
+ "confirm": "Confirm",
+ "note_placeholder": "Anything the marketplace should know (optional)",
+ "submitted_requirement": "Sent",
+ "go": "Go there",
+ "status": {
+ "complete": "Done",
+ "pending": "In review",
+ "rejected": "Needs another look"
+ }
},
"profile": {
"title": "Your profile",
diff --git a/packages/seller-dashboard/src/nav/default.ts b/packages/seller-dashboard/src/nav/default.ts
index 7ddb0f4945..ecc81bf456 100644
--- a/packages/seller-dashboard/src/nav/default.ts
+++ b/packages/seller-dashboard/src/nav/default.ts
@@ -1,5 +1,6 @@
import { i18n, nav } from '@spree/dashboard-core'
-import { StoreIcon, UsersIcon } from 'lucide-react'
+import { ClipboardCheckIcon, StoreIcon, UsersIcon } from 'lucide-react'
+import { OnboardingNavBadge } from '../components/onboarding-nav-badge'
// The panel's built-in sidebar. Registered into the same registry a plugin
// writes to, so a marketplace can remove, reorder or add beside these with
@@ -21,6 +22,19 @@ nav.add({
subject: 'seller_profile',
})
+// First in the rail while a seller is still being admitted: it is the only
+// thing that matters until they are approved. A marketplace that admits
+// sellers some other way removes it like any other entry.
+nav.add({
+ key: 'onboarding',
+ label: i18n.t('nav.onboarding'),
+ path: '/onboarding',
+ icon: ClipboardCheckIcon,
+ position: 150,
+ subject: 'seller_profile',
+ badge: OnboardingNavBadge,
+})
+
nav.add({
key: 'team',
label: i18n.t('nav.team'),
diff --git a/packages/seller-dashboard/src/pages/onboarding.tsx b/packages/seller-dashboard/src/pages/onboarding.tsx
new file mode 100644
index 0000000000..47d6112600
--- /dev/null
+++ b/packages/seller-dashboard/src/pages/onboarding.tsx
@@ -0,0 +1,338 @@
+import {
+ Badge,
+ Button,
+ Card,
+ CardContent,
+ CardHeader,
+ CardTitle,
+ Progress,
+ Textarea,
+} from '@spree/dashboard-ui'
+import type { RequirementStatus } from '@spree/seller-sdk'
+import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
+import { Link, useParams } from '@tanstack/react-router'
+import {
+ CheckCircle2Icon,
+ ChevronRightIcon,
+ CircleIcon,
+ ClockIcon,
+ ExternalLinkIcon,
+ XCircleIcon,
+} from 'lucide-react'
+import { useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import { toast } from 'sonner'
+import { sellerClient } from '../api-client'
+import { CenteredMessage } from '../components/centered-message'
+
+/**
+ * What the marketplace asks of this seller before admitting them.
+ *
+ * Deliberately one page rather than a wizard: the checklist is not ordered by
+ * dependency, a seller can do these in any order, and several are things they
+ * have to go away and come back for (a document to find, an account to open).
+ * A wizard would trap them at step two.
+ *
+ * Every line and the progress bar render from `GET /seller/onboarding` and
+ * nothing else — the same evaluator the operator reads, so the two can never
+ * disagree about what is outstanding.
+ */
+export function OnboardingPage() {
+ const { t } = useTranslation()
+ const { sellerId } = useParams({ from: '/_authenticated/$sellerId' })
+ const queryClient = useQueryClient()
+
+ const { data, isLoading, error } = useQuery({
+ queryKey: ['seller', sellerId, 'onboarding'],
+ queryFn: () => sellerClient().onboarding.get(),
+ })
+
+ const submit = useMutation({
+ mutationFn: () => sellerClient().onboarding.submitForReview(),
+ onSuccess: (next) => {
+ queryClient.setQueryData(['seller', sellerId, 'onboarding'], next)
+ toast.success(t('onboarding.submitted'))
+ },
+ // The server names what is outstanding; showing our own wording instead
+ // would tell the seller less than the API already knows.
+ onError: (err) => toast.error(err instanceof Error ? err.message : t('common.error')),
+ })
+
+ if (isLoading) return <CenteredMessage>{t('common.loading')}</CenteredMessage>
+ if (error || !data) return <CenteredMessage>{t('common.error')}</CenteredMessage>
+
+ const { progress, requirements, status } = data
+ const blocking = requirements.filter((requirement) => requirement.blocking)
+ const submitted = status === 'ready_for_review'
+
+ return (
+ <div className="mx-auto flex max-w-3xl flex-col gap-6">
+ <div>
+ <h1 className="font-medium text-2xl">{t('onboarding.title')}</h1>
+ <p className="text-muted-foreground text-sm">{t('onboarding.subtitle')}</p>
+ </div>
+
+ <Card>
+ <CardHeader className="flex-row items-center justify-between gap-4">
+ <CardTitle>{t('onboarding.progress_title')}</CardTitle>
+ <Badge variant={progress.percentage === 100 ? 'success' : 'secondary'}>
+ {t('onboarding.progress_count', { done: progress.done, total: progress.total })}
+ </Badge>
+ </CardHeader>
+ <CardContent className="flex flex-col gap-4">
+ <Progress value={progress.percentage} />
+
+ {submitted ? (
+ <p className="text-muted-foreground text-sm">{t('onboarding.under_review')}</p>
+ ) : (
+ <div className="flex items-center justify-between gap-4">
+ <p className="text-muted-foreground text-sm">
+ {blocking.length === 0
+ ? t('onboarding.ready')
+ : t('onboarding.remaining', { count: blocking.length })}
+ </p>
+ <Button
+ size="sm"
+ disabled={blocking.length > 0 || submit.isPending}
+ onClick={() => submit.mutate()}
+ >
+ {submit.isPending ? t('onboarding.submitting') : t('onboarding.submit')}
+ </Button>
+ </div>
+ )}
+ </CardContent>
+ </Card>
+
+ {requirements.length > 0 && (
+ <div className="flex flex-col gap-3">
+ {requirements.map((requirement) => (
+ <RequirementCard
+ key={requirement.id}
+ requirement={requirement}
+ // Open the first outstanding line and collapse the rest: it
+ // answers "what do I do next" without the seller hunting for it.
+ defaultOpen={requirement.id === firstOutstanding(requirements)?.id}
+ />
+ ))}
+ </div>
+ )}
+ </div>
+ )
+}
+
+function firstOutstanding(requirements: RequirementStatus[]): RequirementStatus | undefined {
+ return requirements.find((requirement) => requirement.status !== 'complete')
+}
+
+function RequirementCard({
+ requirement,
+ defaultOpen,
+}: {
+ requirement: RequirementStatus
+ defaultOpen: boolean
+}) {
+ const { t } = useTranslation()
+ const [open, setOpen] = useState(defaultOpen)
+
+ return (
+ <Card className="overflow-hidden">
+ <button
+ type="button"
+ onClick={() => setOpen((previous) => !previous)}
+ className="flex w-full cursor-pointer items-center gap-3 p-4 text-left hover:bg-muted/50"
+ >
+ <StatusIcon status={requirement.status} />
+ <div className="flex min-w-0 flex-col">
+ <span className="font-medium text-sm">{requirement.name}</span>
+ {!requirement.required && (
+ <span className="text-muted-foreground text-xs">{t('onboarding.optional')}</span>
+ )}
+ </div>
+ <StatusBadge status={requirement.status} />
+ <ChevronRightIcon
+ className={`ml-auto size-4 shrink-0 text-muted-foreground transition-transform ${
+ open ? 'rotate-90' : ''
+ }`}
+ />
+ </button>
+
+ {open && (
+ <CardContent className="flex flex-col gap-3 border-t pt-4">
+ {requirement.description && (
+ <p className="text-muted-foreground text-sm">{requirement.description}</p>
+ )}
+ <RequirementAction requirement={requirement} />
+ </CardContent>
+ )}
+ </Card>
+ )
+}
+
+/**
+ * What the seller does about one line, keyed off `kind`.
+ *
+ * The server decides which kinds exist and what each means; this only decides
+ * how to ask. An unrecognised kind — one a provider gem added — still renders
+ * its name, description and any `action_url`, so a new kind is useful here
+ * before this file knows about it.
+ */
+function RequirementAction({ requirement }: { requirement: RequirementStatus }) {
+ const { t } = useTranslation()
+ const { sellerId } = useParams({ from: '/_authenticated/$sellerId' })
+ const queryClient = useQueryClient()
+ const [note, setNote] = useState('')
+
+ const invalidate = () =>
+ queryClient.invalidateQueries({ queryKey: ['seller', sellerId, 'onboarding'] })
+
+ const acceptTerms = useMutation({
+ mutationFn: () => sellerClient().profile.update({ accept_terms: true }),
+ onSuccess: () => {
+ toast.success(t('onboarding.terms_accepted'))
+ void invalidate()
+ },
+ onError: (err) => toast.error(err instanceof Error ? err.message : t('common.error')),
+ })
+
+ const attest = useMutation({
+ mutationFn: () =>
+ sellerClient().requirementSubmissions.create(requirement.id, { note: note || undefined }),
+ onSuccess: () => {
+ setNote('')
+ toast.success(t('onboarding.submitted_requirement'))
+ void invalidate()
+ },
+ onError: (err) => toast.error(err instanceof Error ? err.message : t('common.error')),
+ })
+
+ const submission = requirement.submission
+
+ // A rejection the seller cannot read is a rejection they cannot act on.
+ const rejection = submission?.status === 'rejected' && submission.review_note && (
+ <p className="rounded-md bg-destructive/10 p-3 text-destructive text-sm">
+ {submission.review_note}
+ </p>
+ )
+
+ if (requirement.status === 'complete') {
+ return (
+ <>
+ {rejection}
+ <p className="text-muted-foreground text-sm">{t('onboarding.done')}</p>
+ </>
+ )
+ }
+
+ if (requirement.status === 'pending') {
+ return (
+ <>
+ {rejection}
+ <p className="text-muted-foreground text-sm">{t('onboarding.awaiting_review')}</p>
+ </>
+ )
+ }
+
+ return (
+ <>
+ {rejection}
+
+ {requirement.kind === 'accept_terms' && (
+ <div className="flex justify-start">
+ <Button size="sm" disabled={acceptTerms.isPending} onClick={() => acceptTerms.mutate()}>
+ {t('onboarding.accept_terms')}
+ </Button>
+ </div>
+ )}
+
+ {requirement.kind === 'attestation' && (
+ <div className="flex flex-col gap-2">
+ <Textarea
+ rows={2}
+ value={note}
+ placeholder={t('onboarding.note_placeholder')}
+ onChange={(event) => setNote(event.target.value)}
+ />
+ <div className="flex justify-start">
+ <Button size="sm" disabled={attest.isPending} onClick={() => attest.mutate()}>
+ {t('onboarding.confirm')}
+ </Button>
+ </div>
+ </div>
+ )}
+
+ {/* Kinds whose work happens on a page this panel already has. The
+ server cannot supply these: `action_url` is for somewhere it knows
+ about (a provider's hosted flow), and it has no idea how this panel
+ routes. Anything unmapped falls through to `action_url` below, so a
+ kind added by a gem still gets a way in without this file changing. */}
+ {panelRoute(requirement.kind) && (
+ <div className="flex justify-start">
+ <Button size="sm" asChild>
+ <Link to={panelRoute(requirement.kind)!} params={{ sellerId }}>
+ {t('onboarding.go')}
+ <ChevronRightIcon className="size-4" />
+ </Link>
+ </Button>
+ </div>
+ )}
+
+ {requirement.action_url && (
+ <div className="flex justify-start">
+ <Button size="sm" variant="outline" asChild>
+ <a href={requirement.action_url} target="_blank" rel="noreferrer">
+ {t('onboarding.go')}
+ <ExternalLinkIcon className="size-4" />
+ </a>
+ </Button>
+ </div>
+ )}
+ </>
+ )
+}
+
+/**
+ * Where in this panel a seller goes to satisfy a kind.
+ *
+ * Deliberately a short map rather than a per-kind component: these lines say
+ * "go and fill that in", and the page that owns the form already exists. A
+ * kind that is not here renders its description and any `action_url`, which
+ * is what makes a provider's kind useful before this file knows it exists.
+ */
+function panelRoute(kind: string): string | undefined {
+ switch (kind) {
+ case 'billing_address':
+ case 'returns_address':
+ case 'complete_profile':
+ case 'required_custom_fields':
+ return '/$sellerId'
+ // `minimum_products` belongs here too, once the panel has a products
+ // page — until then it falls through and reads as a plain instruction
+ // rather than a link to nowhere.
+ default:
+ return undefined
+ }
+}
+
+function StatusIcon({ status }: { status: string }) {
+ if (status === 'complete') {
+ return <CheckCircle2Icon className="size-4 shrink-0 text-green-600" />
+ }
+ if (status === 'pending') {
+ return <ClockIcon className="size-4 shrink-0 text-amber-600" />
+ }
+ if (status === 'rejected') {
+ return <XCircleIcon className="size-4 shrink-0 text-destructive" />
+ }
+ return <CircleIcon className="size-4 shrink-0 text-muted-foreground" />
+}
+
+function StatusBadge({ status }: { status: string }) {
+ const { t } = useTranslation()
+
+ if (status === 'complete')
+ return <Badge variant="success">{t('onboarding.status.complete')}</Badge>
+ if (status === 'pending') return <Badge variant="warning">{t('onboarding.status.pending')}</Badge>
+ if (status === 'rejected')
+ return <Badge variant="destructive">{t('onboarding.status.rejected')}</Badge>
+ return null
+}
diff --git a/packages/seller-dashboard/src/routeTree.gen.ts b/packages/seller-dashboard/src/routeTree.gen.ts
index 21a33cd7ed..b60866b5db 100644
--- a/packages/seller-dashboard/src/routeTree.gen.ts
+++ b/packages/seller-dashboard/src/routeTree.gen.ts
@@ -16,6 +16,7 @@ import { Route as acceptInvitationDotinvitationIdRouteImport } from './routes/ac
import { Route as authenticatedSellerIdRouteImport } from './routes/_authenticated/$sellerId'
import { Route as IndexRouteImport } from './routes/_authenticated/$sellerId/index'
import { Route as TeamRouteImport } from './routes/_authenticated/$sellerId/team'
+import { Route as OnboardingRouteImport } from './routes/_authenticated/$sellerId/onboarding'
const loginRoute = loginRouteImport.update({
id: '/login',
@@ -52,12 +53,18 @@ const TeamRoute = TeamRouteImport.update({
path: '/team',
getParentRoute: () => authenticatedSellerIdRoute,
} as any)
+const OnboardingRoute = OnboardingRouteImport.update({
+ id: '/onboarding',
+ path: '/onboarding',
+ getParentRoute: () => authenticatedSellerIdRoute,
+} as any)
export interface FileRoutesByFullPath {
'/': typeof authenticatedIndexRoute
'/login': typeof loginRoute
'/$sellerId': typeof authenticatedSellerIdRouteWithChildren
'/accept-invitation/$invitationId': typeof acceptInvitationDotinvitationIdRoute
+ '/$sellerId/onboarding': typeof OnboardingRoute
'/$sellerId/team': typeof TeamRoute
'/$sellerId/': typeof IndexRoute
}
@@ -65,6 +72,7 @@ export interface FileRoutesByTo {
'/login': typeof loginRoute
'/accept-invitation/$invitationId': typeof acceptInvitationDotinvitationIdRoute
'/': typeof authenticatedIndexRoute
+ '/$sellerId/onboarding': typeof OnboardingRoute
'/$sellerId/team': typeof TeamRoute
'/$sellerId': typeof IndexRoute
}
@@ -75,6 +83,7 @@ export interface FileRoutesById {
'/_authenticated/$sellerId': typeof authenticatedSellerIdRouteWithChildren
'/accept-invitation/$invitationId': typeof acceptInvitationDotinvitationIdRoute
'/_authenticated/': typeof authenticatedIndexRoute
+ '/_authenticated/$sellerId/onboarding': typeof OnboardingRoute
'/_authenticated/$sellerId/team': typeof TeamRoute
'/_authenticated/$sellerId/': typeof IndexRoute
}
@@ -85,6 +94,7 @@ export interface FileRouteTypes {
| '/login'
| '/$sellerId'
| '/accept-invitation/$invitationId'
+ | '/$sellerId/onboarding'
| '/$sellerId/team'
| '/$sellerId/'
fileRoutesByTo: FileRoutesByTo
@@ -92,6 +102,7 @@ export interface FileRouteTypes {
| '/login'
| '/accept-invitation/$invitationId'
| '/'
+ | '/$sellerId/onboarding'
| '/$sellerId/team'
| '/$sellerId'
id:
@@ -101,6 +112,7 @@ export interface FileRouteTypes {
| '/_authenticated/$sellerId'
| '/accept-invitation/$invitationId'
| '/_authenticated/'
+ | '/_authenticated/$sellerId/onboarding'
| '/_authenticated/$sellerId/team'
| '/_authenticated/$sellerId/'
fileRoutesById: FileRoutesById
@@ -162,15 +174,24 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof TeamRouteImport
parentRoute: typeof authenticatedSellerIdRoute
}
+ '/_authenticated/$sellerId/onboarding': {
+ id: '/_authenticated/$sellerId/onboarding'
+ path: '/onboarding'
+ fullPath: '/$sellerId/onboarding'
+ preLoaderRoute: typeof OnboardingRouteImport
+ parentRoute: typeof authenticatedSellerIdRoute
+ }
}
}
interface authenticatedSellerIdRouteChildren {
+ OnboardingRoute: typeof OnboardingRoute
TeamRoute: typeof TeamRoute
IndexRoute: typeof IndexRoute
}
const authenticatedSellerIdRouteChildren: authenticatedSellerIdRouteChildren = {
+ OnboardingRoute: OnboardingRoute,
TeamRoute: TeamRoute,
IndexRoute: IndexRoute,
}
diff --git a/packages/seller-dashboard/src/routes/_authenticated/$sellerId/onboarding.tsx b/packages/seller-dashboard/src/routes/_authenticated/$sellerId/onboarding.tsx
new file mode 100644
index 0000000000..6bfa49ddd9
--- /dev/null
+++ b/packages/seller-dashboard/src/routes/_authenticated/$sellerId/onboarding.tsx
@@ -0,0 +1,6 @@
+import { createFileRoute } from '@tanstack/react-router'
+import { OnboardingPage } from '../../../pages/onboarding'
+
+export const Route = createFileRoute('/_authenticated/$sellerId/onboarding')({
+ component: OnboardingPage,
+})
diff --git a/packages/seller-sdk/src/index.ts b/packages/seller-sdk/src/index.ts
index d320398b2f..9cef674cbf 100644
--- a/packages/seller-sdk/src/index.ts
+++ b/packages/seller-sdk/src/index.ts
@@ -8,9 +8,11 @@ export type { Client, Client as SellerApiClient, SellerClientConfig } from './cl
export { createSellerClient } from './client'
export type {
MeResponse,
+ OnboardingResponse,
PermissionRule,
ProductParams,
ProfileUpdateParams,
+ RequirementSubmissionParams,
SellerAddressParams,
} from './seller-client'
// Client class, for advanced use and subclassing
diff --git a/packages/seller-sdk/src/seller-client.ts b/packages/seller-sdk/src/seller-client.ts
index bb33d703ae..a5aa15342f 100644
--- a/packages/seller-sdk/src/seller-client.ts
+++ b/packages/seller-sdk/src/seller-client.ts
@@ -1,6 +1,15 @@
import type { ListParams, ListResponse, RequestFn, RequestOptions } from '@spree/sdk-core'
import { transformListParams } from '@spree/sdk-core'
-import type { AuthTokens, Invitation, Product, Profile, SellerSummary, TeamMember } from './types'
+import type {
+ AuthTokens,
+ Invitation,
+ Product,
+ Profile,
+ RequirementStatus,
+ RequirementSubmission,
+ SellerSummary,
+ TeamMember,
+} from './types'
/**
* Resource methods for the Spree Seller API — the marketplace seller panel.
@@ -113,6 +122,44 @@ export class SellerClient {
this.request<void>('DELETE', `/team/${id}`, options),
}
+ /**
+ * What the marketplace asks of this seller before it will admit them.
+ *
+ * Singular: the checklist is always the acting seller's. Every answer is
+ * computed server-side by the one evaluator the operator's view also uses,
+ * so the panel and the operator cannot show different progress.
+ */
+ readonly onboarding = {
+ get: (options?: RequestOptions): Promise<OnboardingResponse> =>
+ this.request<OnboardingResponse>('GET', '/onboarding', options),
+
+ /**
+ * Says the seller is ready. Refused with the blocking requirements named
+ * when something required is still outstanding.
+ */
+ submitForReview: (options?: RequestOptions): Promise<OnboardingResponse> =>
+ this.request<OnboardingResponse>('POST', '/onboarding/submit_for_review', options),
+ }
+
+ /**
+ * What the seller submits about one requirement: an attestation they tick,
+ * a document they upload, a reference they paste.
+ *
+ * Create only — a submission records what was said and when, so the seller
+ * submits again rather than editing, and the latest one counts.
+ */
+ readonly requirementSubmissions = {
+ create: (
+ requirementId: string,
+ params: RequirementSubmissionParams,
+ options?: RequestOptions,
+ ): Promise<RequirementSubmission> =>
+ this.request<RequirementSubmission>('POST', `/requirements/${requirementId}/submissions`, {
+ ...options,
+ body: params,
+ }),
+ }
+
/**
* Offers nobody has accepted yet.
*
@@ -163,6 +210,23 @@ export class SellerClient {
}
}
+/** What `/seller/onboarding` answers. */
+export interface OnboardingResponse {
+ /** The seller's lifecycle status, e.g. `onboarding`, `ready_for_review`. */
+ status: string
+ /** Optional requirements included — this is how far along, not how close to approval. */
+ progress: { done: number; total: number; percentage: number }
+ requirements: RequirementStatus[]
+}
+
+/** What a seller says about one requirement. */
+export interface RequirementSubmissionParams {
+ note?: string
+ reference?: string
+ /** A direct-upload signed blob id, for kinds that ask for a document. */
+ file?: string
+}
+
/** The fields a seller may set on their own product. */
export interface ProductParams {
name?: string
@@ -217,6 +281,11 @@ export interface ProfileUpdateParams {
cover_photo?: string | null
billing_address?: SellerAddressParams
returns_address?: SellerAddressParams
+ /**
+ * Accepts the marketplace's terms, stamping the moment. One-way: the stamp
+ * records that it happened, so sending `false` does not unmake it.
+ */
+ accept_terms?: boolean
}
export interface SellerAddressParams {
diff --git a/packages/seller-sdk/src/types/generated/RequirementStatus.ts b/packages/seller-sdk/src/types/generated/RequirementStatus.ts
new file mode 100644
index 0000000000..bb561f039f
--- /dev/null
+++ b/packages/seller-sdk/src/types/generated/RequirementStatus.ts
@@ -0,0 +1,19 @@
+// Typelizer digest be0c4985af14b02c335f192aa17291c0
+//
+// DO NOT MODIFY: This file was automatically generated by Typelizer.
+import type {RequirementSubmission} from '@/types'
+
+type RequirementStatus = {
+ id: string;
+ kind: string;
+ name: string;
+ description: string | null;
+ required: boolean;
+ position: number;
+ status: string;
+ action_url: string | null;
+ blocking: boolean;
+ submission?: RequirementSubmission;
+}
+
+export default RequirementStatus;
diff --git a/packages/seller-sdk/src/types/generated/RequirementSubmission.ts b/packages/seller-sdk/src/types/generated/RequirementSubmission.ts
new file mode 100644
index 0000000000..711b26b930
--- /dev/null
+++ b/packages/seller-sdk/src/types/generated/RequirementSubmission.ts
@@ -0,0 +1,18 @@
+// Typelizer digest 099240428d575e6d9c98a42880cd84df
+//
+// DO NOT MODIFY: This file was automatically generated by Typelizer.
+
+type RequirementSubmission = {
+ id: string;
+ status: string;
+ note: string | null;
+ review_note: string | null;
+ reference: string | null;
+ reviewed_at: string | null;
+ created_at: string;
+ updated_at: string;
+ file_url: string | null;
+ file_name: string | null;
+}
+
+export default RequirementSubmission;
diff --git a/packages/seller-sdk/src/types/generated/index.ts b/packages/seller-sdk/src/types/generated/index.ts
index 059b57c18c..00d8818031 100644
--- a/packages/seller-sdk/src/types/generated/index.ts
+++ b/packages/seller-sdk/src/types/generated/index.ts
@@ -1,4 +1,4 @@
-// Typelizer digest c91458a759831a127619fdc0158cbfaa
+// Typelizer digest 42ccaa2ead92516bdbee62661c391b25
//
// DO NOT MODIFY: This file was automatically generated by Typelizer.
export type { default as Address } from './Address'
@@ -12,6 +12,8 @@ export type { default as Price } from './Price'
export type { default as Invitation } from './Invitation'
export type { default as Product } from './Product'
export type { default as Profile } from './Profile'
+export type { default as RequirementStatus } from './RequirementStatus'
+export type { default as RequirementSubmission } from './RequirementSubmission'
export type { default as TeamMember } from './TeamMember'
export type { default as Seller } from './Seller'
export type { default as Variant } from './Variant'
diff --git a/spree/api/app/controllers/spree/api/v3/seller/onboarding_controller.rb b/spree/api/app/controllers/spree/api/v3/seller/onboarding_controller.rb
new file mode 100644
index 0000000000..cb38e92868
--- /dev/null
+++ b/spree/api/app/controllers/spree/api/v3/seller/onboarding_controller.rb
@@ -0,0 +1,65 @@
+module Spree
+ module Api
+ module V3
+ module Seller
+ # What the marketplace asks of this seller, and how far along they are.
+ #
+ # Singular by nature: there is exactly one seller in play and it is
+ # `current_seller`, never an id from the request. The checklist is
+ # computed on read through the one evaluator the operator's view and
+ # the approval gate also use, so the panel and the operator can never
+ # be looking at different answers.
+ class OnboardingController < Seller::BaseController
+ scoped_resource :seller_profile
+
+ # GET /api/v3/seller/onboarding
+ def show
+ render json: onboarding_payload
+ end
+
+ # POST /api/v3/seller/onboarding/submit_for_review
+ #
+ # The seller says they are ready. Refused with the blocking
+ # requirements named — a bare "not ready" leaves them guessing which
+ # of eight things it meant.
+ def submit_for_review
+ result = Spree.seller_submit_for_review_workflow.call(
+ seller: current_seller,
+ submitted_by: try_spree_current_user
+ )
+
+ return render_service_error(result.error) unless result.success?
+
+ render json: onboarding_payload
+ end
+
+ protected
+
+ def read_actions
+ %w[show]
+ end
+
+ private
+
+ def requirements
+ @requirements ||= Spree::Sellers::Requirements.new(current_seller.reload)
+ end
+
+ def onboarding_payload
+ {
+ status: current_seller.status,
+ progress: requirements.progress,
+ requirements: requirements.statuses.map { |status| serialize_status(status) }
+ }
+ end
+
+ def serialize_status(status)
+ Spree.api.seller_requirement_status_serializer.new(
+ status, params: { store: current_store }
+ ).to_h
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/spree/api/app/controllers/spree/api/v3/seller/profile_controller.rb b/spree/api/app/controllers/spree/api/v3/seller/profile_controller.rb
index 84513b86e7..53de30fd44 100644
--- a/spree/api/app/controllers/spree/api/v3/seller/profile_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/seller/profile_controller.rb
@@ -25,7 +25,7 @@ module Spree
end
def update
- if current_seller.update(permitted_params)
+ if current_seller.update(permitted_params.merge(terms_attributes))
render json: serialize_seller
else
render_validation_error(current_seller.errors)
@@ -50,6 +50,18 @@ module Spree
:postal_code, :zipcode, :phone, :country_code, :state_code, :state_name, :label
].freeze
+ # Accepting the marketplace's terms is a profile write, not an endpoint
+ # of its own: `accept_terms: true` stamps the time, which is what the
+ # AcceptTerms requirement reads. Deliberately one-way — a seller
+ # cannot un-accept by sending `false`, since the stamp is a record
+ # that it happened.
+ def terms_attributes
+ return {} unless ActiveModel::Type::Boolean.new.cast(params[:accept_terms])
+ return {} if current_seller.terms_accepted_at.present?
+
+ { terms_accepted_at: Time.current }
+ end
+
def permitted_params
normalize_params(
params.permit(:name, :contact_email, :billing_email, :about,
diff --git a/spree/api/app/controllers/spree/api/v3/seller/requirement_submissions_controller.rb b/spree/api/app/controllers/spree/api/v3/seller/requirement_submissions_controller.rb
new file mode 100644
index 0000000000..1de9dcb8af
--- /dev/null
+++ b/spree/api/app/controllers/spree/api/v3/seller/requirement_submissions_controller.rb
@@ -0,0 +1,86 @@
+module Spree
+ module Api
+ module V3
+ module Seller
+ # What a seller submits about one requirement: an attestation they
+ # tick, a document they upload, a reference they paste.
+ #
+ # Create only. A submission records what was said and when — editing
+ # one would rewrite that history, and withdrawing is not a thing a
+ # seller does: they submit again, and the latest one counts. Accepting,
+ # rejecting and waiving belong to the operator, on their own branch.
+ class RequirementSubmissionsController < Seller::BaseController
+ scoped_resource :seller_profile
+
+ before_action :set_requirement, only: [:create]
+ before_action :set_submission, only: [:download]
+
+ # POST /api/v3/seller/requirements/:requirement_id/submissions
+ def create
+ result = Spree.seller_requirement_submission_create_workflow.call(
+ seller: current_seller,
+ requirement: @requirement,
+ note: params[:note],
+ reference: params[:reference],
+ file: params[:file],
+ submitted_by: try_spree_current_user
+ )
+
+ return render_service_error(result.error) unless result.success?
+
+ render json: serialize(result.value), status: :created
+ end
+
+ # GET /api/v3/seller/requirement_submissions/:id/download
+ #
+ # Authorized per request rather than served from a storage URL:
+ # these are identity documents, and a link that works for anyone
+ # holding it is not a property we want them to have.
+ def download
+ unless @submission.file.attached?
+ return render_error(
+ code: ErrorHandler::ERROR_CODES[:validation_error],
+ message: Spree.t(:seller_submission_no_file),
+ status: :unprocessable_content
+ )
+ end
+
+ send_data(
+ @submission.file.download,
+ filename: @submission.file.filename.to_s,
+ type: @submission.file.content_type,
+ disposition: 'attachment'
+ )
+ end
+
+ protected
+
+ def read_actions
+ %w[download]
+ end
+
+ private
+
+ # Through the store's own checklist: a requirement id belonging to
+ # another marketplace 404s rather than letting a seller submit
+ # against someone else's configuration.
+ def set_requirement
+ @requirement = current_store.seller_requirements.find_by_prefix_id!(params[:requirement_id])
+ end
+
+ # Through the seller, so one seller can never read another's
+ # documents.
+ def set_submission
+ @submission = current_seller.requirement_submissions.find_by_prefix_id!(params[:id])
+ end
+
+ def serialize(submission)
+ Spree.api.seller_requirement_submission_serializer.new(
+ submission, params: { store: current_store }
+ ).to_h
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/spree/api/app/serializers/spree/api/v3/seller/requirement_status_serializer.rb b/spree/api/app/serializers/spree/api/v3/seller/requirement_status_serializer.rb
new file mode 100644
index 0000000000..4853ef7c11
--- /dev/null
+++ b/spree/api/app/serializers/spree/api/v3/seller/requirement_status_serializer.rb
@@ -0,0 +1,43 @@
+module Spree
+ module Api
+ module V3
+ module Seller
+ # One line of this seller's onboarding checklist.
+ #
+ # A value object, so no id of its own: the `id` is the requirement it
+ # came from, which is what the panel posts a submission against.
+ #
+ # `blocking` is serialized rather than derived client-side so the
+ # panel's "what is stopping me" list and the server's refusal on
+ # submit-for-review cannot disagree. `kind` is what the panel keys
+ # presentation off — which line gets a file picker, which gets a
+ # checkbox, which just links away.
+ #
+ # Includes Alba directly instead of inheriting BaseSerializer, as the
+ # operator's twin does: the base renders `id` by calling
+ # `object.prefixed_id`, and this is a value object whose `id` is
+ # already a prefixed id string. Inheriting would render `id: nil` and
+ # cost the panel the one field it posts submissions against.
+ class RequirementStatusSerializer
+ include Alba::Resource
+ include Typelizer::DSL
+
+ typelize id: :string, kind: :string, name: :string,
+ description: [:string, nullable: true],
+ required: :boolean, position: :number, status: :string,
+ blocking: :boolean, action_url: [:string, nullable: true]
+
+ attributes :id, :kind, :name, :description, :required, :position, :status, :action_url
+
+ attribute :blocking do |status|
+ status.blocking?
+ end
+
+ one :submission,
+ resource: proc { Spree.api.seller_requirement_submission_serializer },
+ if: proc { |status| status.submission.present? }
+ end
+ end
+ end
+ end
+end
diff --git a/spree/api/app/serializers/spree/api/v3/seller/requirement_submission_serializer.rb b/spree/api/app/serializers/spree/api/v3/seller/requirement_submission_serializer.rb
new file mode 100644
index 0000000000..51c33dd2a4
--- /dev/null
+++ b/spree/api/app/serializers/spree/api/v3/seller/requirement_submission_serializer.rb
@@ -0,0 +1,47 @@
+module Spree
+ module Api
+ module V3
+ module Seller
+ # What this seller submitted about one requirement, and what the
+ # marketplace made of it.
+ #
+ # Narrower than the operator's view on purpose: no `seller_id` (there
+ # is exactly one seller in play and it is the caller), no
+ # `requirement_name` (the checklist line already carries it), and no
+ # `metadata` — that is the operator's and any provider's workspace,
+ # not something a seller reads back.
+ #
+ # `review_note` IS included: a rejection the seller cannot read is a
+ # rejection they cannot act on.
+ class RequirementSubmissionSerializer < V3::BaseSerializer
+ typelize status: :string, note: [:string, nullable: true],
+ review_note: [:string, nullable: true],
+ reference: [:string, nullable: true],
+ reviewed_at: [:string, nullable: true],
+ file_url: [:string, nullable: true],
+ file_name: [:string, nullable: true]
+
+ attributes :status, :note, :review_note, :reference,
+ reviewed_at: :iso8601,
+ created_at: :iso8601,
+ updated_at: :iso8601
+
+ # This API's own download action, not a storage URL: these are
+ # identity documents, so each download is authorized per request
+ # rather than readable by anyone holding the link.
+ attribute :file_url do |submission|
+ next nil unless submission.file.attached?
+
+ Spree::Core::Engine.routes.url_helpers.download_api_v3_seller_requirement_submission_path(
+ id: submission.prefixed_id
+ )
+ end
+
+ attribute :file_name do |submission|
+ submission.file.attached? ? submission.file.filename.to_s : nil
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/spree/api/config/routes.rb b/spree/api/config/routes.rb
index f4e2fd502b..44f9d31788 100644
--- a/spree/api/config/routes.rb
+++ b/spree/api/config/routes.rb
@@ -685,6 +685,23 @@ Spree::Core::Engine.add_routes do
# A seller's own catalog. The first collection on this branch, and the
# shape every later one follows — rooted in the seller by the anchor.
resources :products, only: [:index, :show, :create, :update, :destroy]
+
+ # What the marketplace asks of this seller. Singular: the checklist is
+ # always `current_seller`'s, never an id from the request.
+ resource :onboarding, only: [:show], controller: 'onboarding' do
+ post :submit_for_review
+ end
+
+ # Submissions are created against a requirement and read back through
+ # the seller who made them.
+ resources :requirements, only: [] do
+ resources :submissions, only: [:create], controller: 'requirement_submissions'
+ end
+ resources :requirement_submissions, only: [] do
+ member do
+ get :download
+ end
+ end
end
# Webhooks (outside of store namespace — no API key authentication)
diff --git a/spree/api/lib/spree/api/dependencies.rb b/spree/api/lib/spree/api/dependencies.rb
index 36cf88a327..ce897e3f2e 100644
--- a/spree/api/lib/spree/api/dependencies.rb
+++ b/spree/api/lib/spree/api/dependencies.rb
@@ -160,6 +160,8 @@ module Spree
seller_team_member_serializer: 'Spree::Api::V3::Seller::TeamMemberSerializer',
seller_invitation_serializer: 'Spree::Api::V3::Seller::InvitationSerializer',
seller_product_serializer: 'Spree::Api::V3::Seller::ProductSerializer',
+ seller_requirement_status_serializer: 'Spree::Api::V3::Seller::RequirementStatusSerializer',
+ seller_requirement_submission_serializer: 'Spree::Api::V3::Seller::RequirementSubmissionSerializer',
admin_seller_serializer: 'Spree::Api::V3::Admin::SellerSerializer',
admin_seller_requirement_serializer: 'Spree::Api::V3::Admin::SellerRequirementSerializer',
admin_seller_requirement_submission_serializer: 'Spree::Api::V3::Admin::SellerRequirementSubmissionSerializer',
diff --git a/spree/api/spec/controllers/spree/api/v3/seller/onboarding_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/seller/onboarding_controller_spec.rb
new file mode 100644
index 0000000000..a9dc051ad8
--- /dev/null
+++ b/spree/api/spec/controllers/spree/api/v3/seller/onboarding_controller_spec.rb
@@ -0,0 +1,95 @@
+require 'spec_helper'
+
+RSpec.describe Spree::Api::V3::Seller::OnboardingController, type: :controller do
+ render_views
+
+ include_context 'API v3 Seller'
+
+ let(:seller) { create(:seller, :onboarding, store: store) }
+ 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
+
+ before do
+ store.seller_requirements.destroy_all
+ request.headers['Authorization'] = "Bearer #{token}"
+ request.headers['X-Spree-Seller-Id'] = seller.prefixed_id
+ end
+
+ describe 'GET #show' do
+ it 'reads as finished when the marketplace asks for nothing' do
+ get :show, as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(json_response['progress']).to include('done' => 0, 'total' => 0, 'percentage' => 100)
+ expect(json_response['requirements']).to eq([])
+ end
+
+ it 'returns the checklist with the seller current standing' do
+ create(:accept_terms_requirement, store: store)
+ create(:billing_address_requirement, store: store)
+ seller.update!(terms_accepted_at: Time.current)
+
+ get :show, as: :json
+
+ expect(json_response['status']).to eq('onboarding')
+ expect(json_response['progress']).to include('done' => 1, 'total' => 2, 'percentage' => 50)
+
+ terms, billing = json_response['requirements'].sort_by { |r| r['position'] }
+ expect(terms).to include('kind' => 'accept_terms', 'status' => 'complete', 'blocking' => false)
+ expect(billing).to include('kind' => 'billing_address', 'status' => 'incomplete', 'blocking' => true)
+ end
+
+ # The id is what the panel posts a submission against, so losing it to a
+ # value-object/serializer mismatch would be silent and fatal.
+ it 'carries the requirement id each line acts on' do
+ requirement = create(:document_requirement, store: store)
+
+ get :show, as: :json
+
+ expect(json_response['requirements'].first['id']).to eq(requirement.prefixed_id)
+ end
+
+ # Naming a seller they do not belong to resolves no `current_seller` at
+ # all, so the request is refused before any checklist is read — there is
+ # no path here that reads another seller's requirements.
+ it "shows another seller's checklist to nobody" do
+ other = create(:seller, :onboarding, store: store)
+ request.headers['X-Spree-Seller-Id'] = other.prefixed_id
+
+ get :show, as: :json
+
+ expect(response).to have_http_status(:forbidden)
+ end
+ end
+
+ describe 'POST #submit_for_review' do
+ it 'moves the seller to ready_for_review once the checklist is met' do
+ create(:accept_terms_requirement, store: store)
+ seller.update!(terms_accepted_at: Time.current)
+
+ post :submit_for_review, as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(seller.reload).to be_ready_for_review
+ expect(json_response['status']).to eq('ready_for_review')
+ end
+
+ # A bare "not ready" leaves the seller guessing which of eight things it
+ # meant, so the refusal names what is outstanding.
+ it 'refuses while something required is outstanding, naming it' do
+ create(:billing_address_requirement, store: store)
+
+ post :submit_for_review, as: :json
+
+ expect(response).to have_http_status(:unprocessable_content)
+ expect(response.body).to match(/billing address/i)
+ expect(seller.reload).to be_onboarding
+ end
+ end
+end
diff --git a/spree/api/spec/controllers/spree/api/v3/seller/profile_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/seller/profile_controller_spec.rb
index fdf6e98657..1df57197e0 100644
--- a/spree/api/spec/controllers/spree/api/v3/seller/profile_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/seller/profile_controller_spec.rb
@@ -88,6 +88,27 @@ RSpec.describe Spree::Api::V3::Seller::ProfileController, type: :controller do
end
# Renaming the storefront address breaks every link pointing at it.
+ # Accepting terms is a profile write, not an endpoint of its own — the
+ # AcceptTerms requirement reads the stamp this sets.
+ it 'stamps the moment the seller accepts the terms' do
+ seller.update!(terms_accepted_at: nil)
+
+ expect {
+ patch :update, params: { accept_terms: true }, as: :json
+ }.to change { seller.reload.terms_accepted_at }.from(nil)
+
+ expect(response).to have_http_status(:ok)
+ end
+
+ # The stamp records that it happened; sending false does not unmake it.
+ it 'does not let a seller un-accept the terms' do
+ accepted = 3.days.ago.change(usec: 0)
+ seller.update!(terms_accepted_at: accepted)
+
+ patch :update, params: { accept_terms: false }, as: :json
+
+ expect(seller.reload.terms_accepted_at).to be_within(1.second).of(accepted)
+ end
it 'cannot change its own slug' do
original = seller.slug
diff --git a/spree/api/spec/controllers/spree/api/v3/seller/requirement_submissions_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/seller/requirement_submissions_controller_spec.rb
new file mode 100644
index 0000000000..eefd44270b
--- /dev/null
+++ b/spree/api/spec/controllers/spree/api/v3/seller/requirement_submissions_controller_spec.rb
@@ -0,0 +1,98 @@
+require 'spec_helper'
+
+RSpec.describe Spree::Api::V3::Seller::RequirementSubmissionsController, type: :controller do
+ render_views
+
+ include_context 'API v3 Seller'
+
+ let(:seller) { create(:seller, :onboarding, store: store) }
+ 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
+
+ before do
+ store.seller_requirements.destroy_all
+ request.headers['Authorization'] = "Bearer #{token}"
+ request.headers['X-Spree-Seller-Id'] = seller.prefixed_id
+ end
+
+ describe 'POST #create' do
+ # An attestation is accepted outright: nobody reviews "I confirm".
+ it 'accepts an attestation the seller ticks' do
+ requirement = create(:attestation_requirement, store: store)
+
+ post :create, params: { requirement_id: requirement.prefixed_id, note: 'I confirm' }, as: :json
+
+ expect(response).to have_http_status(:created)
+ expect(json_response).to include('status' => 'accepted', 'note' => 'I confirm')
+ end
+
+ # Something an operator checks lands pending, and stays that way until
+ # they act on it.
+ it 'leaves an operator-reviewed submission pending' do
+ requirement = create(:operator_review_requirement, store: store)
+
+ post :create, params: { requirement_id: requirement.prefixed_id }, as: :json
+
+ expect(response).to have_http_status(:created)
+ expect(json_response['status']).to eq('pending')
+ end
+
+ it 'refuses a document submission with no file' do
+ requirement = create(:document_requirement, store: store)
+
+ post :create, params: { requirement_id: requirement.prefixed_id }, as: :json
+
+ expect(response).to have_http_status(:unprocessable_content)
+ expect(seller.requirement_submissions).to be_empty
+ end
+
+ # A requirement id from another marketplace is not a 403 telling the
+ # seller it exists — it simply is not on their checklist.
+ it "404s on another store's requirement" do
+ other_store = create(:store)
+ theirs = create(:attestation_requirement, store: other_store)
+
+ post :create, params: { requirement_id: theirs.prefixed_id }, as: :json
+
+ expect(response).to have_http_status(:not_found)
+ end
+ end
+
+ describe 'GET #download' do
+ let(:requirement) { create(:document_requirement, store: store) }
+
+ def submission_for(target_seller)
+ create(:seller_requirement_submission, seller: target_seller, requirement: requirement).tap do |submission|
+ submission.file.attach(
+ io: StringIO.new('passport'), filename: 'id.pdf', content_type: 'application/pdf'
+ )
+ end
+ end
+
+ it 'serves the seller their own document' do
+ submission = submission_for(seller)
+
+ get :download, params: { id: submission.prefixed_id }
+
+ expect(response).to have_http_status(:ok)
+ expect(response.body).to eq('passport')
+ end
+
+ # Identity documents: one seller reading another's is the thing this
+ # endpoint exists to make impossible.
+ it "404s on another seller's document" do
+ other = create(:seller, :onboarding, store: store)
+ theirs = submission_for(other)
+
+ get :download, params: { id: theirs.prefixed_id }
+
+ expect(response).to have_http_status(:not_found)
+ end
+ end
+end
diff --git a/spree/core/config/locales/en.yml b/spree/core/config/locales/en.yml
index dfb810dca1..761f600a61 100644
--- a/spree/core/config/locales/en.yml
+++ b/spree/core/config/locales/en.yml
@@ -1568,6 +1568,7 @@ en:
file_required: A file is required for this requirement
file_type_not_accepted: This requirement accepts %{types}
incomplete: "%{name} is not complete"
+ seller_submission_no_file: This submission has no attached file.
seller_team_last_member: A seller needs at least one team member. Invite someone else before removing this one.
send_consumer_transactional_emails: Send Customer Transactional Emails
seo: SEO