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
Fix: purchase order items now require a unit cost everywhere (#14914)
Damian Legawiec1ff3b911308c
diff --git a/.changeset/purchase-order-unit-cost-required.md b/.changeset/purchase-order-unit-cost-required.mdnew file mode 100644index 0000000000..c287350236--- /dev/null+++ b/.changeset/purchase-order-unit-cost-required.md@@ -0,0 +1,6 @@+---+"@spree/admin-sdk": patch+"@spree/dashboard": patch+---++`unit_cost` is now required on every purchase order item (`PurchaseOrderItemParams`), matching what the API already enforced. The dashboard's purchase order form now starts each line with an empty cost, so Save stays disabled until the merchant prices every line, instead of filling in zero.diff --git a/docs/api-reference/admin.yaml b/docs/api-reference/admin.yamlindex d362f2e0d7..9be4f1ae56 100644--- a/docs/api-reference/admin.yaml+++ b/docs/api-reference/admin.yaml@@ -79173,6 +79173,7 @@ components:required:- variant_id- quantity_ordered+ - unit_costPurchaseOrderUpdateParams:type: objectproperties:diff --git a/packages/admin-sdk/src/types/params/PurchaseOrderItemParams.ts b/packages/admin-sdk/src/types/params/PurchaseOrderItemParams.tsindex 455d65dd4d..2d1d00ae66 100644--- a/packages/admin-sdk/src/types/params/PurchaseOrderItemParams.ts+++ b/packages/admin-sdk/src/types/params/PurchaseOrderItemParams.ts@@ -4,5 +4,5 @@ export type PurchaseOrderItemParams = {variant_id: stringquantity_ordered: number/** What the merchant agreed to pay per unit. */- unit_cost?: string+ unit_cost: string}diff --git a/packages/dashboard/e2e/purchase-orders.spec.ts b/packages/dashboard/e2e/purchase-orders.spec.tsindex ee5f01346f..3946f06cee 100644--- a/packages/dashboard/e2e/purchase-orders.spec.ts+++ b/packages/dashboard/e2e/purchase-orders.spec.ts@@ -94,6 +94,7 @@ test.describe('purchase orders', () => {await picker.getByRole('button', { name: /^add 1$/i }).click()await expect(picker).toBeHidden()await page.getByRole('spinbutton', { name: /^ordered$/i }).fill('12')+ await page.getByLabel(/^unit cost$/i).fill('7.50')await page.getByRole('button', { name: /create draft/i }).click()diff --git a/packages/dashboard/src/components/spree/purchase-order-form.tsx b/packages/dashboard/src/components/spree/purchase-order-form.tsxindex c84b5b3953..790aa38b6f 100644--- a/packages/dashboard/src/components/spree/purchase-order-form.tsx+++ b/packages/dashboard/src/components/spree/purchase-order-form.tsx@@ -31,7 +31,7 @@ import { useState } from 'react'import { useTranslation } from 'react-i18next'import { supplierAutocompleteProps } from '../../hooks/use-suppliers'import { SupplierSheet } from './supplier-sheet'-import { type VariantLine, VariantLineEditor } from './variant-line-editor'+import { type CostedVariantLine, type VariantLine, VariantLineEditor } from './variant-line-editor'export interface PurchaseOrderFormValues {supplierId: string@@ -44,6 +44,23 @@ export interface PurchaseOrderFormValues {lines: VariantLine[]}+export interface PurchaseOrderSubmitValues extends PurchaseOrderFormValues {+ lines: CostedVariantLine[]+}++// A cleared cost input is not zero — it is nothing, which the server rejects+// field-by-field. Trimmed here so the value checked is the value sent.+function costedLine(line: VariantLine): CostedVariantLine | undefined {+ const unitCost = line.unitCost?.trim()+ if (line.quantity <= 0 || !isDecimalString(unitCost) || unitCost.startsWith('-')) return undefined+ return { ...line, unitCost }+}++function costedLines(lines: VariantLine[]): CostedVariantLine[] | undefined {+ const costed = lines.map(costedLine).filter((line) => line !== undefined)+ return costed.length === lines.length ? costed : undefined+}+export const EMPTY_PURCHASE_ORDER: PurchaseOrderFormValues = {supplierId: '',destinationId: '',@@ -87,7 +104,7 @@ export function PurchaseOrderForm({submitLabel: stringpendingLabel: stringpending: boolean- onSubmit: (values: PurchaseOrderFormValues) => void+ onSubmit: (values: PurchaseOrderSubmitValues) => voidonCancel: () => void}) {const { t } = useTranslation()@@ -106,17 +123,8 @@ export function PurchaseOrderForm({const [creatingSupplier, setCreatingSupplier] = useState(false)const [pickerOpen, setPickerOpen] = useState(false)- // A cleared cost input is not zero — it is nothing, which the server rejects- // field-by-field.- const hasCost = (value?: string) => {- const trimmed = value?.trim()- return isDecimalString(trimmed) && !trimmed.startsWith('-')- }-- const canSubmit =- !!supplierId &&- !!destinationId &&- lines.every((line) => line.quantity > 0 && hasCost(line.unitCost))+ const submitLines = costedLines(lines)+ const canSubmit = !!supplierId && !!destinationId && !!submitLinesconst detailsCard = (<Card>@@ -273,6 +281,7 @@ export function PurchaseOrderForm({<Buttontype="button"onClick={() =>+ submitLines &&onSubmit({supplierId,destinationId,@@ -281,7 +290,7 @@ export function PurchaseOrderForm({cancelBy,reference,notes,- lines,+ lines: submitLines,})}disabled={!canSubmit || pending}diff --git a/packages/dashboard/src/components/spree/variant-line-editor.test.ts b/packages/dashboard/src/components/spree/variant-line-editor.test.tsindex d8705bb08d..5788ebf538 100644--- a/packages/dashboard/src/components/spree/variant-line-editor.test.ts+++ b/packages/dashboard/src/components/spree/variant-line-editor.test.ts@@ -38,8 +38,8 @@ describe('addVariantsToLines', () => {expect(lines[0].quantity).toBe(2)})- it('seeds a cost only where the document has one', () => {- expect(addVariantsToLines([], [variant('a')], true)[0].unitCost).toBe('0.00')+ it('leaves a cost blank for the merchant to fill only where the document has one', () => {+ expect(addVariantsToLines([], [variant('a')], true)[0].unitCost).toBe('')expect(addVariantsToLines([], [variant('a')], false)[0].unitCost).toBeUndefined()})diff --git a/packages/dashboard/src/components/spree/variant-line-editor.tsx b/packages/dashboard/src/components/spree/variant-line-editor.tsxindex 1ae932cb20..87ebde5392 100644--- a/packages/dashboard/src/components/spree/variant-line-editor.tsx+++ b/packages/dashboard/src/components/spree/variant-line-editor.tsx@@ -46,6 +46,10 @@ export interface VariantLine {unitCost?: string}+export interface CostedVariantLine extends VariantLine {+ unitCost: string+}+/*** Folds a whole picked batch into the existing lines, in one pass.*@@ -68,7 +72,7 @@ export function addVariantsToLines(for (const variant of variants) {const index = indexByVariantId.get(variant.id)if (index === undefined) {- next.push({ variant, quantity: 1, unitCost: withCost ? '0.00' : undefined })+ next.push({ variant, quantity: 1, unitCost: withCost ? '' : undefined })indexByVariantId.set(variant.id, next.length - 1)} else {next[index] = { ...next[index], quantity: next[index].quantity + 1 }diff --git a/packages/dashboard/src/lib/prefilled-variant.ts b/packages/dashboard/src/lib/prefilled-variant.tsindex 653c37585f..4fe6be0cb4 100644--- a/packages/dashboard/src/lib/prefilled-variant.ts+++ b/packages/dashboard/src/lib/prefilled-variant.ts@@ -34,7 +34,7 @@ export function prefilledLines(search: PrefilledVariantSearch, withCost: booleanthumbnail_url: search.thumbnail_url ?? null,},quantity: 1,- unitCost: withCost ? '0.00' : undefined,+ unitCost: withCost ? '' : undefined,},]}diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/purchase-orders/$purchaseOrderId/edit.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/purchase-orders/$purchaseOrderId/edit.tsxindex 67b5cc483e..090b8c3e55 100644--- a/packages/dashboard/src/routes/_authenticated/$storeId/purchase-orders/$purchaseOrderId/edit.tsx+++ b/packages/dashboard/src/routes/_authenticated/$storeId/purchase-orders/$purchaseOrderId/edit.tsx@@ -4,7 +4,7 @@ import { createFileRoute, useNavigate } from '@tanstack/react-router'import { useTranslation } from 'react-i18next'import {PurchaseOrderForm,- type PurchaseOrderFormValues,+ type PurchaseOrderSubmitValues,} from '../../../../../components/spree/purchase-order-form'import { usePurchaseOrder, useUpdatePurchaseOrder } from '../../../../../hooks/use-purchase-orders'@@ -48,7 +48,7 @@ function EditPurchaseOrderPage() {)}- async function handleSubmit(values: PurchaseOrderFormValues) {+ async function handleSubmit(values: PurchaseOrderSubmitValues) {const saved = await updateMutation.mutateAsync({supplier_id: values.supplierId,@@ -93,7 +93,7 @@ function EditPurchaseOrderPage() {thumbnail_url: item.thumbnail_url,},quantity: item.quantity_ordered,- unitCost: item.unit_cost ?? '0.00',+ unitCost: item.unit_cost ?? '',})),}}// Every line cost is denominated in it, so changing it now woulddiff --git a/packages/dashboard/src/routes/_authenticated/$storeId/purchase-orders/new.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/purchase-orders/new.tsxindex 6c7afca046..702094b40d 100644--- a/packages/dashboard/src/routes/_authenticated/$storeId/purchase-orders/new.tsx+++ b/packages/dashboard/src/routes/_authenticated/$storeId/purchase-orders/new.tsx@@ -4,6 +4,7 @@ import {EMPTY_PURCHASE_ORDER,PurchaseOrderForm,type PurchaseOrderFormValues,+ type PurchaseOrderSubmitValues,} from '../../../../components/spree/purchase-order-form'import { useCreatePurchaseOrder } from '../../../../hooks/use-purchase-orders'import { prefilledLines, prefilledVariantSchema } from '../../../../lib/prefilled-variant'@@ -28,7 +29,7 @@ function NewPurchaseOrderPage() {lines: prefilledLines(search, true),}- async function handleSubmit(values: PurchaseOrderFormValues) {+ async function handleSubmit(values: PurchaseOrderSubmitValues) {// The hook toasts the refusal; navigating would hide it.const purchaseOrder = await createMutation.mutateAsync({diff --git a/spree/api/app/controllers/spree/api/v3/admin/purchase_orders_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/purchase_orders_controller.rbindex 19cb363a0a..d145924cd8 100644--- a/spree/api/app/controllers/spree/api/v3/admin/purchase_orders_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/admin/purchase_orders_controller.rb@@ -47,6 +47,7 @@ module Spreeitem.attribute :variant_id, :id, required: true, example: 'variant_1234567890'item.attribute :quantity_ordered, :integer, required: true, example: 100item.attribute :unit_cost, :decimal,+ required: true,example: '12.50',description: 'What the merchant agreed to pay per unit.'enddiff --git a/spree/core/app/models/spree/purchase_order_item.rb b/spree/core/app/models/spree/purchase_order_item.rbindex 551f7ee7b5..0940fddafb 100644--- a/spree/core/app/models/spree/purchase_order_item.rb+++ b/spree/core/app/models/spree/purchase_order_item.rb@@ -11,7 +11,7 @@ module Spreebelongs_to :purchase_order, class_name: 'Spree::PurchaseOrder', inverse_of: :items, touch: truevalidates :quantity_ordered, numericality: { greater_than: 0, only_integer: true }- validates :unit_cost, numericality: { greater_than_or_equal_to: 0 }+ validates :unit_cost, presence: true, numericality: { greater_than_or_equal_to: 0, allow_nil: true }validates :variant_id, uniqueness: { scope: :purchase_order_id }delegate :currency, to: :purchase_order, allow_nil: true