Skip to content

armgit / spree

Public Imported from GitHub
0

Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.

Give a seller a stock location and a business identity

Damian Legawiec872817379fa4
diff --git a/docs/plans/6.0-multi-vendor-marketplace.md b/docs/plans/6.0-multi-vendor-marketplace.md
index 6146fd7bee..131c1c6cf9 100644
--- a/docs/plans/6.0-multi-vendor-marketplace.md
+++ b/docs/plans/6.0-multi-vendor-marketplace.md
@@ -222,6 +222,29 @@ Until now this plan assumed one product belongs to one seller (`products.seller_
**Supersedes:** the "SKU uniqueness relaxes to per-seller scope" line under Product ownership & approval, which assumed duplicate product rows per seller.
+### 12. A seller's addresses are a stock location and a business identity — not two loose `Address` rows (RESOLVED 2026-08-20)
+
+`spree_sellers` carries `billing_address_id` and `returns_address_id`, both plain `Spree::Address`. Two problems follow, and the legacy module had the shape of both answers already.
+
+**The returns address is a stock location wearing a different hat.** 6.0 routes returns through `Spree::Return`, and a received return has to restock *somewhere* — `spree_stock_movements` is anchored to a `StockLevel`, which is anchored to a `StockLocation`. An address the inventory system cannot restock into is a dead end: the shopper is told where to post the parcel, and the goods arrive somewhere the catalog does not believe in. The legacy module reached the same conclusion from the other direction — it gave every vendor stock locations and created a default one at vendor creation.
+
+So **`returns_address` is dropped and a seller's returns route to a stock location.** `spree_stock_locations.seller_id` (nullable, per the model sketch this plan already carried), a default one provisioned when the seller is created, and `Seller#returns_address` becomes a method reading that location. Sellers manage their locations from the panel — the same records the operator's inventory screens already understand, so seller stock is not a parallel universe.
+
+Two things about `StockLocation` have to move for this to be true, and neither is marketplace-specific:
+
+- **`Spree::UniqueName` scopes location names to the store**, so two sellers could not both call a location "Warehouse". Names become unique per `(store, seller)` — an operator location and a seller's may share a name, which is what a marketplace looks like.
+- **`ensure_one_default` unsets every other default in the store.** A seller saving their default would silently demote the operator's. The default flag becomes per-owner: one default among the operator's locations, one among each seller's.
+
+**Billing is a business identity, and most of it is not an address.** A commission invoice needs the seller's legal name, their registration number and — for EU B2B reverse charge on the fee (Decision 3) — a *verified* VAT number with the evidence retained, because a registry only ever answers "valid now" while an invoice must stay defensible for years. A `vat_number` string cannot carry a verdict, a timestamp or evidence.
+
+Core already models exactly this. `Spree::TaxIdentifier` (from `6.0-tax-provider.md` Phase 7) has `kind` / `value` / `validation_status` / `validated_at` / `validation_evidence` and a validator registry, with four owners. **The seller becomes the fifth owner** — one FK and one line in `exactly_one_owner`, and seller VAT inherits validation for free. `legal_name` and `registration_number` go on `spree_sellers`; `billing_address` stays a plain `Spree::Address` and means only where post goes.
+
+**No per-seller tax rate.** Adding one is the legacy `platform_fee_tax_rate` column this plan already rejected (Resolved Decisions, 2026-06-16): the seller supplies tax *identity*, and the commission tax *rate* resolves through `CommissionRate` + the `TaxProvider` so it stays jurisdiction-correct.
+
+**No `Address` STI subclasses.** The legacy module subclassed `BillingAddress`/`ReturnsAddress` to override `require_name?` (a company address has no first and last name) and `show_company_address_field?`. Both hooks still exist on `Spree::Address`, but `spree_addresses` has no `type` column, so STI would mean a schema change to the table every order, customer and company writes to — to encode a fact the owning FK already states. The seller declares the rules for the addresses it owns instead: company required, personal name waived. Whether the company *field* is shown is a form concern, and the form is React.
+
+**Supersedes** the `belongs_to :returns_address` line in the Seller model sketch below, and the `Spree::SellerRequirements::ReturnsAddress` checklist kind becomes "has a returns location".
+
## Design Details
### Seller identity & teams
@@ -241,10 +264,12 @@ class Spree::Seller < Spree.base_class
belongs_to :store, class_name: 'Spree::Store'
belongs_to :billing_address, class_name: 'Spree::Address', optional: true # on the commission invoice (EU)
- belongs_to :returns_address, class_name: 'Spree::Address', optional: true # where customer returns route
+ # No returns_address: returns route to a stock location, so the goods land
+ # somewhere inventory can restock into (Decision 12).
has_many :products, class_name: 'Spree::Product', dependent: :nullify
has_many :stock_locations, class_name: 'Spree::StockLocation', dependent: :nullify
+ has_many :tax_identifiers, class_name: 'Spree::TaxIdentifier', dependent: :destroy # VAT etc — Decision 12
has_many :orders, class_name: 'Spree::Order' # child (seller) orders
has_many :commission_lines, class_name: 'Spree::CommissionLine'
has_many :seller_transfers, class_name: 'Spree::SellerTransfer'
@@ -718,6 +743,7 @@ Even before this lands, work touching adjacent areas should:
- **Tax provider (`6.0-tax-provider.md`)** and **Delivery rate provider (`6.0-delivery-rate-provider.md`)**: the `PayoutProvider` follows the same pluggable-strategy shape — keep the provider-registration convention consistent so all three (tax, delivery rate, payout) register and resolve the same way.
- **Admin API (`6.0-admin-api.md`)**: the `Seller` prefix is `sel_`. The "Marketplace (new in 6.0)" endpoint group there is the *operator's* API surface — keep it in sync. Seller users never call the Admin API (Decision 10).
- **Auth + RBAC (`6.0-platform-auth.md`, `6.0-admin-rbac.md`)**: no third principal — never add a `SellerUser`/`Spree.seller_user_class`; seller staff are `Spree.admin_user_class`. Never derive back-office membership from `store_id` alone — match `RoleUser.resource_type` (`Ability#staff_roles` and `RoleGrantGuard` already do; the membership check must follow). New login surfaces get their own strategy registry and JWT audience; refresh tokens must carry the audience they were minted for. Catalog resources that sellers may hold must be marked seller-grantable at `register_resource`; `settings`/`staff`/`api_keys` never are. Seller-branch controllers scope-fetch through `current_seller` and never subclass admin controllers.
+- **Seller addresses (Decision 12)**: do not add a `returns_address` back, and do not give a seller a tax *rate* column — identity (`legal_name`, `registration_number`, a `TaxIdentifier`) is the seller's, the rate is `CommissionRate` + `TaxProvider`. Do not subclass `Spree::Address`. Code reading a seller's returns destination goes through `Seller#returns_location`, never a stored address FK. `StockLocation` name-uniqueness and its `default` flag are per-owner, so new code must not assume one default per store.
- Do **not** revive the legacy commission model's shape (label-based rows + denormalized fee totals on the order), do **not** model commission as a polymorphic `Adjustment`, and do **not** write commission as a `Spree::Fee` (fees are buyer-facing and roll into order totals — Decision 2) — 6.0 uses the off-order `Spree::CommissionLine` ledger. Do **not** put the fund ledger in a payment-gateway namespace (the legacy gateway-namespaced-transfer mistake) nor collapse transfer and payout into one model — `Spree::SellerTransfer` (on-fulfillment) and `Spree::SellerPayout` (scheduled) are both core and provider-agnostic.
## Resolved Decisions
@@ -768,6 +794,7 @@ Even before this lands, work touching adjacent areas should:
- **Fund ledger → two levels: `Spree::SellerTransfer` (per-order, on-fulfillment) + `Spree::SellerPayout` (per-interval settlement), both generic in core + pluggable `PayoutProvider` (system no-op in core; basic StripeConnect with the monorepo Stripe gateway per the 2026-07-15 amendment, extended by Enterprise with the money operations)** (RESOLVED 2026-06-25). See Decision 9. Transfer credits the seller balance on fulfillment; payout sweeps unsettled transfers into a scheduled bank settlement (transfers `belong_to` their payout — auditable). `seller.balance(currency) = Σ completed transfers − Σ completed payouts` per currency. Splits the legacy gateway-namespaced transfer ledger (which conflated the two and outsourced settlement to Stripe) into core ledger + provider execution along the OSS/Enterprise seam.
- **Commission tax → one scalar on the line, in TaxLine's vocabulary** (RESOLVED 2026-08-17). `tax_amount` + `tax_rate` + `taxability_reason` + the seller's `country_code`/`state_code` on `Spree::CommissionLine`, with `Spree::CommissionTax` as the value object the resolver returns. Reusing `Spree::TaxLine` itself was rejected: its rows sum into the order total and are exposed on the buyer-facing `/orders/:id/tax_lines`, so a commission row there would overcharge the shopper and leak settlement data. Same shape, opposite side of the ledger — so the words are shared and the rows are not. See Decision 3.
- **Commission VAT base → net item price, VAT added on top of the fee** (RESOLVED 2026-06-25). For EU, commission is computed on the seller's **net (ex-VAT)** item price; the commission `tax_amount` (Decision 3) is then applied **on top of the commission** as a separate B2B service supply — the marketplace fee is a distinct taxable event from the consumer's item sale, so the two VATs never mix. The base toggle stays available for non-EU/edge merchants who genuinely want a gross base, but the EU default is net-base + fee-VAT. Shipped as **`tax_inclusive`** (2026-08-17), matching `Spree::Market#tax_inclusive` rather than the surveyed industry's `include_tax` — the flag says the commission base is tax-inclusive, which is the same adjective the rest of Spree already uses for a price that carries its tax. This makes the marketplace's commission invoice to the seller stand on its own (correct for EU invoicing + remittance).
+- **Seller addresses → a stock location + a business identity** (RESOLVED 2026-08-20). `returns_address` is dropped: returns route to a seller-owned `StockLocation` (default provisioned at creation) so received goods restock where the catalog can see them, which also requires `StockLocation` name-uniqueness and the `default` flag to become per-owner rather than per-store. Billing keeps a plain `Spree::Address`, while the parts that are not an address become `legal_name` + `registration_number` on the seller and a `Spree::TaxIdentifier` owned by it — reusing the validation/evidence rails the tax plan already built, because EU reverse charge on the commission invoice needs a verified number with retained evidence. No per-seller tax rate (that stays `CommissionRate` + `TaxProvider`) and no `Address` STI subclasses (the owning FK already says which address it is; `spree_addresses` has no `type` column). See Decision 12.
- **Store-credit/gift-card payout → payment-source-agnostic** (RESOLVED 2026-06-25). The `SellerTransfer` amount (which rolls up into the payout) is `(seller's sale value) − (commission owed)`, **independent of how the customer paid**. Store credit / gift cards are the platform's funding concern, not the seller's — the seller is owed their full cut of the sale regardless. This **drops the legacy store-credit dual-basis** from the amount calculation; that branch existed only to reconcile the old store-credit funding model and does not belong in the payout basis. (The platform still tracks its own store-credit liability separately — that's orthogonal to what the seller receives.)
- **Commission precedence → an operator-ordered list** (RESOLVED 2026-06-25 as integer priority; **reshaped 2026-08-17 to `acts_as_list`, shipped**). `CommissionRate` carries `position` (`acts_as_list scope: :store_id, add_new_at: :top`) and resolution walks it top-down, first match wins (Decision 4). The list on screen is the precedence, so reordering is dragging rather than assigning numbers; new rates land at the top so they take effect on creation instead of behind the catch-all. `Spree::Seeds::CommissionRates` puts one disabled marketplace-wide rate at the bottom, which yields the product > category > seller order merchants asked for without hardcoding a ladder. No specificity inference — a rate can name all three dimensions at once, so there is nothing to infer from.
- **Commission rate currency → required for fixed, ignored for percentage** (RESOLVED 2026-06-25). A `kind: 'fixed'` rate **must** carry a `currency` (a flat "2" is meaningless without one); a `kind: 'percentage'` rate ignores currency (10% applies in any currency). Enforced by a model validation: `validates :currency, presence: true, if: -> { kind == 'fixed' }`. See the `CommissionRate` model.
diff --git a/packages/dashboard-core/src/components/address-form-dialog.tsx b/packages/dashboard-core/src/components/address-form-dialog.tsx
index 5510563d18..db0bc95347 100644
--- a/packages/dashboard-core/src/components/address-form-dialog.tsx
+++ b/packages/dashboard-core/src/components/address-form-dialog.tsx
@@ -26,6 +26,7 @@ import { StateCombobox, useCountryStates } from './country-state-fields'
export interface AddressParams {
first_name: string
last_name: string
+ company?: string
address1: string
address2: string
city: string
@@ -38,15 +39,7 @@ export interface AddressParams {
is_default_shipping?: boolean
}
-const addressFormSchema = z.object({
- first_name: z
- .string()
- .trim()
- .min(1, { error: requiredMessage('first_name') }),
- last_name: z
- .string()
- .trim()
- .min(1, { error: requiredMessage('last_name') }),
+const addressFormFields = {
address1: z
.string()
.trim()
@@ -69,9 +62,41 @@ const addressFormSchema = z.object({
label: z.string(),
is_default_billing: z.boolean(),
is_default_shipping: z.boolean(),
+}
+
+/**
+ * Whose address this is.
+ *
+ * A person's address is addressed to them, so it needs their name. A
+ * business's is addressed to the company — there is no person to name, and
+ * the company is the part that cannot be left out. Mirrors the same
+ * distinction `Spree::Address` makes server-side, so the form asks for
+ * exactly what the model will accept.
+ */
+const personalSchema = z.object({
+ ...addressFormFields,
+ first_name: z
+ .string()
+ .trim()
+ .min(1, { error: requiredMessage('first_name') }),
+ last_name: z
+ .string()
+ .trim()
+ .min(1, { error: requiredMessage('last_name') }),
+ company: z.string(),
+})
+
+const businessSchema = z.object({
+ ...addressFormFields,
+ first_name: z.string(),
+ last_name: z.string(),
+ company: z
+ .string()
+ .trim()
+ .min(1, { error: requiredMessage('company') }),
})
-type AddressFormValues = z.infer<typeof addressFormSchema>
+type AddressFormValues = z.infer<typeof personalSchema>
/**
* Just the fields this dialog reads.
@@ -86,6 +111,7 @@ export interface EditableAddress {
id?: string
first_name?: string | null
last_name?: string | null
+ company?: string | null
address1?: string | null
address2?: string | null
city?: string | null
@@ -102,6 +128,7 @@ function buildDefaults(address: EditableAddress | null | undefined): AddressForm
return {
first_name: address?.first_name ?? '',
last_name: address?.last_name ?? '',
+ company: address?.company ?? '',
address1: address?.address1 ?? '',
address2: address?.address2 ?? '',
city: address?.city ?? '',
@@ -124,6 +151,7 @@ export function AddressFormDialog({
isPending = false,
showLabel = false,
showDefaultFlags = false,
+ business = false,
}: {
address: EditableAddress | null | undefined
open: boolean
@@ -133,12 +161,14 @@ export function AddressFormDialog({
isPending?: boolean
showLabel?: boolean
showDefaultFlags?: boolean
+ /** Addressed to a company rather than a person — see the schemas above. */
+ business?: boolean
}) {
const { t } = useTranslation()
const resolvedTitle = title ?? t('admin.components.address_form_dialog.edit_title')
const form = useForm<AddressFormValues>({
defaultValues: buildDefaults(address),
- resolver: zodResolver(addressFormSchema),
+ resolver: zodResolver(business ? businessSchema : personalSchema),
})
const { errors } = form.formState
@@ -164,6 +194,7 @@ export function AddressFormDialog({
await onSave({
first_name: values.first_name,
last_name: values.last_name,
+ company: values.company,
address1: values.address1,
address2: values.address2,
city: values.city,
@@ -223,26 +254,38 @@ export function AddressFormDialog({
/>
</Field>
)}
- <div className="grid grid-cols-2 gap-3">
- <Field>
- <FieldLabel htmlFor="addr-fn">{t('admin.fields.first_name.label')}</FieldLabel>
- <Input
- id="addr-fn"
- aria-invalid={!!errors.first_name || undefined}
- {...form.register('first_name')}
- />
- <FieldError errors={[errors.first_name]} />
- </Field>
+ {business ? (
<Field>
- <FieldLabel htmlFor="addr-ln">{t('admin.fields.last_name.label')}</FieldLabel>
+ <FieldLabel htmlFor="addr-co">{t('admin.fields.company.label')}</FieldLabel>
<Input
- id="addr-ln"
- aria-invalid={!!errors.last_name || undefined}
- {...form.register('last_name')}
+ id="addr-co"
+ aria-invalid={!!errors.company || undefined}
+ {...form.register('company')}
/>
- <FieldError errors={[errors.last_name]} />
+ <FieldError errors={[errors.company]} />
</Field>
- </div>
+ ) : (
+ <div className="grid grid-cols-2 gap-3">
+ <Field>
+ <FieldLabel htmlFor="addr-fn">{t('admin.fields.first_name.label')}</FieldLabel>
+ <Input
+ id="addr-fn"
+ aria-invalid={!!errors.first_name || undefined}
+ {...form.register('first_name')}
+ />
+ <FieldError errors={[errors.first_name]} />
+ </Field>
+ <Field>
+ <FieldLabel htmlFor="addr-ln">{t('admin.fields.last_name.label')}</FieldLabel>
+ <Input
+ id="addr-ln"
+ aria-invalid={!!errors.last_name || undefined}
+ {...form.register('last_name')}
+ />
+ <FieldError errors={[errors.last_name]} />
+ </Field>
+ </div>
+ )}
<Field>
<FieldLabel htmlFor="addr-a1">
{t('admin.fields.address.address1.label')}
diff --git a/packages/seller-dashboard/src/components/seller-address-card.tsx b/packages/seller-dashboard/src/components/seller-address-card.tsx
index 19868fbbaa..b3b52d8a09 100644
--- a/packages/seller-dashboard/src/components/seller-address-card.tsx
+++ b/packages/seller-dashboard/src/components/seller-address-card.tsx
@@ -9,7 +9,7 @@ import {
CardHeader,
CardTitle,
} from '@spree/dashboard-ui'
-import type { Profile } from '@spree/seller-sdk'
+import type { Profile, SellerAddressParams } from '@spree/seller-sdk'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { useParams } from '@tanstack/react-router'
import { PencilIcon, PlusIcon } from 'lucide-react'
@@ -18,24 +18,23 @@ import { useTranslation } from 'react-i18next'
import { toast } from 'sonner'
import { sellerClient } from '../api-client'
-export type SellerAddressKey = 'billing_address' | 'returns_address'
-
/**
- * One of the seller's two addresses — where they are invoiced, and where
- * customer returns go — read as a block, edited in the shared address dialog.
+ * Where the seller is invoiced — read as a block, edited in the shared
+ * address dialog.
*
* Used both on the profile page and inline in the onboarding checklist, so a
* seller working through setup fills the address where they are told about
* it rather than being sent somewhere else and losing their place. Same
* component either way, so the two can never diverge.
+ *
+ * Returns are not here: they go to a stock location, which is a record of its
+ * own — see `SellerReturnsLocationCard`.
*/
export function SellerAddressCard({
profile,
- addressKey,
headless = false,
}: {
profile: Profile
- addressKey: SellerAddressKey
/** Render just the body — the onboarding checklist supplies its own frame. */
headless?: boolean
}) {
@@ -44,13 +43,14 @@ export function SellerAddressCard({
const queryClient = useQueryClient()
const [editing, setEditing] = useState(false)
- const address = profile[addressKey]
- const title = t(`profile.${addressKey}`)
+ const address = profile.billing_address
+ const title = t('profile.billing_address')
const save = useMutation({
- // Only the address being edited is sent: the other is untouched, and
- // posting both would rewrite a record the seller never opened.
- mutationFn: (values: unknown) => sellerClient().profile.update({ [addressKey]: values }),
+ // Only the billing address is sent: the rest of the profile is untouched,
+ // and posting it all would rewrite fields the seller never opened.
+ mutationFn: (values: SellerAddressParams) =>
+ sellerClient().profile.update({ billing_address: values }),
onSuccess: (updated) => {
queryClient.setQueryData(['seller', sellerId, 'profile'], updated)
// The checklist reads addresses too, so it has to re-evaluate.
@@ -79,6 +79,7 @@ export function SellerAddressCard({
title={title}
address={address}
open
+ business
onOpenChange={setEditing}
onSave={(values) => save.mutate(values)}
isPending={save.isPending}
diff --git a/packages/seller-dashboard/src/components/seller-returns-location-card.tsx b/packages/seller-dashboard/src/components/seller-returns-location-card.tsx
new file mode 100644
index 0000000000..4af81ea888
--- /dev/null
+++ b/packages/seller-dashboard/src/components/seller-returns-location-card.tsx
@@ -0,0 +1,170 @@
+import { AddressFormDialog, type EditableAddress } from '@spree/dashboard-core'
+import {
+ AddressBlock,
+ Badge,
+ Button,
+ Card,
+ CardAction,
+ CardContent,
+ CardHeader,
+ CardTitle,
+} from '@spree/dashboard-ui'
+import type { StockLocation, StockLocationParams } from '@spree/seller-sdk'
+import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
+import { useParams } from '@tanstack/react-router'
+import { PencilIcon, PlusIcon } from 'lucide-react'
+import { useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import { toast } from 'sonner'
+import { sellerClient } from '../api-client'
+
+/**
+ * Where customers send returns — the address on the seller's default stock
+ * location.
+ *
+ * A location rather than a loose address because returned goods have to be
+ * restocked somewhere the catalog can see: stock movements anchor to a
+ * location, so an address on its own would leave the parcel arriving nowhere.
+ * The seller sees an address form all the same — the location is the record
+ * behind it, not a concept they have to learn to fill this in.
+ */
+export function SellerReturnsLocationCard({ headless = false }: { headless?: boolean }) {
+ const { t } = useTranslation()
+ const { sellerId } = useParams({ from: '/_authenticated/$sellerId' })
+ const queryClient = useQueryClient()
+ const [editing, setEditing] = useState(false)
+
+ const { data: locations } = useQuery({
+ queryKey: ['seller', sellerId, 'stock-locations'],
+ queryFn: () => sellerClient().stockLocations.list({ per_page: 100 }),
+ })
+
+ // The default one is where returns go, matching `Seller#returns_location`.
+ const location = locations?.data.find((candidate) => candidate.default) ?? locations?.data[0]
+ const hasAddress = Boolean(location?.address1)
+ const title = t('profile.returns_address')
+
+ const save = useMutation({
+ mutationFn: (params: StockLocationParams) => {
+ if (!location) throw new Error(t('common.error'))
+ return sellerClient().stockLocations.update(location.id, params)
+ },
+ onSuccess: () => {
+ void queryClient.invalidateQueries({ queryKey: ['seller', sellerId, 'stock-locations'] })
+ // The checklist asks whether this address is filled in, so it has to
+ // re-evaluate.
+ void queryClient.invalidateQueries({ queryKey: ['seller', sellerId, 'onboarding'] })
+ setEditing(false)
+ toast.success(t('profile.saved'))
+ },
+ onError: (err) => toast.error(err instanceof Error ? err.message : t('common.error')),
+ })
+
+ const body =
+ hasAddress && location ? (
+ <AddressBlock address={toAddressBlock(location)} />
+ ) : (
+ <p className="text-muted-foreground text-sm">{t('profile.address_not_provided')}</p>
+ )
+
+ const editButton = (
+ <Button
+ variant={hasAddress ? 'outline' : 'default'}
+ size="sm"
+ disabled={!location}
+ onClick={() => setEditing(true)}
+ >
+ {hasAddress ? <PencilIcon className="size-4" /> : <PlusIcon className="size-4" />}
+ {hasAddress ? t('profile.edit') : t('profile.add_address')}
+ </Button>
+ )
+
+ const dialog = editing && location && (
+ <AddressFormDialog
+ title={title}
+ address={toEditableAddress(location)}
+ open
+ business
+ onOpenChange={setEditing}
+ onSave={(values) => save.mutate(toStockLocationParams(values))}
+ isPending={save.isPending}
+ />
+ )
+
+ if (headless) {
+ return (
+ <div className="flex flex-col items-start gap-3">
+ {body}
+ {editButton}
+ {dialog}
+ </div>
+ )
+ }
+
+ return (
+ <>
+ <Card>
+ <CardHeader>
+ <CardTitle>
+ {title}
+ {hasAddress ? (
+ <Badge variant="success">{t('profile.address_filled')}</Badge>
+ ) : (
+ <Badge variant="outline">{t('profile.address_missing')}</Badge>
+ )}
+ </CardTitle>
+ <CardAction>{editButton}</CardAction>
+ </CardHeader>
+ <CardContent>{body}</CardContent>
+ </Card>
+ {dialog}
+ </>
+ )
+}
+
+/**
+ * The three shapes this card sits between. A stock location stores `zipcode`
+ * where an address says `postal_code`, and carries no personal name — mapping
+ * the fields explicitly is what keeps that difference in one place instead of
+ * leaking a cast into every call.
+ */
+function toAddressBlock(location: StockLocation) {
+ return {
+ company: location.company,
+ address1: location.address1,
+ address2: location.address2,
+ city: location.city,
+ state_text: location.state_text,
+ postal_code: location.zipcode,
+ country_code: location.country_code,
+ country_name: location.country_name,
+ phone: location.phone,
+ }
+}
+
+function toEditableAddress(location: StockLocation) {
+ return {
+ id: location.id,
+ company: location.company,
+ address1: location.address1,
+ address2: location.address2,
+ city: location.city,
+ postal_code: location.zipcode,
+ country_code: location.country_code,
+ state_code: location.state_code,
+ phone: location.phone,
+ }
+}
+
+function toStockLocationParams(values: EditableAddress): StockLocationParams {
+ return {
+ company: values.company,
+ address1: values.address1,
+ address2: values.address2,
+ city: values.city,
+ zipcode: values.postal_code,
+ country_code: values.country_code,
+ state_code: values.state_code,
+ phone: values.phone,
+ }
+}
diff --git a/packages/seller-dashboard/src/pages/onboarding.tsx b/packages/seller-dashboard/src/pages/onboarding.tsx
index c4e57cd3e4..b44a4fa361 100644
--- a/packages/seller-dashboard/src/pages/onboarding.tsx
+++ b/packages/seller-dashboard/src/pages/onboarding.tsx
@@ -24,7 +24,8 @@ import { useTranslation } from 'react-i18next'
import { toast } from 'sonner'
import { sellerClient } from '../api-client'
import { CenteredMessage } from '../components/centered-message'
-import { SellerAddressCard, type SellerAddressKey } from '../components/seller-address-card'
+import { SellerAddressCard } from '../components/seller-address-card'
+import { SellerReturnsLocationCard } from '../components/seller-returns-location-card'
/**
* What the marketplace asks of this seller before admitting them.
@@ -188,7 +189,7 @@ function RequirementAction({ requirement }: { requirement: RequirementStatus })
const { data: profile } = useQuery({
queryKey: ['seller', sellerId, 'profile'],
queryFn: () => sellerClient().profile.get(),
- enabled: Boolean(addressKeyFor(requirement.kind)),
+ enabled: isAddressKind(requirement.kind),
})
const invalidate = () =>
@@ -282,14 +283,15 @@ function RequirementAction({ requirement }: { requirement: RequirementStatus })
{/* Addresses are filled in here rather than on the profile page: a
seller working through setup should not be sent away and lose their
place. Same card either way, so the two cannot diverge. */}
- {addressKeyFor(requirement.kind) && profile && (
- <SellerAddressCard
- profile={profile}
- addressKey={addressKeyFor(requirement.kind)!}
- headless
- />
+ {requirement.kind === 'billing_address' && profile && (
+ <SellerAddressCard profile={profile} headless />
)}
+ {/* Returns go to a stock location rather than a loose address, so this
+ one writes a different record — the seller still just sees an
+ address form. */}
+ {requirement.kind === 'returns_address' && <SellerReturnsLocationCard headless />}
+
{/* Kinds whose work happens on a page this panel already has. The
server cannot supply these: `action_url` is for somewhere it knows
about (a provider's hosted flow), and it has no idea how this panel
@@ -330,9 +332,8 @@ function RequirementAction({ requirement }: { requirement: RequirementStatus })
* is what makes a provider's kind useful before this file knows it exists.
*/
/** Kinds the seller satisfies by filling an address, rendered inline. */
-function addressKeyFor(kind: string): SellerAddressKey | undefined {
- if (kind === 'billing_address' || kind === 'returns_address') return kind
- return undefined
+function isAddressKind(kind: string): boolean {
+ return kind === 'billing_address' || kind === 'returns_address'
}
function panelRoute(kind: string): string | undefined {
diff --git a/packages/seller-dashboard/src/pages/profile.tsx b/packages/seller-dashboard/src/pages/profile.tsx
index 83418a1545..26682acccb 100644
--- a/packages/seller-dashboard/src/pages/profile.tsx
+++ b/packages/seller-dashboard/src/pages/profile.tsx
@@ -32,6 +32,7 @@ import { toast } from 'sonner'
import { sellerClient } from '../api-client'
import { CenteredMessage } from '../components/centered-message'
import { SellerAddressCard } from '../components/seller-address-card'
+import { SellerReturnsLocationCard } from '../components/seller-returns-location-card'
interface ProfileValues {
name: string
@@ -91,8 +92,8 @@ export function ProfilePage() {
<StandingCard profile={profile} />
<AtAGlanceCard profile={profile} teamCount={team?.data?.length} />
<ContactCard profile={profile} onEdit={() => setEditing(true)} />
- <SellerAddressCard profile={profile} addressKey="billing_address" />
- <SellerAddressCard profile={profile} addressKey="returns_address" />
+ <SellerAddressCard profile={profile} />
+ <SellerReturnsLocationCard />
<SettlementCard profile={profile} />
</>
}
diff --git a/packages/seller-sdk/src/index.ts b/packages/seller-sdk/src/index.ts
index 20faa7b6d7..f5af2c7a91 100644
--- a/packages/seller-sdk/src/index.ts
+++ b/packages/seller-sdk/src/index.ts
@@ -15,6 +15,7 @@ export type {
RequirementSubmissionParams,
SellerAddressParams,
SellerCountry,
+ StockLocationParams,
} from './seller-client'
// Client class, for advanced use and subclassing
export { SellerClient } from './seller-client'
diff --git a/packages/seller-sdk/src/seller-client.ts b/packages/seller-sdk/src/seller-client.ts
index ca63f9e07f..feb36c9fcc 100644
--- a/packages/seller-sdk/src/seller-client.ts
+++ b/packages/seller-sdk/src/seller-client.ts
@@ -8,6 +8,7 @@ import type {
RequirementStatus,
RequirementSubmission,
SellerSummary,
+ StockLocation,
TeamMember,
} from './types'
@@ -217,6 +218,56 @@ export class SellerClient {
delete: (id: string, options?: RequestOptions): Promise<void> =>
this.request<void>('DELETE', `/products/${id}`, options),
}
+
+ /**
+ * Where this seller keeps stock, and so where their returns are sent.
+ *
+ * No delete: a location holds stock levels and is named on historical
+ * fulfillments, so a seller retires one by setting `active` to false.
+ */
+ readonly stockLocations = {
+ list: (
+ params?: ListParams & Record<string, unknown>,
+ options?: RequestOptions,
+ ): Promise<ListResponse<StockLocation>> =>
+ this.request<ListResponse<StockLocation>>('GET', '/stock_locations', {
+ ...options,
+ params: params ? transformListParams(params) : undefined,
+ }),
+
+ get: (id: string, options?: RequestOptions): Promise<StockLocation> =>
+ this.request<StockLocation>('GET', `/stock_locations/${id}`, options),
+
+ create: (params: StockLocationParams, options?: RequestOptions): Promise<StockLocation> =>
+ this.request<StockLocation>('POST', '/stock_locations', { ...options, body: params }),
+
+ update: (
+ id: string,
+ params: StockLocationParams,
+ options?: RequestOptions,
+ ): Promise<StockLocation> =>
+ this.request<StockLocation>('PATCH', `/stock_locations/${id}`, {
+ ...options,
+ body: params,
+ }),
+ }
+}
+
+/** What a seller may write on one of their stock locations. */
+export interface StockLocationParams {
+ name?: string
+ company?: string | null
+ address1?: string | null
+ address2?: string | null
+ city?: string | null
+ zipcode?: string | null
+ country_code?: string | null
+ state_code?: string | null
+ state_name?: string | null
+ phone?: string | null
+ active?: boolean
+ default?: boolean
+ kind?: string
}
/** A country as the address form needs it. */
diff --git a/packages/seller-sdk/src/types/generated/StockLocation.ts b/packages/seller-sdk/src/types/generated/StockLocation.ts
new file mode 100644
index 0000000000..31c1040e18
--- /dev/null
+++ b/packages/seller-sdk/src/types/generated/StockLocation.ts
@@ -0,0 +1,28 @@
+// Typelizer digest dfe24071e3e48b3017dfa4c10b8bf178
+//
+// DO NOT MODIFY: This file was automatically generated by Typelizer.
+
+type StockLocation = {
+ id: string;
+ name: string;
+ address1: string | null;
+ city: string | null;
+ zipcode: string | null;
+ country_code: string | null;
+ country_name: string | null;
+ state_code: string | null;
+ state_text: string | null;
+ pickup_ready_in_minutes: number | null;
+ pickup_instructions: string | null;
+ address2: string | null;
+ state_name: string | null;
+ phone: string | null;
+ company: string | null;
+ active: boolean;
+ default: boolean;
+ kind: string;
+ created_at: string;
+ updated_at: string;
+}
+
+export default StockLocation;
diff --git a/packages/seller-sdk/src/types/generated/index.ts b/packages/seller-sdk/src/types/generated/index.ts
index 00d8818031..4006f68e38 100644
--- a/packages/seller-sdk/src/types/generated/index.ts
+++ b/packages/seller-sdk/src/types/generated/index.ts
@@ -1,4 +1,4 @@
-// Typelizer digest 42ccaa2ead92516bdbee62661c391b25
+// Typelizer digest 7332362643df45117ff27e135f8d3e38
//
// DO NOT MODIFY: This file was automatically generated by Typelizer.
export type { default as Address } from './Address'
@@ -14,6 +14,7 @@ export type { default as Product } from './Product'
export type { default as Profile } from './Profile'
export type { default as RequirementStatus } from './RequirementStatus'
export type { default as RequirementSubmission } from './RequirementSubmission'
+export type { default as StockLocation } from './StockLocation'
export type { default as TeamMember } from './TeamMember'
export type { default as Seller } from './Seller'
export type { default as Variant } from './Variant'
diff --git a/spree/api/app/controllers/spree/api/v3/admin/sellers_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/sellers_controller.rb
index c6ecd27f28..4dec9e4594 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/sellers_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/sellers_controller.rb
@@ -116,7 +116,7 @@ module Spree
# every seller on the page, so it loads once. Applied to the scope
# rather than the collection so a single-seller read gets it too.
def scope_includes
- [:billing_address, :returns_address, :requirement_submissions,
+ [:billing_address, :requirement_submissions, { stock_locations: [] },
{ store: :seller_requirements, logo_attachment: :blob, cover_photo_attachment: :blob }]
end
@@ -143,13 +143,19 @@ module Spree
:logo, :square_logo, :cover_photo,
:tax_remittance, :payouts_schedule_interval, :minimum_payout_amount,
:holiday_mode_until,
+ :legal_name, :registration_number,
metadata: {},
billing_address: ADDRESS_KEYS,
- returns_address: ADDRESS_KEYS,
custom_fields: [:id, :custom_field_definition_id, :value, { value: [] }, { value: {} }])
)
end
+ # Creating a seller provisions their stock location too, so it goes
+ # through the workflow rather than the base class's plain build.
+ def create_workflow
+ Spree.seller_create_workflow
+ end
+
# `onboarding` is a read of the seller — it changes nothing.
def read_actions
super + %w[onboarding]
diff --git a/spree/api/app/controllers/spree/api/v3/seller/profile_controller.rb b/spree/api/app/controllers/spree/api/v3/seller/profile_controller.rb
index 53de30fd44..f46a0c6a13 100644
--- a/spree/api/app/controllers/spree/api/v3/seller/profile_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/seller/profile_controller.rb
@@ -66,8 +66,7 @@ module Spree
normalize_params(
params.permit(:name, :contact_email, :billing_email, :about,
:logo, :square_logo, :cover_photo,
- billing_address: ADDRESS_KEYS,
- returns_address: ADDRESS_KEYS)
+ billing_address: ADDRESS_KEYS)
)
end
diff --git a/spree/api/app/controllers/spree/api/v3/seller/stock_locations_controller.rb b/spree/api/app/controllers/spree/api/v3/seller/stock_locations_controller.rb
new file mode 100644
index 0000000000..6ce61b8152
--- /dev/null
+++ b/spree/api/app/controllers/spree/api/v3/seller/stock_locations_controller.rb
@@ -0,0 +1,46 @@
+module Spree
+ module Api
+ module V3
+ module Seller
+ # A seller's own stock locations — where their inventory sits and
+ # where customer returns are sent.
+ #
+ # Rooted in `current_seller.stock_locations`, so an id belonging to
+ # the operator or to another seller is a 404. That matters more here
+ # than on most collections: a stock location is an address a shopper
+ # is given, and the operator's warehouse address is not a seller's to
+ # read or to hand out.
+ #
+ # No destroy: a location holds stock levels and is named on historical
+ # fulfillments, so removing one is an inventory operation rather than
+ # a delete. A seller retires a location by deactivating it.
+ class StockLocationsController < Seller::ResourceController
+ scoped_resource :stock_locations
+
+ protected
+
+ def model_class
+ Spree::StockLocation
+ end
+
+ def serializer_class
+ Spree.api.seller_stock_location_serializer
+ end
+
+ def permitted_params
+ params.permit(
+ :name, :company, :address1, :address2, :city, :zipcode,
+ :country_code, :state_code, :state_name, :phone,
+ :active, :default, :kind
+ )
+ end
+
+ # A new location is this seller's, and its store follows them.
+ def build_resource
+ current_seller.stock_locations.new(permitted_params.merge(store: current_store))
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/spree/api/app/serializers/spree/api/v3/seller/stock_location_serializer.rb b/spree/api/app/serializers/spree/api/v3/seller/stock_location_serializer.rb
new file mode 100644
index 0000000000..71b11ebf24
--- /dev/null
+++ b/spree/api/app/serializers/spree/api/v3/seller/stock_location_serializer.rb
@@ -0,0 +1,24 @@
+module Spree
+ module Api
+ module V3
+ module Seller
+ # A seller's own stock location, as they manage it in the panel.
+ #
+ # Extends the store serializer rather than the admin one: the fields
+ # an operator sees that a seller does not need are the ones about
+ # running the marketplace's own inventory (`admin_name`,
+ # `propagate_all_variants`, `backorderable_default`). What a seller
+ # needs is the address, whether it is live, and whether it is the one
+ # their returns go to.
+ class StockLocationSerializer < V3::StockLocationSerializer
+ typelize address2: [:string, nullable: true], state_name: [:string, nullable: true],
+ phone: [:string, nullable: true], company: [:string, nullable: true],
+ active: :boolean, default: :boolean, kind: :string
+
+ attributes :address2, :state_name, :phone, :company, :active, :default, :kind,
+ created_at: :iso8601, updated_at: :iso8601
+ end
+ end
+ end
+ end
+end
diff --git a/spree/api/config/routes.rb b/spree/api/config/routes.rb
index 1e7e23195d..722c082c3a 100644
--- a/spree/api/config/routes.rb
+++ b/spree/api/config/routes.rb
@@ -686,6 +686,11 @@ Spree::Core::Engine.add_routes do
# shape every later one follows — rooted in the seller by the anchor.
resources :products, only: [:index, :show, :create, :update, :destroy]
+ # Where this seller keeps stock, and so where their returns are sent.
+ # No destroy: a location holds stock levels and is named on historical
+ # fulfillments, so a seller retires one by deactivating it.
+ resources :stock_locations, only: [:index, :show, :create, :update]
+
# Reference data for the panel's address forms — the same list the
# storefront serves, not narrowed to the marketplace's markets.
resources :countries, only: [:index]
diff --git a/spree/api/lib/spree/api/dependencies.rb b/spree/api/lib/spree/api/dependencies.rb
index ce897e3f2e..d2590afe92 100644
--- a/spree/api/lib/spree/api/dependencies.rb
+++ b/spree/api/lib/spree/api/dependencies.rb
@@ -160,6 +160,7 @@ module Spree
seller_team_member_serializer: 'Spree::Api::V3::Seller::TeamMemberSerializer',
seller_invitation_serializer: 'Spree::Api::V3::Seller::InvitationSerializer',
seller_product_serializer: 'Spree::Api::V3::Seller::ProductSerializer',
+ seller_stock_location_serializer: 'Spree::Api::V3::Seller::StockLocationSerializer',
seller_requirement_status_serializer: 'Spree::Api::V3::Seller::RequirementStatusSerializer',
seller_requirement_submission_serializer: 'Spree::Api::V3::Seller::RequirementSubmissionSerializer',
admin_seller_serializer: 'Spree::Api::V3::Admin::SellerSerializer',
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/sellers_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/sellers_controller_spec.rb
index 6426fe5303..13d5b7099b 100644
--- a/spree/api/spec/controllers/spree/api/v3/admin/sellers_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/admin/sellers_controller_spec.rb
@@ -159,7 +159,7 @@ RSpec.describe Spree::Api::V3::Admin::SellersController, type: :controller do
it 'creates the seller its own address from nested attributes' do
patch :update, params: {
id: seller.prefixed_id,
- billing_address: { first_name: 'Ada', last_name: 'Lovelace', address1: '1 Seller Way',
+ billing_address: { company: 'Sparks Trading Ltd', address1: '1 Seller Way',
city: 'London', postal_code: 'EC1A 1BB', country_code: 'GB', phone: '555' }
}, as: :json
diff --git a/spree/api/spec/controllers/spree/api/v3/seller/profile_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/seller/profile_controller_spec.rb
index 1df57197e0..b7952302a8 100644
--- a/spree/api/spec/controllers/spree/api/v3/seller/profile_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/seller/profile_controller_spec.rb
@@ -59,15 +59,26 @@ RSpec.describe Spree::Api::V3::Seller::ProfileController, type: :controller do
expect(seller.contact_email).to eq('[email protected]')
end
- it 'writes an address inline' do
+ it 'writes its billing address inline' do
patch :update, params: {
- returns_address: { first_name: 'Ada', last_name: 'Lovelace', address1: '1 Seller Way',
+ billing_address: { company: 'Sparks Trading Ltd', 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')
+ expect(seller.reload.billing_address.address1).to eq('1 Seller Way')
+ end
+
+ # Returns go to a stock location, which has its own endpoint — a seller
+ # cannot write one through the profile.
+ it 'does not accept a returns address' do
+ patch :update, params: {
+ returns_address: { address1: '1 Seller Way', city: 'London', country_code: 'GB' }
+ }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(seller.reload.returns_address).to be_nil
end
# The lifecycle belongs to the operator's workflows. A seller approving
diff --git a/spree/api/spec/controllers/spree/api/v3/seller/stock_locations_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/seller/stock_locations_controller_spec.rb
new file mode 100644
index 0000000000..bd00c992b6
--- /dev/null
+++ b/spree/api/spec/controllers/spree/api/v3/seller/stock_locations_controller_spec.rb
@@ -0,0 +1,110 @@
+require 'spec_helper'
+
+# A stock location is an address a shopper is given for returns, so the
+# isolation here matters more than on most collections: the operator's
+# warehouse address is not a seller's to read.
+RSpec.describe Spree::Api::V3::Seller::StockLocationsController, type: :controller do
+ render_views
+
+ include_context 'API v3 Seller'
+
+ let(:seller_user) do
+ create(:admin_user, :without_admin_role).tap { |user| seller.add_user(user) }
+ end
+ let(:token) do
+ Spree::Api::V3::TestingSupport.generate_jwt(
+ seller_user, audience: Spree::Api::V3::JwtAuthentication::JWT_AUDIENCE_SELLER
+ )
+ end
+
+ let!(:mine) do
+ seller.stock_locations.create!(store: store, name: 'My Warehouse', default: true,
+ address1: '1 Seller Way', city: 'London', country_code: 'GB')
+ end
+ let(:other_seller) { create(:seller, :approved, store: store) }
+ let!(:theirs) do
+ other_seller.stock_locations.create!(store: store, name: 'Their Warehouse')
+ end
+ let!(:first_party) { create(:stock_location, store: store, name: 'Marketplace Warehouse') }
+
+ before do
+ request.headers['Authorization'] = "Bearer #{token}"
+ request.headers['X-Spree-Seller-Id'] = seller.prefixed_id
+ end
+
+ describe 'GET #index' do
+ it "lists only this seller's locations" do
+ get :index, as: :json
+
+ expect(response).to have_http_status(:ok)
+ names = json_response['data'].pluck('name')
+ expect(names).to include('My Warehouse')
+ expect(names).not_to include('Their Warehouse', 'Marketplace Warehouse')
+ end
+ end
+
+ describe 'GET #show' do
+ it 'finds its own' do
+ get :show, params: { id: mine.prefixed_id }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(json_response['name']).to eq('My Warehouse')
+ end
+
+ # 404 rather than 403: the caller must not learn whether it exists.
+ it "404s on another seller's" do
+ get :show, params: { id: theirs.prefixed_id }, as: :json
+
+ expect(response).to have_http_status(:not_found)
+ end
+
+ it "404s on the operator's own" do
+ get :show, params: { id: first_party.prefixed_id }, as: :json
+
+ expect(response).to have_http_status(:not_found)
+ end
+ end
+
+ describe 'POST #create' do
+ it 'creates one owned by this seller' do
+ post :create, params: { name: 'Second Warehouse', city: 'Leeds', country_code: 'GB' }, as: :json
+
+ expect(response).to have_http_status(:created)
+ created = Spree::StockLocation.find_by(name: 'Second Warehouse')
+ expect(created.seller).to eq(seller)
+ expect(created.store).to eq(store)
+ end
+
+ # The payload does not get to say whose it is.
+ it 'ignores a seller_id in the payload' do
+ post :create, params: { name: 'Third Warehouse', seller_id: other_seller.prefixed_id }, as: :json
+
+ expect(Spree::StockLocation.find_by(name: 'Third Warehouse').seller).to eq(seller)
+ end
+ end
+
+ describe 'PATCH #update' do
+ it 'updates its own' do
+ patch :update, params: { id: mine.prefixed_id, city: 'Manchester' }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(mine.reload.city).to eq('Manchester')
+ end
+
+ it "404s on another seller's" do
+ patch :update, params: { id: theirs.prefixed_id, city: 'Manchester' }, as: :json
+
+ expect(response).to have_http_status(:not_found)
+ expect(theirs.reload.city).not_to eq('Manchester')
+ end
+ end
+
+ # A location holds stock levels and is named on historical fulfillments, so
+ # retiring one is deactivation rather than deletion.
+ describe 'DELETE #destroy' do
+ it 'is not routable' do
+ expect { delete :destroy, params: { id: mine.prefixed_id }, as: :json }.
+ to raise_error(ActionController::UrlGenerationError)
+ end
+ end
+end
diff --git a/spree/api/spec/integration/spree/api/v3/admin/sellers_spec.rb b/spree/api/spec/integration/spree/api/v3/admin/sellers_spec.rb
index 76b95c4645..4192ce15c0 100644
--- a/spree/api/spec/integration/spree/api/v3/admin/sellers_spec.rb
+++ b/spree/api/spec/integration/spree/api/v3/admin/sellers_spec.rb
@@ -241,7 +241,7 @@ RSpec.describe 'Admin Sellers API', type: :request, swagger_doc: 'api-reference/
let(:body) do
{
billing_address: {
- first_name: 'Ada', last_name: 'Lovelace', address1: '1 Seller Way',
+ company: 'Sparks Trading Ltd', address1: '1 Seller Way',
city: 'London', postal_code: 'EC1A 1BB', country_code: 'GB', phone: '555'
}
}
diff --git a/spree/core/app/models/spree/business_address.rb b/spree/core/app/models/spree/business_address.rb
new file mode 100644
index 0000000000..a5d5e6d6ca
--- /dev/null
+++ b/spree/core/app/models/spree/business_address.rb
@@ -0,0 +1,25 @@
+module Spree
+ # An address belonging to a business rather than a person — a seller's
+ # billing address, as a commission invoice must address it.
+ #
+ # Shares `spree_addresses` with its parent rather than being STI: the table
+ # has no `type` column, and adding one to reach every order, customer and
+ # company row would be a heavy migration to record what the owning
+ # association already says.
+ #
+ # What differs is who the address names. There is no person to ask for, and
+ # the company is the part that cannot be left out.
+ class BusinessAddress < Spree::Address
+ def require_name?
+ false
+ end
+
+ def require_company?
+ !quick_checkout
+ end
+
+ def show_company_address_field?
+ true
+ end
+ end
+end
diff --git a/spree/core/app/models/spree/seller.rb b/spree/core/app/models/spree/seller.rb
index ab12b63ccf..eb09b46379 100644
--- a/spree/core/app/models/spree/seller.rb
+++ b/spree/core/app/models/spree/seller.rb
@@ -16,8 +16,11 @@ module Spree
include Spree::TranslatableResource
include Spree::HasCustomFields
include Spree::Metadata
+ include Spree::MemoizedData
include Spree::SanitizableRichText
+ MEMOIZED_METHODS = %w[onboarding_requirements].freeze
+
publishes_lifecycle_events
# Where a seller is in its life on the marketplace. Transitions belong to
@@ -57,32 +60,37 @@ module Spree
# Associations
#
belongs_to :store, class_name: 'Spree::Store'
- # On the commission invoice (EU) and where customer returns route.
- #
- # Written as nested attributes, never by id: an address carries no store of
- # its own, so accepting an id would let any staff member bind — and then
- # read back — a row belonging to another store's customer.
- #
- # Not `dependent: :destroy`, unlike the equivalent on CompanyLocation: a
- # seller is paranoid, so destroy is a soft delete, and taking the addresses
- # with it would hard-delete the rows a restored seller — and its historical
- # commission invoices — still point at.
- belongs_to :billing_address, class_name: 'Spree::Address', optional: true
- belongs_to :returns_address, class_name: 'Spree::Address', optional: true
-
- # update_only, so editing one field of an existing address changes that
- # row instead of building a replacement and orphaning the old one.
+ # Not `dependent: :destroy`: a seller is paranoid, so destroy is a soft
+ # delete, and taking the address with it would hard-delete a row the
+ # seller's historical commission invoices still point at.
+ belongs_to :billing_address, class_name: 'Spree::BusinessAddress', optional: true
+
+ # `update_only` edits the existing row rather than building a replacement
+ # and orphaning it; the association carries the saving and validation that
+ # go with it.
accepts_nested_attributes_for :billing_address, update_only: true
- accepts_nested_attributes_for :returns_address, update_only: true
-
- # The API reads and writes these under the same name, so the writer takes
- # either a record or the nested hash a client sends.
- %i[billing_address returns_address].each do |name|
- define_method(:"#{name}=") do |value|
- value.is_a?(Hash) || value.is_a?(ActionController::Parameters) ? send(:"#{name}_attributes=", value) : super(value)
- end
+
+ # The API reads and writes this under one name, so the writer takes the
+ # attributes a client sends as well as a record. Never an id: an address
+ # carries no store of its own, so binding one by id would reach another
+ # store's rows.
+ def billing_address=(value)
+ return super unless value.is_a?(Hash) || value.is_a?(ActionController::Parameters)
+
+ self.billing_address_attributes = value
end
+ # Where this seller keeps stock, and so where their returns land. Released
+ # rather than destroyed for the same reason products are: the operator
+ # decides what becomes of a departed seller's inventory.
+ has_many :stock_locations, class_name: 'Spree::StockLocation', dependent: :nullify,
+ inverse_of: :seller
+
+ # The seller's tax registrations — the VAT number the commission invoice
+ # needs, with the validation verdict and evidence the model carries.
+ has_many :tax_identifiers, class_name: 'Spree::TaxIdentifier', dependent: :destroy,
+ inverse_of: :seller
+
# Products and stock survive the seller leaving: the operator decides what
# happens to a departed seller's catalog, so it is never cascade-deleted.
# Both levels are released — a variant can carry the seller on its own
@@ -186,6 +194,37 @@ module Spree
terms_accepted_at.present?
end
+ # Where customers send returns — this seller's default stock location.
+ #
+ # A location rather than a loose address because a received return has to
+ # restock somewhere the catalog believes in: stock movements anchor to a
+ # location, so an address alone would leave the goods arriving nowhere.
+ #
+ # @return [Spree::StockLocation, nil]
+ def returns_location
+ stock_locations.active.order_default.first
+ end
+
+ # The postal address a shopper is given for returns.
+ #
+ # Nil until the location has an address on it: the location builds one from
+ # its own columns on demand, so an empty one would otherwise answer with a
+ # blank address that reads as configured.
+ #
+ # @return [Spree::Address, nil]
+ def returns_address
+ location = returns_location
+ return if location.nil? || location.address1.blank?
+<<<<<<< HEAD
+
+ location.address
+ end
+=======
+>>>>>>> f6898122e1 (fixup! Give a seller a stock location and a business identity)
+
+ location.address
+ end
+
# How many products this seller lists. Memoized because two readers ask
# on every list row — the operator's column and the minimum-products
# requirement — and a catalog is the one thing here that can run to
@@ -194,7 +233,7 @@ module Spree
#
# @return [Integer]
def products_count
- @products_count ||= products.count
+ products.count
end
# Where this seller stands against the marketplace's checklist
@@ -219,7 +258,7 @@ module Spree
# @return [Hash{Symbol => Integer}] done, total and percentage over the
# whole checklist, optional requirements included
def onboarding_progress
- @onboarding_progress ||= Spree::Sellers::Requirements.progress_of(onboarding_requirements)
+ Spree::Sellers::Requirements.progress_of(onboarding_requirements)
end
# @return [Integer] 0..100
@@ -232,6 +271,7 @@ module Spree
onboarding_requirements.none?(&:blocking?)
end
+<<<<<<< HEAD
# Drops the memoized checklist with the rest of the instance's state, so a
# flow that changes something and re-reads within one request sees it.
def reload(options = nil)
@@ -241,6 +281,8 @@ module Spree
super
end
+=======
+>>>>>>> f6898122e1 (fixup! Give a seller a stock location and a business identity)
private
def normalize_slug
@@ -249,6 +291,13 @@ module Spree
# Memberships and outstanding invitations are what make a role undeletable.
# They mean nothing once the seller is gone, so they go first.
+<<<<<<< HEAD
+ def mark_billing_address_as_business
+ association(:billing_address).target&.business = true
+ end
+
+=======
+>>>>>>> f6898122e1 (fixup! Give a seller a stock location and a business identity)
def dissolve_team
Spree::RoleUser.where(role_id: roles.ids).delete_all
invitations.destroy_all
diff --git a/spree/core/app/models/spree/seller_requirements/returns_address.rb b/spree/core/app/models/spree/seller_requirements/returns_address.rb
index 9055eb6d60..2745207c0f 100644
--- a/spree/core/app/models/spree/seller_requirements/returns_address.rb
+++ b/spree/core/app/models/spree/seller_requirements/returns_address.rb
@@ -4,9 +4,16 @@ module Spree
module SellerRequirements
# Where customer returns go. Without it a shopper cannot be told where to
# send anything back, which is why most marketplaces ask for it up front.
+ #
+ # Satisfied by a stock location rather than a loose address: a received
+ # return has to restock somewhere the catalog can see, so the address on
+ # its own would leave the goods arriving nowhere (Decision 12).
class ReturnsAddress < Spree::SellerRequirement
def met_by_seller?(seller)
- seller.returns_address.present? && seller.returns_address.persisted?
+ location = seller.returns_location
+ return false if location.nil?
+
+ location.address1.present? && location.city.present? && location.country_code.present?
end
end
end
diff --git a/spree/core/app/models/spree/stock_location.rb b/spree/core/app/models/spree/stock_location.rb
index 0038b394fe..7586ca8bce 100644
--- a/spree/core/app/models/spree/stock_location.rb
+++ b/spree/core/app/models/spree/stock_location.rb
@@ -13,7 +13,6 @@ module Spree
include Spree::SingleStoreResource
include Spree::HasExternalReferences
- include Spree::UniqueName
if defined?(Spree::Security::StockLocations)
include Spree::Security::StockLocations
end
@@ -28,6 +27,18 @@ module Spree
has_iso_geography
+ # Whose shelf this is. Nil is the operator's own — the only case in a store
+ # that is not a marketplace.
+ belongs_to :seller, class_name: 'Spree::Seller', optional: true, inverse_of: :stock_locations
+
+ # Name uniqueness is per owner rather than per store (see UniqueName, which
+ # this deliberately does not include): an operator and each of their sellers
+ # may each have a "Warehouse", which is what a marketplace looks like.
+ normalizes :name, with: ->(value) { value&.to_s&.squish&.presence }
+ validates :name, presence: true,
+ uniqueness: { case_sensitive: false, allow_blank: true,
+ scope: [*spree_base_uniqueness_scope, :store_id, :seller_id] }
+
validates :kind, presence: true
validates :pickup_stock_policy, inclusion: { in: PICKUP_STOCK_POLICIES }
validates :pickup_ready_in_minutes,
@@ -42,6 +53,9 @@ module Spree
scope :active, -> { where(active: true) }
scope :pickup_enabled, -> { where(pickup_enabled: true) }
scope :order_default, -> { order(default: :desc, name: :asc) }
+ # The operator's own locations — a marketplace's first-party stock.
+ scope :first_party, -> { where(seller_id: nil) }
+ scope :owned_by, ->(store_id:, seller_id:) { where(store_id: store_id, seller_id: seller_id) }
after_create :create_stock_levels, if: :propagate_all_variants?
after_save :ensure_one_default
@@ -276,13 +290,15 @@ module Spree
Spree::StockLocations::StockLevels::CreateJob.perform_later(self)
end
- # One default per STORE — scoping to the whole table would let one
- # store's default demote every other store's.
+ # One default per OWNER, not per store: on a marketplace the operator has a
+ # default and so does every seller, so scoping this to the store would let
+ # a seller saving their own default silently demote the operator's.
def ensure_one_default
- if default
- store.stock_locations.where(default: true).where.not(id: id).update_all(default: false)
- store.stock_locations.where.not(id: id).update_all(updated_at: Time.current)
- end
+ return unless default
+
+ siblings = self.class.owned_by(store_id: store_id, seller_id: seller_id).where.not(id: id)
+ siblings.where(default: true).update_all(default: false)
+ siblings.update_all(updated_at: Time.current)
end
def conditional_touch_records
diff --git a/spree/core/app/models/spree/store.rb b/spree/core/app/models/spree/store.rb
index 58753b1fdf..51c81bacb1 100644
--- a/spree/core/app/models/spree/store.rb
+++ b/spree/core/app/models/spree/store.rb
@@ -457,11 +457,16 @@ module Spree
country_codes.filter_map { |code| Spree::Country.by_iso(code) }.sort_by(&:name)
end
- # Returns the default stock location for the store or creates a new one if it doesn't exist
+ # The store's own default stock location, created if it does not exist yet.
+ #
+ # Scoped to this store's first-party locations on both counts: unscoped it
+ # answered with any store's default, and on a marketplace it would answer
+ # with a seller's — putting the operator's stock on someone else's shelf.
+ #
# @return [Spree::StockLocation]
def default_stock_location
@default_stock_location ||= begin
- stock_location_scope = Spree::StockLocation.where(default: true)
+ stock_location_scope = stock_locations.first_party.where(default: true)
stock_location_scope.first || ActiveRecord::Base.connected_to(role: :writing) do
stock_location_scope.create(default: true, name: Spree.t(:default_stock_location_name),
country_code: default_country&.iso)
diff --git a/spree/core/app/models/spree/tax_identifier.rb b/spree/core/app/models/spree/tax_identifier.rb
index 636aa6e09e..c016247e97 100644
--- a/spree/core/app/models/spree/tax_identifier.rb
+++ b/spree/core/app/models/spree/tax_identifier.rb
@@ -3,11 +3,17 @@ module Spree
# Handed to a tax provider through {Spree::TaxProvider::Base#estimate}, where
# it is what makes EU B2B reverse charge possible.
#
- # Three owners, exactly one per row: a customer (the durable profile value), a
- # cart (an override entered during checkout) or an order (the frozen snapshot
- # taken at completion). Orders keep a copy rather than a reference because a
- # registration can be changed or withdrawn later, and an invoice must still
- # show what was true when it was issued.
+ # Owners, exactly one per row: a customer (the durable profile value), a
+ # company (the business a customer buys for), a cart (an override entered
+ # during checkout) or an order (the frozen snapshot taken at completion).
+ # Orders keep a copy rather than a reference because a registration can be
+ # changed or withdrawn later, and an invoice must still show what was true
+ # when it was issued.
+ #
+ # A **seller** owns one too, and it faces the other way: the others say how
+ # the buyer is taxed, while a seller's registration is what the marketplace's
+ # own commission invoice is made out to, and what makes EU reverse charge on
+ # that fee possible (docs/plans/6.0-multi-vendor-marketplace.md Decision 12).
#
# == The +kind+ column
#
@@ -41,6 +47,7 @@ module Spree
# Owner — exactly one
belongs_to :customer, class_name: Spree.customer_class.to_s, optional: true, inverse_of: :tax_identifiers
belongs_to :company, class_name: 'Spree::Company', optional: true, inverse_of: :tax_identifiers
+ belongs_to :seller, class_name: 'Spree::Seller', optional: true, inverse_of: :tax_identifiers
belongs_to :cart, class_name: 'Spree::Cart', optional: true, inverse_of: :tax_identifier
belongs_to :order, class_name: 'Spree::Order', optional: true, inverse_of: :tax_identifier
@@ -64,6 +71,7 @@ module Spree
# own associations.
validates :kind, uniqueness: { scope: :customer_id }, if: -> { customer_id.present? }
validates :kind, uniqueness: { scope: :company_id }, if: -> { company_id.present? }
+ validates :kind, uniqueness: { scope: :seller_id }, if: -> { seller_id.present? }
# Data hygiene, not a format claim — no tax regime issues numbers this long.
validates :value, length: { maximum: 64 }
validates :validation_status, inclusion: { in: VALIDATION_STATUSES }, allow_nil: true
@@ -80,9 +88,9 @@ module Spree
persisted? && order_id.present?
end
- # @return [Spree::Customer, Spree::Company, Spree::Cart, Spree::Order, nil]
+ # @return [Spree::Customer, Spree::Company, Spree::Seller, Spree::Cart, Spree::Order, nil]
def owner
- customer || company || cart || order
+ customer || company || seller || cart || order
end
def verified?
@@ -142,7 +150,7 @@ module Spree
end
def exactly_one_owner
- return if [customer, company, cart, order].compact.one?
+ return if [customer, company, seller, cart, order].compact.one?
errors.add(:base, Spree.t('errors.messages.exactly_one_tax_identifier_owner'))
end
diff --git a/spree/core/app/services/spree/stores/provision_defaults.rb b/spree/core/app/services/spree/stores/provision_defaults.rb
index a3c59e1d85..702581e143 100644
--- a/spree/core/app/services/spree/stores/provision_defaults.rb
+++ b/spree/core/app/services/spree/stores/provision_defaults.rb
@@ -119,7 +119,10 @@ module Spree
# Match on identity alone: folding the other attributes into the finder
# made re-running fail once anything edited them.
def provision_stock_location
- location = store.stock_locations.where(name: Spree.t(:default_stock_location_name)).first_or_initialize
+ # first_party, so a seller who happened to name a location the same
+ # thing is never adopted as the store's own.
+ location = store.stock_locations.first_party.
+ where(name: Spree.t(:default_stock_location_name)).first_or_initialize
location.propagate_all_variants = false if location.new_record?
location.country_code = country.iso
location.active = true
@@ -191,10 +194,10 @@ module Spree
# A counter to collect from is what makes pickup real, so the store's
# default location opens for collection unless one already has.
- if store.stock_locations.where(pickup_enabled: true).none?
- store.stock_locations.find_by(default: true)&.update!(pickup_enabled: true)
+ if store.stock_locations.first_party.where(pickup_enabled: true).none?
+ store.stock_locations.first_party.find_by(default: true)&.update!(pickup_enabled: true)
end
- return if store.stock_locations.where(pickup_enabled: true).none?
+ return if store.stock_locations.first_party.where(pickup_enabled: true).none?
delivery_method = store.delivery_methods.where(name: Spree.t('pickup.store_pickup')).first_or_initialize
delivery_method.delivery_profile = profile
diff --git a/spree/core/app/workflows/spree/returns/create.rb b/spree/core/app/workflows/spree/returns/create.rb
index 07bd02fa38..3a3666c6c8 100644
--- a/spree/core/app/workflows/spree/returns/create.rb
+++ b/spree/core/app/workflows/spree/returns/create.rb
@@ -99,9 +99,14 @@ module Spree
failure(@return_record) unless @return_record.save
end
+ # Where the goods should physically come back to. The fulfillment's own
+ # location is the best answer — it is where they left from — then the
+ # seller's returns location on a marketplace order, so a seller's goods
+ # never come back to the operator's warehouse.
def default_stock_location
@normalized_items.first[:fulfillment_item].fulfillment&.stock_location ||
- order.store.stock_locations.first
+ (order.respond_to?(:seller) ? order.seller&.returns_location : nil) ||
+ order.store.default_stock_location
end
end
end
diff --git a/spree/core/app/workflows/spree/sellers/create.rb b/spree/core/app/workflows/spree/sellers/create.rb
new file mode 100644
index 0000000000..00bbf35bd0
--- /dev/null
+++ b/spree/core/app/workflows/spree/sellers/create.rb
@@ -0,0 +1,69 @@
+module Spree
+ module Sellers
+ # Creates a seller and gives them somewhere to keep stock.
+ #
+ # A workflow rather than plain CRUD because a seller is not usable without
+ # a stock location: it is where their inventory lives and where customer
+ # returns are sent, so provisioning it belongs to creating them rather than
+ # being a step an operator can forget. The legacy multi-vendor gem reached
+ # the same conclusion but did it in an `after_create` callback with a
+ # fallback inside the reader, which put a write inside a read.
+ class Create < Spree::Workflow
+ hooks :validate, :after_create
+
+ # @return [Spree::Seller]
+ attr_reader :seller
+
+ # @return [Spree::StockLocation] provisioned for the new seller
+ attr_reader :stock_location
+
+ # @param store [Spree::Store]
+ # @param attributes [Hash] seller attributes
+ def perform(store:, attributes: {})
+ super
+
+ step :build_seller
+ run_hooks :validate
+
+ ApplicationRecord.transaction do
+ step :save_seller
+ step :provision_stock_location
+ end
+
+ run_hooks :after_create
+ seller.publish_event('seller.created')
+ success(seller.reload)
+ end
+
+ private
+
+ def build_seller
+ @seller = store.sellers.new(attributes)
+ @seller.status ||= Spree::Seller.default_status
+ end
+
+ def save_seller
+ failure(seller, seller.errors) unless seller.save
+ end
+
+ # Named after the seller, since that is what an operator scanning every
+ # location in the marketplace needs to see. `default` is per-owner, so
+ # this is the default among *this seller's* locations and leaves the
+ # operator's own alone.
+ def provision_stock_location
+ @stock_location = seller.stock_locations.new(
+ store: seller.store,
+ name: seller.name,
+ default: true,
+ active: true,
+ country_code: seller.store.default_country_code
+ )
+ # A new seller has no catalog, so there is nothing to propagate — the
+ # levels arrive with their products.
+ @stock_location.propagate_all_variants = false
+
+ failure(@stock_location, @stock_location.errors) unless @stock_location.save
+ end
+ end
+ end
+end
diff --git a/spree/core/db/migrate/20260816000001_create_spree_sellers.rb b/spree/core/db/migrate/20260816000001_create_spree_sellers.rb
index 47a5ee34af..af5ad9e58b 100644
--- a/spree/core/db/migrate/20260816000001_create_spree_sellers.rb
+++ b/spree/core/db/migrate/20260816000001_create_spree_sellers.rb
@@ -9,7 +9,8 @@ class CreateSpreeSellers < ActiveRecord::Migration[8.1]
t.string :billing_email
t.text :about
t.references :billing_address
- t.references :returns_address
+ # No returns_address: returns route to a seller-owned stock location, so
+ # received goods restock somewhere inventory can see (Decision 12).
# Seller acceptance of the store's seller terms — the timestamp is the
# record of it, so onboarding can ask again when the terms change.
diff --git a/spree/core/db/migrate/20260820000001_add_seller_business_identity_and_stock_locations.rb b/spree/core/db/migrate/20260820000001_add_seller_business_identity_and_stock_locations.rb
new file mode 100644
index 0000000000..fa5f469130
--- /dev/null
+++ b/spree/core/db/migrate/20260820000001_add_seller_business_identity_and_stock_locations.rb
@@ -0,0 +1,24 @@
+class AddSellerBusinessIdentityAndStockLocations < ActiveRecord::Migration[8.1]
+ def change
+ # Seller-owned stock. Nullable: an operator's own locations have no seller,
+ # and that is the common case in a store that is not a marketplace.
+ #
+ # No uniqueness index on the name alongside it. Names are unique per owner
+ # once a marketplace has sellers, but that stays a validation as it always
+ # has been on this table — nothing resolves a location by name.
+ add_reference :spree_stock_locations, :seller, null: true
+
+ # The business behind the seller, as a commission invoice must address it.
+ # Distinct from the trading name: "Sparks" sells, "Sparks Trading Ltd"
+ # is invoiced.
+ add_column :spree_sellers, :legal_name, :string
+ add_column :spree_sellers, :registration_number, :string
+
+ # A fifth owner for the tax registration (docs/plans/6.0-tax-provider.md
+ # Phase 7). The seller's VAT number needs the validation verdict and the
+ # retained evidence the model already carries: EU reverse charge on the
+ # commission invoice has to stay defensible years after the registry that
+ # answered has moved on.
+ add_reference :spree_tax_identifiers, :seller, null: true
+ end
+end
diff --git a/spree/core/lib/spree/core/dependencies.rb b/spree/core/lib/spree/core/dependencies.rb
index ce1a9c784f..ea2b86cbc9 100644
--- a/spree/core/lib/spree/core/dependencies.rb
+++ b/spree/core/lib/spree/core/dependencies.rb
@@ -106,6 +106,7 @@ module Spree
claim_cancel_workflow: 'Spree::Claims::Cancel',
# sellers
+ seller_create_workflow: 'Spree::Sellers::Create',
seller_invite_workflow: 'Spree::Sellers::Invite',
seller_approve_workflow: 'Spree::Sellers::Approve',
seller_suspend_workflow: 'Spree::Sellers::Suspend',
diff --git a/spree/core/lib/spree/testing_support/factories/address_factory.rb b/spree/core/lib/spree/testing_support/factories/address_factory.rb
index 1a4c7b98f9..6941078c6f 100644
--- a/spree/core/lib/spree/testing_support/factories/address_factory.rb
+++ b/spree/core/lib/spree/testing_support/factories/address_factory.rb
@@ -37,5 +37,13 @@ FactoryBot.define do
# rejected everywhere else. Specs that care about a particular code pass
# one; the rest just need something the country accepts.
zipcode { Spree::TestingSupport::CountryPool.postal_code_for(country&.iso) }
+
+ # An address addressed to a company rather than a person — a seller's
+ # billing address. Shares the table with its parent, so the only
+ # difference is which fields it asks for.
+ factory :business_address, class: Spree::BusinessAddress do
+ firstname { nil }
+ lastname { nil }
+ end
end
end
diff --git a/spree/core/lib/tasks/seller_sample_data.rake b/spree/core/lib/tasks/seller_sample_data.rake
index 7deeccee60..54d4d44300 100644
--- a/spree/core/lib/tasks/seller_sample_data.rake
+++ b/spree/core/lib/tasks/seller_sample_data.rake
@@ -16,9 +16,20 @@ namespace :spree do
email = ENV.fetch('SELLER_EMAIL', '[email protected]')
password = ENV.fetch('SELLER_PASSWORD', 'spree123')
- seller = Spree::Seller.find_or_initialize_by(name: ENV.fetch('SELLER_NAME', 'Bright Sparks'), store: store)
- seller.status = 'approved' if seller.new_record?
- seller.save! if seller.new_record?
+ seller_name = ENV.fetch('SELLER_NAME', 'Bright Sparks')
+ seller = Spree::Seller.find_by(name: seller_name, store: store)
+
+ # Through the workflow, so the sample seller gets the stock location a
+ # real one does — without it their returns have nowhere to go and the
+ # checklist can never be finished.
+ if seller.nil?
+ result = Spree.seller_create_workflow.call(
+ store: store, attributes: { name: seller_name, status: 'approved' }
+ )
+ abort "Could not create the sample seller: #{result.value.errors.full_messages.to_sentence}" unless result.success?
+
+ seller = result.value
+ end
owner = Spree.admin_user_class.find_by(email: email)
diff --git a/spree/core/spec/models/spree/seller_requirements_spec.rb b/spree/core/spec/models/spree/seller_requirements_spec.rb
index 9d60d953c7..97caf003de 100644
--- a/spree/core/spec/models/spree/seller_requirements_spec.rb
+++ b/spree/core/spec/models/spree/seller_requirements_spec.rb
@@ -114,7 +114,7 @@ RSpec.describe 'seller requirement kinds', type: :model do
it 'is met once an address is saved' do
expect(requirement.satisfied?(seller)).to be false
- seller.update!(billing_address: create(:address))
+ seller.update!(billing_address: build(:business_address))
expect(requirement.satisfied?(seller.reload)).to be true
end
@@ -205,4 +205,27 @@ RSpec.describe 'seller requirement kinds', type: :model do
expect(requirement.satisfied?(seller)).to be true
end
end
+ describe Spree::SellerRequirements::ReturnsAddress do
+ let(:requirement) { create(:returns_address_requirement, store: store) }
+
+ # A location with no address on it tells a shopper nothing about where to
+ # post the parcel, so having the row is not the same as being ready.
+ it 'is unmet while the seller location has no address' do
+ seller.stock_locations.create!(store: store, name: 'Warehouse', default: true)
+
+ expect(requirement.satisfied?(seller.reload)).to be false
+ end
+
+ it 'is met once the returns location can be posted to' do
+ seller.stock_locations.create!(store: store, name: 'Warehouse', default: true,
+ address1: '1 Seller Way', city: 'London', country_code: 'GB')
+
+ expect(requirement.satisfied?(seller.reload)).to be true
+ end
+
+ it 'is unmet when the seller has no location at all' do
+ expect(requirement.satisfied?(seller)).to be false
+ end
+ end
+
end
diff --git a/spree/core/spec/models/spree/seller_spec.rb b/spree/core/spec/models/spree/seller_spec.rb
index 95b9ee9d01..c08e10cd53 100644
--- a/spree/core/spec/models/spree/seller_spec.rb
+++ b/spree/core/spec/models/spree/seller_spec.rb
@@ -201,17 +201,49 @@ describe Spree::Seller do
let(:seller) { create(:seller) }
it 'writes an address from nested attributes' do
- seller.update!(billing_address: { first_name: 'Ada', last_name: 'Lovelace',
+ seller.update!(billing_address: { company: 'Sparks Trading Ltd',
address1: '1 Seller Way', city: 'London',
postal_code: 'EC1A 1BB', country_code: 'GB', phone: '555' })
expect(seller.reload.billing_address.address1).to eq('1 Seller Way')
end
+ # A commission invoice is addressed to the business, so the company is the
+ # part that cannot be left out and a personal name is not asked for.
+ it 'requires the company and not a personal name' do
+ seller.update!(billing_address: { company: 'Sparks Trading Ltd', address1: '1 Seller Way',
+ city: 'London', postal_code: 'EC1A 1BB', country_code: 'GB' })
+
+ expect(seller.reload.billing_address.firstname).to be_blank
+ end
+
+ it 'refuses a billing address with no company' do
+ expect {
+ seller.update!(billing_address: { first_name: 'Ada', last_name: 'Lovelace',
+ address1: '1 Seller Way', city: 'London',
+ postal_code: 'EC1A 1BB', country_code: 'GB' })
+ }.to raise_error(ActiveRecord::RecordInvalid, /company/i)
+ end
+
+ # Loaded through the association, so a seller read fresh still gets the
+ # business rules — editing one field of a saved address must not fail on a
+ # personal name nobody was ever asked for.
+ it 'reads a saved billing address back as a business address' do
+ seller.update!(billing_address: { company: 'Sparks Trading Ltd', address1: '1 Seller Way',
+ city: 'London', postal_code: 'EC1A 1BB', country_code: 'GB' })
+
+ reloaded = described_class.find(seller.id)
+ expect(reloaded.billing_address).to be_a(Spree::BusinessAddress)
+ expect(reloaded.update(billing_address: { city: 'Manchester' })).to be(true)
+ end
+
# A seller is paranoid, so destroy is a soft delete. Taking the addresses
# with it would hard-delete rows a restored seller still points at.
it 'keeps its addresses when soft-deleted, and finds them again on restore' do
- seller.update!(billing_address: create(:address))
+ seller.update!(billing_address: Spree::BusinessAddress.create!(
+ company: 'Sparks Trading Ltd', address1: '1 Seller Way', city: 'London',
+ zipcode: 'EC1A 1BB', country_code: 'GB'
+ ))
address_id = seller.billing_address_id
seller.destroy
diff --git a/spree/core/spec/models/spree/store_spec.rb b/spree/core/spec/models/spree/store_spec.rb
index 3da1db53ee..ccade2feb3 100644
--- a/spree/core/spec/models/spree/store_spec.rb
+++ b/spree/core/spec/models/spree/store_spec.rb
@@ -820,11 +820,26 @@ describe Spree::Store, type: :model, without_global_store: true do
before { Spree::Current.store = subject }
context 'with default stock location' do
- let!(:default_stock_location) { create(:stock_location, default: true) }
+ let!(:default_stock_location) { create(:stock_location, store: subject, default: true) }
it 'returns the default stock location' do
expect(subject.default_stock_location).to eq(default_stock_location)
end
+
+ # The lookup is scoped to this store's own locations on both counts —
+ # another store's default is not this one's, and neither is a seller's.
+ it 'ignores a default belonging to another store' do
+ create(:stock_location, store: create(:store), default: true)
+
+ expect(subject.default_stock_location).to eq(default_stock_location)
+ end
+
+ it 'ignores a seller default' do
+ seller = create(:seller, store: subject)
+ seller.stock_locations.create!(store: subject, name: 'Seller warehouse', default: true)
+
+ expect(subject.default_stock_location).to eq(default_stock_location.reload)
+ end
end
context 'without default stock location' do
diff --git a/spree/core/spec/models/spree/tax_identifier_spec.rb b/spree/core/spec/models/spree/tax_identifier_spec.rb
index 1844a00c82..bd63f5c9f5 100644
--- a/spree/core/spec/models/spree/tax_identifier_spec.rb
+++ b/spree/core/spec/models/spree/tax_identifier_spec.rb
@@ -198,4 +198,32 @@ describe Spree::TaxIdentifier, type: :model do
expect(identifier.owner).to eq(company)
end
end
+ # A seller's registration faces the other way from the rest: it is what the
+ # marketplace's own commission invoice is made out to, and what makes EU
+ # reverse charge on that fee possible.
+ describe 'a seller owner' do
+ let(:seller) { create(:seller) }
+
+ it 'is a valid owner' do
+ identifier = described_class.new(seller: seller, kind: 'eu_vat', value: 'GB123456789')
+
+ expect(identifier).to be_valid
+ expect(identifier.owner).to eq(seller)
+ end
+
+ it 'holds one registration per kind' do
+ described_class.create!(seller: seller, kind: 'eu_vat', value: 'GB123456789')
+ duplicate = described_class.new(seller: seller, kind: 'eu_vat', value: 'GB987654321')
+
+ expect(duplicate).not_to be_valid
+ end
+
+ it 'cannot also belong to somebody else' do
+ identifier = described_class.new(seller: seller, company: create(:company),
+ kind: 'eu_vat', value: 'GB123456789')
+
+ expect(identifier).not_to be_valid
+ end
+ end
+
end
diff --git a/spree/core/spec/services/spree/commissions/commission_order_spec.rb b/spree/core/spec/services/spree/commissions/commission_order_spec.rb
index bc14812b19..1e20ca6b4d 100644
--- a/spree/core/spec/services/spree/commissions/commission_order_spec.rb
+++ b/spree/core/spec/services/spree/commissions/commission_order_spec.rb
@@ -171,7 +171,7 @@ RSpec.describe Spree::Commissions::CommissionOrder do
# be able to see why their fee was taxed the way it was.
it 'records the treatment and jurisdiction on the line' do
line_for(seller)
- seller.update!(billing_address: create(:address, country_iso: 'DE'))
+ seller.update!(billing_address: build(:business_address, country_iso: 'DE'))
allow_any_instance_of(Spree::TaxProvider::Internal).to receive(:service_tax_rate).and_return(0.19)
line = commission.first
diff --git a/spree/core/spec/workflows/spree/sellers/create_spec.rb b/spree/core/spec/workflows/spree/sellers/create_spec.rb
new file mode 100644
index 0000000000..bad0f0ec8a
--- /dev/null
+++ b/spree/core/spec/workflows/spree/sellers/create_spec.rb
@@ -0,0 +1,73 @@
+require 'spec_helper'
+
+RSpec.describe Spree::Sellers::Create do
+ let(:store) { @default_store }
+
+ subject { described_class.call(store: store, attributes: attributes) }
+
+ let(:attributes) { { name: 'Sparks' } }
+
+ it 'creates the seller' do
+ expect(subject).to be_success
+ expect(subject.value.name).to eq('Sparks')
+ end
+
+ # A seller with nowhere to keep stock has nowhere for returns to go either,
+ # so provisioning it is part of creating them.
+ it 'provisions a stock location named after the seller' do
+ seller = subject.value
+
+ expect(seller.stock_locations.count).to eq(1)
+ expect(seller.stock_locations.first).to have_attributes(name: 'Sparks', default: true, active: true)
+ end
+
+ it 'makes that location the seller returns route' do
+ seller = subject.value
+
+ expect(seller.returns_location).to eq(seller.stock_locations.first)
+ end
+
+ # The default flag is per owner, so a seller's default must not demote the
+ # marketplace's own.
+ it 'leaves the operator default alone' do
+ operator_default = store.default_stock_location
+
+ subject
+
+ expect(operator_default.reload).to be_default
+ end
+
+ # Two sellers may each call their warehouse the same thing, which is what a
+ # marketplace looks like.
+ it 'allows two sellers to hold a location with the same name' do
+ first = described_class.call(store: store, attributes: { name: 'Sparks' }).value
+ second = described_class.call(store: store, attributes: { name: 'Embers' }).value
+
+ second.stock_locations.first.update!(name: first.stock_locations.first.name)
+
+ expect(second.stock_locations.first.reload.name).to eq('Sparks')
+ end
+
+ # The operator may hold one by that name too.
+ it 'allows a seller location to share a name with the operator' do
+ operator_name = store.default_stock_location.name
+ seller = described_class.call(store: store, attributes: { name: 'Sparks' }).value
+
+ expect(seller.stock_locations.first.update(name: operator_name)).to be(true)
+ end
+
+ # Within one seller, though, names still have to be distinct.
+ it 'refuses a duplicate name within the same seller' do
+ seller = subject.value
+ duplicate = seller.stock_locations.new(store: store, name: seller.stock_locations.first.name)
+
+ expect(duplicate).not_to be_valid
+ end
+
+ it 'fails without a name, and writes no location' do
+ result = described_class.call(store: store, attributes: { name: '' })
+
+ expect(result).not_to be_success
+ expect(store.stock_locations.where.not(seller_id: nil)).to be_empty
+ end
+end