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.

Act on the first code review

Łukasz Adamczyk1ea0034987e4
diff --git a/docs/plans/6.0-inventory-operations.md b/docs/plans/6.0-inventory-operations.md
index 2393378a8c..0c5ca912c7 100644
--- a/docs/plans/6.0-inventory-operations.md
+++ b/docs/plans/6.0-inventory-operations.md
@@ -155,6 +155,12 @@ plan written against 5.x idioms that 6.0 has since retired.
attempt — including across two partial receives at different prices. `StockLocation#restock` and
`#move` take an optional `unit_cost:`; transfers and returns leave it null, because moving stock a
merchant already owns is not a purchase.
+- **A soft-deleted supplier keeps its name** (found in review). The obvious shape — a unique index
+ narrowed to `deleted_at IS NULL`, matching a validation narrowed the same way — is not portable:
+ MySQL has no partial indexes and Rails drops the `WHERE` silently, so the same delete-and-recreate
+ would save on PostgreSQL and raise a constraint violation on MySQL. The index is therefore plain
+ and the validation reads through soft-deleted rows to match it, which costs the ability to reuse a
+ deleted supplier's name and buys identical behaviour on all three databases.
- **Status transitions are `PATCH` member routes**, matching `orders/:id/cancel`,
`returns/:id/receive` and every other transition already in the Admin API. The plan's claim that
these are POSTs describes no existing endpoint.
diff --git a/packages/dashboard-core/src/hooks/use-resource-mutation.ts b/packages/dashboard-core/src/hooks/use-resource-mutation.ts
index 0e56014b29..abc9d8c7bb 100644
--- a/packages/dashboard-core/src/hooks/use-resource-mutation.ts
+++ b/packages/dashboard-core/src/hooks/use-resource-mutation.ts
@@ -103,16 +103,35 @@ export function useResourceMutation<TData = unknown, TError = Error, TVariables
},
onError: (error, variables, onMutateResult, ctx) => {
if (errorMessage !== false && !isValidationError(error)) {
- toastManager.add({ type: 'error', title: errorMessage })
+ // A refusal with no field to hang off — a workflow saying the source
+ // shelf cannot cover this transfer — says something the caller's
+ // generic message does not, so it speaks for itself.
+ toastManager.add({ type: 'error', title: refusalMessage(error) ?? errorMessage })
}
return onError?.(error, variables, onMutateResult, ctx)
},
})
}
-// 422 with `details` means the model rejected the payload (e.g., "Code can't
-// be blank"). The form renders these next to the offending input via
-// `mapSpreeErrorsToForm`, so toasting the same thing would just be noise.
+// 422 *with* `details` means the model rejected the payload field by field
+// (e.g. "Code can't be blank"). The form renders those next to the offending
+// input via `mapSpreeErrorsToForm`, so toasting them again would be noise.
+//
+// A 422 without `details` is a different animal: a workflow declining the
+// whole operation ("Only a transfer in transit can be received"). Nothing
+// renders it inline, so suppressing it leaves the merchant staring at a page
+// that silently did nothing.
function isValidationError(error: unknown): boolean {
- return error instanceof SpreeError && error.status === 422
+ return error instanceof SpreeError && error.status === 422 && hasFieldDetails(error)
+}
+
+function hasFieldDetails(error: SpreeError): boolean {
+ return !!error.details && Object.keys(error.details).length > 0
+}
+
+/** The server's own wording for a refusal that names no field. */
+function refusalMessage(error: unknown): string | undefined {
+ if (!(error instanceof SpreeError) || hasFieldDetails(error)) return undefined
+
+ return error.message || undefined
}
diff --git a/packages/dashboard/src/locales/ar.json b/packages/dashboard/src/locales/ar.json
index 831d905d5f..f508afe948 100644
--- a/packages/dashboard/src/locales/ar.json
+++ b/packages/dashboard/src/locales/ar.json
@@ -5156,7 +5156,12 @@
},
"ship_confirm": {
"title": "إرسال هذا التحويل؟",
- "message": "ستغادر {{count}} وحدة المستودع المصدر الآن ولن تكون متاحة فيه حتى وصولها."
+ "message_zero": "لن تغادر أي وحدة المستودع المصدر.",
+ "message_one": "ستغادر وحدة واحدة المستودع المصدر الآن ولن تكون متاحة فيه حتى وصولها.",
+ "message_two": "ستغادر وحدتان المستودع المصدر الآن ولن تكونا متاحتين فيه حتى وصولهما.",
+ "message_few": "ستغادر {{count}} وحدات المستودع المصدر الآن ولن تكون متاحة فيه حتى وصولها.",
+ "message_many": "ستغادر {{count}} وحدة المستودع المصدر الآن ولن تكون متاحة فيه حتى وصولها.",
+ "message_other": "ستغادر {{count}} وحدة المستودع المصدر الآن ولن تكون متاحة فيه حتى وصولها."
},
"cancel_confirm": {
"title": "إلغاء هذا التحويل؟",
@@ -5594,7 +5599,7 @@
},
"delete_confirm": {
"title": "حذف هذا المورد؟",
- "message": "لن يكون {{name}} متاحًا لأوامر شراء جديدة. أوامر الشراء الحالية ستظل تشير إليه."
+ "message": "لن يكون {{name}} متاحًا لأوامر شراء جديدة. لا يمكن حذف مورد ما زال أي أمر شراء يشير إليه."
}
}
}
diff --git a/packages/dashboard/src/locales/de.json b/packages/dashboard/src/locales/de.json
index f74ea6d807..3f8dfd361e 100644
--- a/packages/dashboard/src/locales/de.json
+++ b/packages/dashboard/src/locales/de.json
@@ -5134,7 +5134,8 @@
},
"ship_confirm": {
"title": "Diese Umlagerung versenden?",
- "message": "{{count}} Einheiten verlassen jetzt das Quelllager und sind dort erst nach Ankunft wieder verfügbar."
+ "message_one": "{{count}} Einheit verlässt jetzt das Quelllager und ist dort erst nach Ankunft wieder verfügbar.",
+ "message_other": "{{count}} Einheiten verlassen jetzt das Quelllager und sind dort erst nach Ankunft wieder verfügbar."
},
"cancel_confirm": {
"title": "Diese Umlagerung abbrechen?",
@@ -5569,7 +5570,7 @@
},
"delete_confirm": {
"title": "Diesen Lieferanten löschen?",
- "message": "{{name}} steht für neue Bestellungen nicht mehr zur Verfügung. Bestehende Bestellungen nennen ihn weiterhin."
+ "message": "{{name}} steht für neue Bestellungen nicht mehr zur Verfügung. Ein Lieferant, den noch eine Bestellung nennt, kann nicht gelöscht werden."
}
}
}
diff --git a/packages/dashboard/src/locales/en.json b/packages/dashboard/src/locales/en.json
index 09fe944ab8..72e3452f1f 100644
--- a/packages/dashboard/src/locales/en.json
+++ b/packages/dashboard/src/locales/en.json
@@ -5134,7 +5134,8 @@
},
"ship_confirm": {
"title": "Send this transfer?",
- "message": "{{count}} units leave the source warehouse now and will not be available there until they arrive."
+ "message_one": "{{count}} unit leaves the source warehouse now and will not be available there until it arrives.",
+ "message_other": "{{count}} units leave the source warehouse now and will not be available there until they arrive."
},
"cancel_confirm": {
"title": "Cancel this transfer?",
@@ -5569,7 +5570,7 @@
},
"delete_confirm": {
"title": "Delete this supplier?",
- "message": "{{name}} will no longer be available for new purchase orders. Existing orders keep naming them."
+ "message": "{{name}} will no longer be available for new purchase orders. A supplier that any purchase order still names cannot be deleted."
}
}
}
diff --git a/packages/dashboard/src/locales/fr.json b/packages/dashboard/src/locales/fr.json
index ed25553e58..3957fd1fda 100644
--- a/packages/dashboard/src/locales/fr.json
+++ b/packages/dashboard/src/locales/fr.json
@@ -5134,7 +5134,8 @@
},
"ship_confirm": {
"title": "Expédier ce transfert ?",
- "message": "{{count}} unités quittent maintenant l'entrepôt d'origine et n'y seront plus disponibles avant leur arrivée."
+ "message_one": "{{count}} unité quitte maintenant l'entrepôt d'origine et n'y sera plus disponible avant son arrivée.",
+ "message_other": "{{count}} unités quittent maintenant l'entrepôt d'origine et n'y seront plus disponibles avant leur arrivée."
},
"cancel_confirm": {
"title": "Annuler ce transfert ?",
@@ -5569,7 +5570,7 @@
},
"delete_confirm": {
"title": "Supprimer ce fournisseur ?",
- "message": "{{name}} ne sera plus disponible pour de nouveaux bons de commande. Les commandes existantes continuent de le nommer."
+ "message": "{{name}} ne sera plus disponible pour de nouveaux bons de commande. Un fournisseur encore nommé par un bon de commande ne peut pas être supprimé."
}
}
}
diff --git a/packages/dashboard/src/locales/pl.json b/packages/dashboard/src/locales/pl.json
index 272f8be1c1..7b67775059 100644
--- a/packages/dashboard/src/locales/pl.json
+++ b/packages/dashboard/src/locales/pl.json
@@ -5192,7 +5192,10 @@
},
"ship_confirm": {
"title": "Wysłać to przesunięcie?",
- "message": "{{count}} jednostek opuszcza teraz magazyn źródłowy i nie będzie tam dostępnych do czasu dotarcia."
+ "message_one": "{{count}} jednostka opuszcza teraz magazyn źródłowy i nie będzie tam dostępna do czasu dotarcia.",
+ "message_few": "{{count}} jednostki opuszczają teraz magazyn źródłowy i nie będą tam dostępne do czasu dotarcia.",
+ "message_many": "{{count}} jednostek opuszcza teraz magazyn źródłowy i nie będzie tam dostępnych do czasu dotarcia.",
+ "message_other": "{{count}} jednostki opuszczają teraz magazyn źródłowy i nie będą tam dostępne do czasu dotarcia."
},
"cancel_confirm": {
"title": "Anulować to przesunięcie?",
@@ -5629,7 +5632,7 @@
},
"delete_confirm": {
"title": "Usunąć tego dostawcę?",
- "message": "{{name}} nie będzie już dostępny w nowych zamówieniach zakupu. Istniejące zamówienia nadal będą go wskazywać."
+ "message": "{{name}} nie będzie już dostępny w nowych zamówieniach zakupu. Dostawcy, którego wskazuje jakiekolwiek zamówienie zakupu, nie można usunąć."
}
}
}
diff --git a/packages/dashboard/src/locales/zh-CN.json b/packages/dashboard/src/locales/zh-CN.json
index 5c1080241b..c0e3085c95 100644
--- a/packages/dashboard/src/locales/zh-CN.json
+++ b/packages/dashboard/src/locales/zh-CN.json
@@ -5125,7 +5125,7 @@
},
"ship_confirm": {
"title": "发出此调拨?",
- "message": "{{count}} 件将立即离开来源仓库,在到货前不可在该仓库使用。"
+ "message_other": "{{count}} 件将立即离开来源仓库,在到货前不可在该仓库使用。"
},
"cancel_confirm": {
"title": "取消此调拨?",
@@ -5559,7 +5559,7 @@
},
"delete_confirm": {
"title": "删除此供应商?",
- "message": "{{name}} 将无法用于新的采购订单。已有订单仍会显示该供应商。"
+ "message": "{{name}} 将无法用于新的采购订单。仍被任何采购订单引用的供应商无法删除。"
}
}
}
diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/products/purchase-orders/$purchaseOrderId.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/products/purchase-orders/$purchaseOrderId.tsx
index 5c757c6fa4..5e6128f2b7 100644
--- a/packages/dashboard/src/routes/_authenticated/$storeId/products/purchase-orders/$purchaseOrderId.tsx
+++ b/packages/dashboard/src/routes/_authenticated/$storeId/products/purchase-orders/$purchaseOrderId.tsx
@@ -128,7 +128,8 @@ function SummaryCard({ purchaseOrder }: { purchaseOrder: PurchaseOrder }) {
* The lines, and — once the order has been placed — the receive screen.
*
* `quantity_received` is the running total for the line, so a second delivery
- * tops it up rather than starting over.
+ * tops it up rather than starting over — and the inputs show what has actually
+ * arrived, not what was ordered.
*/
function ItemsCard({ purchaseOrder }: { purchaseOrder: PurchaseOrder }) {
const { t } = useTranslation()
@@ -138,7 +139,7 @@ function ItemsCard({ purchaseOrder }: { purchaseOrder: PurchaseOrder }) {
purchaseOrder.status === 'ordered' || purchaseOrder.status === 'partially_received'
const [counts, setCounts] = useState<Record<string, number>>(() =>
- Object.fromEntries(items.map((item) => [item.id, item.quantity_ordered])),
+ Object.fromEntries(items.map((item) => [item.id, item.quantity_received])),
)
const totalCounted = items.reduce((sum, item) => sum + (counts[item.id] ?? 0), 0)
diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/products/purchase-orders/new.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/products/purchase-orders/new.tsx
index 846b70f807..e72584045b 100644
--- a/packages/dashboard/src/routes/_authenticated/$storeId/products/purchase-orders/new.tsx
+++ b/packages/dashboard/src/routes/_authenticated/$storeId/products/purchase-orders/new.tsx
@@ -59,19 +59,23 @@ function NewPurchaseOrderPage() {
async function handleSubmit() {
if (!canSubmit) return
- const purchaseOrder = await createMutation.mutateAsync({
- supplier_id: supplierId,
- destination_location_id: destinationId,
- currency,
- expected_at: expectedAt,
- reference: reference.trim() || undefined,
- notes: notes.trim() || undefined,
- items: lines.map((line) => ({
- variant_id: line.variant.id,
- quantity_ordered: line.quantity,
- unit_cost: line.unitCost,
- })),
- })
+ // The hook toasts the refusal; navigating would hide it.
+ const purchaseOrder = await createMutation
+ .mutateAsync({
+ supplier_id: supplierId,
+ destination_location_id: destinationId,
+ currency,
+ expected_at: expectedAt,
+ reference: reference.trim() || undefined,
+ notes: notes.trim() || undefined,
+ items: lines.map((line) => ({
+ variant_id: line.variant.id,
+ quantity_ordered: line.quantity,
+ unit_cost: line.unitCost,
+ })),
+ })
+ .catch(() => undefined)
+ if (!purchaseOrder) return
navigate({
to: '/$storeId/products/purchase-orders/$purchaseOrderId',
diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/products/transfers/$transferId.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/products/transfers/$transferId.tsx
index 243126089d..9002cad59e 100644
--- a/packages/dashboard/src/routes/_authenticated/$storeId/products/transfers/$transferId.tsx
+++ b/packages/dashboard/src/routes/_authenticated/$storeId/products/transfers/$transferId.tsx
@@ -199,8 +199,9 @@ function PlannedItemsCard({ transfer }: { transfer: StockTransfer }) {
* In transit and beyond: the receive screen.
*
* `quantity_received` is the running total for the line, so a second delivery
- * tops it up rather than starting over — which is why the inputs are seeded
- * with what has already been counted rather than with zero.
+ * tops it up rather than starting over. The inputs are therefore seeded with
+ * what has already arrived, not with what was sent: reopening a part-received
+ * transfer has to show the shelf as it is.
*/
function ReceiveCard({ transfer }: { transfer: StockTransfer }) {
const { t } = useTranslation()
@@ -209,7 +210,7 @@ function ReceiveCard({ transfer }: { transfer: StockTransfer }) {
const editable = isInFlight(transfer.status)
const [counts, setCounts] = useState<Record<string, number>>(() =>
- Object.fromEntries(items.map((item) => [item.id, item.quantity_shipped])),
+ Object.fromEntries(items.map((item) => [item.id, item.quantity_received])),
)
const [reasons, setReasons] = useState<Record<string, string>>(() =>
Object.fromEntries(items.map((item) => [item.id, item.discrepancy_reason ?? ''])),
diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/products/transfers/new.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/products/transfers/new.tsx
index 23b2f8aebb..0560cee822 100644
--- a/packages/dashboard/src/routes/_authenticated/$storeId/products/transfers/new.tsx
+++ b/packages/dashboard/src/routes/_authenticated/$storeId/products/transfers/new.tsx
@@ -51,16 +51,21 @@ function NewStockTransferPage() {
async function handleSubmit() {
if (!canSubmit) return
- const transfer = await createMutation.mutateAsync({
- source_location_id: sourceId,
- destination_location_id: destinationId,
- reference: reference.trim() || undefined,
- notes: notes.trim() || undefined,
- items: lines.map((line) => ({
- variant_id: line.variant.id,
- quantity_shipped: line.quantity,
- })),
- })
+ // The hook toasts the refusal; there is nowhere inline to put it on a
+ // page that has no form errors, and navigating would hide it.
+ const transfer = await createMutation
+ .mutateAsync({
+ source_location_id: sourceId,
+ destination_location_id: destinationId,
+ reference: reference.trim() || undefined,
+ notes: notes.trim() || undefined,
+ items: lines.map((line) => ({
+ variant_id: line.variant.id,
+ quantity_shipped: line.quantity,
+ })),
+ })
+ .catch(() => undefined)
+ if (!transfer) return
navigate({
to: '/$storeId/products/transfers/$transferId',
diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/settings/suppliers.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/settings/suppliers.tsx
index 66eb397b5e..fd43fe24b2 100644
--- a/packages/dashboard/src/routes/_authenticated/$storeId/settings/suppliers.tsx
+++ b/packages/dashboard/src/routes/_authenticated/$storeId/settings/suppliers.tsx
@@ -207,13 +207,18 @@ function SupplierSheet({
async function handleSubmit() {
if (!form.name.trim()) return
- // Blank strings would overwrite a stored value with an empty one; the
- // API reads a missing key as "leave it alone".
+ // Emptied fields are sent as null, not dropped: the API reads a missing
+ // key as "leave it alone", so dropping them would make a cleared phone
+ // number come back on the next fetch.
const payload = Object.fromEntries(
- Object.entries(form).map(([key, value]) => [key, value.trim() || undefined]),
- ) as Record<string, string | undefined>
+ Object.entries(form).map(([key, value]) => [key, value.trim() || null]),
+ ) as Record<string, string | null>
+
+ const saved = await mutation
+ .mutateAsync({ ...payload, name: form.name.trim() })
+ .catch(() => undefined)
+ if (!saved) return
- await mutation.mutateAsync({ ...payload, name: form.name.trim() })
onOpenChange(false)
}
diff --git a/spree/api/app/controllers/concerns/spree/api/v3/admin/receivable_actions.rb b/spree/api/app/controllers/concerns/spree/api/v3/admin/receivable_actions.rb
index 4ae1e6517d..fd1c685e93 100644
--- a/spree/api/app/controllers/concerns/spree/api/v3/admin/receivable_actions.rb
+++ b/spree/api/app/controllers/concerns/spree/api/v3/admin/receivable_actions.rb
@@ -75,11 +75,15 @@ module Spree
return nil if sent.nil?
sent.map do |item|
- {
+ received = {
item: @resource.items.find_by_prefix_id!(item[:id]),
- quantity_received: item[:quantity_received],
- discrepancy_reason: item[:discrepancy_reason]
+ quantity_received: item[:quantity_received]
}
+ # Only when the payload actually carried one: a second receive
+ # that tops a line up without repeating the reason must not erase
+ # the audit text the first one recorded.
+ received[:discrepancy_reason] = item[:discrepancy_reason] if item.key?('discrepancy_reason')
+ received
end
end
diff --git a/spree/core/app/models/spree/purchase_order.rb b/spree/core/app/models/spree/purchase_order.rb
index 3bacb35b22..c4af9ec0cb 100644
--- a/spree/core/app/models/spree/purchase_order.rb
+++ b/spree/core/app/models/spree/purchase_order.rb
@@ -44,7 +44,7 @@ module Spree
before_validation :ensure_currency
validates :currency, presence: true
- validates :items, presence: true, unless: :draft?
+ validates :items, presence: true, unless: -> { draft? || canceled? }
self.whitelisted_ransackable_attributes = %w[number status currency reference expected_at
ordered_at received_at supplier_id
diff --git a/spree/core/app/models/spree/stock_transfer.rb b/spree/core/app/models/spree/stock_transfer.rb
index 3f0409e29e..c649e1c1c3 100644
--- a/spree/core/app/models/spree/stock_transfer.rb
+++ b/spree/core/app/models/spree/stock_transfer.rb
@@ -49,7 +49,11 @@ module Spree
accepts_nested_attributes_for :items, allow_destroy: true
validates :source_location, :destination_location, presence: true
- validates :items, presence: true, unless: :draft?
+ # A document that has left draft describes a box that physically exists —
+ # except a cancelled one, which describes a trip that never happened. The
+ # guard covers both because `update` assigns the status before validating,
+ # so cancelling an empty draft would otherwise be refused.
+ validates :items, presence: true, unless: -> { draft? || canceled? }
validate :source_location_is_not_destination_location
validate :locations_belong_to_the_same_store
diff --git a/spree/core/app/models/spree/store.rb b/spree/core/app/models/spree/store.rb
index 0d93f399cb..36643ce19a 100644
--- a/spree/core/app/models/spree/store.rb
+++ b/spree/core/app/models/spree/store.rb
@@ -248,8 +248,13 @@ module Spree
# carry their own store rather than borrowing the destination warehouse's,
# so the admin endpoint has a scope to fetch through.
has_many :stock_transfers, class_name: 'Spree::StockTransfer', dependent: :destroy_async, inverse_of: :store
+ # Purchase orders are declared before suppliers, and both cascade in the
+ # same transaction: a supplier refuses to be destroyed while a purchase
+ # order names it (`restrict_with_error`), so tearing a store down has to
+ # reach the orders first. `destroy_async` on either side would break that
+ # ordering and leave the suppliers behind.
+ has_many :purchase_orders, class_name: 'Spree::PurchaseOrder', dependent: :destroy, inverse_of: :store
has_many :suppliers, class_name: 'Spree::Supplier', dependent: :destroy, inverse_of: :store
- has_many :purchase_orders, class_name: 'Spree::PurchaseOrder', dependent: :destroy_async, inverse_of: :store
has_many :promotions, class_name: 'Spree::Promotion', dependent: :nullify
has_many :tax_categories, class_name: 'Spree::TaxCategory', dependent: :destroy, inverse_of: :store
diff --git a/spree/core/app/models/spree/supplier.rb b/spree/core/app/models/spree/supplier.rb
index 6e3278b924..1d2c0aa312 100644
--- a/spree/core/app/models/spree/supplier.rb
+++ b/spree/core/app/models/spree/supplier.rb
@@ -19,9 +19,13 @@ module Spree
has_many :purchase_orders, class_name: 'Spree::PurchaseOrder', inverse_of: :supplier,
dependent: :restrict_with_error
+ # Deliberately not narrowed to live rows: the unique index cannot be, on
+ # every database Spree supports, so a validation that ignored soft-deleted
+ # suppliers would pass and then hit the index. A deleted supplier keeps its
+ # name; restore or rename it to use the name again.
validates :name, presence: true,
uniqueness: { scope: [:store_id, *spree_base_uniqueness_scope],
- conditions: -> { where(deleted_at: nil) } }
+ conditions: -> { unscope(where: :deleted_at) } }
validates :email, email: { allow_blank: true }, length: { maximum: 254, allow_blank: true }
normalizes :email, with: ->(email) { email.strip.downcase }
diff --git a/spree/core/app/workflows/spree/stock_transfers/receive.rb b/spree/core/app/workflows/spree/stock_transfers/receive.rb
index d296df0d86..f06b9be5f8 100644
--- a/spree/core/app/workflows/spree/stock_transfers/receive.rb
+++ b/spree/core/app/workflows/spree/stock_transfers/receive.rb
@@ -70,12 +70,16 @@ module Spree
variant: line.variant_name, shipped: line.quantity_shipped))
end
- {
+ normalized = {
item: line,
quantity_received: quantity,
- discrepancy_reason: item[:discrepancy_reason],
delta: quantity - line.quantity_received.to_i
}
+ # Carried through only when the caller named one, so a top-up receive
+ # that says nothing about the discrepancy leaves the recorded reason
+ # alone rather than erasing it.
+ normalized[:discrepancy_reason] = item[:discrepancy_reason] if item.key?(:discrepancy_reason)
+ normalized
end
def record_receipt
diff --git a/spree/core/db/migrate/20260907000001_add_inventory_operations.rb b/spree/core/db/migrate/20260907000001_add_inventory_operations.rb
index f262f486ed..54abc80250 100644
--- a/spree/core/db/migrate/20260907000001_add_inventory_operations.rb
+++ b/spree/core/db/migrate/20260907000001_add_inventory_operations.rb
@@ -57,6 +57,11 @@ class AddInventoryOperations < ActiveRecord::Migration[8.1]
t.datetime :deleted_at
t.timestamps
end
+ # No `where: 'deleted_at IS NULL'`: MySQL has no partial indexes and drops
+ # the condition silently, so a soft-deleted supplier's name would be
+ # reusable on PostgreSQL and a 500 on MySQL. The model's uniqueness
+ # validation matches this index exactly instead — a deleted supplier keeps
+ # its name, and re-using it is refused with a message rather than an error.
add_index :spree_suppliers, [:store_id, :name], unique: true
add_index :spree_suppliers, :deleted_at
diff --git a/spree/core/lib/spree/upgrades/5_6_to_6_0/manifest.yml b/spree/core/lib/spree/upgrades/5_6_to_6_0/manifest.yml
index 5ce1ea43bf..41ca120ea1 100644
--- a/spree/core/lib/spree/upgrades/5_6_to_6_0/manifest.yml
+++ b/spree/core/lib/spree/upgrades/5_6_to_6_0/manifest.yml
@@ -634,3 +634,32 @@ steps:
Idempotent — a store that already has a default package type is left
alone, so a box edited since the upgrade is never overwritten.
+
+ - id: migrate_external_receives_to_purchase_orders
+ name: "Turn 5.x supplier receives into purchase orders, and give every transfer a store"
+ task: "spree:upgrade:migrate_external_receives_to_purchase_orders"
+ notes: |
+ A 5.x supplier receive was recorded as a stock transfer with no source
+ location. Spree 6.0 has a purchase order for that — with a supplier, a
+ unit cost and an expected date — and a transfer now moves stock between
+ two of the merchant's own warehouses only.
+
+ Each source-less transfer becomes a received purchase order against a
+ "Migrated receives" supplier, its existing stock movements are re-pointed
+ at that order, and the transfer is soft-deleted so its T-… number stays
+ findable for historical reporting without the same receive appearing
+ twice in the admin. Historical unit costs are unknowable and recorded as
+ zero.
+
+ Until this runs, every pre-existing transfer has no store and no status.
+ A transfer without a store is invisible to the admin list, which reads
+ through the current store, and one without a status cannot be saved
+ through the app at all — so this is the step that makes existing
+ transfers usable again, not only the one that converts receives.
+
+ Stock is never touched: those movements already moved it, at the time.
+
+ Idempotent. A transfer whose movements no longer resolve to a variant is
+ reported and skipped rather than guessed at, and one bad row does not
+ stop the run. Purge the soft-deleted rows later with
+ spree:upgrade:purge_migrated_external_receives.
diff --git a/spree/core/lib/tasks/inventory_operations_migration.rake b/spree/core/lib/tasks/inventory_operations_migration.rake
index a39e47894c..e44bf03aeb 100644
--- a/spree/core/lib/tasks/inventory_operations_migration.rake
+++ b/spree/core/lib/tasks/inventory_operations_migration.rake
@@ -55,7 +55,13 @@ module Spree
raise ActiveRecord::Rollback
end
- purchase_order.save!
+ # A legacy receive whose movements cancel out to zero for a variant
+ # cannot become a line, and must not take the rest of the run with it.
+ unless purchase_order.save
+ skip(transfer, purchase_order.errors.full_messages.join(', '))
+ raise ActiveRecord::Rollback
+ end
+
Spree::StockMovement.where(id: movements.map(&:id)).update_all(purchase_order_id: purchase_order.id)
transfer.update_columns(status: 'received', deleted_at: Time.current)
diff --git a/spree/core/spec/models/spree/supplier_spec.rb b/spree/core/spec/models/spree/supplier_spec.rb
index dfd5d8e132..6bdedc616f 100644
--- a/spree/core/spec/models/spree/supplier_spec.rb
+++ b/spree/core/spec/models/spree/supplier_spec.rb
@@ -15,12 +15,16 @@ module Spree
expect(build(:supplier, store: create(:store), name: 'Acme Wholesale')).to be_valid
end
- # A supplier deleted a year ago must not block the name a merchant wants
- # to use today.
- it 'frees the name again once the supplier is deleted' do
+ # A soft-deleted supplier keeps its name. The unique index cannot be
+ # narrowed to live rows on every database Spree supports, so the
+ # validation matches the index — and a merchant gets a message rather
+ # than the constraint violation a narrowed validation would let through.
+ it 'keeps the name reserved after the supplier is deleted' do
create(:supplier, store: store, name: 'Acme Wholesale').destroy
- expect(build(:supplier, store: store, name: 'Acme Wholesale')).to be_valid
+ reused = build(:supplier, store: store, name: 'Acme Wholesale')
+ expect(reused).to be_invalid
+ expect(reused.errors[:name]).to be_present
end
it 'refuses an email that is not one' do
diff --git a/spree/core/spec/workflows/spree/purchase_orders/lifecycle_spec.rb b/spree/core/spec/workflows/spree/purchase_orders/lifecycle_spec.rb
index 28b54adf5a..5e44c12db0 100644
--- a/spree/core/spec/workflows/spree/purchase_orders/lifecycle_spec.rb
+++ b/spree/core/spec/workflows/spree/purchase_orders/lifecycle_spec.rb
@@ -166,6 +166,15 @@ describe 'purchase order lifecycle', type: :model do
expect(on_hand).to eq(60)
end
+ it 'cancels a draft that never got any lines' do
+ empty = create(:purchase_order, store: store, quantity: 0)
+
+ result = Spree::PurchaseOrders::Cancel.call(purchase_order: empty)
+
+ expect(result).to be_success
+ expect(result.value).to be_canceled
+ end
+
it 'refuses an order that is already over' do
Spree::PurchaseOrders::MarkOrdered.call(purchase_order: purchase_order)
Spree::PurchaseOrders::Receive.call(purchase_order: purchase_order.reload)
diff --git a/spree/core/spec/workflows/spree/stock_transfers/lifecycle_spec.rb b/spree/core/spec/workflows/spree/stock_transfers/lifecycle_spec.rb
index dc258a855d..8356257ede 100644
--- a/spree/core/spec/workflows/spree/stock_transfers/lifecycle_spec.rb
+++ b/spree/core/spec/workflows/spree/stock_transfers/lifecycle_spec.rb
@@ -164,6 +164,21 @@ describe 'stock transfer lifecycle', type: :model do
expect(transfer.reload.stock_movements.received.sum(:quantity)).to eq(10)
end
+ # A second receive that says nothing about the discrepancy must not erase
+ # the audit text the first one recorded.
+ it 'keeps the recorded discrepancy reason when a later receive omits it' do
+ item = transfer.reload.items.sole
+ Spree::StockTransfers::Receive.call(
+ stock_transfer: transfer,
+ items: [{ item: item, quantity_received: 8, discrepancy_reason: 'damaged_in_transit' }]
+ )
+
+ Spree::StockTransfers::Receive.call(stock_transfer: transfer.reload,
+ items: [{ item: item.reload, quantity_received: 9 }])
+
+ expect(item.reload.discrepancy_reason).to eq('damaged_in_transit')
+ end
+
it 'refuses to receive more than was shipped' do
result = Spree::StockTransfers::Receive.call(
stock_transfer: transfer.reload, items: [{ item: transfer.items.sole, quantity_received: 11 }]
@@ -215,6 +230,18 @@ describe 'stock transfer lifecycle', type: :model do
expect(transfer.reload.stock_movements).to be_empty
end
+ # `update` assigns the status before validating, so a draft-only guard on
+ # the items validation refused to cancel a transfer with no lines — which
+ # the new-transfer screen lets a merchant create.
+ it 'cancels a draft that never got any lines' do
+ empty = create(:stock_transfer, store: store, quantity: 0)
+
+ result = Spree::StockTransfers::Cancel.call(stock_transfer: empty)
+
+ expect(result).to be_success
+ expect(result.value).to be_canceled
+ end
+
# The units are physically gone from the source, so guessing would either
# invent stock or destroy it.
it 'refuses to cancel an in-transit transfer without a decision' do