Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
Move a product's stock history behind a button and link each row to its cause
Damian Legawiec509e0977c46f
diff --git a/packages/admin-sdk/src/types/generated/StockMovement.ts b/packages/admin-sdk/src/types/generated/StockMovement.tsindex debca375dd..ec31eb3c79 100644--- a/packages/admin-sdk/src/types/generated/StockMovement.ts+++ b/packages/admin-sdk/src/types/generated/StockMovement.ts@@ -1,4 +1,4 @@-// Typelizer digest 259088ce278bbc8af5c6946765ea52b6+// Typelizer digest 1a23ee23f4c0171b322384f1b782dc8e//// DO NOT MODIFY: This file was automatically generated by Typelizer.@@ -22,6 +22,11 @@ interface StockMovement {stock_transfer_id: string | null;stock_receipt_id: string | null;purchase_order_id: string | null;+ order_number: string | null;+ return_number: string | null;+ exchange_number: string | null;+ stock_transfer_number: string | null;+ purchase_order_number: string | null;unit_cost: string | null;display_unit_cost: string | null;}diff --git a/packages/dashboard-core/src/products/product-form-cards.tsx b/packages/dashboard-core/src/products/product-form-cards.tsxindex 6a63ffdaec..e6344a365e 100644--- a/packages/dashboard-core/src/products/product-form-cards.tsx+++ b/packages/dashboard-core/src/products/product-form-cards.tsx@@ -26,6 +26,7 @@ import {import {Button,Card,+ CardAction,CardContent,CardHeader,CardTitle,@@ -764,12 +765,14 @@ function SortableMediaThumbnail({export function InventoryCard({form,stockLocationHref,-}: FormCardProps & { stockLocationHref?: (id: string) => string }) {+ actions,+}: FormCardProps & { stockLocationHref?: (id: string) => string; actions?: React.ReactNode }) {const { t } = useTranslation()return (<Card><CardHeader><CardTitle>{t('admin.pages.products.section_inventory')}</CardTitle>+ {actions && <CardAction>{actions}</CardAction>}</CardHeader><CardContent className="p-0"><InventorySection form={form} stockLocationHref={stockLocationHref} />diff --git a/packages/dashboard/src/components/spree/stock-history-card.tsx b/packages/dashboard/src/components/spree/stock-history-card.tsxindex b1a261f1fc..7ffb3708d4 100644--- a/packages/dashboard/src/components/spree/stock-history-card.tsx+++ b/packages/dashboard/src/components/spree/stock-history-card.tsx@@ -1,10 +1,17 @@import type { StockMovement } from '@spree/admin-sdk'-import { adminClient, useResourceKey } from '@spree/dashboard-core'+import { adminClient, useResourceKey, useStore } from '@spree/dashboard-core'import {+ Button,Card,CardContent,CardHeader,CardTitle,+ Dialog,+ DialogBody,+ DialogContent,+ DialogDescription,+ DialogHeader,+ DialogTitle,Pagination,RelativeTime,StatusBadge,@@ -16,25 +23,20 @@ import {TableRow,} from '@spree/dashboard-ui'import { useQuery } from '@tanstack/react-query'+import { Link } from '@tanstack/react-router'+import { HistoryIcon } from 'lucide-react'import { useState } from 'react'import { useTranslation } from 'react-i18next'/**- * Why the on-hand number is what it is.- *- * Movement history is only ever read about something — a SKU ("why is this 47?"),- * a warehouse ("what changed in Brooklyn this week?"), or one document ("what- * did this trip actually move?"). The legacy admin's undifferentiated firehose- * answered none of them (docs/plans/6.0-inventory-operations.md), so this is a- * panel, never a page, and it takes exactly one subject.+ * What the history is about. Movement history is only ever read about+ * something — a SKU ("why is this 47?"), a warehouse ("what changed in+ * Brooklyn this week?"), or one document ("what did this trip actually+ * move?"). The legacy admin's undifferentiated firehose answered none of them+ * (docs/plans/6.0-inventory-operations.md), so every surface takes exactly+ * one subject.*/-export function StockHistoryCard({- variantIds,- stockLocationId,- stockTransferId,- purchaseOrderId,- title,-}: {+type StockHistoryScope = {/** One SKU's history, or a product's across all of its variants. */variantIds?: string[]stockLocationId?: string | null@@ -42,8 +44,58 @@ export function StockHistoryCard({stockTransferId?: string | null/** One order's own rows: every delivery counted in against it. */purchaseOrderId?: string | null- title?: string-}) {+}++/** Why the on-hand number is what it is, as a card on a document's page. */+export function StockHistoryCard({ title, ...scope }: StockHistoryScope & { title?: string }) {+ const { t } = useTranslation()++ return (+ <Card>+ <CardHeader>+ <CardTitle>{title ?? t('admin.stock_history.title')}</CardTitle>+ </CardHeader>+ <CardContent className="p-0">+ <StockHistoryTable {...scope} />+ </CardContent>+ </Card>+ )+}++/**+ * The same history behind a button, for a page that is a form: a product's+ * ledger is read, never edited, so it sits beside the inventory card rather+ * than between two things the merchant is about to save.+ */+export function StockHistoryDialog(scope: StockHistoryScope) {+ const { t } = useTranslation()+ const [open, setOpen] = useState(false)++ return (+ <>+ <Button type="button" variant="outline" size="sm" onClick={() => setOpen(true)}>+ <HistoryIcon />+ {t('admin.stock_history.title')}+ </Button>+ <Dialog open={open} onOpenChange={setOpen}>+ <DialogContent className="sm:max-w-[min(1100px,calc(100%-2rem))]">+ <DialogHeader>+ <DialogTitle>{t('admin.stock_history.title')}</DialogTitle>+ <DialogDescription>{t('admin.stock_history.description')}</DialogDescription>+ </DialogHeader>+ <DialogBody className="p-0">{open && <StockHistoryTable {...scope} />}</DialogBody>+ </DialogContent>+ </Dialog>+ </>+ )+}++function StockHistoryTable({+ variantIds,+ stockLocationId,+ stockTransferId,+ purchaseOrderId,+}: StockHistoryScope) {const { t } = useTranslation()const [page, setPage] = useState(1)@@ -76,76 +128,68 @@ export function StockHistoryCard({const movements = data?.data ?? []const paginated = (data?.meta?.pages ?? 1) > 1+ if (isLoading) {+ return <p className="p-3 text-muted-foreground text-sm">{t('admin.common.loading')}</p>+ }+ if (movements.length === 0) {+ return <p className="p-3 text-muted-foreground text-sm">{t('admin.stock_history.empty')}</p>+ }+return (- <Card>- <CardHeader>- <CardTitle>{title ?? t('admin.stock_history.title')}</CardTitle>- </CardHeader>- <CardContent className="p-0">- {isLoading ? (- <p className="p-3 text-muted-foreground text-sm">{t('admin.common.loading')}</p>- ) : movements.length === 0 ? (- <p className="p-3 text-muted-foreground text-sm">{t('admin.stock_history.empty')}</p>- ) : (- <>- {/* The pagination bar brings its own top rule and padding, so it- takes the card's bottom curve when it is there — and the last- row takes it when the history fits on one page. */}- <Table scrollX roundedBottom={!paginated}>- <TableHeader>- <TableRow>- <TableHead>{t('admin.stock_history.columns.when')}</TableHead>- <TableHead>{t('admin.stock_history.columns.product')}</TableHead>- <TableHead>{t('admin.stock_history.columns.where')}</TableHead>- <TableHead>{t('admin.stock_history.columns.change')}</TableHead>- <TableHead>{t('admin.stock_history.columns.kind')}</TableHead>- <TableHead>{t('admin.stock_history.columns.cause')}</TableHead>- </TableRow>- </TableHeader>- <TableBody>- {movements.map((movement) => (- <TableRow key={movement.id}>- <TableCell className="whitespace-nowrap text-muted-foreground text-sm">- <RelativeTime iso={movement.created_at} />- </TableCell>- <TableCell>- <div className="min-w-0">- <div className="truncate font-medium">{movement.variant_name ?? '—'}</div>- {movement.variant_sku && (- <div className="text-muted-foreground text-xs">- {movement.variant_sku}- </div>- )}- </div>- </TableCell>- <TableCell className="whitespace-nowrap text-sm">- {movement.stock_location_name ?? '—'}- </TableCell>- <TableCell className="font-medium tabular-nums">- <QuantityChange movement={movement} />- </TableCell>- <TableCell>- {movement.kind ? (- <StatusBadge- status={movement.kind}- label={t(`admin.stock_history.kinds.${movement.kind}`)}- />- ) : (- '—'- )}- </TableCell>- <TableCell className="text-sm">- <MovementCause movement={movement} />- </TableCell>- </TableRow>- ))}- </TableBody>- </Table>- {paginated && data?.meta && <Pagination meta={data.meta} onPageChange={setPage} />}- </>- )}- </CardContent>- </Card>+ <>+ {/* The pagination bar brings its own top rule and padding, so it takes+ the bottom curve when it is there — and the last row takes it when+ the history fits on one page. */}+ <Table scrollX roundedBottom={!paginated}>+ <TableHeader>+ <TableRow>+ <TableHead>{t('admin.stock_history.columns.date')}</TableHead>+ <TableHead>{t('admin.stock_history.columns.product')}</TableHead>+ <TableHead>{t('admin.stock_history.columns.where')}</TableHead>+ <TableHead>{t('admin.stock_history.columns.change')}</TableHead>+ <TableHead>{t('admin.stock_history.columns.kind')}</TableHead>+ <TableHead>{t('admin.stock_history.columns.cause')}</TableHead>+ </TableRow>+ </TableHeader>+ <TableBody>+ {movements.map((movement) => (+ <TableRow key={movement.id}>+ <TableCell className="whitespace-nowrap text-muted-foreground text-sm">+ <RelativeTime iso={movement.created_at} />+ </TableCell>+ <TableCell>+ <div className="min-w-0">+ <div className="truncate font-medium">{movement.variant_name ?? '—'}</div>+ {movement.variant_sku && (+ <div className="text-muted-foreground text-xs">{movement.variant_sku}</div>+ )}+ </div>+ </TableCell>+ <TableCell className="whitespace-nowrap text-sm">+ {movement.stock_location_name ?? '—'}+ </TableCell>+ <TableCell className="font-medium tabular-nums">+ <QuantityChange movement={movement} />+ </TableCell>+ <TableCell>+ {movement.kind ? (+ <StatusBadge+ status={movement.kind}+ label={t(`admin.stock_history.kinds.${movement.kind}`)}+ />+ ) : (+ '—'+ )}+ </TableCell>+ <TableCell className="whitespace-nowrap text-sm">+ <MovementCause movement={movement} />+ </TableCell>+ </TableRow>+ ))}+ </TableBody>+ </Table>+ {paginated && data?.meta && <Pagination meta={data.meta} onPageChange={setPage} />}+ </>)}@@ -167,24 +211,68 @@ function QuantityChange({ movement }: { movement: StockMovement }) {)}-/** What caused the change, in the merchant's own vocabulary. */+/**+ * What caused the change, named the way the merchant knows it — "Stock+ * transfer T1001" — and pointing at the document where one has a page. A+ * return or an exchange lives on its order's page, so its row goes there.+ */function MovementCause({ movement }: { movement: StockMovement }) {const { t } = useTranslation()+ const { storeId } = useStore()- if (movement.purchase_order_id) {- return <span>{t('admin.stock_history.causes.purchase_order')}</span>- }- if (movement.stock_transfer_id) {- return <span>{t('admin.stock_history.causes.stock_transfer')}</span>+ const orderHref = movement.order_id ? `/${storeId}/orders/${movement.order_id}` : null+ const cause = movement.purchase_order_id+ ? {+ label: t('admin.stock_history.causes.purchase_order'),+ number: movement.purchase_order_number,+ href: `/${storeId}/purchase-orders/${movement.purchase_order_id}`,+ }+ : movement.stock_transfer_id+ ? {+ label: t('admin.stock_history.causes.stock_transfer'),+ number: movement.stock_transfer_number,+ href: `/${storeId}/transfers/${movement.stock_transfer_id}`,+ }+ : movement.return_id+ ? {+ label: t('admin.stock_history.causes.return'),+ number: movement.return_number,+ href: orderHref,+ }+ : movement.exchange_id+ ? {+ label: t('admin.stock_history.causes.exchange'),+ number: movement.exchange_number,+ href: orderHref,+ }+ : movement.fulfillment_id+ ? {+ label: t('admin.stock_history.causes.fulfillment'),+ number: movement.order_number,+ href: orderHref,+ }+ : movement.order_id+ ? {+ label: t('admin.stock_history.causes.order'),+ number: movement.order_number,+ href: orderHref,+ }+ : null++ if (!cause) {+ return (+ <span className="text-muted-foreground">+ {movement.reason ?? t('admin.stock_history.causes.manual')}+ </span>+ )}- if (movement.return_id) return <span>{t('admin.stock_history.causes.return')}</span>- if (movement.exchange_id) return <span>{t('admin.stock_history.causes.exchange')}</span>- if (movement.fulfillment_id) return <span>{t('admin.stock_history.causes.fulfillment')}</span>- if (movement.order_id) return <span>{t('admin.stock_history.causes.order')}</span>++ const text = cause.number ? `${cause.label} ${cause.number}` : cause.label+ if (!cause.href) return <span>{text}</span>return (- <span className="text-muted-foreground">- {movement.reason ?? t('admin.stock_history.causes.manual')}- </span>+ <Link to={cause.href} className="font-medium hover:underline">+ {text}+ </Link>)}diff --git a/packages/dashboard/src/locales/ar.json b/packages/dashboard/src/locales/ar.jsonindex 773adeda14..160205f4ca 100644--- a/packages/dashboard/src/locales/ar.json+++ b/packages/dashboard/src/locales/ar.json@@ -5477,7 +5477,7 @@"title": "سجل المخزون","empty": "لم يتغير هذا المخزون بعد","columns": {- "when": "الوقت",+ "date": "التاريخ","product": "المنتج","change": "التغيير","where": "المكان",@@ -5499,7 +5499,8 @@"fulfillment": "تنفيذ الطلب","order": "طلب","manual": "تعديل يدوي"- }+ },+ "description": "كل تغيير في هذا المخزون، الأحدث أولاً، وسببه."},"purchase_orders": {"title": "أوامر الشراء",diff --git a/packages/dashboard/src/locales/de.json b/packages/dashboard/src/locales/de.jsonindex a0f90715af..32e1205137 100644--- a/packages/dashboard/src/locales/de.json+++ b/packages/dashboard/src/locales/de.json@@ -5448,7 +5448,7 @@"title": "Bestandsverlauf","empty": "Dieser Bestand hat sich noch nicht verändert","columns": {- "when": "Wann",+ "date": "Datum","product": "Produkt","change": "Änderung","where": "Wo",@@ -5470,7 +5470,8 @@"fulfillment": "Auftragsabwicklung","order": "Auftrag","manual": "Manuelle Korrektur"- }+ },+ "description": "Jede Änderung an diesem Bestand, neueste zuerst, und was sie ausgelöst hat."},"purchase_orders": {"title": "Bestellungen",diff --git a/packages/dashboard/src/locales/en.json b/packages/dashboard/src/locales/en.jsonindex e5ed49c959..1712cf5118 100644--- a/packages/dashboard/src/locales/en.json+++ b/packages/dashboard/src/locales/en.json@@ -5448,7 +5448,7 @@"title": "Stock history","empty": "Nothing has changed this stock yet","columns": {- "when": "When",+ "date": "Date","product": "Product","change": "Change","where": "Where",@@ -5470,7 +5470,8 @@"fulfillment": "Fulfillment","order": "Order","manual": "Manual adjustment"- }+ },+ "description": "Every change to this stock, newest first, and what caused it."},"purchase_orders": {"title": "Purchase Orders",diff --git a/packages/dashboard/src/locales/fr.json b/packages/dashboard/src/locales/fr.jsonindex 088315388e..50c76fe691 100644--- a/packages/dashboard/src/locales/fr.json+++ b/packages/dashboard/src/locales/fr.json@@ -5448,7 +5448,7 @@"title": "Historique du stock","empty": "Ce stock n'a pas encore changé","columns": {- "when": "Quand",+ "date": "Date","product": "Produit","change": "Variation","where": "Où",@@ -5470,7 +5470,8 @@"fulfillment": "Préparation","order": "Commande","manual": "Ajustement manuel"- }+ },+ "description": "Chaque variation de ce stock, de la plus récente à la plus ancienne, et sa cause."},"purchase_orders": {"title": "Bons de commande",diff --git a/packages/dashboard/src/locales/pl.json b/packages/dashboard/src/locales/pl.jsonindex 8dcdda9736..ad53799c5c 100644--- a/packages/dashboard/src/locales/pl.json+++ b/packages/dashboard/src/locales/pl.json@@ -5510,7 +5510,7 @@"title": "Historia stanu","empty": "Ten stan jeszcze się nie zmieniał","columns": {- "when": "Kiedy",+ "date": "Data","product": "Produkt","change": "Zmiana","where": "Gdzie",@@ -5532,7 +5532,8 @@"fulfillment": "Realizacja","order": "Zamówienie","manual": "Korekta ręczna"- }+ },+ "description": "Każda zmiana tego stanu magazynowego, od najnowszej, wraz z jej przyczyną."},"purchase_orders": {"title": "Zamówienia zakupu",diff --git a/packages/dashboard/src/locales/zh-CN.json b/packages/dashboard/src/locales/zh-CN.jsonindex e28e5b231f..34e714a23b 100644--- a/packages/dashboard/src/locales/zh-CN.json+++ b/packages/dashboard/src/locales/zh-CN.json@@ -5437,7 +5437,7 @@"title": "库存记录","empty": "此库存尚无变动","columns": {- "when": "时间",+ "date": "日期","product": "商品","change": "变动","where": "位置",@@ -5459,7 +5459,8 @@"fulfillment": "履约","order": "订单","manual": "手动调整"- }+ },+ "description": "此库存的每一次变动(最新优先)及其原因。"},"purchase_orders": {"title": "采购订单",diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/products/$productId.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/products/$productId.tsxindex 749f2b39a8..fa267160f8 100644--- a/packages/dashboard/src/routes/_authenticated/$storeId/products/$productId.tsx+++ b/packages/dashboard/src/routes/_authenticated/$storeId/products/$productId.tsx@@ -44,7 +44,7 @@ import { ProductCustomFieldsProvider } from '../../../../components/spree/producimport { ProductReviewActions } from '../../../../components/spree/products/product-review-actions'import { ProductSellerCard } from '../../../../components/spree/products/product-seller-card'import { PublishingCard } from '../../../../components/spree/products/publishing-card'-import { StockHistoryCard } from '../../../../components/spree/stock-history-card'+import { StockHistoryDialog } from '../../../../components/spree/stock-history-card'import { ResourceTranslationsCard } from '../../../../components/spree/translations/resource-translations-card'import { useDeleteProduct, useProduct, useUpdateProduct } from '../../../../hooks/use-product'import { useProductMedia } from '../../../../hooks/use-product-media'@@ -290,11 +290,15 @@ function ProductForm({ product }: { product: Product }) {stockLocationHref={(id) =>`/${storeId}/settings/stock-locations?edit=${encodeURIComponent(id)}`}+ // Why the on-hand numbers are what they are. Across every+ // variant, because that is the question a merchant asks on a+ // product page (docs/plans/6.0-inventory-operations.md).+ actions={+ <StockHistoryDialog+ variantIds={assignableVariants.map((variant) => variant.id)}+ />+ }/>- {/* Why the on-hand numbers above are what they are. Across every- variant, because that is the question a merchant asks on a- product page (docs/plans/6.0-inventory-operations.md). */}- <StockHistoryCard variantIds={assignableVariants.map((variant) => variant.id)} /><DigitalAssetsCard productId={productId} variants={assignableVariants} /><ProductCustomFieldsProvider form={form} productTypeId={selectedProductTypeId}><CustomFieldsInlineCard />diff --git a/spree/api/app/controllers/spree/api/v3/admin/stock_movements_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/stock_movements_controller.rbindex 566fbe59b5..f51639a300 100644--- a/spree/api/app/controllers/spree/api/v3/admin/stock_movements_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/admin/stock_movements_controller.rb@@ -18,10 +18,11 @@ module SpreeSpree.api.admin_stock_movement_serializerend- # Every row names its shelf and its SKU, so both come along rather- # than costing a query each.+ # Every row names its shelf, its SKU and its cause by number, so all+ # of them come along rather than costing a query each.def collection_includes- [{ stock_level: [:stock_location, { variant: :product }] }]+ [{ stock_level: [:stock_location, { variant: :product }] },+ :order, :return, :exchange, :stock_transfer, :purchase_order]end# Newest first: a stock history is read from the most recent changediff --git a/spree/api/app/serializers/spree/api/v3/admin/stock_movement_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/stock_movement_serializer.rbindex 073efef586..6fb5f67e2c 100644--- a/spree/api/app/serializers/spree/api/v3/admin/stock_movement_serializer.rb+++ b/spree/api/app/serializers/spree/api/v3/admin/stock_movement_serializer.rb@@ -8,6 +8,10 @@ module Spreestock_transfer_id: [:string, nullable: true],purchase_order_id: [:string, nullable: true],stock_receipt_id: [:string, nullable: true],+ order_number: [:string, nullable: true], return_number: [:string, nullable: true],+ exchange_number: [:string, nullable: true],+ stock_transfer_number: [:string, nullable: true],+ purchase_order_number: [:string, nullable: true],unit_cost: [:string, nullable: true],display_unit_cost: [:string, nullable: true],stock_location_id: [:string, nullable: true],@@ -72,6 +76,29 @@ module SpreeSpree::PurchaseOrder.prefixed_id_for(movement.purchase_order_id)end+ # The cause by the name a merchant knows it by — "T1001", "PO1003",+ # "R123456789" — so a history row can point at its document without+ # a second request to look the number up.+ attribute :order_number do |movement|+ movement.order&.number+ end++ attribute :return_number do |movement|+ movement.return&.number+ end++ attribute :exchange_number do |movement|+ movement.exchange&.number+ end++ attribute :stock_transfer_number do |movement|+ movement.stock_transfer&.number+ end++ attribute :purchase_order_number do |movement|+ movement.purchase_order&.number+ end+# What the units cost, on the rows where that means something: a# purchase. Null on a transfer or a return — moving stock the# merchant already owns is not buying it.diff --git a/spree/api/spec/controllers/spree/api/v3/admin/stock_movements_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/stock_movements_controller_spec.rbindex 58ee881968..f5b2d3c091 100644--- a/spree/api/spec/controllers/spree/api/v3/admin/stock_movements_controller_spec.rb+++ b/spree/api/spec/controllers/spree/api/v3/admin/stock_movements_controller_spec.rb@@ -42,6 +42,7 @@ RSpec.describe Spree::Api::V3::Admin::StockMovementsController, type: :controllerow = json_response['data'].find { |m| m['id'] == allocation.prefixed_id }expect(row['fulfillment_id']).to eq(fulfillment.prefixed_id)expect(row['order_id']).to eq(order.prefixed_id)+ expect(row['order_number']).to eq(order.number)endit 'filters by kind' do@@ -82,6 +83,7 @@ RSpec.describe Spree::Api::V3::Admin::StockMovementsController, type: :controlleget :index, params: { q: { kind_eq: 'received' } }, as: :jsonrow = json_response['data'].find { |m| m['purchase_order_id'] == purchase_order.prefixed_id }+ expect(row['purchase_order_number']).to eq(purchase_order.number)expect(row['unit_cost']).to eq('9.5')expect(row['display_unit_cost']).to eq('$9.50')end