Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
Give sellers their own panel, SDK and API surface
Damian Legawiec6e3834782063
diff --git a/docs/plans/6.0-multi-vendor-marketplace.md b/docs/plans/6.0-multi-vendor-marketplace.mdindex 6cad6919ff..d23c9bf22a 100644--- a/docs/plans/6.0-multi-vendor-marketplace.md+++ b/docs/plans/6.0-multi-vendor-marketplace.md@@ -737,6 +737,8 @@ 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.+- **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.- **The storefront sees a seller's profile, never their operational state** (RESOLVED 2026-08-16, shipped). `Spree::Api::V3::SellerSerializer` carries `name`, `slug`, `about`/`about_html` and the three image URLs — and nothing else. `status` and `sellable` are excluded on purpose (a seller a shopper can reach is sellable by definition), along with settlement/tax configuration, contact and billing addresses, team size and every timestamp; a spec asserts the exact key set so nothing leaks in later. The admin serializer extends this one rather than duplicating it, per the house rule. Store endpoints are read-only `index`/`show` scoped to `sellable` — a seller onboarding, suspended or away is neither listed nor fetchable (404), since listing them would advertise products nobody can buy — and resolve by slug or prefixed id so a storefront can route `/sellers/<slug>`. Products expose `seller_id` on **both** APIs without an expand (so a storefront can group or link by seller cheaply) plus `one :seller` behind `?expand=seller`; the admin serializer additionally carries `seller_name` for its list column. `Spree::Product` gains `seller_id` and `seller` to its ransack allowlists — without them the products-table filter silently matches nothing.- **Seller management is staff-only, on its own catalog resource** (RESOLVED 2026-08-16, shipped). `register_resource(:sellers, …)` mints `read_sellers`/`write_sellers` with `Spree::Seller` as its subject, and is deliberately not offered to the `seller` audience — a seller administering other sellers is the one thing the seller key must never allow. `seller_profile` (the seller's own record, on the seller branch) therefore claims no subject, so the subject→resource lookup stays unambiguous.- **Seller principal → `Spree::AdminUser` (`Spree.admin_user_class`), no `SellerUser` model** (RESOLVED 2026-08-15). Reuse the whole shipped auth stack and the RBAC rails (`RoleUser`/`Invitation` on `resource: seller`); membership is by resource type, never `store_id`. Isolation guaranteed at the token layer: own `seller_api` JWT audience, own `Spree.seller_authentication_strategies` + `/seller/auth/*` (so staff can be SSO-only while sellers use passwords; the seller login refuses non-members), `spree_refresh_tokens.audience`. See Decision 10 + `decisions.md` 2026-08-15.diff --git a/packages/dashboard-core/src/api-client.ts b/packages/dashboard-core/src/api-client.tsnew file mode 100644index 0000000000..3269d1a7ec--- /dev/null+++ b/packages/dashboard-core/src/api-client.ts@@ -0,0 +1,101 @@+/**+ * The client registry.+ *+ * `@spree/dashboard-core` is the framework behind more than one panel: the+ * marketplace operator's dashboard talks to the Admin API, a seller's panel+ * talks to the Seller API. Those are different surfaces with different+ * credentials — a seller JWT and `X-Spree-Seller-Id` rather than a secret key+ * and a store header — so the framework cannot own either client. Each host+ * builds its own and registers it here at boot.+ *+ * Only the surface both panels share is typed. Anything admin-only+ * (`customFieldDefinitions`, `exports`, `imports`, store switching) stays on+ * the admin client, imported directly by the code that needs it — typing it+ * here would promise the seller panel methods its API does not have.+ */++import type { PermissionRule } from '@spree/admin-sdk'++/** What the permission provider needs, whichever panel asked. */+export interface PanelPermissions {+ /**+ * CanCanCan rules. The seller panel returns none — its capability is the+ * key list alone — so an empty array is a valid answer, not a failure.+ */+ rules: PermissionRule[]+ keys: string[]+}++/** What every panel's client can do, whichever API it talks to. */+export interface PanelApiClient {+ auth: {+ login(params: { email: string; password: string }): Promise<PanelSession>+ refresh(): Promise<PanelSession>+ logout(): Promise<void>+ /**+ * Admin-only sign-in flows. A seller's panel has none of these: sellers+ * arrive by invitation on the staff rail, and password reset and+ * first-run setup are the marketplace's own.+ */+ acceptInvitation?(id: string, token: string, params: unknown): Promise<PanelSession>+ resetPassword?(token: string, params: unknown): Promise<PanelSession>+ completeSetup?(params: unknown): Promise<PanelSession>+ }+ setToken(token: string): void+ onUnauthorized(handler: () => Promise<boolean>): void+ /**+ * Forgets which tenant the session was acting as — the store on the admin+ * panel, the seller on a seller's. Left set, it rides into the next+ * principal's first requests and 403s them against a tenant they may hold+ * no role on.+ */+ clearTenant?(): void+ /**+ * Reads the signed-in principal's capability. Panel-specific because the+ * two APIs answer different shapes: the admin `/me` returns CanCanCan rules+ * and keys, the seller `/me` returns keys scoped to the selected seller.+ */+ fetchPermissions(): Promise<PanelPermissions>+}++/** What a sign-in returns, whichever panel asked. */+export interface PanelSession {+ token: string+ // Panel-specific: an AdminUser here, the same class through the seller API.+ // Typed loosely so core does not depend on either package's user type.+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ user: any+}++let registered: PanelApiClient | null = null++/**+ * Registers the client for this panel. Call once at boot, before rendering —+ * providers read it on mount.+ */+export function setApiClient(client: PanelApiClient): void {+ registered = client+}++/**+ * The registered client.+ *+ * Throws rather than returning null: a panel that renders without registering+ * one is misconfigured, and every call would otherwise fail somewhere further+ * away with a less useful message.+ */+export function getApiClient(): PanelApiClient {+ if (!registered) {+ throw new Error(+ '@spree/dashboard-core: no API client registered. Call setApiClient(client) at boot, ' ++ 'before rendering the app.',+ )+ }++ return registered+}++/** Whether a client has been registered. For tests and conditional boot paths. */+export function hasApiClient(): boolean {+ return registered !== null+}diff --git a/packages/dashboard-core/src/components/store-switcher.tsx b/packages/dashboard-core/src/components/store-switcher.tsxindex c22b7621d5..4e3626ab30 100644--- a/packages/dashboard-core/src/components/store-switcher.tsx+++ b/packages/dashboard-core/src/components/store-switcher.tsx@@ -91,11 +91,12 @@ export function StoreSwitcher() {>{stores.map((availableStore) => (<DropdownMenuItem key={availableStore.id} asChild>- <Link- to="/$storeId"- params={{ storeId: availableStore.id }}- className="no-underline"- >+ {/* Built as a runtime path rather than a typed literal: core+ is the framework behind more than one panel, and a panel+ with no `/$storeId` route (a seller's) would fail to+ typecheck against a route it never registers. Same approach+ as the nav registries, which take paths as strings. */}+ <Link to={`/${availableStore.id}` as never} className="no-underline"><span className="flex-1 truncate">{availableStore.name}</span>{availableStore.id === store?.id && <CheckIcon className="size-4" />}</Link>diff --git a/packages/dashboard-core/src/index.ts b/packages/dashboard-core/src/index.tsindex 7786ed73f8..469d05fbb2 100644--- a/packages/dashboard-core/src/index.ts+++ b/packages/dashboard-core/src/index.ts@@ -11,6 +11,7 @@// import { AuthProvider } from '@spree/dashboard-core/providers/auth-provider'// import { useResourceMutation } from '@spree/dashboard-core/hooks/use-resource-mutation'+export * from './api-client'// ---------------------------------------------------------------------------// Admin SDK client (Vite-aware singleton; reads VITE_SPREE_API_URL at build)// ---------------------------------------------------------------------------diff --git a/packages/dashboard-core/src/providers/auth-provider.tsx b/packages/dashboard-core/src/providers/auth-provider.tsxindex bcf279ba88..2ce569e922 100644--- a/packages/dashboard-core/src/providers/auth-provider.tsx+++ b/packages/dashboard-core/src/providers/auth-provider.tsx@@ -6,7 +6,7 @@ import type {SetupParams,} from '@spree/admin-sdk'import { createContext, type ReactNode, useCallback, useEffect, useRef, useState } from 'react'-import { adminClient } from '../client'+import { getApiClient, type PanelSession } from '../api-client'import { ADMIN_LOCALE_STORAGE_KEY, switchLocale } from '../lib/i18n'interface AuthContextValue {@@ -49,6 +49,27 @@ export const AuthContext = createContext<AuthContextValue | null>(null)// Refresh ~30s before the JWT expires (default 5min TTL).const REFRESH_INTERVAL_MS = 4 * 60 * 1000 + 30 * 1000+/**+ * Reaches an admin-only sign-in flow. A seller's panel has none of these, so+ * calling one there is a bug in the host rather than a runtime condition to+ * handle — it fails here with a name rather than as `undefined is not a+ * function` somewhere further away.+ */+function requireAuthMethod<K extends 'acceptInvitation' | 'resetPassword' | 'completeSetup'>(+ name: K,+ // The three flows take different arguments; their concrete types live on+ // each panel's own client, so this signature stays deliberately loose.+): (...args: any[]) => Promise<PanelSession> {+ const method = getApiClient().auth[name] as+ | ((...args: any[]) => Promise<PanelSession>)+ | undefined+ if (typeof method !== 'function') {+ throw new Error(`@spree/dashboard-core: this panel's API client has no auth.${name}()`)+ }++ return method.bind(getApiClient().auth) as (...args: any[]) => Promise<PanelSession>+}+export function AuthProvider({ children }: { children: ReactNode }) {const [token, setToken] = useState<string | null>(null)const [user, setUser] = useState<AdminUser | null>(null)@@ -66,7 +87,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {}, [])const applySession = useCallback((accessToken: string, authUser: AdminUser) => {- adminClient.setToken(accessToken)+ getApiClient().setToken(accessToken)setToken(accessToken)setUser(authUser)// The account's saved admin language is the source of truth across devices.@@ -86,11 +107,13 @@ export function AuthProvider({ children }: { children: ReactNode }) {}, [])const clearSession = useCallback(() => {- adminClient.setToken('')- // The store header is session state too — left set, it would ride into- // the next admin's first requests (permissions, the index redirect) and- // 403 them against a store they may hold no role on.- adminClient.setStore('')+ const client = getApiClient()+ client.setToken('')+ // The tenant header is session state too — the store on the admin panel,+ // the seller on a seller's. Left set, it would ride into the next+ // principal's first requests (permissions, the index redirect) and 403+ // them against a tenant they may hold no role on.+ client.clearTenant?.()setToken(null)setUser(null)clearRefreshTimer()@@ -98,7 +121,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {const doRefresh = useCallback(async (): Promise<boolean> => {try {- const res = await adminClient.auth.refresh()+ const res = await getApiClient().auth.refresh()applySession(res.token, res.user)return true} catch {@@ -143,30 +166,30 @@ export function AuthProvider({ children }: { children: ReactNode }) {)const login = useCallback(- (email: string, password: string) => establish(adminClient.auth.login({ email, password })),+ (email: string, password: string) => establish(getApiClient().auth.login({ email, password })),[establish],)const acceptInvitation = useCallback((id: string, token: string, params: InvitationAcceptParams) =>- establish(adminClient.auth.acceptInvitation(id, token, params)),+ establish(requireAuthMethod('acceptInvitation')(id, token, params)),[establish],)const resetPassword = useCallback((token: string, params: PasswordResetParams) =>- establish(adminClient.auth.resetPassword(token, params)),+ establish(requireAuthMethod('resetPassword')(token, params)),[establish],)const completeSetup = useCallback(- (params: SetupParams) => establish(adminClient.auth.completeSetup(params)),+ (params: SetupParams) => establish(requireAuthMethod('completeSetup')(params)),[establish],)const logout = useCallback(async () => {try {- await adminClient.auth.logout()+ await getApiClient().auth.logout()} catch {// Server unreachable — clear locally; the row will expire naturally.} finally {@@ -176,7 +199,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {// biome-ignore lint/correctness/useExhaustiveDependencies: only run on mountuseEffect(() => {- adminClient.onUnauthorized(async () => {+ getApiClient().onUnauthorized(async () => {const success = await refreshAccessToken()if (success) scheduleRefresh()return successdiff --git a/packages/dashboard-core/src/providers/permission-provider.tsx b/packages/dashboard-core/src/providers/permission-provider.tsxindex 54932b1219..d5f67957af 100644--- a/packages/dashboard-core/src/providers/permission-provider.tsx+++ b/packages/dashboard-core/src/providers/permission-provider.tsx@@ -9,7 +9,7 @@ import {useRef,useState,} from 'react'-import { adminClient } from '../client'+import { getApiClient } from '../api-client'import { useAuth } from '../hooks/use-auth'import type { ActionName, SubjectName } from '../lib/permissions'@@ -103,10 +103,10 @@ export function PermissionProvider({ children }: { children: ReactNode }) {const generation = ++requestGeneration.currentsetIsLoading(true)try {- const res = await adminClient.me.get()+ const res = await getApiClient().fetchPermissions()if (generation !== requestGeneration.current) return- setRules(res.permissions)- setPermissionKeys(res.permission_keys ?? [])+ setRules(res.rules)+ setPermissionKeys(res.keys)} catch {if (generation !== requestGeneration.current) returnsetRules([])diff --git a/packages/dashboard-core/src/vite/index.ts b/packages/dashboard-core/src/vite/index.tsindex a8c2ea6a00..b59ecc2352 100644--- a/packages/dashboard-core/src/vite/index.ts+++ b/packages/dashboard-core/src/vite/index.ts@@ -21,6 +21,17 @@ export interface SpreeDashboardPluginOptions {*/cssEntry?: string+ /**+ * Shell packages whose source Tailwind should scan, on top of+ * `@spree/dashboard-core` and `@spree/dashboard-ui`. Defaults to+ * `['@spree/dashboard']`, the operator's dashboard. A different panel — a+ * seller's, or a host's own shell — passes its own package name here so its+ * components' classes survive the build. Unresolvable names are skipped+ * rather than erroring: a custom dashboard composed straight from core + ui+ * has no shell at all.+ */+ shellPackages?: string[]+/*** Names of dashboard plugin packages installed in the host app. Each name* must be a resolvable npm package specifier — the same string you'd pass@@ -155,11 +166,15 @@ function dashboardTailwindSourcePlugin(options: SpreeDashboardPluginOptions): PlpluginErrors.push({ pkg, kind: 'unresolved' })}}- // The app shell is optional: present when the host builds on the full- // `@spree/dashboard` package, absent for custom dashboards composed- // directly from core + ui — hence no error when unresolved.- const shellDir = resolvePackageSourceDir('@spree/dashboard', fromHost)- if (shellDir) resolvedSources.push(shellDir)+ // The app shell is optional: present when the host builds on a full+ // shell package, absent for custom dashboards composed directly from+ // core + ui — hence no error when unresolved. Which shell varies by+ // panel: `@spree/dashboard` for the operator's, `@spree/seller-dashboard`+ // for a seller's, or a host's own.+ for (const shell of options.shellPackages ?? ['@spree/dashboard']) {+ const shellDir = resolvePackageSourceDir(shell, fromHost)+ if (shellDir) resolvedSources.push(shellDir)+ }for (const pkg of pluginPackages) {const dir = resolvePackageSourceDir(pkg, fromHost)if (dir) {diff --git a/packages/dashboard/src/api-client-setup.ts b/packages/dashboard/src/api-client-setup.tsnew file mode 100644index 0000000000..b02185f4cd--- /dev/null+++ b/packages/dashboard/src/api-client-setup.ts@@ -0,0 +1,21 @@+import { adminClient, setApiClient } from '@spree/dashboard-core'++/**+ * Registers the Admin API client as this panel's client.+ *+ * `@spree/dashboard-core` is shared with the seller panel, which talks to a+ * different API with different credentials, so the framework holds no client+ * of its own — each host installs one. Side-effect import, run before any+ * provider mounts.+ */+setApiClient({+ auth: adminClient.auth,+ setToken: (token: string) => adminClient.setToken(token),+ onUnauthorized: (handler) => adminClient.onUnauthorized(handler),+ clearTenant: () => adminClient.setStore(''),+ fetchPermissions: async () => {+ const response = await adminClient.me.get()++ return { rules: response.permissions, keys: response.permission_keys ?? [] }+ },+})diff --git a/packages/dashboard/src/dashboard.tsx b/packages/dashboard/src/dashboard.tsxindex 16a904b470..bdc132c6a1 100644--- a/packages/dashboard/src/dashboard.tsx+++ b/packages/dashboard/src/dashboard.tsx@@ -7,6 +7,7 @@ import { StrictMode } from 'react'// bundle), the default sidebar nav, settings nav, and command-palette search// entries. Importing this module runs them — before any chrome component// reads the registries, and before plugin modules that call i18n.t at load.+import './api-client-setup'import './i18n-setup'import './nav/default'import './nav/settings'diff --git a/packages/seller-dashboard-starter/.env.example b/packages/seller-dashboard-starter/.env.examplenew file mode 100644index 0000000000..d65f9e6c85--- /dev/null+++ b/packages/seller-dashboard-starter/.env.example@@ -0,0 +1,7 @@+# The Rails server the dev proxy forwards /api to. The panel stays same-origin+# with the API in dev, which is what lets the seller refresh cookie ride under+# SameSite=Lax without HTTPS.+#+# Do NOT set VITE_SPREE_API_URL here — it switches the SDK to absolute+# cross-origin URLs and bypasses this proxy.+VITE_API_PROXY_TARGET=http://localhost:3000diff --git a/packages/seller-dashboard-starter/.gitignore b/packages/seller-dashboard-starter/.gitignorenew file mode 100644index 0000000000..d97f3f9c91--- /dev/null+++ b/packages/seller-dashboard-starter/.gitignore@@ -0,0 +1,3 @@+dist+node_modules+.env.localdiff --git a/packages/seller-dashboard-starter/biome.json b/packages/seller-dashboard-starter/biome.jsonnew file mode 100644index 0000000000..d7684827d2--- /dev/null+++ b/packages/seller-dashboard-starter/biome.json@@ -0,0 +1,8 @@+{+ "$schema": "https://biomejs.dev/schemas/2.4.13/schema.json",+ "root": false,+ "extends": ["../../biome.json"],+ "files": {+ "includes": ["src/**", "*.ts", "index.html", "!src/routeTree.gen.ts", "!src/**/*.css"]+ }+}diff --git a/packages/seller-dashboard-starter/index.html b/packages/seller-dashboard-starter/index.htmlnew file mode 100644index 0000000000..8a696cd4dc--- /dev/null+++ b/packages/seller-dashboard-starter/index.html@@ -0,0 +1,27 @@+<!doctype html>+<html lang="en">+ <head>+ <meta charset="UTF-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <title>Spree Seller Panel</title>+ </head>+ <body>+ <script>+ (() => {+ try {+ const stored = localStorage.getItem('spree-admin-theme');+ const mode = stored === 'light' || stored === 'dark' ? stored : 'system';+ const dark =+ mode === 'dark' ||+ (mode === 'system' && window.matchMedia('(prefers-color-scheme: dark)').matches);+ if (dark) document.documentElement.classList.add('dark');+ document.documentElement.style.colorScheme = dark ? 'dark' : 'light';+ } catch (_) {+ /* localStorage unavailable */+ }+ })();+ </script>+ <div id="root"></div>+ <script type="module" src="/src/main.tsx"></script>+ </body>+</html>diff --git a/packages/seller-dashboard-starter/package.json b/packages/seller-dashboard-starter/package.jsonnew file mode 100644index 0000000000..008421376f--- /dev/null+++ b/packages/seller-dashboard-starter/package.json@@ -0,0 +1,31 @@+{+ "name": "@spree/seller-dashboard-starter",+ "private": true,+ "license": "MIT",+ "version": "0.0.0",+ "type": "module",+ "scripts": {+ "dev": "vite",+ "build": "vite build",+ "preview": "vite preview",+ "typecheck": "tsc --noEmit",+ "lint": "biome check .",+ "lint:fix": "biome check --fix ."+ },+ "dependencies": {+ "@spree/seller-dashboard": "workspace:^",+ "@spree/seller-sdk": "workspace:^",+ "@tanstack/react-query": "^5.100.9",+ "@tanstack/react-router": "^1.169.2",+ "react": "^19.2.6",+ "react-dom": "^19.2.6"+ },+ "devDependencies": {+ "@biomejs/biome": "^2.4.14",+ "@types/react": "^19.2.14",+ "@types/react-dom": "^19.2.3",+ "@vitejs/plugin-react": "^6.0.1",+ "typescript": "~6.0.3",+ "vite": "^8.0.16"+ }+}diff --git a/packages/seller-dashboard-starter/src/main.tsx b/packages/seller-dashboard-starter/src/main.tsxnew file mode 100644index 0000000000..22558f6013--- /dev/null+++ b/packages/seller-dashboard-starter/src/main.tsx@@ -0,0 +1,23 @@+import { createSellerApiClient, createSellerRouter, SellerDashboard } from '@spree/seller-dashboard'+import { createRoot } from 'react-dom/client'+import './styles.css'+// Generated by @spree/seller-dashboard/vite on every dev start and build.+// Commit it — its diff on upgrades shows exactly which pages changed.+import { routeTree } from './routeTree.gen'++// Build the Seller API client and register it with the shared framework+// before anything renders: the providers read it on mount.+createSellerApiClient({ baseUrl: import.meta.env.VITE_SPREE_API_URL || '' })++// basepath mirrors Vite's `base` so sub-path mounts route correctly.+const router = createSellerRouter(routeTree, { basepath: import.meta.env.BASE_URL })++// Registers the router program-wide so <Link> and navigation are type-checked+// against the real route tree.+declare module '@tanstack/react-router' {+ interface Register {+ router: typeof router+ }+}++createRoot(document.getElementById('root')!).render(<SellerDashboard router={router} />)diff --git a/packages/seller-dashboard-starter/src/routeTree.gen.ts b/packages/seller-dashboard-starter/src/routeTree.gen.tsnew file mode 100644index 0000000000..f899130695--- /dev/null+++ b/packages/seller-dashboard-starter/src/routeTree.gen.ts@@ -0,0 +1,173 @@+/* eslint-disable */++// @ts-nocheck++// noinspection JSUnusedGlobalSymbols++// This file was automatically generated by TanStack Router.+// You should NOT make any changes in this file as it will be overwritten.+// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified.++import { Route as rootRouteImport } from './../../seller-dashboard/src/routes/__root'+import { Route as loginRouteImport } from './../../seller-dashboard/src/routes/login'+import { Route as authenticatedRouteImport } from './../../seller-dashboard/src/routes/_authenticated'+import { Route as authenticatedIndexRouteImport } from './../../seller-dashboard/src/routes/_authenticated/index'+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'++const loginRoute = loginRouteImport.update({+ id: '/login',+ path: '/login',+ getParentRoute: () => rootRouteImport,+} as any)+const authenticatedRoute = authenticatedRouteImport.update({+ id: '/_authenticated',+ getParentRoute: () => rootRouteImport,+} as any)+const authenticatedIndexRoute = authenticatedIndexRouteImport.update({+ id: '/',+ path: '/',+ getParentRoute: () => authenticatedRoute,+} as any)+const authenticatedSellerIdRoute = authenticatedSellerIdRouteImport.update({+ id: '/$sellerId',+ path: '/$sellerId',+ getParentRoute: () => authenticatedRoute,+} as any)+const IndexRoute = IndexRouteImport.update({+ id: '/',+ path: '/',+ getParentRoute: () => authenticatedSellerIdRoute,+} as any)+const TeamRoute = TeamRouteImport.update({+ id: '/team',+ path: '/team',+ getParentRoute: () => authenticatedSellerIdRoute,+} as any)++export interface FileRoutesByFullPath {+ '/': typeof authenticatedIndexRoute+ '/login': typeof loginRoute+ '/$sellerId': typeof authenticatedSellerIdRouteWithChildren+ '/$sellerId/team': typeof TeamRoute+ '/$sellerId/': typeof IndexRoute+}+export interface FileRoutesByTo {+ '/login': typeof loginRoute+ '/': typeof authenticatedIndexRoute+ '/$sellerId/team': typeof TeamRoute+ '/$sellerId': typeof IndexRoute+}+export interface FileRoutesById {+ __root__: typeof rootRouteImport+ '/_authenticated': typeof authenticatedRouteWithChildren+ '/login': typeof loginRoute+ '/_authenticated/$sellerId': typeof authenticatedSellerIdRouteWithChildren+ '/_authenticated/': typeof authenticatedIndexRoute+ '/_authenticated/$sellerId/team': typeof TeamRoute+ '/_authenticated/$sellerId/': typeof IndexRoute+}+export interface FileRouteTypes {+ fileRoutesByFullPath: FileRoutesByFullPath+ fullPaths: '/' | '/login' | '/$sellerId' | '/$sellerId/team' | '/$sellerId/'+ fileRoutesByTo: FileRoutesByTo+ to: '/login' | '/' | '/$sellerId/team' | '/$sellerId'+ id:+ | '__root__'+ | '/_authenticated'+ | '/login'+ | '/_authenticated/$sellerId'+ | '/_authenticated/'+ | '/_authenticated/$sellerId/team'+ | '/_authenticated/$sellerId/'+ fileRoutesById: FileRoutesById+}+export interface RootRouteChildren {+ authenticatedRoute: typeof authenticatedRouteWithChildren+ loginRoute: typeof loginRoute+}++declare module '@tanstack/react-router' {+ interface FileRoutesByPath {+ '/login': {+ id: '/login'+ path: '/login'+ fullPath: '/login'+ preLoaderRoute: typeof loginRouteImport+ parentRoute: typeof rootRouteImport+ }+ '/_authenticated': {+ id: '/_authenticated'+ path: ''+ fullPath: '/'+ preLoaderRoute: typeof authenticatedRouteImport+ parentRoute: typeof rootRouteImport+ }+ '/_authenticated/': {+ id: '/_authenticated/'+ path: '/'+ fullPath: '/'+ preLoaderRoute: typeof authenticatedIndexRouteImport+ parentRoute: typeof authenticatedRoute+ }+ '/_authenticated/$sellerId': {+ id: '/_authenticated/$sellerId'+ path: '/$sellerId'+ fullPath: '/$sellerId'+ preLoaderRoute: typeof authenticatedSellerIdRouteImport+ parentRoute: typeof authenticatedRoute+ }+ '/_authenticated/$sellerId/': {+ id: '/_authenticated/$sellerId/'+ path: '/'+ fullPath: '/$sellerId/'+ preLoaderRoute: typeof IndexRouteImport+ parentRoute: typeof authenticatedSellerIdRoute+ }+ '/_authenticated/$sellerId/team': {+ id: '/_authenticated/$sellerId/team'+ path: '/team'+ fullPath: '/$sellerId/team'+ preLoaderRoute: typeof TeamRouteImport+ parentRoute: typeof authenticatedSellerIdRoute+ }+ }+}++interface authenticatedSellerIdRouteChildren {+ TeamRoute: typeof TeamRoute+ IndexRoute: typeof IndexRoute+}++const authenticatedSellerIdRouteChildren: authenticatedSellerIdRouteChildren = {+ TeamRoute: TeamRoute,+ IndexRoute: IndexRoute,+}++const authenticatedSellerIdRouteWithChildren =+ authenticatedSellerIdRoute._addFileChildren(+ authenticatedSellerIdRouteChildren,+ )++interface authenticatedRouteChildren {+ authenticatedSellerIdRoute: typeof authenticatedSellerIdRouteWithChildren+ authenticatedIndexRoute: typeof authenticatedIndexRoute+}++const authenticatedRouteChildren: authenticatedRouteChildren = {+ authenticatedSellerIdRoute: authenticatedSellerIdRouteWithChildren,+ authenticatedIndexRoute: authenticatedIndexRoute,+}++const authenticatedRouteWithChildren = authenticatedRoute._addFileChildren(+ authenticatedRouteChildren,+)++const rootRouteChildren: RootRouteChildren = {+ authenticatedRoute: authenticatedRouteWithChildren,+ loginRoute: loginRoute,+}+export const routeTree = rootRouteImport+ ._addFileChildren(rootRouteChildren)+ ._addFileTypes<FileRouteTypes>()diff --git a/packages/seller-dashboard-starter/src/styles.css b/packages/seller-dashboard-starter/src/styles.cssnew file mode 100644index 0000000000..45cae6a15e--- /dev/null+++ b/packages/seller-dashboard-starter/src/styles.css@@ -0,0 +1,8 @@+/* CSS entry. The Spree stylesheet chain provides Tailwind v4 layers, design+ * tokens, and base styles; the Vite plugin appends `@source` directives here+ * at build time so Tailwind scans every Spree dashboard package for class+ * usage.+ *+ * Add your own styles below the import. */++@import "@spree/seller-dashboard/styles.css";diff --git a/packages/seller-dashboard-starter/tsconfig.json b/packages/seller-dashboard-starter/tsconfig.jsonnew file mode 100644index 0000000000..f0d6247d64--- /dev/null+++ b/packages/seller-dashboard-starter/tsconfig.json@@ -0,0 +1,21 @@+{+ "compilerOptions": {+ "target": "ES2022",+ "ignoreDeprecations": "6.0",+ "useDefineForClassFields": true,+ "lib": ["ES2022", "DOM", "DOM.Iterable"],+ "module": "ESNext",+ "types": ["vite/client"],+ "skipLibCheck": true,+ "moduleResolution": "bundler",+ "allowImportingTsExtensions": true,+ "verbatimModuleSyntax": true,+ "moduleDetection": "force",+ "noEmit": true,+ "jsx": "react-jsx",+ "strict": true,+ "noFallthroughCasesInSwitch": true,+ "noUncheckedSideEffectImports": true+ },+ "include": ["src", "vite.config.ts"]+}diff --git a/packages/seller-dashboard-starter/vite.config.ts b/packages/seller-dashboard-starter/vite.config.tsnew file mode 100644index 0000000000..8f916d85ba--- /dev/null+++ b/packages/seller-dashboard-starter/vite.config.ts@@ -0,0 +1,27 @@+import { spreeSellerDashboardPlugin } from '@spree/seller-dashboard/vite'+import react from '@vitejs/plugin-react'+import { defineConfig, loadEnv } from 'vite'++export default defineConfig(({ mode }) => {+ // loadEnv, not process.env: Vite doesn't load .env files before evaluating+ // this config, and .env.local is where the proxy target is written.+ const env = loadEnv(mode, process.cwd(), 'VITE_')+ const proxyTarget = env.VITE_API_PROXY_TARGET || 'http://localhost:3000'++ return {+ base: process.env.VITE_BASE_PATH,+ // spreeSellerDashboardPlugin bundles Tailwind, injects @source directives+ // for every Spree dashboard package, and composes the panel's file routes+ // into src/routeTree.gen.ts on each dev start/build — commit that file.+ plugins: [spreeSellerDashboardPlugin(), react()],+ // Proxy /api to Rails so the panel is same-origin with the API in dev,+ // keeping the refresh-token cookie working under SameSite=Lax without+ // HTTPS. /rails covers Active Storage's presigned URLs.+ server: {+ proxy: {+ '/api': { target: proxyTarget, changeOrigin: true },+ '/rails': { target: proxyTarget, changeOrigin: true },+ },+ },+ }+})diff --git a/packages/seller-dashboard/biome.json b/packages/seller-dashboard/biome.jsonnew file mode 100644index 0000000000..d7684827d2--- /dev/null+++ b/packages/seller-dashboard/biome.json@@ -0,0 +1,8 @@+{+ "$schema": "https://biomejs.dev/schemas/2.4.13/schema.json",+ "root": false,+ "extends": ["../../biome.json"],+ "files": {+ "includes": ["src/**", "*.ts", "index.html", "!src/routeTree.gen.ts", "!src/**/*.css"]+ }+}diff --git a/packages/seller-dashboard/package.json b/packages/seller-dashboard/package.jsonnew file mode 100644index 0000000000..7cf0f0e2ab--- /dev/null+++ b/packages/seller-dashboard/package.json@@ -0,0 +1,60 @@+{+ "name": "@spree/seller-dashboard",+ "version": "0.1.0",+ "license": "MIT",+ "type": "module",+ "description": "Spree marketplace seller panel \u2014 the seller-facing counterpart to the admin dashboard.",+ "exports": {+ ".": "./src/index.ts",+ "./styles.css": "./src/styles.css",+ "./vite": {+ "types": "./src/vite/index.ts",+ "default": "./dist/vite-plugin/index.js"+ },+ "./package.json": "./package.json"+ },+ "files": [+ "src",+ "dist/vite-plugin",+ "README.md",+ "LICENSE"+ ],+ "scripts": {+ "build": "pnpm generate:routes && tsup",+ "typecheck": "tsc -b",+ "lint": "biome check .",+ "lint:fix": "biome check --fix .",+ "format": "biome format --write .",+ "generate:routes": "node scripts/generate-routes.mjs"+ },+ "dependencies": {+ "@spree/dashboard-core": "workspace:*",+ "@spree/dashboard-ui": "workspace:*",+ "@spree/seller-sdk": "workspace:*",+ "@tanstack/react-query": "^5.90.2",+ "@tanstack/react-router": "^1.133.32",+ "@tanstack/router-plugin": "^1.167.35",+ "@tanstack/virtual-file-routes": "^1.162.0",+ "i18next": "^25.6.0",+ "lucide-react": "^0.545.0",+ "react-hook-form": "^7.65.0",+ "react-i18next": "^16.0.0",+ "sonner": "^2.0.7"+ },+ "peerDependencies": {+ "react": "^19.0.0",+ "react-dom": "^19.0.0"+ },+ "devDependencies": {+ "@biomejs/biome": "2.4.13",+ "@types/node": "^25.6.0",+ "@types/react": "^19.2.2",+ "@types/react-dom": "^19.2.1",+ "@vitejs/plugin-react": "^6.0.1",+ "react": "^19.2.0",+ "react-dom": "^19.2.0",+ "tsup": "^8.5.0",+ "typescript": "~6.0.3",+ "vite": "^8.0.0"+ }+}diff --git a/packages/seller-dashboard/scripts/generate-routes.mjs b/packages/seller-dashboard/scripts/generate-routes.mjsnew file mode 100644index 0000000000..9dbf91e945--- /dev/null+++ b/packages/seller-dashboard/scripts/generate-routes.mjs@@ -0,0 +1,10 @@+// Regenerates the shell's committed routeTree.gen.ts.+//+// The shell is a library, not an app — it has no index.html, so a full+// `vite build` has no entry to resolve. Running Vite in dev-config mode gets+// the route generator (which runs on config resolution) without asking Vite+// to build anything.+import { createServer } from 'vite'++const server = await createServer({ configFile: './vite.config.ts', logLevel: 'error' })+await server.close()diff --git a/packages/seller-dashboard/src/api-client.ts b/packages/seller-dashboard/src/api-client.tsnew file mode 100644index 0000000000..6c6025e856--- /dev/null+++ b/packages/seller-dashboard/src/api-client.ts@@ -0,0 +1,95 @@+import { setApiClient } from '@spree/dashboard-core'+import type { SellerApiClient } from '@spree/seller-sdk'+import { createSellerClient } from '@spree/seller-sdk'++/**+ * Which seller the signed-in user is acting as.+ *+ * Kept out of React state because the client needs it on every request,+ * including ones fired before any component renders. The URL is the real+ * source of truth — the `$sellerId` route layout writes it here as it renders+ * — and this copy is only what the request headers read.+ */+const SELLER_STORAGE_KEY = 'spree.seller.id'++let client: SellerApiClient | null = null++/**+ * Builds the Seller API client and registers it with the shared framework.+ *+ * The host calls this once at boot, before rendering. `@spree/dashboard-core`+ * is the framework behind both panels, so it cannot own either client — the+ * operator's dashboard registers an Admin API client the same way.+ *+ * Leave `baseUrl` unset for relative URLs, so the Vite dev proxy (or a+ * static-host rewrite in production) keeps the panel same-origin with the API+ * — which is what lets the seller refresh cookie ride under `SameSite=Lax`+ * without HTTPS. Set it only for a genuinely cross-origin deployment.+ */+export function createSellerApiClient({+ baseUrl = '',+}: {+ baseUrl?: string+} = {}): SellerApiClient {+ client = createSellerClient({ baseUrl })++ const remembered = rememberedSeller()+ if (remembered) client.setSeller(remembered)++ setApiClient({+ auth: client.auth,+ setToken: (token: string) => sellerClient().setToken(token),+ onUnauthorized: (handler) => sellerClient().onUnauthorized(handler),+ // A stale seller header would ride into the next seller's first requests+ // and 403 them against a seller they may hold no role on.+ clearTenant: forgetSeller,+ fetchPermissions: async () => {+ const response = await sellerClient().me()++ // The seller API grants capability by key alone — there are no CanCanCan+ // rules to report, and an empty list is the correct answer rather than a+ // missing one.+ return { rules: [], keys: response.permission_keys ?? [] }+ },+ })++ return client+}++/**+ * The registered client.+ *+ * Throws rather than returning null: a panel rendering without one is+ * misconfigured, and every call would otherwise fail further away with a less+ * useful message.+ */+export function sellerClient(): SellerApiClient {+ if (!client) {+ throw new Error(+ '@spree/seller-dashboard: no API client created. Call createSellerApiClient() at boot, ' ++ 'before rendering the panel.',+ )+ }++ return client+}++/** Points subsequent requests at a seller, without persisting the choice. */+export function setActiveSeller(sellerId: string): void {+ sellerClient().setSeller(sellerId)+}++/** Persists the choice so a reload does not drop the seller back to the picker. */+export function rememberSeller(sellerId: string): void {+ localStorage.setItem(SELLER_STORAGE_KEY, sellerId)+ setActiveSeller(sellerId)+}++export function forgetSeller(): void {+ localStorage.removeItem(SELLER_STORAGE_KEY)+ client?.setSeller('')+}++export function rememberedSeller(): string | null {+ return localStorage.getItem(SELLER_STORAGE_KEY)+}diff --git a/packages/seller-dashboard/src/components/centered-message.tsx b/packages/seller-dashboard/src/components/centered-message.tsxnew file mode 100644index 0000000000..bd0a31f9b7--- /dev/null+++ b/packages/seller-dashboard/src/components/centered-message.tsx@@ -0,0 +1,8 @@+/** Full-height placeholder for the panel's loading and error states. */+export function CenteredMessage({ children }: { children: React.ReactNode }) {+ return (+ <div className="flex min-h-screen items-center justify-center text-muted-foreground text-sm">+ {children}+ </div>+ )+}diff --git a/packages/seller-dashboard/src/create-router.ts b/packages/seller-dashboard/src/create-router.tsnew file mode 100644index 0000000000..efde61b661--- /dev/null+++ b/packages/seller-dashboard/src/create-router.ts@@ -0,0 +1,32 @@+import type { AnyRoute, RouterConstructorOptions, RouterHistory } from '@tanstack/react-router'+import { createRouter } from '@tanstack/react-router'++export interface SellerRouterOptions {+ /** Mirrors Vite's `base` so sub-path mounts route correctly. */+ basepath?: string+}++/**+ * Builds the panel's router from a route tree.+ *+ * Hosts own their entry point and pass the tree in, exactly as they do for+ * the operator's dashboard — so a marketplace can add its own seller-facing+ * pages without forking this package.+ */+export function createSellerRouter<TRouteTree extends AnyRoute>(+ routeTree: TRouteTree,+ { basepath }: SellerRouterOptions = {},+) {+ // Cast because the shell's root route requires no router context, which+ // TypeScript cannot prove through the generic tree parameter. The return+ // type stays parameterized by TRouteTree — that's what keeps links typed.+ const options = { routeTree, basepath } as RouterConstructorOptions<+ TRouteTree,+ 'never',+ false,+ RouterHistory,+ Record<string, unknown>+ >++ return createRouter(options)+}diff --git a/packages/seller-dashboard/src/i18n.ts b/packages/seller-dashboard/src/i18n.tsnew file mode 100644index 0000000000..0ffa85ec65--- /dev/null+++ b/packages/seller-dashboard/src/i18n.ts@@ -0,0 +1,18 @@+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.+ */+void i18n.use(initReactI18next).init({+ resources: { en: { translation: en } },+ lng: 'en',+ fallbackLng: 'en',+ interpolation: { escapeValue: false },+})++export default i18ndiff --git a/packages/seller-dashboard/src/index.ts b/packages/seller-dashboard/src/index.tsnew file mode 100644index 0000000000..9c46d0ba32--- /dev/null+++ b/packages/seller-dashboard/src/index.ts@@ -0,0 +1,10 @@+export {+ createSellerApiClient,+ rememberedSeller,+ rememberSeller,+ setActiveSeller,+} from './api-client'+export { CenteredMessage } from './components/centered-message'+export type { SellerRouterOptions } from './create-router'+export { createSellerRouter } from './create-router'+export { SellerDashboard } from './seller-dashboard'diff --git a/packages/seller-dashboard/src/locales/en.json b/packages/seller-dashboard/src/locales/en.jsonnew file mode 100644index 0000000000..44a17c950a--- /dev/null+++ b/packages/seller-dashboard/src/locales/en.json@@ -0,0 +1,69 @@+{+ "app": {+ "name": "Seller panel"+ },+ "login": {+ "title": "Sign in to your seller panel",+ "subtitle": "Manage your storefront, team and payouts.",+ "email": "Email",+ "password": "Password",+ "submit": "Sign in",+ "submitting": "Signing in…",+ "failed": "That email and password did not match a seller account.",+ "no_seller": "This account does not run a seller on this marketplace."+ },+ "seller_picker": {+ "title": "Choose a seller",+ "subtitle": "You run more than one. Pick which to manage.",+ "status": "Status"+ },+ "nav": {+ "profile": "Profile",+ "team": "Team",+ "sign_out": "Sign out"+ },+ "profile": {+ "title": "Your profile",+ "subtitle": "How your storefront presents you, and how the marketplace reaches you.",+ "section_presentation": "Presentation",+ "section_contact": "Contact",+ "section_standing": "Standing",+ "section_settlement": "Payouts and tax",+ "name": "Name",+ "about": "About",+ "contact_email": "Contact email",+ "billing_email": "Billing email",+ "handle": "Storefront address",+ "status": "Status",+ "sellable": "Currently selling",+ "not_sellable": "Not currently selling",+ "products_count": "Products",+ "tax_remittance": "Tax remitted by",+ "payout_schedule": "Payout schedule",+ "minimum_payout": "Minimum payout",+ "operator_managed": "Set by the marketplace",+ "save": "Save changes",+ "saving": "Saving…",+ "saved": "Profile saved",+ "not_provided": "Not provided"+ },+ "team": {+ "title": "Your team",+ "subtitle": "The people who can sign in and manage this seller.",+ "invite": "Invite someone",+ "invite_email": "Email",+ "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."+ },+ "common": {+ "loading": "Loading…",+ "error": "Something went wrong.",+ "retry": "Try again"+ }+}diff --git a/packages/seller-dashboard/src/pages/login.tsx b/packages/seller-dashboard/src/pages/login.tsxnew file mode 100644index 0000000000..dc2ad7d756--- /dev/null+++ b/packages/seller-dashboard/src/pages/login.tsx@@ -0,0 +1,89 @@+import { useAuth } from '@spree/dashboard-core'+import { Button, Field, FieldError, FieldGroup, FieldLabel, Input } from '@spree/dashboard-ui'+import { useState } from 'react'+import { useForm } from 'react-hook-form'+import { useTranslation } from 'react-i18next'++interface LoginValues {+ email: string+ password: string+}++/**+ * Sign-in for sellers.+ *+ * Its own surface rather than the admin login: the two read different+ * strategy registries against the same user class, so a marketplace can+ * require SSO for its own staff while sellers still use a password.+ */+export function LoginPage() {+ const { t } = useTranslation()+ const { login } = useAuth()+ const [error, setError] = useState<string | null>(null)+ const form = useForm<LoginValues>({ defaultValues: { email: '', password: '' } })++ async function onSubmit(values: LoginValues) {+ setError(null)+ try {+ await login(values.email, values.password)+ // Where to go next is the index route's decision — it already knows how+ // to skip the picker for a seller who runs exactly one seller, and+ // duplicating that here would leave two rules to keep in step.+ } catch {+ // The API refuses a staff member who runs no seller with the same+ // status as a bad password, so the panel says the same thing: it must+ // not become a way to discover which accounts exist.+ setError(t('login.failed'))+ }+ }++ const { errors, isSubmitting } = form.formState++ return (+ <div className="flex min-h-screen items-center justify-center p-6">+ <div className="w-full max-w-sm">+ <h1 className="font-medium text-xl">{t('login.title')}</h1>+ <p className="mt-1 mb-6 text-muted-foreground text-sm">{t('login.subtitle')}</p>++ <form onSubmit={form.handleSubmit(onSubmit)}>+ <FieldGroup>+ {error && (+ <p className="text-destructive text-sm" role="alert">+ {error}+ </p>+ )}++ <Field>+ <FieldLabel htmlFor="email">{t('login.email')}</FieldLabel>+ <Input+ id="email"+ type="email"+ autoComplete="email"+ autoFocus+ aria-invalid={!!errors.email || undefined}+ {...form.register('email', { required: true })}+ />+ <FieldError errors={[errors.email]} />+ </Field>++ <Field>+ <FieldLabel htmlFor="password">{t('login.password')}</FieldLabel>+ <Input+ id="password"+ type="password"+ autoComplete="current-password"+ aria-invalid={!!errors.password || undefined}+ {...form.register('password', { required: true })}+ />+ <FieldError errors={[errors.password]} />+ </Field>++ <Button type="submit" disabled={isSubmitting}>+ {isSubmitting ? t('login.submitting') : t('login.submit')}+ </Button>+ </FieldGroup>+ </form>+ </div>+ </div>+ )+}diff --git a/packages/seller-dashboard/src/pages/profile.tsx b/packages/seller-dashboard/src/pages/profile.tsxnew file mode 100644index 0000000000..641e944e73--- /dev/null+++ b/packages/seller-dashboard/src/pages/profile.tsx@@ -0,0 +1,185 @@+import {+ Button,+ Card,+ CardContent,+ CardHeader,+ CardTitle,+ Field,+ FieldError,+ FieldGroup,+ FieldLabel,+ Input,+ StatusBadge,+ Textarea,+} from '@spree/dashboard-ui'+import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'+import { useParams } from '@tanstack/react-router'+import { useEffect } 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'++interface ProfileValues {+ name: string+ contact_email: string+ billing_email: string+ about: string+}++/**+ * The seller's own record.+ *+ * Split by who owns each fact: what the seller maintains is a form, what the+ * marketplace decides is shown read-only. Hiding the latter would leave a+ * seller unable to see they had been suspended, or on what terms they are+ * paid; making it editable would let them approve themselves.+ */+export function ProfilePage() {+ const { t } = useTranslation()+ const queryClient = useQueryClient()+ const { sellerId } = useParams({ from: '/_authenticated/$sellerId' })++ const {+ data: profile,+ isLoading,+ error,+ } = useQuery({+ queryKey: ['seller', sellerId, 'profile'],+ queryFn: () => sellerClient().profile.get(),+ })++ const form = useForm<ProfileValues>({+ defaultValues: { name: '', contact_email: '', billing_email: '', about: '' },+ })++ useEffect(() => {+ if (!profile) return++ form.reset({+ name: profile.name,+ contact_email: profile.contact_email ?? '',+ billing_email: profile.billing_email ?? '',+ about: profile.about_html ?? '',+ })+ }, [profile, form])++ const save = useMutation({+ mutationFn: (values: ProfileValues) =>+ sellerClient().profile.update({+ name: values.name,+ contact_email: values.contact_email || null,+ billing_email: values.billing_email || null,+ about: values.about || null,+ }),+ onSuccess: (updated) => {+ queryClient.setQueryData(['seller', sellerId, 'profile'], updated)+ toast.success(t('profile.saved'))+ },+ onError: () => toast.error(t('common.error')),+ })++ if (isLoading) return <CenteredMessage>{t('common.loading')}</CenteredMessage>+ if (error || !profile) return <CenteredMessage>{t('common.error')}</CenteredMessage>++ const { errors, isDirty } = form.formState++ return (+ <div className="mx-auto flex max-w-3xl flex-col gap-6">+ <div>+ <h1 className="font-medium text-2xl">{t('profile.title')}</h1>+ <p className="text-muted-foreground text-sm">{t('profile.subtitle')}</p>+ </div>++ <Card>+ <CardHeader>+ <CardTitle>{t('profile.section_presentation')}</CardTitle>+ </CardHeader>+ <CardContent>+ <FieldGroup>+ <Field>+ <FieldLabel htmlFor="name">{t('profile.name')}</FieldLabel>+ <Input+ id="name"+ aria-invalid={!!errors.name || undefined}+ {...form.register('name', { required: true })}+ />+ <FieldError errors={[errors.name]} />+ </Field>++ <Field>+ <FieldLabel htmlFor="about">{t('profile.about')}</FieldLabel>+ <Textarea id="about" rows={5} {...form.register('about')} />+ </Field>++ <Field>+ <FieldLabel htmlFor="contact_email">{t('profile.contact_email')}</FieldLabel>+ <Input id="contact_email" type="email" {...form.register('contact_email')} />+ </Field>++ <Field>+ <FieldLabel htmlFor="billing_email">{t('profile.billing_email')}</FieldLabel>+ <Input id="billing_email" type="email" {...form.register('billing_email')} />+ </Field>++ <div className="flex justify-end">+ <Button+ type="button"+ disabled={!isDirty || save.isPending}+ onClick={form.handleSubmit((values) => save.mutate(values))}+ >+ {save.isPending ? t('profile.saving') : t('profile.save')}+ </Button>+ </div>+ </FieldGroup>+ </CardContent>+ </Card>++ {/* Read-only: the marketplace decides these, and a seller who cannot see+ them cannot tell why their products stopped selling. */}+ <Card>+ <CardHeader>+ <CardTitle>{t('profile.section_standing')}</CardTitle>+ </CardHeader>+ <CardContent className="flex flex-col gap-3">+ <ReadRow label={t('profile.status')}>+ <StatusBadge status={profile.status} />+ </ReadRow>+ <ReadRow label={t('profile.handle')}>/{profile.slug}</ReadRow>+ <ReadRow label={t('profile.products_count')}>{profile.products_count}</ReadRow>+ <ReadRow label={t('profile.sellable')}>+ {profile.sellable ? t('profile.sellable') : t('profile.not_sellable')}+ </ReadRow>+ </CardContent>+ </Card>++ <Card>+ <CardHeader>+ <CardTitle>{t('profile.section_settlement')}</CardTitle>+ </CardHeader>+ <CardContent className="flex flex-col gap-3">+ <p className="text-muted-foreground text-xs">{t('profile.operator_managed')}</p>+ <ReadRow label={t('profile.tax_remittance')}>{profile.tax_remittance}</ReadRow>+ <ReadRow label={t('profile.payout_schedule')}>+ {profile.payouts_schedule_interval}+ </ReadRow>+ <ReadRow label={t('profile.minimum_payout')}>{profile.minimum_payout_amount}</ReadRow>+ </CardContent>+ </Card>+ </div>+ )+}++function ReadRow({ label, children }: { label: string; children: React.ReactNode }) {+ const { t } = useTranslation()++ return (+ <div className="flex items-start justify-between gap-3 text-sm">+ <span className="text-muted-foreground">{label}</span>+ <span className="text-right">+ {children ?? <span className="text-muted-foreground">{t('profile.not_provided')}</span>}+ </span>+ </div>+ )+}diff --git a/packages/seller-dashboard/src/pages/seller-picker.tsx b/packages/seller-dashboard/src/pages/seller-picker.tsxnew file mode 100644index 0000000000..17fccd8420--- /dev/null+++ b/packages/seller-dashboard/src/pages/seller-picker.tsx@@ -0,0 +1,46 @@+import { Badge, Button, Card, CardContent, CardHeader, CardTitle } from '@spree/dashboard-ui'+import { useQuery } from '@tanstack/react-query'+import { Link } from '@tanstack/react-router'+import { useTranslation } from 'react-i18next'+import { sellerClient } from '../api-client'+import { CenteredMessage } from '../components/centered-message'++/**+ * Which seller to act as.+ *+ * Only shown to a seller who runs more than one — the panel acts as exactly+ * one at a time, because every request carries a single `X-Spree-Seller-Id`.+ */+export function SellerPicker() {+ const { t } = useTranslation()+ const { data, isLoading, error } = useQuery({+ queryKey: ['seller', 'me'],+ queryFn: () => sellerClient().me(),+ })++ if (isLoading) return <CenteredMessage>{t('common.loading')}</CenteredMessage>+ if (error) return <CenteredMessage>{t('common.error')}</CenteredMessage>++ const sellers = data?.sellers ?? []++ return (+ <div className="flex min-h-screen items-center justify-center p-6">+ <Card className="w-full max-w-md">+ <CardHeader>+ <CardTitle>{t('seller_picker.title')}</CardTitle>+ </CardHeader>+ <CardContent className="flex flex-col gap-2">+ <p className="mb-2 text-muted-foreground text-sm">{t('seller_picker.subtitle')}</p>+ {sellers.map((seller) => (+ <Button key={seller.id} variant="outline" className="justify-between" asChild>+ <Link to="/$sellerId" params={{ sellerId: seller.id }}>+ <span>{seller.name}</span>+ <Badge variant="outline">{seller.status}</Badge>+ </Link>+ </Button>+ ))}+ </CardContent>+ </Card>+ </div>+ )+}diff --git a/packages/seller-dashboard/src/pages/team.tsx b/packages/seller-dashboard/src/pages/team.tsxnew file mode 100644index 0000000000..a0ac0eb0be--- /dev/null+++ b/packages/seller-dashboard/src/pages/team.tsx@@ -0,0 +1,144 @@+import {+ Button,+ Card,+ CardContent,+ CardHeader,+ CardTitle,+ Field,+ FieldGroup,+ FieldLabel,+ Input,+ useConfirm,+} from '@spree/dashboard-ui'+import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'+import { useParams } from '@tanstack/react-router'+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.+ *+ * 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.+ */+export function TeamPage() {+ const { t } = useTranslation()+ const queryClient = useQueryClient()+ const confirm = useConfirm()+ const { sellerId } = useParams({ from: '/_authenticated/$sellerId' })++ const { data, isLoading, error } = useQuery({+ queryKey: ['seller', sellerId, 'team'],+ queryFn: () => sellerClient().team.list(),+ })++ const form = useForm<{ email: string }>({ defaultValues: { email: '' } })++ const invalidate = () => queryClient.invalidateQueries({ queryKey: ['seller', sellerId, 'team'] })++ const invite = useMutation({+ mutationFn: (email: string) => sellerClient().team.invite({ email }),+ onSuccess: () => {+ form.reset({ email: '' })+ toast.success(t('team.invited'))+ void invalidate()+ },+ onError: () => toast.error(t('common.error')),+ })++ const remove = useMutation({+ mutationFn: (id: string) => sellerClient().team.remove(id),+ onSuccess: () => {+ toast.success(t('team.removed'))+ 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')),+ })++ if (isLoading) return <CenteredMessage>{t('common.loading')}</CenteredMessage>+ if (error) return <CenteredMessage>{t('common.error')}</CenteredMessage>++ const members = data?.data ?? []++ 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>++ <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>+ )+}diff --git a/packages/seller-dashboard/src/panel-chrome.tsx b/packages/seller-dashboard/src/panel-chrome.tsxnew file mode 100644index 0000000000..e00d879f43--- /dev/null+++ b/packages/seller-dashboard/src/panel-chrome.tsx@@ -0,0 +1,77 @@+import { useAuth } from '@spree/dashboard-core'+import { Button } from '@spree/dashboard-ui'+import { Link, useParams } from '@tanstack/react-router'+import { StoreIcon, UsersIcon } from 'lucide-react'+import type { ReactNode } from 'react'+import { useTranslation } from 'react-i18next'++/**+ * The panel's frame: a nav rail and a content column.+ *+ * Deliberately small. The admin dashboard's chrome carries a store switcher,+ * a command palette and a plugin slot system, none of which a seller managing+ * one seller needs yet.+ */+export function PanelChrome({ children }: { children: ReactNode }) {+ const { t } = useTranslation()+ const { logout } = useAuth()+ const { sellerId } = useParams({ from: '/_authenticated/$sellerId' })++ return (+ <div className="flex min-h-screen">+ <nav className="flex w-56 shrink-0 flex-col gap-1 border-border border-r p-4">+ <p className="mb-4 font-medium text-sm">{t('app.name')}</p>++ <NavLink to="/$sellerId" params={{ sellerId }} icon={<StoreIcon className="size-4" />}>+ {t('nav.profile')}+ </NavLink>+ <NavLink to="/$sellerId/team" params={{ sellerId }} icon={<UsersIcon className="size-4" />}>+ {t('nav.team')}+ </NavLink>++ <div className="mt-auto flex flex-col gap-1">+ <Button variant="ghost" size="sm" className="justify-start" asChild>+ <Link to="/">{t('seller_picker.title')}</Link>+ </Button>+ <Button variant="ghost" size="sm" className="justify-start" onClick={() => logout()}>+ {t('nav.sign_out')}+ </Button>+ </div>+ </nav>++ <main className="min-w-0 flex-1 p-8">{children}</main>+ </div>+ )+}++/**+ * A rail entry that highlights itself when its route is the active one.+ *+ * `activeProps` is TanStack's own active-state channel, so the highlight+ * follows the router rather than a copy of the current page held in state.+ */+function NavLink({+ to,+ params,+ icon,+ children,+}: {+ to: string+ params: Record<string, string>+ icon: ReactNode+ children: ReactNode+}) {+ return (+ <Button variant="ghost" className="justify-start" asChild>+ <Link+ to={to}+ params={params}+ activeOptions={{ exact: true }}+ activeProps={{ 'data-active': 'true', className: 'bg-accent text-accent-foreground' }}+ >+ {icon}+ {children}+ </Link>+ </Button>+ )+}diff --git a/packages/seller-dashboard/src/routeTree.gen.ts b/packages/seller-dashboard/src/routeTree.gen.tsnew file mode 100644index 0000000000..79dd91c46d--- /dev/null+++ b/packages/seller-dashboard/src/routeTree.gen.ts@@ -0,0 +1,173 @@+/* eslint-disable */++// @ts-nocheck++// noinspection JSUnusedGlobalSymbols++// This file was automatically generated by TanStack Router.+// You should NOT make any changes in this file as it will be overwritten.+// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified.++import { Route as rootRouteImport } from './routes/__root'+import { Route as loginRouteImport } from './routes/login'+import { Route as authenticatedRouteImport } from './routes/_authenticated'+import { Route as authenticatedIndexRouteImport } from './routes/_authenticated/index'+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'++const loginRoute = loginRouteImport.update({+ id: '/login',+ path: '/login',+ getParentRoute: () => rootRouteImport,+} as any)+const authenticatedRoute = authenticatedRouteImport.update({+ id: '/_authenticated',+ getParentRoute: () => rootRouteImport,+} as any)+const authenticatedIndexRoute = authenticatedIndexRouteImport.update({+ id: '/',+ path: '/',+ getParentRoute: () => authenticatedRoute,+} as any)+const authenticatedSellerIdRoute = authenticatedSellerIdRouteImport.update({+ id: '/$sellerId',+ path: '/$sellerId',+ getParentRoute: () => authenticatedRoute,+} as any)+const IndexRoute = IndexRouteImport.update({+ id: '/',+ path: '/',+ getParentRoute: () => authenticatedSellerIdRoute,+} as any)+const TeamRoute = TeamRouteImport.update({+ id: '/team',+ path: '/team',+ getParentRoute: () => authenticatedSellerIdRoute,+} as any)++export interface FileRoutesByFullPath {+ '/': typeof authenticatedIndexRoute+ '/login': typeof loginRoute+ '/$sellerId': typeof authenticatedSellerIdRouteWithChildren+ '/$sellerId/team': typeof TeamRoute+ '/$sellerId/': typeof IndexRoute+}+export interface FileRoutesByTo {+ '/login': typeof loginRoute+ '/': typeof authenticatedIndexRoute+ '/$sellerId/team': typeof TeamRoute+ '/$sellerId': typeof IndexRoute+}+export interface FileRoutesById {+ __root__: typeof rootRouteImport+ '/_authenticated': typeof authenticatedRouteWithChildren+ '/login': typeof loginRoute+ '/_authenticated/$sellerId': typeof authenticatedSellerIdRouteWithChildren+ '/_authenticated/': typeof authenticatedIndexRoute+ '/_authenticated/$sellerId/team': typeof TeamRoute+ '/_authenticated/$sellerId/': typeof IndexRoute+}+export interface FileRouteTypes {+ fileRoutesByFullPath: FileRoutesByFullPath+ fullPaths: '/' | '/login' | '/$sellerId' | '/$sellerId/team' | '/$sellerId/'+ fileRoutesByTo: FileRoutesByTo+ to: '/login' | '/' | '/$sellerId/team' | '/$sellerId'+ id:+ | '__root__'+ | '/_authenticated'+ | '/login'+ | '/_authenticated/$sellerId'+ | '/_authenticated/'+ | '/_authenticated/$sellerId/team'+ | '/_authenticated/$sellerId/'+ fileRoutesById: FileRoutesById+}+export interface RootRouteChildren {+ authenticatedRoute: typeof authenticatedRouteWithChildren+ loginRoute: typeof loginRoute+}++declare module '@tanstack/react-router' {+ interface FileRoutesByPath {+ '/login': {+ id: '/login'+ path: '/login'+ fullPath: '/login'+ preLoaderRoute: typeof loginRouteImport+ parentRoute: typeof rootRouteImport+ }+ '/_authenticated': {+ id: '/_authenticated'+ path: ''+ fullPath: '/'+ preLoaderRoute: typeof authenticatedRouteImport+ parentRoute: typeof rootRouteImport+ }+ '/_authenticated/': {+ id: '/_authenticated/'+ path: '/'+ fullPath: '/'+ preLoaderRoute: typeof authenticatedIndexRouteImport+ parentRoute: typeof authenticatedRoute+ }+ '/_authenticated/$sellerId': {+ id: '/_authenticated/$sellerId'+ path: '/$sellerId'+ fullPath: '/$sellerId'+ preLoaderRoute: typeof authenticatedSellerIdRouteImport+ parentRoute: typeof authenticatedRoute+ }+ '/_authenticated/$sellerId/': {+ id: '/_authenticated/$sellerId/'+ path: '/'+ fullPath: '/$sellerId/'+ preLoaderRoute: typeof IndexRouteImport+ parentRoute: typeof authenticatedSellerIdRoute+ }+ '/_authenticated/$sellerId/team': {+ id: '/_authenticated/$sellerId/team'+ path: '/team'+ fullPath: '/$sellerId/team'+ preLoaderRoute: typeof TeamRouteImport+ parentRoute: typeof authenticatedSellerIdRoute+ }+ }+}++interface authenticatedSellerIdRouteChildren {+ TeamRoute: typeof TeamRoute+ IndexRoute: typeof IndexRoute+}++const authenticatedSellerIdRouteChildren: authenticatedSellerIdRouteChildren = {+ TeamRoute: TeamRoute,+ IndexRoute: IndexRoute,+}++const authenticatedSellerIdRouteWithChildren =+ authenticatedSellerIdRoute._addFileChildren(+ authenticatedSellerIdRouteChildren,+ )++interface authenticatedRouteChildren {+ authenticatedSellerIdRoute: typeof authenticatedSellerIdRouteWithChildren+ authenticatedIndexRoute: typeof authenticatedIndexRoute+}++const authenticatedRouteChildren: authenticatedRouteChildren = {+ authenticatedSellerIdRoute: authenticatedSellerIdRouteWithChildren,+ authenticatedIndexRoute: authenticatedIndexRoute,+}++const authenticatedRouteWithChildren = authenticatedRoute._addFileChildren(+ authenticatedRouteChildren,+)++const rootRouteChildren: RootRouteChildren = {+ authenticatedRoute: authenticatedRouteWithChildren,+ loginRoute: loginRoute,+}+export const routeTree = rootRouteImport+ ._addFileChildren(rootRouteChildren)+ ._addFileTypes<FileRouteTypes>()diff --git a/packages/seller-dashboard/src/routes/__root.tsx b/packages/seller-dashboard/src/routes/__root.tsxnew file mode 100644index 0000000000..d24bb29953--- /dev/null+++ b/packages/seller-dashboard/src/routes/__root.tsx@@ -0,0 +1,15 @@+import { Toaster } from '@spree/dashboard-ui'+import { createRootRoute, Outlet } from '@tanstack/react-router'++export const Route = createRootRoute({+ component: RootLayout,+})++function RootLayout() {+ return (+ <>+ <Outlet />+ <Toaster position="bottom-right" />+ </>+ )+}diff --git a/packages/seller-dashboard/src/routes/_authenticated.tsx b/packages/seller-dashboard/src/routes/_authenticated.tsxnew file mode 100644index 0000000000..fa07857db5--- /dev/null+++ b/packages/seller-dashboard/src/routes/_authenticated.tsx@@ -0,0 +1,13 @@+import { useAuth } from '@spree/dashboard-core'+import { createFileRoute, Navigate, Outlet } from '@tanstack/react-router'++export const Route = createFileRoute('/_authenticated')({+ component: AuthenticatedLayout,+})++function AuthenticatedLayout() {+ const { isInitializing, isAuthenticated } = useAuth()+ if (isInitializing) return null+ if (!isAuthenticated) return <Navigate to="/login" replace />+ return <Outlet />+}diff --git a/packages/seller-dashboard/src/routes/_authenticated/$sellerId.tsx b/packages/seller-dashboard/src/routes/_authenticated/$sellerId.tsxnew file mode 100644index 0000000000..a4452d1f3e--- /dev/null+++ b/packages/seller-dashboard/src/routes/_authenticated/$sellerId.tsx@@ -0,0 +1,34 @@+import { createFileRoute, Outlet, useParams } from '@tanstack/react-router'+import { useEffect } from 'react'+import { rememberSeller, setActiveSeller } from '../../api-client'+import { PanelChrome } from '../../panel-chrome'++export const Route = createFileRoute('/_authenticated/$sellerId')({+ component: SellerLayout,+})++/**+ * Everything below this route acts as one seller.+ *+ * The id in the URL is the single source of truth — the client header follows+ * it, so a seller can keep two sellers open in two tabs without one stealing+ * the other's session, and a bookmarked page opens the seller it belongs to.+ */+function SellerLayout() {+ const { sellerId } = useParams({ from: '/_authenticated/$sellerId' })++ // Synchronously, not in an effect: children render (and fetch) before+ // effects run, and a request sent under the previous seller's header would+ // load the wrong seller's data into this one's screen.+ setActiveSeller(sellerId)++ useEffect(() => {+ rememberSeller(sellerId)+ }, [sellerId])++ return (+ <PanelChrome>+ <Outlet />+ </PanelChrome>+ )+}diff --git a/packages/seller-dashboard/src/routes/_authenticated/$sellerId/index.tsx b/packages/seller-dashboard/src/routes/_authenticated/$sellerId/index.tsxnew file mode 100644index 0000000000..8384c64817--- /dev/null+++ b/packages/seller-dashboard/src/routes/_authenticated/$sellerId/index.tsx@@ -0,0 +1,6 @@+import { createFileRoute } from '@tanstack/react-router'+import { ProfilePage } from '../../../pages/profile'++export const Route = createFileRoute('/_authenticated/$sellerId/')({+ component: ProfilePage,+})diff --git a/packages/seller-dashboard/src/routes/_authenticated/$sellerId/team.tsx b/packages/seller-dashboard/src/routes/_authenticated/$sellerId/team.tsxnew file mode 100644index 0000000000..cc9d3be007--- /dev/null+++ b/packages/seller-dashboard/src/routes/_authenticated/$sellerId/team.tsx@@ -0,0 +1,6 @@+import { createFileRoute } from '@tanstack/react-router'+import { TeamPage } from '../../../pages/team'++export const Route = createFileRoute('/_authenticated/$sellerId/team')({+ component: TeamPage,+})diff --git a/packages/seller-dashboard/src/routes/_authenticated/index.tsx b/packages/seller-dashboard/src/routes/_authenticated/index.tsxnew file mode 100644index 0000000000..97090510f2--- /dev/null+++ b/packages/seller-dashboard/src/routes/_authenticated/index.tsx@@ -0,0 +1,48 @@+import { useQuery } from '@tanstack/react-query'+import { createFileRoute, useNavigate } from '@tanstack/react-router'+import { useEffect } from 'react'+import { useTranslation } from 'react-i18next'+import { rememberedSeller, sellerClient } from '../../api-client'+import { CenteredMessage } from '../../components/centered-message'+import { SellerPicker } from '../../pages/seller-picker'++export const Route = createFileRoute('/_authenticated/')({+ component: SellerEntry,+})++/**+ * Where a signed-in seller lands.+ *+ * Unlike the operator's dashboard, which always redirects into a store, a+ * seller may genuinely run several sellers — so the picker is a real page.+ * It is skipped in the two cases where the answer is already known: a+ * remembered choice from last session, or exactly one seller.+ */+function SellerEntry() {+ const { t } = useTranslation()+ const navigate = useNavigate()++ const { data, isLoading, error } = useQuery({+ queryKey: ['seller', 'me'],+ queryFn: () => sellerClient().me(),+ })++ const sellers = data?.sellers ?? []+ const remembered = rememberedSeller()+ // A remembered id is only honoured if the seller still runs that seller —+ // access can be revoked between sessions, and following a stale id would+ // land them on a page that 403s.+ const target =+ (remembered && sellers.some((seller) => seller.id === remembered) ? remembered : null) ??+ (sellers.length === 1 ? sellers[0].id : null)++ useEffect(() => {+ if (target) navigate({ to: '/$sellerId', params: { sellerId: target }, replace: true })+ }, [navigate, target])++ if (isLoading) return <CenteredMessage>{t('common.loading')}</CenteredMessage>+ if (error) return <CenteredMessage>{t('common.error')}</CenteredMessage>+ if (target) return null++ return <SellerPicker />+}diff --git a/packages/seller-dashboard/src/routes/login.tsx b/packages/seller-dashboard/src/routes/login.tsxnew file mode 100644index 0000000000..cfda855348--- /dev/null+++ b/packages/seller-dashboard/src/routes/login.tsx@@ -0,0 +1,15 @@+import { useAuth } from '@spree/dashboard-core'+import { createFileRoute, Navigate } from '@tanstack/react-router'+import { LoginPage } from '../pages/login'++export const Route = createFileRoute('/login')({+ component: Login,+})++function Login() {+ const { isInitializing, isAuthenticated } = useAuth()+ if (isInitializing) return null+ // A live session landing on /login goes where it was headed instead.+ if (isAuthenticated) return <Navigate to="/" replace />+ return <LoginPage />+}diff --git a/packages/seller-dashboard/src/seller-dashboard.tsx b/packages/seller-dashboard/src/seller-dashboard.tsxnew file mode 100644index 0000000000..74613a60b5--- /dev/null+++ b/packages/seller-dashboard/src/seller-dashboard.tsx@@ -0,0 +1,51 @@+import { AuthProvider, PermissionProvider, queryClient } from '@spree/dashboard-core'+import { ConfirmProvider, ThemeProvider, TooltipProvider } from '@spree/dashboard-ui'+import { QueryClientProvider } from '@tanstack/react-query'+import type { AnyRouter } from '@tanstack/react-router'+import { RouterProvider } from '@tanstack/react-router'+import { StrictMode } from 'react'+import './i18n'++/**+ * The seller panel shell.+ *+ * The same providers as the marketplace operator's dashboard — that is what+ * `@spree/dashboard-core` and `@spree/dashboard-ui` are for — pointed at the+ * Seller API. The host registers that client before rendering:+ *+ * // src/main.tsx+ * import { createRoot } from 'react-dom/client'+ * import { SellerDashboard, createSellerRouter } from '@spree/seller-dashboard'+ * import './api-client' // registers the Seller API client+ * import './styles.css'+ * import { routeTree } from './routeTree.gen'+ *+ * const router = createSellerRouter(routeTree)+ *+ * declare module '@tanstack/react-router' {+ * interface Register {+ * router: typeof router+ * }+ * }+ *+ * createRoot(document.getElementById('root')!).render(<SellerDashboard router={router} />)+ */+export function SellerDashboard({ router }: { router: AnyRouter }) {+ return (+ <StrictMode>+ <QueryClientProvider client={queryClient}>+ <ThemeProvider>+ <TooltipProvider>+ <ConfirmProvider>+ <AuthProvider>+ <PermissionProvider>+ <RouterProvider router={router} />+ </PermissionProvider>+ </AuthProvider>+ </ConfirmProvider>+ </TooltipProvider>+ </ThemeProvider>+ </QueryClientProvider>+ </StrictMode>+ )+}diff --git a/packages/seller-dashboard/src/styles.css b/packages/seller-dashboard/src/styles.cssnew file mode 100644index 0000000000..d43dc4c6aa--- /dev/null+++ b/packages/seller-dashboard/src/styles.css@@ -0,0 +1,18 @@+/* Seller panel CSS entry.+ *+ * Pulls in the design system stylesheet from `@spree/dashboard-ui` — the same+ * components and the same look as the marketplace operator's dashboard, with+ * a different API behind them.+ *+ * `@source` directives for this package and `@spree/dashboard-core` are+ * appended at build time by `spreeSellerDashboardPlugin` from+ * `@spree/seller-dashboard/vite`. Resolution goes through Node module+ * resolution, so paths stay correct under any package layout (workspace+ * symlinks, npm tarballs, pnpm's `.pnpm/` hoisting) — never hardcode them+ * relative to this file.+ *+ * The Vite plugin bundles `@tailwindcss/vite` internally, so host apps must+ * NOT register `tailwindcss()` separately.+ */++@import "@spree/dashboard-ui/styles.css";diff --git a/packages/seller-dashboard/src/vite/index.ts b/packages/seller-dashboard/src/vite/index.tsnew file mode 100644index 0000000000..908e98573c--- /dev/null+++ b/packages/seller-dashboard/src/vite/index.ts@@ -0,0 +1,82 @@+import { createRequire } from 'node:module'+import path from 'node:path'+import {+ type SpreeDashboardPluginOptions as CoreOptions,+ spreeDashboardPlugin as spreeDashboardCorePlugin,+} from '@spree/dashboard-core/vite'+import { TanStackRouterVite } from '@tanstack/router-plugin/vite'+import { index, layout, physical, rootRoute, route } from '@tanstack/virtual-file-routes'+import type { PluginOption } from 'vite'++export interface SpreeSellerDashboardPluginOptions extends CoreOptions {+ /**+ * Where the composed route tree is generated, relative to the host root.+ * Commit this file: it regenerates on every dev start/build, and its diff+ * on a `@spree/seller-dashboard` upgrade shows exactly which pages the+ * upgrade added or moved.+ */+ generatedRouteTree?: string+ /**+ * Host project root. Defaults to `process.cwd()` — correct when Vite runs+ * from the package directory, which is how the starter operates.+ */+ root?: string+}++/**+ * Vite integration for the seller panel.+ *+ * The Tailwind and plugin-discovery half comes from `@spree/dashboard-core`+ * unchanged — neither is admin-specific. Only the route skeleton differs,+ * because a seller's panel is scoped by seller where the operator's is scoped+ * by store.+ */+export function spreeSellerDashboardPlugin(+ options: SpreeSellerDashboardPluginOptions = {},+): PluginOption[] {+ const hostRoot = options.root ?? process.cwd()+ return [+ // Name this shell so Tailwind scans the panel's own components; core+ // defaults to the operator's dashboard, which a seller's host does not+ // install.+ ...spreeDashboardCorePlugin({+ shellPackages: ['@spree/seller-dashboard'],+ ...options,+ }),+ sellerRouterPlugin(hostRoot, options),+ ]+}++/**+ * The TanStack Router generator, configured with a virtual route config+ * mirroring the panel's layout skeleton: public sign-in, then an+ * authenticated branch whose pages all hang off a seller.+ */+function sellerRouterPlugin(hostRoot: string, options: SpreeSellerDashboardPluginOptions) {+ const fromHost = createRequire(path.join(hostRoot, 'package.json'))+ // Resolve the shell's routes directory from wherever the host's+ // `@spree/seller-dashboard` lives (workspace symlink or npm install). The+ // `.` export maps to a file in src/, so `routes/` is its sibling.+ const shellEntry = fromHost.resolve('@spree/seller-dashboard')+ const shellRoutesDir = path.join(path.dirname(shellEntry), 'routes')++ const virtualRouteConfig = rootRoute('__root.tsx', [+ route('/login', 'login.tsx'),+ layout('_authenticated.tsx', [+ index('_authenticated/index.tsx'),+ route('/$sellerId', '_authenticated/$sellerId.tsx', [+ physical('', '_authenticated/$sellerId'),+ ]),+ ]),+ ])++ return TanStackRouterVite({+ target: 'react',+ virtualRouteConfig,+ routesDirectory: shellRoutesDir,+ generatedRouteTree: path.resolve(+ hostRoot,+ options.generatedRouteTree ?? 'src/routeTree.gen.ts',+ ),+ })+}diff --git a/packages/seller-dashboard/tsconfig.app.json b/packages/seller-dashboard/tsconfig.app.jsonnew file mode 100644index 0000000000..2aaf75ec1e--- /dev/null+++ b/packages/seller-dashboard/tsconfig.app.json@@ -0,0 +1,30 @@+{+ "compilerOptions": {+ "tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",+ "target": "ES2022",+ "ignoreDeprecations": "6.0",+ "useDefineForClassFields": true,+ "lib": ["ES2022", "DOM", "DOM.Iterable"],+ "module": "ESNext",+ "types": ["vite/client"],+ "skipLibCheck": true,++ /* Bundler mode */+ "moduleResolution": "bundler",+ "allowImportingTsExtensions": true,+ "verbatimModuleSyntax": true,+ "moduleDetection": "force",+ "noEmit": true,+ "jsx": "react-jsx",++ /* Linting */+ "strict": true,+ "noUnusedLocals": true,+ "noUnusedParameters": true,+ "erasableSyntaxOnly": true,+ "noFallthroughCasesInSwitch": true,+ "noUncheckedSideEffectImports": true+ },+ "include": ["src"],+ "exclude": ["src/vite"]+}diff --git a/packages/seller-dashboard/tsconfig.json b/packages/seller-dashboard/tsconfig.jsonnew file mode 100644index 0000000000..d32ff68200--- /dev/null+++ b/packages/seller-dashboard/tsconfig.json@@ -0,0 +1,4 @@+{+ "files": [],+ "references": [{ "path": "./tsconfig.app.json" }, { "path": "./tsconfig.node.json" }]+}diff --git a/packages/seller-dashboard/tsconfig.node.json b/packages/seller-dashboard/tsconfig.node.jsonnew file mode 100644index 0000000000..52dee95dee--- /dev/null+++ b/packages/seller-dashboard/tsconfig.node.json@@ -0,0 +1,27 @@+{+ "compilerOptions": {+ "tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",+ "target": "ES2023",+ "ignoreDeprecations": "6.0",+ "lib": ["ES2023"],+ "module": "ESNext",+ "types": ["node"],+ "skipLibCheck": true,++ /* Bundler mode */+ "moduleResolution": "bundler",+ "allowImportingTsExtensions": true,+ "verbatimModuleSyntax": true,+ "moduleDetection": "force",+ "noEmit": true,++ /* Linting */+ "strict": true,+ "noUnusedLocals": true,+ "noUnusedParameters": true,+ "erasableSyntaxOnly": true,+ "noFallthroughCasesInSwitch": true,+ "noUncheckedSideEffectImports": true+ },+ "include": ["src/vite", "tsup.config.ts"]+}diff --git a/packages/seller-dashboard/tsup.config.ts b/packages/seller-dashboard/tsup.config.tsnew file mode 100644index 0000000000..ef307d07b4--- /dev/null+++ b/packages/seller-dashboard/tsup.config.ts@@ -0,0 +1,15 @@+import { defineConfig } from 'tsup'++// Compile ONLY the Node-side Vite integration to JS — Node refuses to+// type-strip .ts under node_modules, and vite.config.ts imports resolve+// through Node. bundle: false transpiles 1:1; bare imports (dashboard-core,+// TanStack) resolve through node_modules at runtime.+export default defineConfig({+ entry: ['src/vite/index.ts'],+ outDir: 'dist/vite-plugin',+ format: ['esm'],+ target: 'node20',+ bundle: false,+ splitting: false,+ clean: true,+})diff --git a/packages/seller-dashboard/vite.config.ts b/packages/seller-dashboard/vite.config.tsnew file mode 100644index 0000000000..271bffad4b--- /dev/null+++ b/packages/seller-dashboard/vite.config.ts@@ -0,0 +1,12 @@+import react from '@vitejs/plugin-react'+import { defineConfig } from 'vite'+// Self-import of the shell's own Vite integration — the same composition+// hosts get from `@spree/seller-dashboard/vite`. It wraps the TanStack Router+// generator, so the shell's committed routeTree.gen.ts is produced by the+// exact machinery hosts use, which is what makes the shell's own routes+// typecheck against the tree they compose into.+import { spreeSellerDashboardPlugin } from './src/vite'++export default defineConfig({+ plugins: [spreeSellerDashboardPlugin({ root: import.meta.dirname }), react()],+})diff --git a/packages/seller-sdk/biome.json b/packages/seller-sdk/biome.jsonnew file mode 100644index 0000000000..aa04ce3dcf--- /dev/null+++ b/packages/seller-sdk/biome.json@@ -0,0 +1,8 @@+{+ "$schema": "https://biomejs.dev/schemas/2.4.13/schema.json",+ "root": false,+ "extends": ["../../biome.json"],+ "files": {+ "includes": ["src/**", "tests/**", "!src/types/generated", "!src/zod/generated"]+ }+}diff --git a/packages/seller-sdk/package.json b/packages/seller-sdk/package.jsonnew file mode 100644index 0000000000..3b5d44e6ef--- /dev/null+++ b/packages/seller-sdk/package.json@@ -0,0 +1,90 @@+{+ "name": "@spree/seller-sdk",+ "version": "0.1.0",+ "description": "TypeScript client for the Spree Seller API — the marketplace seller panel.",+ "type": "module",+ "main": "./dist/index.cjs",+ "module": "./dist/index.js",+ "types": "./dist/index.d.ts",+ "exports": {+ ".": {+ "import": {+ "types": "./dist/index.d.ts",+ "default": "./dist/index.js"+ },+ "require": {+ "types": "./dist/index.d.cts",+ "default": "./dist/index.cjs"+ }+ },+ "./types": {+ "import": {+ "types": "./dist/types/index.d.ts",+ "default": "./dist/types/index.js"+ },+ "require": {+ "types": "./dist/types/index.d.cts",+ "default": "./dist/types/index.cjs"+ }+ }+ },+ "files": [+ "dist",+ "README.md",+ "LICENSE"+ ],+ "scripts": {+ "build": "tsup",+ "dev": "tsup --watch",+ "typecheck": "tsc --noEmit",+ "test": "vitest run --passWithNoTests",+ "test:watch": "vitest",+ "lint": "biome check src",+ "lint:fix": "biome check --fix src",+ "format": "biome format --write src",+ "clean": "rm -rf dist",+ "prepublishOnly": "npm run build"+ },+ "keywords": [+ "spree",+ "commerce",+ "ecommerce",+ "admin",+ "api",+ "sdk",+ "typescript"+ ],+ "author": "Vendo Connect Inc.",+ "license": "MIT",+ "repository": {+ "type": "git",+ "url": "https://github.com/spree/spree.git",+ "directory": "packages/admin-sdk"+ },+ "homepage": "https://spreecommerce.org",+ "bugs": {+ "url": "https://github.com/spree/spree/issues"+ },+ "devDependencies": {+ "@spree/sdk-core": "workspace:*",+ "@types/node": "^25.6.0",+ "@vitest/coverage-v8": "^4.1.5",+ "msw": "^2.14.3",+ "tsup": "^8.0.0",+ "tsx": "^4.0.0",+ "typescript": "^6.0.3",+ "vitest": "^4.1.5",+ "yaml": "^2.8.4"+ },+ "peerDependencies": {+ "typescript": ">=4.7.0"+ },+ "peerDependenciesMeta": {+ "typescript": {+ "optional": true+ }+ },+ "engines": {+ "node": ">=18.0.0"+ }+}diff --git a/packages/seller-sdk/src/client.ts b/packages/seller-sdk/src/client.tsnew file mode 100644index 0000000000..ba2970298c--- /dev/null+++ b/packages/seller-sdk/src/client.ts@@ -0,0 +1,127 @@+import type { InternalRequestOptions, RequestConfig, RequestFn, RetryConfig } from '@spree/sdk-core'+import { createRequestFn, resolveRetryConfig, SpreeError } from '@spree/sdk-core'+import { SellerClient } from './seller-client'++export interface SellerClientConfig {+ /** Base URL of the Spree API (e.g., 'https://api.mystore.com'). Use '' for relative URLs (Vite proxy). */+ baseUrl: string+ /**+ * JWT token for seller panel sessions. There is deliberately no secret-key+ * equivalent: the Seller API has no server-to-server credential, because a+ * key that acts as a seller without a seller signing in is exactly what the+ * `seller_api` audience exists to prevent.+ */+ jwtToken?: string+ /**+ * Which seller the signed-in user is acting as. Sent as `X-Spree-Seller-Id`; the+ * store is derived from the seller server-side, never sent alongside, so no+ * header here can widen what the seller reaches.+ */+ sellerId?: string+ /** Custom fetch implementation (optional, defaults to global fetch) */+ fetch?: typeof fetch+ /** Retry configuration. Enabled by default. Pass false to disable. */+ retry?: RetryConfig | false+ /**+ * Credentials mode for cross-origin requests. Defaults to `'include'` so the+ * seller refresh-token cookie is sent on `/api/v3/seller/auth/*`. That cookie+ * has its own name and path — sharing either would let a session issued for+ * one panel be redeemed on the other.+ */+ credentials?: RequestCredentials+}++export interface Client extends SellerClient {+ /** Set or change which seller the signed-in user is acting as. */+ setSeller(sellerId: string): void+ /** Set the JWT for an authenticated seller session. */+ setToken(token: string): void+ /**+ * Register a callback that fires on 401 responses.+ * Return `true` to retry the original request (after refreshing the token via setToken).+ * Return `false` to let the error propagate.+ */+ onUnauthorized(handler: () => Promise<boolean>): void+}++export function createSellerClient(config: SellerClientConfig): Client {+ const baseUrl = config.baseUrl.replace(/\/$/, '')+ const fetchFn = config.fetch || fetch.bind(globalThis)+ const retryConfig = resolveRetryConfig(config.retry)+ const requestConfig: RequestConfig = {+ baseUrl,+ fetchFn,+ retryConfig,+ credentials: config.credentials ?? 'include',+ }++ let currentToken = config.jwtToken+ let currentSellerId = config.sellerId+ let unauthorizedHandler: (() => Promise<boolean>) | null = null++ const basePath = '/api/v3/seller'++ const dynamicRequestFn: RequestFn = async <T>(+ method: string,+ path: string,+ options: InternalRequestOptions = {},+ ): Promise<T> => {+ const extraHeaders: Record<string, string> = {}+ // Auth endpoints run before a seller is chosen — `/me` is what tells the+ // panel which sellers the user may act for — so a stale id from a+ // previous session must never be able to 403 the way back in.+ if (currentSellerId && !path.startsWith('/auth/')) {+ extraHeaders['X-Spree-Seller-Id'] = currentSellerId+ }++ const mergedOptions: InternalRequestOptions = {+ ...options,+ headers: {+ ...extraHeaders,+ ...options.headers,+ },+ }++ const makeRequest = () => {+ const requestFn = createRequestFn(requestConfig, basePath, {+ headerName: 'Authorization',+ headerValue: currentToken ? `Bearer ${currentToken}` : '',+ })+ return requestFn<T>(method, path, mergedOptions)+ }++ try {+ return await makeRequest()+ } catch (error) {+ if (+ error instanceof SpreeError &&+ error.status === 401 &&+ unauthorizedHandler &&+ !path.includes('/auth/')+ ) {+ const shouldRetry = await unauthorizedHandler()+ if (shouldRetry) {+ return makeRequest()+ }+ }+ throw error+ }+ }++ const sellerClient = new SellerClient(dynamicRequestFn)+ const client = Object.create(sellerClient) as Client++ client.setSeller = (sellerId: string) => {+ currentSellerId = sellerId+ }++ client.setToken = (token: string) => {+ currentToken = token+ }++ client.onUnauthorized = (handler: () => Promise<boolean>) => {+ unauthorizedHandler = handler+ }++ return client+}diff --git a/packages/seller-sdk/src/index.ts b/packages/seller-sdk/src/index.tsnew file mode 100644index 0000000000..e48bd90a0d--- /dev/null+++ b/packages/seller-sdk/src/index.ts@@ -0,0 +1,12 @@+export type { RequestOptions, RetryConfig } from '@spree/sdk-core'+// Request infrastructure (re-exported from sdk-core)+export { SpreeError } from '@spree/sdk-core'+// `Client` is the whole configured client (auth + resources + token/seller+// setters); `SellerClient` below is just the resource group. Exported under+// both names so hosts can say what they mean.+export type { Client, Client as SellerApiClient, SellerClientConfig } from './client'+export { createSellerClient } from './client'+export type { MeResponse, ProfileUpdateParams, SellerAddressParams } from './seller-client'+// Client class, for advanced use and subclassing+export { SellerClient } from './seller-client'+export type * from './types'diff --git a/packages/seller-sdk/src/seller-client.ts b/packages/seller-sdk/src/seller-client.tsnew file mode 100644index 0000000000..d0050dfe9e--- /dev/null+++ b/packages/seller-sdk/src/seller-client.ts@@ -0,0 +1,116 @@+import type { RequestFn, RequestOptions } from '@spree/sdk-core'+import type { AuthTokens, Profile, SellerSummary, TeamMember } from './types'++/**+ * Resource methods for the Spree Seller API — the marketplace seller panel.+ *+ * Every path is relative to `/api/v3/seller` and is scoped server-side to the+ * seller named in `X-Spree-Seller-Id`, so nothing here takes a seller id: a+ * seller acts as one seller at a time, chosen from the list `me()` returns.+ */+export class SellerClient {+ constructor(private readonly request: RequestFn) {}++ readonly auth = {+ /**+ * Signs a seller in. Fails for a store staff member who runs no seller —+ * authenticating is not enough, since staff share the same user class.+ */+ login: (+ params: { email: string; password: string },+ options?: RequestOptions,+ ): Promise<AuthTokens> =>+ this.request<AuthTokens>('POST', '/auth/login', { ...options, body: params }),++ /** Exchanges the refresh cookie for a fresh access token. */+ refresh: (options?: RequestOptions): Promise<AuthTokens> =>+ this.request<AuthTokens>('POST', '/auth/refresh', options),++ /** Clears the session server-side and drops the refresh cookie. */+ logout: (options?: RequestOptions): Promise<void> =>+ this.request<void>('POST', '/auth/logout', options),++ /** Sign-in methods this marketplace offers sellers, for the login page. */+ providers: (options?: RequestOptions): Promise<{ providers: unknown[] }> =>+ this.request<{ providers: unknown[] }>('GET', '/auth/providers', options),+ }++ /**+ * The signed-in seller: who they are, which sellers they may act for, and+ * what they may do on the selected one.+ *+ * `permission_keys` is empty until a seller is named — capability is per+ * seller, so there is no answer spanning all of them.+ */+ me = (options?: RequestOptions): Promise<MeResponse> =>+ this.request<MeResponse>('GET', '/me', options)++ /** The seller's own record, as they maintain it. */+ readonly profile = {+ get: (options?: RequestOptions): Promise<Profile> =>+ this.request<Profile>('GET', '/profile', options),++ /**+ * Edits presentation, contact details and addresses. `status`, the+ * settlement terms and `slug` are readable but not writable — the+ * lifecycle belongs to the marketplace operator.+ */+ update: (params: ProfileUpdateParams, options?: RequestOptions): Promise<Profile> =>+ this.request<Profile>('PATCH', '/profile', { ...options, body: params }),+ }++ /** Who runs this seller. */+ readonly team = {+ list: (options?: RequestOptions): Promise<{ data: TeamMember[] }> =>+ this.request<{ data: TeamMember[] }>('GET', '/team', options),++ /**+ * Invites a colleague. They join when they accept; the seller's own+ * lifecycle is untouched, since hiring is not a transition.+ */+ invite: (params: { email: string }, options?: RequestOptions): Promise<unknown> =>+ this.request<unknown>('POST', '/team', { ...options, body: params }),++ /** Revokes a member's access. The last remaining member cannot be removed. */+ remove: (id: string, options?: RequestOptions): Promise<void> =>+ this.request<void>('DELETE', `/team/${id}`, options),+ }+}++/** What `/seller/me` answers. */+export interface MeResponse {+ user: TeamMember+ sellers: SellerSummary[]+ permission_keys: string[]+}++/** The fields a seller may change on their own record. */+export interface ProfileUpdateParams {+ name?: string+ contact_email?: string | null+ billing_email?: string | null+ /** Sanitized HTML — the seller's public description. */+ about?: string | null+ /** ActiveStorage signed ids; `null` removes the attachment. */+ logo?: string | null+ square_logo?: string | null+ cover_photo?: string | null+ billing_address?: SellerAddressParams+ returns_address?: SellerAddressParams+}++export interface SellerAddressParams {+ first_name?: string+ last_name?: string+ company?: string+ address1?: string+ address2?: string+ city?: string+ postal_code?: string+ zipcode?: string+ phone?: string+ country_code?: string+ state_code?: string+ state_name?: string+ label?: string+}diff --git a/packages/seller-sdk/src/types/generated/Address.ts b/packages/seller-sdk/src/types/generated/Address.tsnew file mode 100644index 0000000000..dc715bd353--- /dev/null+++ b/packages/seller-sdk/src/types/generated/Address.ts@@ -0,0 +1,28 @@+// Typelizer digest ae6dcb29f0fe083fb2edf1bbc854d643+//+// DO NOT MODIFY: This file was automatically generated by Typelizer.++type Address = {+ id: string;+ first_name: string | null;+ last_name: string | null;+ full_name: string;+ address1: string | null;+ address2: string | null;+ postal_code: string | null;+ city: string | null;+ phone: string | null;+ company: string | null;+ country_name: string;+ country_code: string;+ state_text: string | null;+ state_code: string | null;+ quick_checkout: boolean;+ is_default_billing: boolean;+ is_default_shipping: boolean;+ state_abbr: string | null;+ country_iso: string;+ state_name: string | null;+}++export default Address;diff --git a/packages/seller-sdk/src/types/generated/Invitation.ts b/packages/seller-sdk/src/types/generated/Invitation.tsnew file mode 100644index 0000000000..5e0b57fdfb--- /dev/null+++ b/packages/seller-sdk/src/types/generated/Invitation.ts@@ -0,0 +1,14 @@+// Typelizer digest 2f0e6fde2c5925909616a667b6846796+//+// DO NOT MODIFY: This file was automatically generated by Typelizer.++type Invitation = {+ id: string;+ email: string;+ created_at: string;+ status: string;+ expires_at: string | null;+ accepted_at: string | null;+}++export default Invitation;diff --git a/packages/seller-sdk/src/types/generated/Profile.ts b/packages/seller-sdk/src/types/generated/Profile.tsnew file mode 100644index 0000000000..04c304e156--- /dev/null+++ b/packages/seller-sdk/src/types/generated/Profile.ts@@ -0,0 +1,31 @@+// Typelizer digest 6b7b053665b4f97a30ab33385227b3c6+//+// DO NOT MODIFY: This file was automatically generated by Typelizer.+import type {Address} from '@/types'++type Profile = {+ id: string;+ name: string;+ slug: string;+ about: string;+ about_html: string;+ logo_url: string | null;+ square_logo_url: string | null;+ cover_photo_url: string | null;+ status: string;+ contact_email: string | null;+ billing_email: string | null;+ tax_remittance: string;+ payouts_schedule_interval: string | null;+ holiday_mode_until: string | null;+ terms_accepted_at: string | null;+ created_at: string;+ minimum_payout_amount: string | null;+ on_holiday: boolean;+ sellable: boolean;+ products_count: number;+ billing_address?: Address;+ returns_address?: Address;+}++export default Profile;diff --git a/packages/seller-sdk/src/types/generated/TeamMember.ts b/packages/seller-sdk/src/types/generated/TeamMember.tsnew file mode 100644index 0000000000..67984c2b0d--- /dev/null+++ b/packages/seller-sdk/src/types/generated/TeamMember.ts@@ -0,0 +1,15 @@+// Typelizer digest bf84647793494b48e041c4eaa864a85f+//+// DO NOT MODIFY: This file was automatically generated by Typelizer.++type TeamMember = {+ id: string;+ email: string;+ first_name: string | null;+ last_name: string | null;+ full_name: string | null;+ created_at: string;+ avatar_url: string | null;+}++export default TeamMember;diff --git a/packages/seller-sdk/src/types/generated/index.ts b/packages/seller-sdk/src/types/generated/index.tsnew file mode 100644index 0000000000..f055630176--- /dev/null+++ b/packages/seller-sdk/src/types/generated/index.ts@@ -0,0 +1,7 @@+// Typelizer digest 8ec41eedc9512a04635310303372ff56+//+// DO NOT MODIFY: This file was automatically generated by Typelizer.+export type { default as Address } from './Address'+export type { default as Invitation } from './Invitation'+export type { default as Profile } from './Profile'+export type { default as TeamMember } from './TeamMember'diff --git a/packages/seller-sdk/src/types/index.ts b/packages/seller-sdk/src/types/index.tsnew file mode 100644index 0000000000..a04c091407--- /dev/null+++ b/packages/seller-sdk/src/types/index.ts@@ -0,0 +1,34 @@+// Re-export shared types from sdk-core+export type {+ ErrorResponse,+ ListParams,+ ListResponse,+ PaginatedResponse,+ PaginationMeta,+} from '@spree/sdk-core'++// Generated from the Seller API's serializers (`Spree::Api::V3::Seller::*`).+// `TeamMember`, `Invitation`, `Profile` and `Address` come from here — the+// serializers are the contract, so hand-writing them again would let the two+// drift apart silently.+export * from './generated'++import type { default as TeamMember } from './generated/TeamMember'++/**+ * A seller as the login and `/me` responses summarise it — enough for the+ * panel to let a seller choose which seller to act as.+ */+export interface SellerSummary {+ id: string+ name: string+ slug?: string+ status: string+}++/** What the login and refresh endpoints answer. */+export interface AuthTokens {+ token: string+ user: TeamMember+ sellers: SellerSummary[]+}diff --git a/packages/seller-sdk/tsconfig.json b/packages/seller-sdk/tsconfig.jsonnew file mode 100644index 0000000000..7e1e5236f0--- /dev/null+++ b/packages/seller-sdk/tsconfig.json@@ -0,0 +1,28 @@+{+ "compilerOptions": {+ "target": "ES2022",+ "module": "ESNext",+ "moduleResolution": "bundler",+ "lib": ["ES2022", "DOM"],+ "ignoreDeprecations": "6.0",+ "strict": true,+ "esModuleInterop": true,+ "skipLibCheck": true,+ "forceConsistentCasingInFileNames": true,+ "declaration": true,+ "declarationMap": true,+ "sourceMap": true,+ "outDir": "./dist",+ "rootDir": "./src",+ "paths": {+ "@/types": ["./src/types/generated/index.ts"]+ },+ "resolveJsonModule": true,+ "noUnusedLocals": true,+ "noUnusedParameters": true,+ "noImplicitReturns": true,+ "noFallthroughCasesInSwitch": true+ },+ "include": ["src/**/*"],+ "exclude": ["node_modules", "dist"]+}diff --git a/packages/seller-sdk/tsup.config.ts b/packages/seller-sdk/tsup.config.tsnew file mode 100644index 0000000000..ef64090ff3--- /dev/null+++ b/packages/seller-sdk/tsup.config.ts@@ -0,0 +1,23 @@+import path from 'node:path'+import { defineConfig } from 'tsup'++export default defineConfig({+ entry: {+ index: 'src/index.ts',+ 'types/index': 'src/types/index.ts',+ },+ format: ['cjs', 'esm'],+ dts: { resolve: ['@spree/sdk-core'] },+ splitting: false,+ sourcemap: true,+ clean: true,+ treeshake: true,+ minify: false,+ // sdk-core is workspace-private; inline it into the published bundle.+ noExternal: ['@spree/sdk-core'],+ esbuildOptions(options) {+ options.alias = {+ '@/types': path.resolve(import.meta.dirname, 'src/types/generated/index.ts'),+ }+ },+})diff --git a/packages/seller-sdk/vitest.config.ts b/packages/seller-sdk/vitest.config.tsnew file mode 100644index 0000000000..bfe3e781da--- /dev/null+++ b/packages/seller-sdk/vitest.config.ts@@ -0,0 +1,20 @@+import path from 'node:path'+import { defineConfig } from 'vitest/config'++export default defineConfig({+ resolve: {+ alias: {+ '@/types': path.resolve(import.meta.dirname, 'src/types/generated/index.ts'),+ },+ },+ test: {+ globals: true,+ environment: 'node',+ setupFiles: ['./tests/setup.ts'],+ coverage: {+ provider: 'v8',+ include: ['src/**/*.ts'],+ exclude: ['src/types/**'],+ },+ },+})diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 4a0005e632..4c837b4999 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -651,6 +651,146 @@ importers:specifier: ^6.0.3version: 6.0.3+ packages/seller-dashboard:+ dependencies:+ '@spree/dashboard-core':+ specifier: workspace:*+ version: link:../dashboard-core+ '@spree/dashboard-ui':+ specifier: workspace:*+ version: link:../dashboard-ui+ '@spree/seller-sdk':+ specifier: workspace:*+ version: link:../seller-sdk+ '@tanstack/react-query':+ specifier: ^5.90.2+ version: 5.100.9([email protected])+ '@tanstack/react-router':+ specifier: ^1.133.32+ '@tanstack/router-plugin':+ specifier: ^1.167.35+ version: 1.167.35(@tanstack/[email protected]([email protected]([email protected]))([email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected]))+ '@tanstack/virtual-file-routes':+ specifier: ^1.162.0+ version: 1.162.0+ i18next:+ specifier: ^25.6.0+ version: 25.10.10([email protected])+ lucide-react:+ specifier: ^0.545.0+ version: 0.545.0([email protected])+ react-hook-form:+ specifier: ^7.65.0+ version: 7.75.0([email protected])+ react-i18next:+ specifier: ^16.0.0+ version: 16.6.6([email protected]([email protected]))([email protected]([email protected]))([email protected])([email protected])+ sonner:+ specifier: ^2.0.7+ devDependencies:+ '@biomejs/biome':+ specifier: 2.4.13+ version: 2.4.13+ '@types/node':+ specifier: ^25.6.0+ version: 25.6.0+ '@types/react':+ specifier: ^19.2.2+ version: 19.2.14+ '@types/react-dom':+ specifier: ^19.2.1+ version: 19.2.3(@types/[email protected])+ '@vitejs/plugin-react':+ specifier: ^6.0.1+ version: 6.0.1([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected]))+ react:+ specifier: ^19.2.0+ version: 19.2.6+ react-dom:+ specifier: ^19.2.0+ version: 19.2.6([email protected])+ tsup:+ specifier: ^8.5.0+ version: 8.5.1([email protected])([email protected])([email protected])([email protected])([email protected])+ typescript:+ specifier: ~6.0.3+ version: 6.0.3+ vite:+ specifier: ^8.0.16+ version: 8.0.16(@types/[email protected])([email protected])([email protected])([email protected])([email protected])++ packages/seller-dashboard-starter:+ dependencies:+ '@spree/seller-dashboard':+ specifier: workspace:^+ version: link:../seller-dashboard+ '@spree/seller-sdk':+ specifier: workspace:^+ version: link:../seller-sdk+ '@tanstack/react-query':+ specifier: ^5.100.9+ version: 5.100.9([email protected])+ '@tanstack/react-router':+ specifier: ^1.169.2+ react:+ specifier: ^19.2.6+ version: 19.2.6+ react-dom:+ specifier: ^19.2.6+ version: 19.2.6([email protected])+ devDependencies:+ '@biomejs/biome':+ specifier: ^2.4.14+ version: 2.4.14+ '@types/react':+ specifier: ^19.2.14+ version: 19.2.14+ '@types/react-dom':+ specifier: ^19.2.3+ version: 19.2.3(@types/[email protected])+ '@vitejs/plugin-react':+ specifier: ^6.0.1+ version: 6.0.1([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected]))+ typescript:+ specifier: ~6.0.3+ version: 6.0.3+ vite:+ specifier: ^8.0.16+ version: 8.0.16(@types/[email protected])([email protected])([email protected])([email protected])([email protected])++ packages/seller-sdk:+ devDependencies:+ '@spree/sdk-core':+ specifier: workspace:*+ version: link:../sdk-core+ '@types/node':+ specifier: ^25.6.0+ version: 25.6.0+ '@vitest/coverage-v8':+ specifier: ^4.1.5+ version: 4.1.5([email protected])+ msw:+ specifier: ^2.14.3+ version: 2.14.3(@types/[email protected])([email protected])+ tsup:+ specifier: ^8.0.0+ version: 8.5.1([email protected])([email protected])([email protected])([email protected])([email protected])+ tsx:+ specifier: ^4.0.0+ version: 4.21.0+ typescript:+ specifier: ^6.0.3+ version: 6.0.3+ vitest:+ specifier: ^4.1.5+ version: 4.1.5(@types/[email protected])(@vitest/[email protected])([email protected](@types/[email protected])([email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected]))+ yaml:+ specifier: ^2.8.4+ version: 2.8.4+packages:'@babel/[email protected]':@@ -817,23 +957,47 @@ packages:resolution: {integrity: sha512-6zABk/ECA/QYSCQ1NGiVwwbQerUCZ+TQbp64Q3AgmfNvurHH0j8TtXa1qbShXA6qqkpAj4V5W8pP6mLe1mcMqA==}engines: {node: '>=18'}+ '@biomejs/[email protected]':+ resolution: {integrity: sha512-gLXOwkOBBg0tr7bDsqlkIh4uFeKuMjxvqsrb1Tukww1iDmHcfr4Uu8MoQxp0Rcte+69+osRNWXwHsu/zxT6XqA==}+ engines: {node: '>=14.21.3'}+ hasBin: true+'@biomejs/[email protected]':resolution: {integrity: sha512-TmAvxOEgrpLypzVGJ8FulIZnlyA9TxrO1hyqYrCz9r+bwma9xXxuLA5IuYnj55XQneFx460KjRbx6SWGLkg3bQ==}engines: {node: '>=14.21.3'}hasBin: true+ '@biomejs/[email protected]':+ resolution: {integrity: sha512-2KImO1jhNFBa2oWConyr0x6flxbQpGKv6902uGXpYM62Xyem8U80j441SyUJ8KyngsmKbQjeIv1q2CQfDkNnYg==}+ engines: {node: '>=14.21.3'}+ cpu: [arm64]+ os: [darwin]+'@biomejs/[email protected]':resolution: {integrity: sha512-XvgoE9XOawUOQPdmvs4J7wPhi/DLwSCGks3AlPJDmh34O0awRTqCED1HRcRDdpf1Zrp4us4MGOOdIxNpbqNF5Q==}engines: {node: '>=14.21.3'}cpu: [arm64]os: [darwin]+ '@biomejs/[email protected]':+ resolution: {integrity: sha512-BKrJklbaFN4p1Ts4kPBczo+PkbsHQg57kmJ+vON9u2t6uN5okYHaSr7h/MutPCWQgg2lglaWoSmm+zhYW+oOkg==}+ engines: {node: '>=14.21.3'}+ cpu: [x64]+ os: [darwin]+'@biomejs/[email protected]':resolution: {integrity: sha512-jE7hKBCFhOx3uUh+ZkWBfOHxAcILPfhFplNkuID/eZeSTLHzfZzoZxW8fbqY9xXRnPi7jGNAf1iPVR+0yWsM/Q==}engines: {node: '>=14.21.3'}cpu: [x64]os: [darwin]+ '@biomejs/[email protected]':+ resolution: {integrity: sha512-U5MsuBQW25dXaYtqWWSPM3P96H6Y+fHuja3TQpMNnylocHW0tEbtFTDlUj6oM+YJLntvEkQy4grBvQNUD4+RCg==}+ engines: {node: '>=14.21.3'}+ cpu: [arm64]+ os: [linux]+ libc: [musl]+'@biomejs/[email protected]':resolution: {integrity: sha512-/z+6gqAqqUQTHazwStxSXKHg9b8UvqBmDFRp+c4wYbq2KXhELQDon9EoC9RpmQ8JWkqQx/lIUy/cs+MhzDZp6A==}engines: {node: '>=14.21.3'}@@ -841,6 +1005,13 @@ packages:os: [linux]libc: [musl]+ '@biomejs/[email protected]':+ resolution: {integrity: sha512-NzkUDSqfvMBrPplKgVr3aXLHZ2NEELvvF4vZxXulEylKWIGqlvNEcwUcj9OLrn75TD3lJ/GIqCVlBwd1MZCuYQ==}+ engines: {node: '>=14.21.3'}+ cpu: [arm64]+ os: [linux]+ libc: [glibc]+'@biomejs/[email protected]':resolution: {integrity: sha512-2TELhZnW5RSLL063l9rc5xLpA0ZIw0Ccwy/0q384rvNAgFw3yI76bd59547yxowdQr5MNPET/xDLrLuvgSeeWQ==}engines: {node: '>=14.21.3'}@@ -848,6 +1019,13 @@ packages:os: [linux]libc: [glibc]+ '@biomejs/[email protected]':+ resolution: {integrity: sha512-Z601MienRgTBDza/+u2CH3RSrWoXo9rtr8NK6A4KJzqGgfxx+H3VlyLgTJ4sRo40T3pIsqpTmiOQEvYzQvBRvQ==}+ engines: {node: '>=14.21.3'}+ cpu: [x64]+ os: [linux]+ libc: [musl]+'@biomejs/[email protected]':resolution: {integrity: sha512-R6BWgJdQOwW9ulJatuTVrQkjnODjqHZkKNOqb1sz++3Noe5LYd0i3PchnOBUCYAPHoPWHhjJqbdZlHEu0hpjdA==}engines: {node: '>=14.21.3'}@@ -855,6 +1033,13 @@ packages:os: [linux]libc: [musl]+ '@biomejs/[email protected]':+ resolution: {integrity: sha512-Az3ZZedYRBo9EQzNnD9SxFcR1G5QsGo6VEc2hIyVPZ1rdKwee/7E9oeBBZFpE8Z44ekxsDQBqbiWGW5ShOhUSQ==}+ engines: {node: '>=14.21.3'}+ cpu: [x64]+ os: [linux]+ libc: [glibc]+'@biomejs/[email protected]':resolution: {integrity: sha512-zHrlQZDBDUz4OLAraYpWKcnLS6HOewBFWYOzY91d1ZjdqZwibOyb6BEu6WuWLugyo0P3riCmsbV9UqV1cSXwQg==}engines: {node: '>=14.21.3'}@@ -862,12 +1047,24 @@ packages:os: [linux]libc: [glibc]+ '@biomejs/[email protected]':+ resolution: {integrity: sha512-Px9PS2B5/Q183bUwy/5VHqp3J2lzdOCeVGzMpphYfl8oSa7VDCqenBdqWpy6DCy/en4Rbf/Y1RieZF6dJPcc9A==}+ engines: {node: '>=14.21.3'}+ cpu: [arm64]+ os: [win32]+'@biomejs/[email protected]':resolution: {integrity: sha512-M3EH5hqOI/F/FUA2u4xcLoUgmxd218mvuj/6JL7Hv2toQvr2/AdOvKSpGkoRuWFCtQPVa+ZqkEV3Q5xBA9+XSA==}engines: {node: '>=14.21.3'}cpu: [arm64]os: [win32]+ '@biomejs/[email protected]':+ resolution: {integrity: sha512-tTcMkXyBrmHi9BfrD2VNHs/5rYIUKETqsBlYOvSAABwBkJhSDVb5e7wPukftsQbO3WzQkXe6kaztC6WtUOXSoQ==}+ engines: {node: '>=14.21.3'}+ cpu: [x64]+ os: [win32]+'@biomejs/[email protected]':resolution: {integrity: sha512-WL0EG5qE+EAKomGXbf2g6VnSKJhTL3tXC0QRzWRwA5VpjxNYa6H4P7ZWfymbGE4IhZZQi1KXQ2R0YjwInmz2fA==}engines: {node: '>=14.21.3'}@@ -3051,6 +3248,14 @@ packages:resolution: {integrity: sha512-eKCa6bwnJhvxj14kZk5NCPc6Hb6BdsU9DZcOnmQKSnO1VKrfV0zCvtttPZUsBvjmNDn8rpcJfpwSYnHBjc95MQ==}engines: {node: '>=18.18.0'}+ resolution: {integrity: sha512-cqUW2Z3EkRx7NqSyywjkgCLK7KLCL6IFVFcONG7nVYIJ3ekZ1/N5jUsihHV6Bq37NfhgtczxJcxduELtjTwkuQ==}+ peerDependencies:+ typescript: ^5 || ^6+ peerDependenciesMeta:+ typescript:+ optional: true+resolution: {integrity: sha512-zwBHldHdTmwN7r6UNc7lC6GWNN+YYg3DrRSeHR5PRRBf5QnJZcYHrQc0uaU26qZeYxR7iFZD+Y315dPnKP47wA==}peerDependencies:@@ -3364,6 +3569,11 @@ packages:resolution: {integrity: sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==}+ resolution: {integrity: sha512-7r1/yUuflQDSt4f1bpn5ZAocyIxcTyVyBBChSVtBKn5M+392cPmI5YJMWOJKk/HUWGm5wg83chlAZtCcGbEZtw==}+ peerDependencies:+ react: ^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0+resolution: {integrity: sha512-+1mdWcfSJVUsaTIjN9zoezmUhfXo5l0vP7ekBMPo3jcS/aIkxHnXqAPsByszMZx/Y8oQBRJxJx5xg+RH3urzxA==}peerDependencies:@@ -3795,6 +4005,22 @@ packages:peerDependencies:react: ^16.8.0 || ^17 || ^18 || ^19+ resolution: {integrity: sha512-ZgL2HUoW34UKUkOV7uSQFE1CDnRPD+tCR3ywSuWH7u2iapnz86U8Bi3Vrs620qNDzCf1F47NxglCEkchCTDOHw==}+ peerDependencies:+ i18next: '>= 25.10.9'+ react: '>= 16.8.0'+ react-dom: '*'+ react-native: '*'+ typescript: ^5 || ^6+ peerDependenciesMeta:+ react-dom:+ optional: true+ react-native:+ optional: true+ typescript:+ optional: true+resolution: {integrity: sha512-0ooKbGLU8JXhe1zwpQUWIeXSgLPOfwJmgheWRIUpcoA0CpyabpGhayjdG+/eA5esC1AQ8h2jWpXjJfzQzeDOCw==}peerDependencies:@@ -4719,6 +4945,17 @@ snapshots:'@bcoe/[email protected]': {}+ '@biomejs/[email protected]':+ optionalDependencies:+ '@biomejs/cli-darwin-arm64': 2.4.13+ '@biomejs/cli-darwin-x64': 2.4.13+ '@biomejs/cli-linux-arm64': 2.4.13+ '@biomejs/cli-linux-arm64-musl': 2.4.13+ '@biomejs/cli-linux-x64': 2.4.13+ '@biomejs/cli-linux-x64-musl': 2.4.13+ '@biomejs/cli-win32-arm64': 2.4.13+ '@biomejs/cli-win32-x64': 2.4.13+'@biomejs/[email protected]':optionalDependencies:'@biomejs/cli-darwin-arm64': 2.4.14@@ -4730,27 +4967,51 @@ snapshots:'@biomejs/cli-win32-arm64': 2.4.14'@biomejs/cli-win32-x64': 2.4.14+ '@biomejs/[email protected]':+ optional: true+'@biomejs/[email protected]':optional: true+ '@biomejs/[email protected]':+ optional: true+'@biomejs/[email protected]':optional: true+ '@biomejs/[email protected]':+ optional: true+'@biomejs/[email protected]':optional: true+ '@biomejs/[email protected]':+ optional: true+'@biomejs/[email protected]':optional: true+ '@biomejs/[email protected]':+ optional: true+'@biomejs/[email protected]':optional: true+ '@biomejs/[email protected]':+ optional: true+'@biomejs/[email protected]':optional: true+ '@biomejs/[email protected]':+ optional: true+'@biomejs/[email protected]':optional: true+ '@biomejs/[email protected]':+ optional: true+'@biomejs/[email protected]':optional: true@@ -6820,6 +7081,12 @@ snapshots:+ dependencies:+ '@babel/runtime': 7.29.2+ optionalDependencies:+ typescript: 6.0.3+optionalDependencies:typescript: 6.0.3@@ -7034,6 +7301,10 @@ snapshots:dependencies:yallist: 3.1.1+ dependencies:+ react: 19.2.6+dependencies:react: 19.2.6@@ -7467,6 +7738,17 @@ snapshots:dependencies:react: 19.2.6+ [email protected]([email protected]([email protected]))([email protected]([email protected]))([email protected])([email protected]):+ dependencies:+ '@babel/runtime': 7.29.2+ html-parse-stringify: 3.0.1+ i18next: 25.10.10([email protected])+ react: 19.2.6+ use-sync-external-store: 1.6.0([email protected])+ optionalDependencies:+ react-dom: 19.2.6([email protected])+ typescript: 6.0.3+[email protected]([email protected]([email protected]))([email protected]([email protected]))([email protected])([email protected]):dependencies:'@babel/runtime': 7.29.2diff --git a/spree/api/app/controllers/concerns/spree/api/v3/seller/seller_context.rb b/spree/api/app/controllers/concerns/spree/api/v3/seller/seller_context.rbindex b73c2c7e0c..e7311679ad 100644--- a/spree/api/app/controllers/concerns/spree/api/v3/seller/seller_context.rb+++ b/spree/api/app/controllers/concerns/spree/api/v3/seller/seller_context.rb@@ -37,9 +37,17 @@ module Spree## @return [Spree::Seller, nil]def current_seller- return @current_seller if defined?(@current_seller)+ return @current_seller if defined?(@current_seller) && !@current_seller.nil?- @current_seller = resolve_current_seller+ # Deliberately not memoising a nil: the locale/currency chain reads+ # `current_store` — and so this — before authentication has run, and+ # caching that first miss would leave a controller which skips the+ # context callback (MeController) permanently without a seller even with+ # a valid header.+ resolved = resolve_current_seller+ @current_seller = resolved if resolved++ resolvedend# Derived from the seller, so a seller can never widen their reach bydiff --git a/spree/api/app/controllers/spree/api/v3/seller/auth_controller.rb b/spree/api/app/controllers/spree/api/v3/seller/auth_controller.rbindex ddf9cb3c36..ef9642cc68 100644--- a/spree/api/app/controllers/spree/api/v3/seller/auth_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/seller/auth_controller.rb@@ -136,7 +136,7 @@ module Spreedef auth_response(user){token: generate_jwt(user, audience: Spree::Api::V3::JwtAuthentication::JWT_AUDIENCE_SELLER),- user: Spree.api.admin_user_serializer.new(user, params: { store: user.sellers.first&.store }).to_h,+ user: Spree.api.seller_team_member_serializer.new(user, params: { store: user.sellers.first&.store }).to_h,sellers: serialized_sellers(user)}enddiff --git a/spree/api/app/controllers/spree/api/v3/seller/me_controller.rb b/spree/api/app/controllers/spree/api/v3/seller/me_controller.rbindex a54e81e22f..00e7f5e608 100644--- a/spree/api/app/controllers/spree/api/v3/seller/me_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/seller/me_controller.rb@@ -22,7 +22,7 @@ module Spreedef me_response{- user: Spree.api.admin_user_serializer.new(current_user, params: serializer_params).to_h,+ user: Spree.api.seller_team_member_serializer.new(current_user, params: serializer_params).to_h,sellers: serialized_sellers,permission_keys: permission_keys}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.rbnew file mode 100644index 0000000000..84513b86e7--- /dev/null+++ b/spree/api/app/controllers/spree/api/v3/seller/profile_controller.rb@@ -0,0 +1,73 @@+module Spree+ module Api+ module V3+ module Seller+ # The seller's own record, as they maintain it.+ #+ # Singular by nature: there is exactly one seller in play, and it is+ # `current_seller` — never an id from the request. A seller cannot+ # address another seller here even by guessing one.+ #+ # What they may change is presentation, contact and addresses. Absent+ # by design: `status` (the lifecycle belongs to the operator's+ # workflows), the settlement and tax configuration, and `slug` — a+ # seller renaming their own storefront address breaks every link+ # pointing at it.+ class ProfileController < Seller::BaseController+ # A singular resource, so this extends the plain base rather than+ # ResourceController — which is where the params normalizer lives.+ include Spree::Api::V3::ParamsNormalizer++ scoped_resource :seller_profile++ def show+ render json: serialize_seller+ end++ def update+ if current_seller.update(permitted_params)+ render json: serialize_seller+ else+ render_validation_error(current_seller.errors)+ end+ end++ protected++ # The params normalizer resolves nested attributes against this.+ def model_class+ Spree::Seller+ end++ def read_actions+ %w[show]+ end++ # Enumerated rather than borrowing the legacy global list, which+ # permits :id, :user_id and :deleted_at.+ ADDRESS_KEYS = [+ :first_name, :last_name, :company, :address1, :address2, :city,+ :postal_code, :zipcode, :phone, :country_code, :state_code, :state_name, :label+ ].freeze++ def permitted_params+ normalize_params(+ params.permit(:name, :contact_email, :billing_email, :about,+ :logo, :square_logo, :cover_photo,+ billing_address: ADDRESS_KEYS,+ returns_address: ADDRESS_KEYS)+ )+ end++ private++ def serialize_seller+ Spree.api.seller_profile_serializer.new(+ current_seller.reload, params: { store: current_store }+ ).to_h+ end+ end+ end+ end+ end+enddiff --git a/spree/api/app/controllers/spree/api/v3/seller/team_controller.rb b/spree/api/app/controllers/spree/api/v3/seller/team_controller.rbnew file mode 100644index 0000000000..edea060e48--- /dev/null+++ b/spree/api/app/controllers/spree/api/v3/seller/team_controller.rb@@ -0,0 +1,89 @@+module Spree+ module Api+ module V3+ module Seller+ # The people who run this seller.+ #+ # Rooted at `current_seller` throughout, so a seller can only ever see+ # and change their own team. Inviting reuses the workflow the operator+ # calls, which means one invitation rail and one set of hooks.+ #+ # No custom roles: every member holds the seller's own seeded admin+ # role, which already carries the whole seller vocabulary. Splitting+ # that into narrower roles is a design of its own.+ class TeamController < Seller::BaseController+ scoped_resource :seller_profile++ before_action :set_member, only: [:destroy]++ def index+ render json: { data: members.map { |member| serialize_member(member) } }+ end++ # Invites a colleague onto this seller's team. They join when they+ # accept, on the same invitation rail — and same email — the+ # marketplace operator's invitations use.+ #+ # Not `Spree::Sellers::Invite`: that workflow means "open this seller+ # for its first owner" and moves the seller to `invited`. A trading+ # seller's status must not flip because someone hired staff, and the+ # workflow rightly refuses an approved seller. Hiring is not a+ # lifecycle transition.+ def create+ invitation = current_seller.invitations.new(+ email: params[:email],+ role: current_seller.default_user_role,+ inviter: try_spree_current_user+ )++ if invitation.save+ render json: serialize_invitation(invitation), status: :created+ else+ render_validation_error(invitation.errors)+ end+ end++ # Revokes a member's access. The seller keeps at least one member:+ # emptying the team would leave a seller nobody can sign in to, and+ # only the operator could put someone back.+ def destroy+ if members.size <= 1+ return render_error(+ code: ErrorHandler::ERROR_CODES[:processing_error],+ message: Spree.t(:seller_team_last_member),+ status: :unprocessable_content+ )+ end++ current_seller.remove_user(@member)+ head :no_content+ end++ protected++ def read_actions+ %w[index]+ end++ private++ def members+ @members ||= current_seller.users.to_a+ end++ def set_member+ @member = current_seller.users.find_by_prefix_id!(params[:id])+ end++ def serialize_member(member)+ Spree.api.seller_team_member_serializer.new(member, params: { store: current_store }).to_h+ end++ def serialize_invitation(invitation)+ Spree.api.seller_invitation_serializer.new(invitation, params: { store: current_store }).to_h+ end+ end+ end+ end+ end+enddiff --git a/spree/api/app/serializers/spree/api/v3/seller/address_serializer.rb b/spree/api/app/serializers/spree/api/v3/seller/address_serializer.rbnew file mode 100644index 0000000000..4cbf38545a--- /dev/null+++ b/spree/api/app/serializers/spree/api/v3/seller/address_serializer.rb@@ -0,0 +1,15 @@+module Spree+ module Api+ module V3+ module Seller+ # A seller's own address, as they see it.+ #+ # Identical to the storefront's — an address is an address — but it+ # lives in this namespace so the seller SDK generates its own type+ # rather than importing one from a package it does not depend on.+ class AddressSerializer < V3::AddressSerializer+ end+ end+ end+ end+enddiff --git a/spree/api/app/serializers/spree/api/v3/seller/invitation_serializer.rb b/spree/api/app/serializers/spree/api/v3/seller/invitation_serializer.rbnew file mode 100644index 0000000000..d338d073fb--- /dev/null+++ b/spree/api/app/serializers/spree/api/v3/seller/invitation_serializer.rb@@ -0,0 +1,34 @@+module Spree+ module Api+ module V3+ module Seller+ # A pending invitation to join this seller.+ #+ # Only what the inviting seller needs to see: who was invited, whether+ # they have accepted, and when it lapses. The shared serializer's+ # polymorphic fields (`resource_type`, `inviter_id`, `role_id`) describe+ # plumbing the seller cannot act on — and the invitation is always to+ # the seller whose panel they are already looking at.+ class InvitationSerializer < V3::BaseSerializer+ typelize email: :string, status: :string,+ expires_at: [:string, nullable: true],+ accepted_at: [:string, nullable: true]++ attributes :email, created_at: :iso8601++ attribute :status do |invitation|+ invitation.status.to_s+ end++ attribute :expires_at do |invitation|+ invitation.expires_at&.iso8601+ end++ attribute :accepted_at do |invitation|+ invitation.accepted_at&.iso8601+ end+ end+ end+ end+ end+enddiff --git a/spree/api/app/serializers/spree/api/v3/seller/profile_serializer.rb b/spree/api/app/serializers/spree/api/v3/seller/profile_serializer.rbnew file mode 100644index 0000000000..4e0544fbc1--- /dev/null+++ b/spree/api/app/serializers/spree/api/v3/seller/profile_serializer.rb@@ -0,0 +1,60 @@+module Spree+ module Api+ module V3+ module Seller+ # A seller's own record, as they see it.+ #+ # Sits between the two existing views: more than the shopper's public+ # profile (the seller needs their contact details and where they stand+ # in the marketplace), less than the operator's (they read their+ # settlement terms but never the operator's private notes).+ #+ # `status` and `sellable` are readable but not writable — a seller+ # should know they are suspended; moving between states is the+ # operator's decision, made through workflows.+ class ProfileSerializer < V3::SellerSerializer+ typelize status: :string,+ contact_email: [:string, nullable: true],+ billing_email: [:string, nullable: true],+ tax_remittance: :string,+ payouts_schedule_interval: [:string, nullable: true],+ minimum_payout_amount: [:string, nullable: true],+ holiday_mode_until: [:string, nullable: true],+ terms_accepted_at: [:string, nullable: true],+ on_holiday: :boolean, sellable: :boolean,+ products_count: :number++ attributes :status, :contact_email, :billing_email,+ :tax_remittance, :payouts_schedule_interval,+ holiday_mode_until: :iso8601,+ terms_accepted_at: :iso8601,+ created_at: :iso8601++ attribute :minimum_payout_amount do |seller|+ seller.minimum_payout_amount&.to_s+ end++ attribute :on_holiday do |seller|+ seller.on_holiday?+ end++ attribute :sellable do |seller|+ seller.sellable?+ end++ attribute :products_count do |seller|+ seller.products.count+ end++ one :billing_address,+ resource: proc { Spree.api.seller_address_serializer },+ if: proc { |seller| seller.billing_address.present? }++ one :returns_address,+ resource: proc { Spree.api.seller_address_serializer },+ if: proc { |seller| seller.returns_address.present? }+ end+ end+ end+ end+enddiff --git a/spree/api/app/serializers/spree/api/v3/seller/team_member_serializer.rb b/spree/api/app/serializers/spree/api/v3/seller/team_member_serializer.rbnew file mode 100644index 0000000000..241b8a4ab2--- /dev/null+++ b/spree/api/app/serializers/spree/api/v3/seller/team_member_serializer.rb@@ -0,0 +1,31 @@+module Spree+ module Api+ module V3+ module Seller+ # A teammate, as their colleagues on the same seller see them.+ #+ # Deliberately not the operator's `AdminUserSerializer`. That one+ # renders every store the user holds a role on, so the marketplace's+ # own store switcher can offer them — rendered to a seller it would+ # disclose the name and code of unrelated stores their teammate happens+ # to work for. It also scopes `roles` to the current *store*, which+ # answers a question nobody asked here: what matters is the teammate's+ # standing on this seller.+ class TeamMemberSerializer < V3::BaseSerializer+ typelize email: :string,+ first_name: [:string, nullable: true],+ last_name: [:string, nullable: true],+ full_name: [:string, nullable: true],+ avatar_url: [:string, nullable: true]++ attributes :email, :first_name, :last_name, :full_name,+ created_at: :iso8601++ attribute :avatar_url do |user|+ image_url_for(user.avatar)+ end+ end+ end+ end+ end+enddiff --git a/spree/api/config/initializers/typelizer.rb b/spree/api/config/initializers/typelizer.rbindex 3de913f8b8..a081890124 100644--- a/spree/api/config/initializers/typelizer.rb+++ b/spree/api/config/initializers/typelizer.rb@@ -34,7 +34,7 @@ Rails.application.config.after_initialize doc.output_dir = api_root.join('../../packages/sdk/src/types/generated')c.reject_class = ->(serializer:) {name = serializer.name.to_s- name.include?('::Admin::') ||+ name.include?('::Admin::') || name.include?('::Seller::') ||store_excluded.include?(name.sub(/\ASpree::Api::V3::/, '').sub(/Serializer\z/, ''))}c.serializer_name_mapper = ->(serializer) {@@ -54,5 +54,18 @@ Rails.application.config.after_initialize do.sub(/Serializer\z/, '')}end++ # Seller SDK — the seller panel's own branch. Keyed on the `::Seller::`+ # namespace exactly as admin is on `::Admin::`, which is why seller+ # serializers must live there and nowhere else.+ config.writer(:seller) do |c|+ c.output_dir = api_root.join('../../packages/seller-sdk/src/types/generated')+ c.reject_class = ->(serializer:) { !serializer.name.to_s.include?('::Seller::') }+ c.serializer_name_mapper = ->(serializer) {+ serializer.name.to_s+ .sub(/\ASpree::Api::V3::Seller::/, '')+ .sub(/Serializer\z/, '')+ }+ endendenddiff --git a/spree/api/config/routes.rb b/spree/api/config/routes.rbindex 0003cfc31c..dc558b913f 100644--- a/spree/api/config/routes.rb+++ b/spree/api/config/routes.rb@@ -660,6 +660,14 @@ Spree::Core::Engine.add_routes doget 'auth/providers', to: 'auth#providers'get 'me', to: 'me#show'++ # The seller's own record. Singular — there is exactly one seller in+ # play and it is `current_seller`, never an id from the request.+ resource :profile, only: [:show, :update], controller: 'profile'++ # 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'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.rbindex 30585cd3c9..66857daff1 100644--- a/spree/api/lib/spree/api/dependencies.rb+++ b/spree/api/lib/spree/api/dependencies.rb@@ -156,6 +156,10 @@ module Spreeadmin_tax_exemption_certificate_serializer: 'Spree::Api::V3::Admin::TaxExemptionCertificateSerializer',admin_admin_user_serializer: 'Spree::Api::V3::Admin::AdminUserSerializer',seller_serializer: 'Spree::Api::V3::SellerSerializer',+ seller_profile_serializer: 'Spree::Api::V3::Seller::ProfileSerializer',+ seller_address_serializer: 'Spree::Api::V3::Seller::AddressSerializer',+ seller_team_member_serializer: 'Spree::Api::V3::Seller::TeamMemberSerializer',+ seller_invitation_serializer: 'Spree::Api::V3::Seller::InvitationSerializer',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/auth_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/seller/auth_controller_spec.rbnew file mode 100644index 0000000000..087e482ddb--- /dev/null+++ b/spree/api/spec/controllers/spree/api/v3/seller/auth_controller_spec.rb@@ -0,0 +1,40 @@+require 'spec_helper'++RSpec.describe Spree::Api::V3::Seller::AuthController, type: :controller do+ render_views++ include_context 'API v3 Seller'++ before do+ seller_user.update!(password: 'secret123', password_confirmation: 'secret123')+ end++ describe 'POST #create' do+ # The response serializes the signed-in user, and the registry key for that+ # is `admin_admin_user_serializer` — the shorter name resolves to nothing,+ # so every seller login used to raise before this spec existed.+ it 'signs a seller in' do+ post :create, params: { email: seller_user.email, password: 'secret123' }, as: :json++ expect(response).to have_http_status(:ok)+ expect(json_response['token']).to be_present+ expect(json_response['user']['email']).to eq(seller_user.email)+ end++ # The panel cannot make any other request until it knows which seller to+ # name in X-Spree-Seller-Id.+ it 'returns the sellers the user may act for' do+ post :create, params: { email: seller_user.email, password: 'secret123' }, as: :json++ expect(json_response['sellers'].pluck('id')).to eq([seller.prefixed_id])+ end++ it 'refuses a store staff member who runs no seller' do+ staff = create(:admin_user, password: 'secret123', password_confirmation: 'secret123')++ post :create, params: { email: staff.email, password: 'secret123' }, as: :json++ expect(response).to have_http_status(:unauthorized)+ end+ end+enddiff --git a/spree/api/spec/controllers/spree/api/v3/seller/me_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/seller/me_controller_spec.rbnew file mode 100644index 0000000000..657a7a9239--- /dev/null+++ b/spree/api/spec/controllers/spree/api/v3/seller/me_controller_spec.rb@@ -0,0 +1,43 @@+require 'spec_helper'++RSpec.describe Spree::Api::V3::Seller::MeController, 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++ before { request.headers['Authorization'] = "Bearer #{token}" }++ # Same serializer-key bug as the login endpoint: this used to raise.+ it 'answers before a seller is chosen' do+ get :show, as: :json++ expect(response).to have_http_status(:ok)+ expect(json_response['user']['email']).to eq(seller_user.email)+ expect(json_response['sellers'].pluck('id')).to eq([seller.prefixed_id])+ end++ # Capability is per seller, so there is no meaningful answer spanning all of+ # them — the panel names one and asks again.+ it 'reports no permissions until a seller is named' do+ get :show, as: :json++ expect(json_response['permission_keys']).to eq([])+ end++ it 'reports the seeded seller permissions once one is named' do+ request.headers['X-Spree-Seller-Id'] = seller.prefixed_id++ get :show, as: :json++ expect(json_response['permission_keys']).to include('write_seller_profile', 'write_products')+ end+enddiff --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.rbnew file mode 100644index 0000000000..fdf6e98657--- /dev/null+++ b/spree/api/spec/controllers/spree/api/v3/seller/profile_controller_spec.rb@@ -0,0 +1,116 @@+require 'spec_helper'++RSpec.describe Spree::Api::V3::Seller::ProfileController, type: :controller do+ render_views++ include_context 'API v3 Seller'++ # The seeded role, not the shared context's narrow one — this is what a+ # seller actually holds on their own 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++ before do+ request.headers['Authorization'] = "Bearer #{token}"+ request.headers['X-Spree-Seller-Id'] = seller.prefixed_id+ end++ describe 'GET #show' do+ it 'returns the seller their own record' do+ get :show, as: :json++ expect(response).to have_http_status(:ok)+ expect(json_response['id']).to eq(seller.prefixed_id)+ expect(json_response['name']).to eq(seller.name)+ end++ # A seller should know they are suspended, and what they are owed on.+ it 'shows their standing and settlement terms' do+ get :show, as: :json++ expect(json_response).to include('status', 'sellable', 'tax_remittance',+ 'payouts_schedule_interval')+ end++ # There is no id in the request to tamper with — the seller comes from the+ # token's membership. This is the whole point of a singular resource here.+ it 'ignores any seller named in the params' do+ other = create(:seller, :approved, store: store)++ get :show, params: { id: other.prefixed_id }, as: :json++ expect(json_response['id']).to eq(seller.prefixed_id)+ end+ end++ describe 'PATCH #update' do+ it 'edits presentation and contact details' do+ patch :update, params: { name: 'Sparks Audio Ltd', contact_email: '[email protected]' },+ as: :json++ expect(response).to have_http_status(:ok)+ expect(seller.reload.name).to eq('Sparks Audio Ltd')+ expect(seller.contact_email).to eq('[email protected]')+ end++ it 'writes an address inline' do+ patch :update, params: {+ returns_address: { first_name: 'Ada', last_name: 'Lovelace', address1: '1 Seller Way',+ city: 'London', postal_code: 'EC1A 1BB', country_code: 'GB',+ phone: '555' }+ }, as: :json++ expect(response).to have_http_status(:ok)+ expect(seller.reload.returns_address.address1).to eq('1 Seller Way')+ end++ # The lifecycle belongs to the operator's workflows. A seller approving+ # themselves would skip the mail, the payouts and every extension hook.+ it 'refuses to move its own status' do+ patch :update, params: { status: 'approved' }, as: :json++ expect(seller.reload).to be_approved # was already approved+ expect(seller.status).to eq('approved')+ end++ it 'cannot change its own settlement terms' do+ patch :update, params: { tax_remittance: 'platform', minimum_payout_amount: '9999' },+ as: :json++ expect(seller.reload.tax_remittance).to eq('seller')+ expect(seller.minimum_payout_amount).to be_nil+ end++ # Renaming the storefront address breaks every link pointing at it.+ it 'cannot change its own slug' do+ original = seller.slug++ patch :update, params: { slug: 'something-else' }, as: :json++ expect(seller.reload.slug).to eq(original)+ end++ it 'reports validation errors' do+ patch :update, params: { name: '' }, as: :json++ expect(response).to have_http_status(:unprocessable_content)+ end+ end++ describe 'another seller' do+ it 'cannot act as a seller they do not belong to' do+ other = create(:seller, :approved, store: store)++ request.headers['X-Spree-Seller-Id'] = other.prefixed_id+ get :show, as: :json++ expect(response).to have_http_status(:forbidden)+ end+ end+enddiff --git a/spree/api/spec/controllers/spree/api/v3/seller/team_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/seller/team_controller_spec.rbnew file mode 100644index 0000000000..792bfbdcd5--- /dev/null+++ b/spree/api/spec/controllers/spree/api/v3/seller/team_controller_spec.rb@@ -0,0 +1,111 @@+require 'spec_helper'++RSpec.describe Spree::Api::V3::Seller::TeamController, 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++ before do+ request.headers['Authorization'] = "Bearer #{token}"+ request.headers['X-Spree-Seller-Id'] = seller.prefixed_id+ end++ describe 'GET #index' do+ it 'lists the seller team' do+ get :index, as: :json++ expect(response).to have_http_status(:ok)+ expect(json_response['data'].pluck('id')).to include(seller_user.prefixed_id)+ end++ # The whole point of the branch: a seller reads their own team, never+ # another seller's and never the store's staff.+ it "does not list another seller's team" do+ other = create(:seller, :approved, store: store)+ outsider = create(:admin_user, :without_admin_role)+ other.add_user(outsider)++ get :index, as: :json++ expect(json_response['data'].pluck('id')).not_to include(outsider.prefixed_id)+ end+ end++ describe 'POST #create' do+ it 'invites someone onto the team' do+ expect do+ post :create, params: { email: '[email protected]' }, as: :json+ end.to change { seller.invitations.count }.by(1)++ expect(response).to have_http_status(:created)+ end++ # The invitation lands on the seller's own role, so accepting it grants+ # access here and nowhere else.+ it "invites into the seller's own role" do+ post :create, params: { email: '[email protected]' }, as: :json++ expect(seller.invitations.last.role.resource).to eq(seller)+ end++ # Hiring is not a lifecycle transition. `Spree::Sellers::Invite` means+ # "open this seller for its first owner" and would flip an approved seller+ # to `invited` — which is why team invites take the invitation rail+ # directly instead.+ it 'does not move the seller through its lifecycle' do+ expect do+ post :create, params: { email: '[email protected]' }, as: :json+ end.not_to change { seller.reload.status }++ expect(seller).to be_approved+ end++ it 'reports a bad address' do+ post :create, params: { email: '' }, as: :json++ expect(response).to have_http_status(:unprocessable_content)+ end+ end++ describe 'DELETE #destroy' do+ it 'revokes a member' do+ colleague = create(:admin_user, :without_admin_role)+ seller.add_user(colleague)++ expect do+ delete :destroy, params: { id: colleague.prefixed_id }, as: :json+ end.to change { seller.reload.users.count }.by(-1)++ expect(response).to have_http_status(:no_content)+ end++ # Emptying the team would leave a seller nobody can sign in to, and only+ # the marketplace operator could put someone back.+ it 'refuses to remove the last member' do+ delete :destroy, params: { id: seller_user.prefixed_id }, as: :json++ expect(response).to have_http_status(:unprocessable_content)+ expect(seller.reload.users).to include(seller_user)+ end++ it "404s on someone outside this seller's team" do+ other = create(:seller, :approved, store: store)+ outsider = create(:admin_user, :without_admin_role)+ other.add_user(outsider)+ seller.add_user(create(:admin_user, :without_admin_role))++ delete :destroy, params: { id: outsider.prefixed_id }, as: :json++ expect(response).to have_http_status(:not_found)+ end+ end+enddiff --git a/spree/api/spec/serializers/spree/api/v3/seller/team_member_serializer_spec.rb b/spree/api/spec/serializers/spree/api/v3/seller/team_member_serializer_spec.rbnew file mode 100644index 0000000000..1a36c49e5b--- /dev/null+++ b/spree/api/spec/serializers/spree/api/v3/seller/team_member_serializer_spec.rb@@ -0,0 +1,35 @@+require 'spec_helper'++RSpec.describe Spree::Api::V3::Seller::TeamMemberSerializer do+ let!(:store) { @default_store }+ let!(:other_store) { create(:store, name: 'Unrelated Store', code: 'unrelated') }+ let(:seller) { create(:seller, store: store) }+ let(:member) { create(:admin_user) }++ subject(:payload) { described_class.new(member.reload, params: { store: store }).to_h }++ before do+ seller.add_user(member)+ # The teammate also works for an unrelated store, as staff commonly do.+ other_store.add_user(member)+ end++ it 'renders the teammate the seller needs to recognise' do+ expect(payload.keys).to match_array(+ %w[id email first_name last_name full_name avatar_url created_at]+ )+ end++ # The operator's serializer lists every store a user holds a role on, to feed+ # the marketplace store switcher. A seller must not learn the identity of+ # stores their teammate happens to work for.+ it 'does not disclose the stores a teammate works for' do+ expect(payload).not_to have_key('stores')+ expect(payload.to_s).not_to include('Unrelated Store')+ expect(payload.to_s).not_to include('unrelated')+ end++ it 'does not disclose marketplace roles' do+ expect(payload).not_to have_key('roles')+ end+enddiff --git a/spree/core/app/models/spree/seller.rb b/spree/core/app/models/spree/seller.rbindex 11e567b397..ab12b63ccf 100644--- a/spree/core/app/models/spree/seller.rb+++ b/spree/core/app/models/spree/seller.rb@@ -147,10 +147,23 @@ module Spreebefore_destroy :dissolve_team, prepend: true# A seller's own team is granted through its roles, not the store's.+ # A store's "admin" role is the protected super-role and needs no+ # permissions — `Ability#activate_full_access` short-circuits it. A+ # seller's cannot take that path (`Role#admin?` requires `staff?`), so+ # without seeding, whoever runs the seller would hold nothing and every+ # endpoint on their own panel would refuse them.+ #+ # Seeded at creation rather than patched afterwards: the role is born+ # immutable, so a later write would have to defeat its own guard.## @return [Spree::Role]def default_user_role- Spree::Role.default_admin_role(self)+ roles.for_resource(self).find_by(name: Spree::Role::ADMIN_ROLE) ||+ roles.create!(+ name: Spree::Role::ADMIN_ROLE,+ mutable: false,+ permissions: Spree.permissions.grantable_keys(:seller)+ )end# Whether the seller is currently away. The catalog stays visible; whatdiff --git a/spree/core/config/locales/en.yml b/spree/core/config/locales/en.ymlindex 4af296ac25..fc041c04da 100644--- a/spree/core/config/locales/en.yml+++ b/spree/core/config/locales/en.yml@@ -1565,6 +1565,7 @@ en:file_required: A file is required for this requirementfile_type_not_accepted: This requirement accepts %{types}incomplete: "%{name} is not complete"+ 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 Emailsseo: SEOseo_title: SEO Titlediff --git a/spree/core/spec/models/spree/seller_spec.rb b/spree/core/spec/models/spree/seller_spec.rbindex 1a8c327173..95b9ee9d01 100644--- a/spree/core/spec/models/spree/seller_spec.rb+++ b/spree/core/spec/models/spree/seller_spec.rb@@ -281,4 +281,39 @@ describe Spree::Seller doendend++ describe '#default_user_role' do+ let(:seller) { create(:seller) }++ # A store's admin role short-circuits through `activate_full_access`; a+ # seller's cannot (`Role#admin?` requires `staff?`), so without seeding the+ # person running the seller would hold nothing at all.+ it 'grants the whole seller vocabulary' do+ expect(seller.default_user_role.permissions).+ to match_array(Spree.permissions.grantable_keys(:seller))+ end++ it 'is immutable, like the store role it mirrors' do+ expect(seller.default_user_role).not_to be_mutable+ end++ it 'returns the same role rather than creating another' do+ first = seller.default_user_role++ expect(seller.default_user_role).to eq(first)+ expect(seller.roles.count).to eq(1)+ end++ # The operator's `sellers` key is not in the seller vocabulary, so holding+ # this role never lets a seller administer sellers — their own included.+ it 'does not let its holder manage the seller record' do+ user = create(:admin_user)+ seller.add_user(user)++ ability = Spree::Ability.new(user, resource: seller)++ expect(ability).to be_can(:manage, :seller_profile)+ expect(ability).not_to be_can(:manage, seller)+ end+ endend