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 the seller panel a real product form

Damian Legawiec6903e3b6c6db
diff --git a/packages/dashboard-ui/src/index.ts b/packages/dashboard-ui/src/index.ts
index 5547d44e40..3dfb215215 100644
--- a/packages/dashboard-ui/src/index.ts
+++ b/packages/dashboard-ui/src/index.ts
@@ -48,6 +48,7 @@ export * from './spree/form-actions'
export * from './spree/language-menu-items'
export * from './spree/metadata/metadata-card'
+export * from './spree/products/status-card'
export * from './spree/relative-time'
export * from './spree/resource-combobox'
export * from './spree/resource-layout'
diff --git a/packages/dashboard-ui/src/spree/products/status-card.tsx b/packages/dashboard-ui/src/spree/products/status-card.tsx
new file mode 100644
index 0000000000..536e970523
--- /dev/null
+++ b/packages/dashboard-ui/src/spree/products/status-card.tsx
@@ -0,0 +1,70 @@
+import type { Control, FieldValues, Path } from 'react-hook-form'
+import { Controller } from 'react-hook-form'
+import { Card, CardContent, CardHeader, CardTitle } from '../../ui/card'
+import { Field, FieldLabel } from '../../ui/field'
+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '../../ui/select'
+
+export type StatusOption = { value: string; label: string }
+
+/**
+ * The product's status, chosen from whatever the caller allows.
+ *
+ * The options are a prop rather than a constant because the two dashboards
+ * offer different ones: an operator publishes directly, while a seller submits
+ * for review and can only take a listing back down. Headless, so the labels
+ * arrive translated.
+ */
+export function StatusCard<TFieldValues extends FieldValues>({
+ control,
+ name,
+ title,
+ label,
+ options,
+ disabled,
+ description,
+}: {
+ control: Control<TFieldValues>
+ name: Path<TFieldValues>
+ title: string
+ label: string
+ options: StatusOption[]
+ disabled?: boolean
+ description?: string
+}) {
+ return (
+ <Card>
+ <CardHeader>
+ <CardTitle>{title}</CardTitle>
+ </CardHeader>
+ <CardContent className="flex flex-col gap-4">
+ <Field>
+ <FieldLabel>{label}</FieldLabel>
+ <Controller
+ name={name}
+ control={control}
+ render={({ field }) => (
+ <Select
+ items={options as never}
+ value={field.value}
+ onValueChange={field.onChange}
+ disabled={disabled}
+ >
+ <SelectTrigger className="w-full">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {options.map((option) => (
+ <SelectItem key={option.value} value={option.value}>
+ {option.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ )}
+ />
+ {description && <p className="text-muted-foreground text-sm">{description}</p>}
+ </Field>
+ </CardContent>
+ </Card>
+ )
+}
diff --git a/packages/dashboard/src/components/spree/products/product-form-cards.tsx b/packages/dashboard/src/components/spree/products/product-form-cards.tsx
index 9ea2d89631..c41d3d9a34 100644
--- a/packages/dashboard/src/components/spree/products/product-form-cards.tsx
+++ b/packages/dashboard/src/components/spree/products/product-form-cards.tsx
@@ -43,6 +43,7 @@ import {
SelectItem,
SelectTrigger,
SelectValue,
+ StatusCard as SharedStatusCard,
Textarea,
toastManager,
useConfirm,
@@ -58,7 +59,7 @@ import {
TrashIcon,
} from 'lucide-react'
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
-import { Controller, type UseFormReturn, useWatch } from 'react-hook-form'
+import { type Control, Controller, type UseFormReturn, useWatch } from 'react-hook-form'
import { useTranslation } from 'react-i18next'
import { categoryAutocompleteProps, useCategories } from '../../../hooks/use-categories'
import { collectionAutocompleteProps, useCollections } from '../../../hooks/use-collections'
@@ -784,44 +785,18 @@ export function SEOCard({ form, product }: FormCardProps & { product?: Product }
export function StatusCard({ form }: FormCardProps) {
const { t } = useTranslation()
- const statusItems = [
- { value: 'draft', label: t('admin.pages.products.status_options.draft') },
- { value: 'active', label: t('admin.pages.products.status_options.active') },
- { value: 'archived', label: t('admin.pages.products.status_options.archived') },
- ]
+
return (
- <Card>
- <CardHeader>
- <CardTitle>{t('admin.fields.status.label')}</CardTitle>
- </CardHeader>
- <CardContent className="flex flex-col gap-4">
- <Field>
- <FieldLabel>{t('admin.fields.status.label')}</FieldLabel>
- <Controller
- name="status"
- control={form.control}
- render={({ field }) => (
- <Select
- items={statusItems as never}
- value={field.value}
- onValueChange={field.onChange}
- >
- <SelectTrigger className="w-full">
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- {statusItems.map((o) => (
- <SelectItem key={o.value} value={o.value}>
- {o.label}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- )}
- />
- </Field>
- </CardContent>
- </Card>
+ <SharedStatusCard<ProductFormValues>
+ control={form.control as Control<ProductFormValues>}
+ name="status"
+ title={t('admin.fields.status.label')}
+ label={t('admin.fields.status.label')}
+ options={['draft', 'active', 'archived'].map((value) => ({
+ value,
+ label: t(`admin.pages.products.status_options.${value}`),
+ }))}
+ />
)
}
diff --git a/packages/seller-dashboard/src/components/product-custom-fields.tsx b/packages/seller-dashboard/src/components/product-custom-fields.tsx
new file mode 100644
index 0000000000..3d154c2315
--- /dev/null
+++ b/packages/seller-dashboard/src/components/product-custom-fields.tsx
@@ -0,0 +1,80 @@
+import {
+ Card,
+ CardContent,
+ CardHeader,
+ CardTitle,
+ Field,
+ FieldGroup,
+ FieldLabel,
+ Input,
+ Switch,
+ Textarea,
+} from '@spree/dashboard-ui'
+import type { ProductTypeCustomFieldDefinition } from '@spree/seller-sdk'
+import type { Control, FieldValues, Path, UseFormRegister } from 'react-hook-form'
+import { Controller } from 'react-hook-form'
+import { useTranslation } from 'react-i18next'
+
+/**
+ * The fields a product type asks a seller to fill in.
+ *
+ * Values only. Which fields exist is the operator's to define, so there is no
+ * affordance here to add one — a seller answers the questions rather than
+ * setting them.
+ */
+export function ProductCustomFields<TFieldValues extends FieldValues>({
+ definitions,
+ register,
+ control,
+}: {
+ definitions: ProductTypeCustomFieldDefinition[]
+ // Generic over the caller's form rather than `any`: react-hook-form's
+ // Control is invariant, so a loose type here does not accept a precise one.
+ register: UseFormRegister<TFieldValues>
+ control: Control<TFieldValues>
+}) {
+ const { t } = useTranslation()
+
+ if (definitions.length === 0) return null
+
+ const sorted = [...definitions].sort((a, b) => a.sort_order - b.sort_order)
+
+ return (
+ <Card>
+ <CardHeader>
+ <CardTitle>{t('products.custom_fields')}</CardTitle>
+ </CardHeader>
+ <CardContent>
+ <FieldGroup>
+ {sorted.map((definition) => {
+ const name = `custom_fields.${definition.key}` as Path<TFieldValues>
+
+ return (
+ <Field key={definition.id}>
+ <FieldLabel htmlFor={name}>{definition.label}</FieldLabel>
+
+ {definition.field_type === 'long_text' || definition.field_type === 'rich_text' ? (
+ <Textarea id={name} rows={4} {...register(name)} />
+ ) : definition.field_type === 'boolean' ? (
+ <Controller
+ name={name}
+ control={control}
+ render={({ field }) => (
+ <Switch id={name} checked={!!field.value} onCheckedChange={field.onChange} />
+ )}
+ />
+ ) : (
+ <Input
+ id={name}
+ inputMode={definition.field_type === 'number' ? 'decimal' : undefined}
+ {...register(name)}
+ />
+ )}
+ </Field>
+ )
+ })}
+ </FieldGroup>
+ </CardContent>
+ </Card>
+ )
+}
diff --git a/packages/seller-dashboard/src/components/product-status-card.tsx b/packages/seller-dashboard/src/components/product-status-card.tsx
new file mode 100644
index 0000000000..6e7ff165df
--- /dev/null
+++ b/packages/seller-dashboard/src/components/product-status-card.tsx
@@ -0,0 +1,108 @@
+import {
+ Button,
+ Card,
+ CardContent,
+ CardHeader,
+ CardTitle,
+ StatusBadge,
+ toastManager,
+ useConfirm,
+} from '@spree/dashboard-ui'
+import type { Product } from '@spree/seller-sdk'
+import { useMutation } from '@tanstack/react-query'
+import { useTranslation } from 'react-i18next'
+import { sellerClient } from '../api-client'
+
+/**
+ * Where a product stands with the marketplace, and the one move available
+ * from here.
+ *
+ * Not a status dropdown: a seller cannot choose to be on sale. They submit
+ * and the operator decides, so each status offers only what it can actually
+ * do next (docs/plans/6.0-seller-product-submission.md).
+ */
+export function ProductStatusCard({ product, onDone }: { product: Product; onDone: () => void }) {
+ const { t } = useTranslation()
+ const confirm = useConfirm()
+
+ const move = useMutation({
+ mutationFn: (action: 'submit' | 'draft' | 'archive') =>
+ sellerClient().products[action](product.id),
+ onSuccess: () => {
+ toastManager.add({ type: 'success', title: t('products.status_updated') })
+ onDone()
+ },
+ onError: (err) =>
+ toastManager.add({
+ type: 'error',
+ title: err instanceof Error ? err.message : t('common.error'),
+ }),
+ })
+
+ const status = product.status
+ const canSubmit = status === 'draft' || status === 'rejected'
+ const canTakeDown = status === 'active' || status === 'proposed'
+
+ return (
+ <Card>
+ <CardHeader>
+ <CardTitle>{t('products.fields.status')}</CardTitle>
+ </CardHeader>
+ <CardContent className="flex flex-col items-start gap-3">
+ <StatusBadge status={status} />
+
+ <p className="text-muted-foreground text-sm">{t(`products.status_help.${status}`)}</p>
+
+ {/* Why the operator turned it down, so the seller knows what to fix. */}
+ {status === 'rejected' && typeof product.metadata?.rejection_reason === 'string' && (
+ <p className="text-sm">
+ {t('products.rejection_reason', { reason: product.metadata.rejection_reason })}
+ </p>
+ )}
+
+ <div className="flex flex-wrap gap-2">
+ {canSubmit && (
+ <Button disabled={move.isPending} onClick={() => move.mutate('submit')}>
+ {t('products.submit_for_review')}
+ </Button>
+ )}
+
+ {canTakeDown && (
+ <Button
+ variant="outline"
+ disabled={move.isPending}
+ onClick={async () => {
+ const confirmed = await confirm({
+ title: t('products.take_down_confirm_title'),
+ message: t('products.take_down_confirm_description'),
+ confirmLabel: t('products.take_down'),
+ })
+ if (confirmed) move.mutate('draft')
+ }}
+ >
+ {t('products.take_down')}
+ </Button>
+ )}
+
+ {status !== 'archived' && (
+ <Button
+ variant="outline"
+ disabled={move.isPending}
+ onClick={async () => {
+ const confirmed = await confirm({
+ title: t('products.archive_confirm_title'),
+ message: t('products.archive_confirm_description'),
+ confirmLabel: t('products.archive'),
+ variant: 'destructive',
+ })
+ if (confirmed) move.mutate('archive')
+ }}
+ >
+ {t('products.archive')}
+ </Button>
+ )}
+ </div>
+ </CardContent>
+ </Card>
+ )
+}
diff --git a/packages/seller-dashboard/src/locales/en.json b/packages/seller-dashboard/src/locales/en.json
index 72826f7415..6550150b62 100644
--- a/packages/seller-dashboard/src/locales/en.json
+++ b/packages/seller-dashboard/src/locales/en.json
@@ -117,11 +117,15 @@
},
"products": {
"add": "Add product",
+ "archive": "Archive",
+ "archive_confirm_description": "It comes off sale and out of your active listings.",
+ "archive_confirm_title": "Archive this product?",
"columns": {
"name": "Product",
"price": "Price",
"status": "Status"
},
+ "custom_fields": "Product details",
"details": "Details",
"empty": "No products yet. Add one to start selling.",
"fields": {
@@ -129,17 +133,40 @@
"name": "Name",
"price": "Price",
"price_placeholder": "Leave blank to keep the current price",
- "status": "Status"
+ "status": "Status",
+ "slug": "URL handle",
+ "meta_title": "Page title",
+ "meta_description": "Meta description",
+ "meta_keywords": "Meta keywords",
+ "product_type": "Product type",
+ "product_type_placeholder": "Choose a type"
},
"new_title": "New product",
"not_found": "That product could not be found.",
+ "organization": "Organisation",
+ "rejection_reason": "Reason: {{reason}}",
"saved": "Product saved",
"search_placeholder": "Search by name…",
+ "seo": "Search engine listing",
+ "status_help": {
+ "draft": "Only you can see this. Submit it when you are ready for the marketplace to review it.",
+ "proposed": "Waiting for the marketplace to review it. You can still make changes.",
+ "active": "On sale and visible to shoppers.",
+ "rejected": "The marketplace asked for changes. Edit it, then submit it again.",
+ "archived": "Off sale and out of your active listings."
+ },
+ "status_updated": "Status updated",
"statuses": {
"active": "Active",
"archived": "Archived",
- "draft": "Draft"
+ "draft": "Draft",
+ "proposed": "In review",
+ "rejected": "Changes needed"
},
+ "submit_for_review": "Submit for review",
+ "take_down": "Take down",
+ "take_down_confirm_description": "Shoppers will no longer see it. You can submit it again later.",
+ "take_down_confirm_title": "Take this listing down?",
"title": "Products"
},
"profile": {
diff --git a/packages/seller-dashboard/src/pages/product.tsx b/packages/seller-dashboard/src/pages/product.tsx
index 4c8d26b8c1..8763073798 100644
--- a/packages/seller-dashboard/src/pages/product.tsx
+++ b/packages/seller-dashboard/src/pages/product.tsx
@@ -15,6 +15,7 @@ import {
SelectItem,
SelectTrigger,
SelectValue,
+ StatusBadge,
Textarea,
toastManager,
} from '@spree/dashboard-ui'
@@ -26,15 +27,32 @@ import { useForm } from 'react-hook-form'
import { useTranslation } from 'react-i18next'
import { sellerClient } from '../api-client'
import { CenteredMessage } from '../components/centered-message'
+import { ProductCustomFields } from '../components/product-custom-fields'
+import { ProductStatusCard } from '../components/product-status-card'
import { RetryableError } from '../components/retryable-error'
-const STATUSES = ['draft', 'active', 'archived'] as const
-
interface ProductFormValues {
name: string
description: string
- status: string
amount: string
+ slug: string
+ meta_title: string
+ meta_description: string
+ meta_keywords: string
+ product_type_id: string
+ custom_fields: Record<string, string>
+}
+
+const EMPTY_VALUES: ProductFormValues = {
+ name: '',
+ description: '',
+ amount: '',
+ slug: '',
+ meta_title: '',
+ meta_description: '',
+ meta_keywords: '',
+ product_type_id: '',
+ custom_fields: {},
}
/**
@@ -42,6 +60,11 @@ interface ProductFormValues {
*
* The same form either way: a seller filling in a new listing and a seller
* correcting an old one are doing the same thing, and two screens would drift.
+ *
+ * Status is deliberately absent from the form. A seller does not choose
+ * whether their product is on sale — they submit it and the marketplace
+ * decides, which is what the status card does instead
+ * (docs/plans/6.0-seller-product-submission.md).
*/
export function ProductPage({ mode }: { mode: 'new' | 'edit' }) {
const { t } = useTranslation()
@@ -51,40 +74,59 @@ export function ProductPage({ mode }: { mode: 'new' | 'edit' }) {
const navigate = useNavigate()
const queryClient = useQueryClient()
+ const productKey = ['seller', sellerId, 'product', productId]
const {
data: product,
isLoading,
isError,
refetch,
} = useQuery({
- queryKey: ['seller', sellerId, 'product', productId],
+ queryKey: productKey,
queryFn: () => sellerClient().products.get(productId as string),
enabled: !!productId,
})
- const form = useForm<ProductFormValues>({
- defaultValues: { name: '', description: '', status: 'draft', amount: '' },
+ // The types a seller may list against, with the custom fields each asks for.
+ const { data: productTypes } = useQuery({
+ queryKey: ['seller', sellerId, 'product-types'],
+ queryFn: () => sellerClient().productTypes.list({ per_page: 100 }),
})
+ const form = useForm<ProductFormValues>({ defaultValues: EMPTY_VALUES })
+
// Reset once the record arrives, so the inputs show what was last saved
// rather than the blank defaults the form mounted with.
useEffect(() => {
if (!product) return
form.reset({
+ ...EMPTY_VALUES,
name: product.name ?? '',
description: product.description ?? '',
- status: product.status ?? 'draft',
amount: product.price?.amount ?? '',
+ slug: product.slug ?? '',
+ meta_title: product.meta_title ?? '',
+ meta_description: product.meta_description ?? '',
+ meta_keywords: product.meta_keywords ?? '',
+ product_type_id: product.product_type_id ?? '',
+ custom_fields: (product.metadata ?? {}) as Record<string, string>,
})
}, [product, form])
+ const selectedTypeId = form.watch('product_type_id')
+ const selectedType = productTypes?.data.find((type) => type.id === selectedTypeId)
+
const save = useMutation({
mutationFn: (values: ProductFormValues) => {
const payload: ProductParams = {
name: values.name,
description: values.description,
- status: values.status,
+ slug: values.slug || undefined,
+ meta_title: values.meta_title,
+ meta_description: values.meta_description,
+ meta_keywords: values.meta_keywords,
+ product_type_id: values.product_type_id || undefined,
+ metadata: values.custom_fields,
}
// Only sent when the seller typed one: an empty box means "leave the
// price alone", not "price this at nothing".
@@ -136,9 +178,12 @@ export function ProductPage({ mode }: { mode: 'new' | 'edit' }) {
return (
<form onSubmit={form.handleSubmit(onSubmit)} className="flex flex-col gap-4">
<div className="flex items-center justify-between gap-4">
- <h1 className="font-medium text-2xl">
- {productId ? product?.name : t('products.new_title')}
- </h1>
+ <div className="flex items-center gap-3">
+ <h1 className="font-medium text-2xl">
+ {productId ? product?.name : t('products.new_title')}
+ </h1>
+ {product?.status && <StatusBadge status={product.status} />}
+ </div>
<Button type="submit" disabled={isSubmitting}>
{isSubmitting ? t('common.saving') : t('common.save')}
</Button>
@@ -150,60 +195,134 @@ export function ProductPage({ mode }: { mode: 'new' | 'edit' }) {
</p>
)}
- <Card>
- <CardHeader>
- <CardTitle>{t('products.details')}</CardTitle>
- </CardHeader>
- <CardContent>
- <FieldGroup>
- <Field>
- <FieldLabel htmlFor="name">{t('products.fields.name')}</FieldLabel>
- <Input
- id="name"
- aria-invalid={!!errors.name || undefined}
- {...form.register('name', { required: true })}
- />
- <FieldError errors={[errors.name]} />
- </Field>
-
- <Field>
- <FieldLabel htmlFor="description">{t('products.fields.description')}</FieldLabel>
- <Textarea id="description" rows={5} {...form.register('description')} />
- <FieldError errors={[errors.description]} />
- </Field>
-
- <Field>
- <FieldLabel htmlFor="amount">{t('products.fields.price')}</FieldLabel>
- <Input
- id="amount"
- inputMode="decimal"
- placeholder={t('products.fields.price_placeholder')}
- {...form.register('amount')}
- />
- <FieldError errors={[errors.amount]} />
- </Field>
-
- <Field>
- <FieldLabel htmlFor="status">{t('products.fields.status')}</FieldLabel>
- <Select
- value={form.watch('status')}
- onValueChange={(value) => form.setValue('status', value, { shouldDirty: true })}
- >
- <SelectTrigger id="status">
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- {STATUSES.map((status) => (
- <SelectItem key={status} value={status}>
- {t(`products.statuses.${status}`)}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- </Field>
- </FieldGroup>
- </CardContent>
- </Card>
+ <div className="grid gap-4 lg:grid-cols-3">
+ <div className="flex flex-col gap-4 lg:col-span-2">
+ <Card>
+ <CardHeader>
+ <CardTitle>{t('products.details')}</CardTitle>
+ </CardHeader>
+ <CardContent>
+ <FieldGroup>
+ <Field>
+ <FieldLabel htmlFor="name">{t('products.fields.name')}</FieldLabel>
+ <Input
+ id="name"
+ aria-invalid={!!errors.name || undefined}
+ {...form.register('name', { required: true })}
+ />
+ <FieldError errors={[errors.name]} />
+ </Field>
+
+ <Field>
+ <FieldLabel htmlFor="description">{t('products.fields.description')}</FieldLabel>
+ <Textarea id="description" rows={6} {...form.register('description')} />
+ <FieldError errors={[errors.description]} />
+ </Field>
+
+ <Field>
+ <FieldLabel htmlFor="amount">{t('products.fields.price')}</FieldLabel>
+ <Input
+ id="amount"
+ inputMode="decimal"
+ placeholder={t('products.fields.price_placeholder')}
+ {...form.register('amount')}
+ />
+ <FieldError errors={[errors.amount]} />
+ </Field>
+ </FieldGroup>
+ </CardContent>
+ </Card>
+
+ {selectedType && (
+ <ProductCustomFields
+ definitions={selectedType.custom_field_definitions ?? []}
+ register={form.register}
+ control={form.control}
+ />
+ )}
+
+ <Card>
+ <CardHeader>
+ <CardTitle>{t('products.seo')}</CardTitle>
+ </CardHeader>
+ <CardContent>
+ <FieldGroup>
+ <Field>
+ <FieldLabel htmlFor="slug">{t('products.fields.slug')}</FieldLabel>
+ <Input id="slug" {...form.register('slug')} />
+ <FieldError errors={[errors.slug]} />
+ </Field>
+
+ <Field>
+ <FieldLabel htmlFor="meta_title">{t('products.fields.meta_title')}</FieldLabel>
+ <Input id="meta_title" {...form.register('meta_title')} />
+ </Field>
+
+ <Field>
+ <FieldLabel htmlFor="meta_description">
+ {t('products.fields.meta_description')}
+ </FieldLabel>
+ <Textarea id="meta_description" rows={3} {...form.register('meta_description')} />
+ </Field>
+
+ <Field>
+ <FieldLabel htmlFor="meta_keywords">
+ {t('products.fields.meta_keywords')}
+ </FieldLabel>
+ <Input id="meta_keywords" {...form.register('meta_keywords')} />
+ </Field>
+ </FieldGroup>
+ </CardContent>
+ </Card>
+ </div>
+
+ <div className="flex flex-col gap-4">
+ {productId && product && (
+ <ProductStatusCard
+ product={product}
+ onDone={() => {
+ void queryClient.invalidateQueries({ queryKey: productKey })
+ void queryClient.invalidateQueries({ queryKey: ['seller-products'] })
+ }}
+ />
+ )}
+
+ <Card>
+ <CardHeader>
+ <CardTitle>{t('products.organization')}</CardTitle>
+ </CardHeader>
+ <CardContent>
+ <Field>
+ <FieldLabel htmlFor="product_type_id">
+ {t('products.fields.product_type')}
+ </FieldLabel>
+ <Select
+ value={selectedTypeId}
+ onValueChange={(value) =>
+ form.setValue('product_type_id', value, { shouldDirty: true })
+ }
+ >
+ <SelectTrigger id="product_type_id">
+ <SelectValue placeholder={t('products.fields.product_type_placeholder')}>
+ {(value) =>
+ productTypes?.data.find((type) => type.id === value)?.name ??
+ t('products.fields.product_type_placeholder')
+ }
+ </SelectValue>
+ </SelectTrigger>
+ <SelectContent>
+ {productTypes?.data.map((type) => (
+ <SelectItem key={type.id} value={type.id}>
+ {type.name}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </Field>
+ </CardContent>
+ </Card>
+ </div>
+ </div>
</form>
)
}
diff --git a/packages/seller-sdk/src/seller-client.ts b/packages/seller-sdk/src/seller-client.ts
index 47b167790f..792fb57c6f 100644
--- a/packages/seller-sdk/src/seller-client.ts
+++ b/packages/seller-sdk/src/seller-client.ts
@@ -6,6 +6,7 @@ import type {
Invitation,
Order,
Product,
+ ProductType,
Profile,
RequirementStatus,
RequirementSubmission,
@@ -219,6 +220,40 @@ export class SellerClient {
delete: (id: string, options?: RequestOptions): Promise<void> =>
this.request<void>('DELETE', `/products/${id}`, options),
+
+ /**
+ * Ask the marketplace to put this product on sale.
+ *
+ * Status is not an attribute a seller can send: whether a listing goes
+ * live is the operator's decision, so it moves through these actions.
+ */
+ submit: (id: string, options?: RequestOptions): Promise<Product> =>
+ this.request<Product>('PATCH', `/products/${id}/submit`, options),
+
+ /** Take a listing back down. Withdrawing your own needs nobody's approval. */
+ draft: (id: string, options?: RequestOptions): Promise<Product> =>
+ this.request<Product>('PATCH', `/products/${id}/draft`, options),
+
+ archive: (id: string, options?: RequestOptions): Promise<Product> =>
+ this.request<Product>('PATCH', `/products/${id}/archive`, options),
+ }
+
+ /**
+ * The types a seller may list against, and the custom fields each asks
+ * them to fill in. Read only — defining a type is the operator's.
+ */
+ readonly productTypes = {
+ list: (
+ params?: ListParams & Record<string, unknown>,
+ options?: RequestOptions,
+ ): Promise<PaginatedResponse<ProductType>> =>
+ this.request<PaginatedResponse<ProductType>>('GET', '/product_types', {
+ ...options,
+ params: params ? transformListParams(params) : undefined,
+ }),
+
+ get: (id: string, options?: RequestOptions): Promise<ProductType> =>
+ this.request<ProductType>('GET', `/product_types/${id}`, options),
}
/**
@@ -381,7 +416,6 @@ export interface ProductParams {
name?: string
description?: string
slug?: string
- status?: string
meta_title?: string
meta_description?: string
meta_keywords?: string
diff --git a/packages/seller-sdk/src/types/generated/Product.ts b/packages/seller-sdk/src/types/generated/Product.ts
index 6717591481..84eb1aea85 100644
--- a/packages/seller-sdk/src/types/generated/Product.ts
+++ b/packages/seller-sdk/src/types/generated/Product.ts
@@ -1,4 +1,4 @@
-// Typelizer digest 21609f9855e7faa547d892c708b53c59
+// Typelizer digest f006c41b975a1f3ae9b1bcc2fe0c00d6
//
// DO NOT MODIFY: This file was automatically generated by Typelizer.
import type {Price, PriceHistory, Seller, Media, Variant, OptionType, OptionValue, Category, CustomField} from '@/types'
@@ -38,8 +38,11 @@ type Product = {
custom_fields?: Array<CustomField>;
prior_price?: PriceHistory | null;
status: string;
+ metadata: Record<string, unknown>;
created_at: string;
updated_at: string;
+ product_type_id: string | null;
+ category_ids: Array<string>;
}
export default Product;
diff --git a/spree/api/app/serializers/spree/api/v3/seller/product_serializer.rb b/spree/api/app/serializers/spree/api/v3/seller/product_serializer.rb
index 315f27cf69..b0040ceec6 100644
--- a/spree/api/app/serializers/spree/api/v3/seller/product_serializer.rb
+++ b/spree/api/app/serializers/spree/api/v3/seller/product_serializer.rb
@@ -2,10 +2,33 @@ module Spree
module Api
module V3
module Seller
+ # A seller's own product.
+ #
+ # Read and write have to name the same fields: the panel loads a
+ # product into a form and sends it back, so anything the controller
+ # accepts but this withholds would be blanked on save.
+ #
+ # `category_ids` is a flat list rather than the operator's expandable
+ # association — the form binds ids, and a seller has no use for the
+ # rest of a category.
class ProductSerializer < V3::ProductSerializer
- typelize status: :string
+ typelize status: :string,
+ product_type_id: [:string, nullable: true],
+ category_ids: [:string, multi: true],
+ metadata: 'Record<string, unknown>'
- attributes :status, created_at: :iso8601, updated_at: :iso8601
+ attributes :status, :metadata, created_at: :iso8601, updated_at: :iso8601
+
+ attribute :product_type_id do |product|
+ product.product_type&.prefixed_id
+ end
+
+ attribute :category_ids do |product|
+ store_id = current_store&.id
+ product.categories.filter_map do |category|
+ category.prefixed_id if store_id.nil? || category.store_id == store_id
+ end
+ end
end
end
end
diff --git a/spree/api/spec/controllers/spree/api/v3/seller/products_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/seller/products_controller_spec.rb
index b3c756b034..130d30aeb3 100644
--- a/spree/api/spec/controllers/spree/api/v3/seller/products_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/seller/products_controller_spec.rb
@@ -160,6 +160,25 @@ RSpec.describe Spree::Api::V3::Seller::ProductsController, type: :controller do
end
end
+ # The panel loads a product into a form and sends it back, so anything the
+ # controller accepts must come back out — otherwise a save blanks it.
+ it 'returns every field it accepts on write' do
+ category = create(:category, store: store)
+ product_type = create(:product_type, store: store)
+ mine.update!(product_type: product_type, categories: [category], metadata: { 'care' => 'wash cold' })
+
+ get :show, params: { id: mine.prefixed_id }, as: :json
+
+ expect(json_response).to include(
+ 'name', 'description', 'slug',
+ 'meta_title', 'meta_description', 'meta_keywords',
+ 'product_type_id', 'category_ids', 'metadata'
+ )
+ expect(json_response['product_type_id']).to eq(product_type.prefixed_id)
+ expect(json_response['category_ids']).to eq([category.prefixed_id])
+ expect(json_response['metadata']).to eq('care' => 'wash cold')
+ end
+
describe 'PATCH #update' do
it 'edits their own product' do
patch :update, params: { id: mine.prefixed_id, name: 'Renamed Lamp' }, as: :json