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 second code review

Łukasz Adamczyk8b8ca6cc855c
diff --git a/packages/admin-sdk/src/types/generated/Supplier.ts b/packages/admin-sdk/src/types/generated/Supplier.ts
index 924fe1f7be..043c911f94 100644
--- a/packages/admin-sdk/src/types/generated/Supplier.ts
+++ b/packages/admin-sdk/src/types/generated/Supplier.ts
@@ -1,4 +1,4 @@
-// Typelizer digest 612de3d818dc99033bbcd1c7821ff3ba
+// Typelizer digest 512af3d1c9db676d1e9b7c18eec00ef4
//
// DO NOT MODIFY: This file was automatically generated by Typelizer.
@@ -16,11 +16,11 @@ interface Supplier {
state_code: string | null;
country_code: string | null;
postal_code: string | null;
+ purchase_orders_count: number;
metadata: Record<string, unknown>;
created_at: string;
updated_at: string;
deleted_at: string | null;
- purchase_orders_count: number;
}
export default Supplier;
diff --git a/packages/dashboard-core/src/hooks/use-resource-mutation.ts b/packages/dashboard-core/src/hooks/use-resource-mutation.ts
index abc9d8c7bb..5b87711fa5 100644
--- a/packages/dashboard-core/src/hooks/use-resource-mutation.ts
+++ b/packages/dashboard-core/src/hooks/use-resource-mutation.ts
@@ -46,6 +46,12 @@ interface UseResourceMutationOptions<TData, TError, TVariables>
* auth, gateway).
*/
errorMessage?: string | false
+ /**
+ * Toast a field-level 422 too, joining its messages. Set this on a page
+ * with no form to render them inline — otherwise the rejection is silent
+ * and the merchant sees a button re-enable with no explanation.
+ */
+ showValidationErrors?: boolean
/** Forwarded onSuccess callback. Runs after invalidation + toast. */
onSuccess?: UseMutationOptions<TData, TError, TVariables>['onSuccess']
/** Forwarded onError callback. Runs after error toast. */
@@ -77,6 +83,7 @@ export function useResourceMutation<TData = unknown, TError = Error, TVariables
doNotInvalidate,
successMessage = i18n.t('admin.messages.saved'),
errorMessage = i18n.t('admin.errors.generic'),
+ showValidationErrors = false,
onSuccess,
onError,
...rest
@@ -102,7 +109,9 @@ export function useResourceMutation<TData = unknown, TError = Error, TVariables
return onSuccess?.(data, variables, onMutateResult, ctx)
},
onError: (error, variables, onMutateResult, ctx) => {
- if (errorMessage !== false && !isValidationError(error)) {
+ if (errorMessage !== false && showValidationErrors && isValidationError(error)) {
+ toastManager.add({ type: 'error', title: fieldMessages(error) ?? errorMessage })
+ } else if (errorMessage !== false && !isValidationError(error)) {
// 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.
@@ -129,6 +138,20 @@ function hasFieldDetails(error: SpreeError): boolean {
return !!error.details && Object.keys(error.details).length > 0
}
+/** Every field message the server sent, as one line. */
+function fieldMessages(error: unknown): string | undefined {
+ if (!(error instanceof SpreeError) || !error.details) return undefined
+
+ const lines = Object.values(error.details).flatMap((entry) =>
+ (entry as Array<string | { message?: string }>).map((item) =>
+ typeof item === 'string' ? item : item?.message,
+ ),
+ )
+ const joined = lines.filter(Boolean).join('. ')
+
+ return joined || undefined
+}
+
/** 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
diff --git a/packages/dashboard/src/hooks/use-purchase-orders.ts b/packages/dashboard/src/hooks/use-purchase-orders.ts
index 8b18bd81b5..68d9902d56 100644
--- a/packages/dashboard/src/hooks/use-purchase-orders.ts
+++ b/packages/dashboard/src/hooks/use-purchase-orders.ts
@@ -30,6 +30,8 @@ export function useCreatePurchaseOrder() {
invalidate: [['purchase-orders']],
successMessage: i18n.t('admin.purchase_orders.messages.created'),
errorMessage: i18n.t('admin.purchase_orders.errors.failed_to_create'),
+ // These screens have no inline error surface.
+ showValidationErrors: true,
})
}
@@ -39,6 +41,8 @@ export function useUpdatePurchaseOrder(id: string) {
invalidate: [['purchase-orders'], ['purchase-orders', id]],
successMessage: i18n.t('admin.purchase_orders.messages.saved'),
errorMessage: i18n.t('admin.purchase_orders.errors.failed_to_save'),
+ // These screens have no inline error surface.
+ showValidationErrors: true,
})
}
@@ -51,6 +55,8 @@ export function useDeletePurchaseOrder() {
invalidate: [['purchase-orders']],
successMessage: i18n.t('admin.purchase_orders.messages.deleted'),
errorMessage: i18n.t('admin.purchase_orders.errors.failed_to_delete'),
+ // These screens have no inline error surface.
+ showValidationErrors: true,
onSuccess: (_data, id) => {
queryClient.removeQueries({ queryKey: buildKey('purchase-orders', id) })
},
@@ -63,6 +69,8 @@ export function useMarkPurchaseOrderOrdered(id: string) {
invalidate: [['purchase-orders'], ['purchase-orders', id]],
successMessage: i18n.t('admin.purchase_orders.messages.ordered'),
errorMessage: i18n.t('admin.purchase_orders.errors.failed_to_order'),
+ // These screens have no inline error surface.
+ showValidationErrors: true,
})
}
@@ -78,6 +86,8 @@ export function useReceivePurchaseOrder(id: string) {
],
successMessage: i18n.t('admin.purchase_orders.messages.received'),
errorMessage: i18n.t('admin.purchase_orders.errors.failed_to_receive'),
+ // These screens have no inline error surface.
+ showValidationErrors: true,
})
}
@@ -87,5 +97,7 @@ export function useCancelPurchaseOrder(id: string) {
invalidate: [['purchase-orders'], ['purchase-orders', id]],
successMessage: i18n.t('admin.purchase_orders.messages.canceled'),
errorMessage: i18n.t('admin.purchase_orders.errors.failed_to_cancel'),
+ // These screens have no inline error surface.
+ showValidationErrors: true,
})
}
diff --git a/packages/dashboard/src/hooks/use-stock-transfers.ts b/packages/dashboard/src/hooks/use-stock-transfers.ts
index a92281e158..ae1b639a84 100644
--- a/packages/dashboard/src/hooks/use-stock-transfers.ts
+++ b/packages/dashboard/src/hooks/use-stock-transfers.ts
@@ -31,6 +31,8 @@ export function useCreateStockTransfer() {
invalidate: [['stock-transfers']],
successMessage: i18n.t('admin.stock_transfers.messages.created'),
errorMessage: i18n.t('admin.stock_transfers.errors.failed_to_create'),
+ // These screens have no inline error surface.
+ showValidationErrors: true,
})
}
@@ -40,6 +42,8 @@ export function useUpdateStockTransfer(id: string) {
invalidate: [['stock-transfers'], ['stock-transfers', id]],
successMessage: i18n.t('admin.stock_transfers.messages.saved'),
errorMessage: i18n.t('admin.stock_transfers.errors.failed_to_save'),
+ // These screens have no inline error surface.
+ showValidationErrors: true,
})
}
@@ -52,6 +56,8 @@ export function useDeleteStockTransfer() {
invalidate: [['stock-transfers']],
successMessage: i18n.t('admin.stock_transfers.messages.deleted'),
errorMessage: i18n.t('admin.stock_transfers.errors.failed_to_delete'),
+ // These screens have no inline error surface.
+ showValidationErrors: true,
onSuccess: (_data, id) => {
queryClient.removeQueries({ queryKey: buildKey('stock-transfers', id) })
},
@@ -64,6 +70,8 @@ export function useMarkStockTransferReady(id: string) {
invalidate: [['stock-transfers'], ['stock-transfers', id]],
successMessage: i18n.t('admin.stock_transfers.messages.marked_ready'),
errorMessage: i18n.t('admin.stock_transfers.errors.failed_to_mark_ready'),
+ // These screens have no inline error surface.
+ showValidationErrors: true,
})
}
@@ -82,6 +90,8 @@ export function useMarkStockTransferInTransit(id: string) {
],
successMessage: i18n.t('admin.stock_transfers.messages.marked_in_transit'),
errorMessage: i18n.t('admin.stock_transfers.errors.failed_to_mark_in_transit'),
+ // These screens have no inline error surface.
+ showValidationErrors: true,
})
}
@@ -96,6 +106,8 @@ export function useReceiveStockTransfer(id: string) {
],
successMessage: i18n.t('admin.stock_transfers.messages.received'),
errorMessage: i18n.t('admin.stock_transfers.errors.failed_to_receive'),
+ // These screens have no inline error surface.
+ showValidationErrors: true,
})
}
@@ -110,5 +122,7 @@ export function useCancelStockTransfer(id: string) {
],
successMessage: i18n.t('admin.stock_transfers.messages.canceled'),
errorMessage: i18n.t('admin.stock_transfers.errors.failed_to_cancel'),
+ // These screens have no inline error surface.
+ showValidationErrors: true,
})
}
diff --git a/packages/dashboard/src/hooks/use-suppliers.ts b/packages/dashboard/src/hooks/use-suppliers.ts
index 0fdf014aa8..53071e8704 100644
--- a/packages/dashboard/src/hooks/use-suppliers.ts
+++ b/packages/dashboard/src/hooks/use-suppliers.ts
@@ -29,6 +29,8 @@ export function useCreateSupplier() {
invalidate: [['suppliers']],
successMessage: i18n.t('admin.suppliers.messages.created'),
errorMessage: i18n.t('admin.suppliers.errors.failed_to_create'),
+ // These screens have no inline error surface.
+ showValidationErrors: true,
})
}
@@ -38,6 +40,8 @@ export function useUpdateSupplier(id: string) {
invalidate: [['suppliers'], ['suppliers', id]],
successMessage: i18n.t('admin.suppliers.messages.saved'),
errorMessage: i18n.t('admin.suppliers.errors.failed_to_save'),
+ // These screens have no inline error surface.
+ showValidationErrors: true,
})
}
@@ -50,6 +54,8 @@ export function useDeleteSupplier() {
invalidate: [['suppliers']],
successMessage: i18n.t('admin.suppliers.messages.deleted'),
errorMessage: i18n.t('admin.suppliers.errors.failed_to_delete'),
+ // These screens have no inline error surface.
+ showValidationErrors: true,
onSuccess: (_data, id) => {
queryClient.removeQueries({ queryKey: buildKey('suppliers', id) })
},
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 e72584045b..40342ee1ef 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
@@ -1,6 +1,9 @@
+import type { Supplier } from '@spree/admin-sdk'
import {
+ adminClient,
CurrencySelect,
PageHeader,
+ ResourceCombobox,
StoreDatePicker,
useStockLocations,
} from '@spree/dashboard-core'
@@ -29,7 +32,6 @@ import {
VariantLineEditor,
} from '../../../../../components/spree/variant-line-editor'
import { useCreatePurchaseOrder } from '../../../../../hooks/use-purchase-orders'
-import { useSuppliers } from '../../../../../hooks/use-suppliers'
export const Route = createFileRoute('/_authenticated/$storeId/products/purchase-orders/new')({
component: NewPurchaseOrderPage,
@@ -40,10 +42,7 @@ function NewPurchaseOrderPage() {
const { storeId } = Route.useParams()
const navigate = useNavigate()
const createMutation = useCreatePurchaseOrder()
- const { data: suppliers } = useSuppliers({ limit: 100 })
const { data: stockLocations } = useStockLocations({ limit: 100 })
-
- const supplierOptions = suppliers?.data ?? []
const locations = stockLocations?.data ?? []
const [supplierId, setSupplierId] = useState('')
@@ -54,7 +53,12 @@ function NewPurchaseOrderPage() {
const [notes, setNotes] = useState('')
const [lines, setLines] = useState<VariantLine[]>([])
- const canSubmit = !!supplierId && !!destinationId && lines.every((line) => line.quantity > 0)
+ const canSubmit =
+ !!supplierId &&
+ !!destinationId &&
+ // A cleared cost input is not zero — it is nothing, which the server
+ // rejects field-by-field. Catch it here, where the field is.
+ lines.every((line) => line.quantity > 0 && Number.isFinite(Number(line.unitCost)))
async function handleSubmit() {
if (!canSubmit) return
@@ -97,22 +101,21 @@ function NewPurchaseOrderPage() {
<FieldLabel htmlFor="supplier">
{t('admin.purchase_orders.fields.supplier')}
</FieldLabel>
- <Select value={supplierId} onValueChange={setSupplierId}>
- <SelectTrigger id="supplier">
- <SelectValue placeholder={t('admin.purchase_orders.fields.supplier_placeholder')}>
- {(value) =>
- supplierOptions.find((s) => s.id === value)?.name ?? (value as string)
- }
- </SelectValue>
- </SelectTrigger>
- <SelectContent>
- {supplierOptions.map((supplier) => (
- <SelectItem key={supplier.id} value={supplier.id}>
- {supplier.name}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
+ {/* Searchable rather than a capped list: a wholesaler can hold
+ more suppliers than one page of a Select would show, and a
+ Select says nothing about the ones it left out. */}
+ <ResourceCombobox<Supplier>
+ id="supplier"
+ queryKey="purchase-order-supplier-picker"
+ value={supplierId}
+ onChange={(id) => setSupplierId(id ?? '')}
+ search={(query) => adminClient.suppliers.list({ search: query, limit: 20 })}
+ hydrate={(ids) =>
+ adminClient.suppliers.list({ q: { id_in: ids }, limit: ids.length || 1 })
+ }
+ getOptionLabel={(supplier) => supplier.name}
+ placeholder={t('admin.purchase_orders.fields.supplier_placeholder')}
+ />
</Field>
<Field>
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 9002cad59e..ccfaecea2d 100644
--- a/packages/dashboard/src/routes/_authenticated/$storeId/products/transfers/$transferId.tsx
+++ b/packages/dashboard/src/routes/_authenticated/$storeId/products/transfers/$transferId.tsx
@@ -221,11 +221,19 @@ function ReceiveCard({ transfer }: { transfer: StockTransfer }) {
async function handleReceive() {
await receiveMutation
.mutateAsync({
- items: items.map((item) => ({
- id: item.id,
- quantity_received: counts[item.id] ?? item.quantity_received,
- discrepancy_reason: reasons[item.id] || undefined,
- })),
+ items: items.map((item) => {
+ const received = counts[item.id] ?? item.quantity_received
+ const reason = reasons[item.id]
+
+ return {
+ id: item.id,
+ quantity_received: received,
+ // Only while the line is actually short. The select hides once the
+ // count is raised, but its state survives — and a fully received
+ // line carrying "damaged in transit" is simply wrong.
+ discrepancy_reason: received < item.quantity_shipped ? reason || undefined : undefined,
+ }
+ }),
})
.catch(() => undefined)
}
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 ed780e174a..bbf6272472 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
@@ -3,14 +3,16 @@ module Spree
module V3
module Admin
# What a stock transfer and a purchase order have in common as
- # endpoints: line items resolved out of a flat payload, and statuses
- # moved one named action at a time
- # (docs/plans/6.0-inventory-operations.md).
+ # endpoints: resolving the lines, warehouses and variants a flat
+ # payload names (docs/plans/6.0-inventory-operations.md). The status
+ # workflows themselves are run by the actions, which is where the
+ # keyword each one takes the document under stays visible.
#
# Every id a payload names is resolved through the store — or through
# the document itself, for its own lines — so an id belonging to
# another tenant answers 404 rather than being acted on. That is also
- # why nothing here assigns a `*_id` from the payload: `permitted_params`
+ # why nothing here assigns a `*_id` from the payload, and why the lines
+ # come from the raw payload rather than `permitted_params`: the latter
# decodes prefixed ids into primary keys, and a decoded key carries no
# evidence of whose record it is.
module ReceivableActions
@@ -19,22 +21,6 @@ module Spree
protected
- # Runs one of the document's status workflows and renders the result.
- def run_transition(workflow, **arguments)
- result = workflow.call(workflow_record_key => @resource, **arguments)
-
- if result.success?
- render json: serialize_resource(result.value)
- else
- render_result_error(result)
- end
- end
-
- # @return [Symbol] the keyword this document's workflows take it under
- def workflow_record_key
- raise NotImplementedError, "#{self.class} must implement #workflow_record_key"
- end
-
# The lines a create or update named, or nil when the payload said
# nothing about them — which on an update means "leave them alone".
#
@@ -43,7 +29,7 @@ module Spree
# `:quantity_ordered`, `:unit_cost`)
# @return [Array<Hash>, nil]
def items_from_params(*attribute_keys)
- sent = sent_items([:variant_id, *attribute_keys])
+ sent = items_payload([:variant_id, *attribute_keys])
return nil if sent.nil?
sent.map do |item|
@@ -63,7 +49,7 @@ module Spree
# @param keys [Array<Symbol>] the per-line keys to permit
# @return [Array<Hash>, nil]
def items_for_receive(keys)
- sent = sent_items(keys)
+ sent = items_payload(keys)
return nil if sent.nil?
sent.map do |item|
@@ -93,15 +79,6 @@ module Spree
def variants_scope
current_store.variants.accessible_by(current_ability, :show)
end
-
- private
-
- # Raw `params`, not `permitted_params`: the latter decodes anything
- # shaped like a prefixed id into a primary key, and these lines are
- # looked up by prefixed id precisely so their scope is checked.
- def sent_items(keys)
- items_payload(keys)
- end
end
end
end
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.rb
index 2b947b4d27..c659369c6f 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
@@ -38,21 +38,34 @@ module Spree
# PATCH /api/v3/admin/purchase_orders/:id/mark_ordered
def mark_ordered
- run_transition(Spree.purchase_order_mark_ordered_workflow)
+ result = Spree.purchase_order_mark_ordered_workflow.call(purchase_order: @resource)
+ return render_result_error(result) unless result.success?
+
+ render json: serialize_resource(result.value)
end
# PATCH /api/v3/admin/purchase_orders/:id/receive
def receive
- run_transition(Spree.purchase_order_receive_workflow,
- items: items_for_receive([:id, :quantity_received]),
- received_by: try_spree_current_user)
+ result = Spree.purchase_order_receive_workflow.call(
+ purchase_order: @resource,
+ items: items_for_receive([:id, :quantity_received]),
+ received_by: try_spree_current_user
+ )
+ return render_result_error(result) unless result.success?
+
+ render json: serialize_resource(result.value)
end
# PATCH /api/v3/admin/purchase_orders/:id/cancel
def cancel
- run_transition(Spree.purchase_order_cancel_workflow,
- reason: params[:reason],
- canceler: try_spree_current_user)
+ result = Spree.purchase_order_cancel_workflow.call(
+ purchase_order: @resource,
+ reason: params[:reason],
+ canceler: try_spree_current_user
+ )
+ return render_result_error(result) unless result.success?
+
+ render json: serialize_resource(result.value)
end
protected
@@ -77,10 +90,6 @@ module Spree
Spree.purchase_order_update_workflow
end
- def workflow_record_key
- :purchase_order
- end
-
def create_workflow_arguments
{
store: current_store,
diff --git a/spree/api/app/controllers/spree/api/v3/admin/stock_transfers_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/stock_transfers_controller.rb
index 80282be359..35be0a7726 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/stock_transfers_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/stock_transfers_controller.rb
@@ -28,39 +28,68 @@ module Spree
# A draft is the only transfer a merchant may throw away: past that
# it describes a box that physically exists, which is cancelled
# rather than deleted.
+ #
+ # Really deleted, not stamped. Soft deletion exists for the upgrade
+ # task's converted receives, whose numbers have to stay findable; a
+ # draft nobody sent has nothing to preserve, and `destroy` would
+ # hard-delete its lines regardless (they are not paranoid), leaving a
+ # soft-deleted row that could never be restored intact.
def destroy
- return super if @resource.draft?
+ unless @resource.draft?
+ return render_error(
+ code: 'invalid_status',
+ message: Spree.t('stock_transfer.errors.only_draft_can_be_deleted'),
+ status: :unprocessable_content
+ )
+ end
- render_error(
- code: 'invalid_status',
- message: Spree.t('stock_transfer.errors.only_draft_can_be_deleted'),
- status: :unprocessable_content
- )
+ authorize_resource!(@resource, :destroy)
+ @resource.really_destroy!
+ head :no_content
end
# PATCH /api/v3/admin/stock_transfers/:id/mark_ready
def mark_ready
- run_transition(Spree.stock_transfer_mark_ready_workflow)
+ result = Spree.stock_transfer_mark_ready_workflow.call(stock_transfer: @resource)
+ return render_result_error(result) unless result.success?
+
+ render json: serialize_resource(result.value)
end
# PATCH /api/v3/admin/stock_transfers/:id/mark_in_transit
def mark_in_transit
- run_transition(Spree.stock_transfer_mark_in_transit_workflow, force: params[:force].to_b)
+ result = Spree.stock_transfer_mark_in_transit_workflow.call(
+ stock_transfer: @resource,
+ force: params[:force].to_b
+ )
+ return render_result_error(result) unless result.success?
+
+ render json: serialize_resource(result.value)
end
# PATCH /api/v3/admin/stock_transfers/:id/receive
def receive
- run_transition(Spree.stock_transfer_receive_workflow,
- items: items_for_receive([:id, :quantity_received, :discrepancy_reason]),
- received_by: try_spree_current_user)
+ result = Spree.stock_transfer_receive_workflow.call(
+ stock_transfer: @resource,
+ items: items_for_receive([:id, :quantity_received, :discrepancy_reason]),
+ received_by: try_spree_current_user
+ )
+ return render_result_error(result) unless result.success?
+
+ render json: serialize_resource(result.value)
end
# PATCH /api/v3/admin/stock_transfers/:id/cancel
def cancel
- run_transition(Spree.stock_transfer_cancel_workflow,
- on_in_transit: params[:on_in_transit],
- reason: params[:reason],
- canceler: try_spree_current_user)
+ result = Spree.stock_transfer_cancel_workflow.call(
+ stock_transfer: @resource,
+ on_in_transit: params[:on_in_transit],
+ reason: params[:reason],
+ canceler: try_spree_current_user
+ )
+ return render_result_error(result) unless result.success?
+
+ render json: serialize_resource(result.value)
end
protected
@@ -85,10 +114,6 @@ module Spree
Spree.stock_transfer_update_workflow
end
- def workflow_record_key
- :stock_transfer
- end
-
def create_workflow_arguments
{
store: current_store,
diff --git a/spree/api/app/controllers/spree/api/v3/admin/suppliers_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/suppliers_controller.rb
index e6d6a01858..eb509625a8 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/suppliers_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/suppliers_controller.rb
@@ -23,13 +23,6 @@ module Spree
:address1, :address2, :city, :state_name, :state_code,
:country_code, :postal_code, { metadata: {} }]
end
-
- # The list shows how many orders each supplier has. `size` on an
- # unloaded association is a COUNT per row, and ar_lazy_preload does
- # not reach it — so the association is loaded up front instead.
- def collection_includes
- [:purchase_orders]
- end
end
end
end
diff --git a/spree/api/app/serializers/spree/api/v3/admin/supplier_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/supplier_serializer.rb
index 9fe39f46cf..4126d610ad 100644
--- a/spree/api/app/serializers/spree/api/v3/admin/supplier_serializer.rb
+++ b/spree/api/app/serializers/spree/api/v3/admin/supplier_serializer.rb
@@ -23,12 +23,8 @@ module Spree
attributes :name, :contact_name, :email, :phone, :notes,
:address1, :address2, :city, :state_name, :state_code,
- :country_code, :postal_code, :metadata,
+ :country_code, :postal_code, :purchase_orders_count, :metadata,
created_at: :iso8601, updated_at: :iso8601, deleted_at: :iso8601
-
- attribute :purchase_orders_count do |supplier|
- supplier.purchase_orders.size
- end
end
end
end
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/stock_transfers_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/stock_transfers_controller_spec.rb
index ce8617cb99..b2c5a486ab 100644
--- a/spree/api/spec/controllers/spree/api/v3/admin/stock_transfers_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/admin/stock_transfers_controller_spec.rb
@@ -298,6 +298,19 @@ RSpec.describe Spree::Api::V3::Admin::StockTransfersController, type: :controlle
expect(response).to have_http_status(:no_content)
end
+ # Really gone, not stamped. The soft-delete column exists for the upgrade
+ # task's converted receives, whose numbers have to stay findable; a draft
+ # nobody sent has nothing to preserve, and `destroy` hard-deletes its lines
+ # regardless, which would leave a row that could never be restored intact.
+ it 'leaves no soft-deleted row or orphaned lines behind' do
+ item_id = transfer.items.sole.id
+
+ delete :destroy, params: { id: transfer.prefixed_id }, as: :json
+
+ expect(Spree::StockTransfer.only_deleted.where(id: transfer.id)).to be_empty
+ expect(Spree::StockTransferItem.where(id: item_id)).to be_empty
+ end
+
# Past draft the transfer describes a box that physically exists.
it 'refuses to delete a transfer that has shipped' do
Spree::StockTransfers::MarkInTransit.call(stock_transfer: transfer)
diff --git a/spree/core/app/models/spree/purchase_order.rb b/spree/core/app/models/spree/purchase_order.rb
index c4af9ec0cb..1319bbf3e8 100644
--- a/spree/core/app/models/spree/purchase_order.rb
+++ b/spree/core/app/models/spree/purchase_order.rb
@@ -16,9 +16,10 @@ module Spree
class PurchaseOrder < Spree.base_class
has_prefix_id :po
+ # Before `has_spree_number` — see the note on Spree::StockTransfer.
+ include Spree::SingleStoreResource
has_spree_number prefix: 'PO'
include Spree::NumberIdentifier
- include Spree::SingleStoreResource
include Spree::HasStatus
include Spree::Receivable
include Spree::HasCustomFields
@@ -29,7 +30,8 @@ module Spree
has_status :draft, :ordered, :partially_received, :received, :canceled,
default: :draft
- belongs_to :supplier, class_name: 'Spree::Supplier', inverse_of: :purchase_orders
+ belongs_to :supplier, class_name: 'Spree::Supplier', inverse_of: :purchase_orders,
+ counter_cache: true
belongs_to :destination_location, class_name: 'Spree::StockLocation'
belongs_to :created_by, class_name: Spree.admin_user_class.to_s, optional: true
diff --git a/spree/core/app/models/spree/stock_transfer.rb b/spree/core/app/models/spree/stock_transfer.rb
index c649e1c1c3..080113aa6e 100644
--- a/spree/core/app/models/spree/stock_transfer.rb
+++ b/spree/core/app/models/spree/stock_transfer.rb
@@ -19,9 +19,13 @@ module Spree
class StockTransfer < Spree.base_class
has_prefix_id :st
+ # Before `has_spree_number`, deliberately: both register a
+ # `before_validation`, and numbering reads the store to pick up its
+ # sequence. Registered the other way round, a transfer built without an
+ # explicit store would draw its number from the default store's counter.
+ include Spree::SingleStoreResource
has_spree_number prefix: 'T'
include Spree::NumberIdentifier
- include Spree::SingleStoreResource
include Spree::HasStatus
include Spree::Receivable
include Spree::HasCustomFields
diff --git a/spree/core/app/workflows/spree/purchase_orders/create.rb b/spree/core/app/workflows/spree/purchase_orders/create.rb
index 00b8775192..c6c6c8b67a 100644
--- a/spree/core/app/workflows/spree/purchase_orders/create.rb
+++ b/spree/core/app/workflows/spree/purchase_orders/create.rb
@@ -32,7 +32,7 @@ module Spree
end
run_hooks :after_create
- purchase_order.publish_event('purchase_order.created')
+ # The model's lifecycle events already emit `purchase_order.created`.
success(purchase_order.reload)
end
diff --git a/spree/core/app/workflows/spree/stock_transfers/create.rb b/spree/core/app/workflows/spree/stock_transfers/create.rb
index e9c909147b..fad5fa7328 100644
--- a/spree/core/app/workflows/spree/stock_transfers/create.rb
+++ b/spree/core/app/workflows/spree/stock_transfers/create.rb
@@ -29,7 +29,9 @@ module Spree
end
run_hooks :after_create
- stock_transfer.publish_event('stock_transfer.created')
+ # No `publish_event` here: `publishes_lifecycle_events` on the model
+ # already emits `stock_transfer.created` after commit, and publishing
+ # it again fires every subscriber and webhook twice.
success(stock_transfer.reload)
end
diff --git a/spree/core/db/migrate/20260907000001_add_inventory_operations.rb b/spree/core/db/migrate/20260907000001_add_inventory_operations.rb
index 54abc80250..09968af54c 100644
--- a/spree/core/db/migrate/20260907000001_add_inventory_operations.rb
+++ b/spree/core/db/migrate/20260907000001_add_inventory_operations.rb
@@ -40,6 +40,10 @@ class AddInventoryOperations < ActiveRecord::Migration[8.1]
t.string :phone
t.text :notes
t.references :store, null: false
+ # Kept by Active Record's counter cache, so the suppliers list can show
+ # "3 purchase orders" without a query per row — and without loading a
+ # supplier's whole purchasing history to count it.
+ t.integer :purchase_orders_count, null: false, default: 0
# Inline address columns, mirroring spree_stock_locations: a supplier is
# a place goods come from, edited as one flat form.
t.string :address1
diff --git a/spree/core/lib/tasks/inventory_operations_migration.rake b/spree/core/lib/tasks/inventory_operations_migration.rake
index e44bf03aeb..84f8c8205a 100644
--- a/spree/core/lib/tasks/inventory_operations_migration.rake
+++ b/spree/core/lib/tasks/inventory_operations_migration.rake
@@ -178,8 +178,15 @@ namespace :spree do
where(source_location_id: nil).
where.not(id: still_owning_movements)
- count = migrated.count
- migrated.find_each(&:really_destroy!)
+ count = 0
+ migrated.find_each do |transfer|
+ # The movements kept naming the transfer for lineage while it was only
+ # soft-deleted. It is about to stop existing, so that reference has to
+ # go with it rather than becoming an id that resolves to nothing.
+ Spree::StockMovement.where(stock_transfer_id: transfer.id).update_all(stock_transfer_id: nil)
+ transfer.really_destroy!
+ count += 1
+ end
puts " Purged #{count} migrated external receive(s)."
end
diff --git a/spree/core/spec/lib/tasks/inventory_operations_migration_spec.rb b/spree/core/spec/lib/tasks/inventory_operations_migration_spec.rb
index 8f8844f3df..facb3c67b3 100644
--- a/spree/core/spec/lib/tasks/inventory_operations_migration_spec.rb
+++ b/spree/core/spec/lib/tasks/inventory_operations_migration_spec.rb
@@ -120,6 +120,20 @@ describe 'spree:upgrade inventory operations' do
expect(Spree::StockTransfer.only_deleted.where(id: transfer.id)).to be_empty
end
+ # Otherwise the movement keeps an `st_…` reference the serializer hands to
+ # clients, pointing at a row that no longer exists.
+ it 'stops the migrated movements naming the transfer it destroys' do
+ transfer = legacy_external_receive
+ Rake::Task['spree:upgrade:migrate_external_receives_to_purchase_orders'].tap(&:reenable).invoke
+ movement = Spree::StockMovement.find_by(stock_transfer_id: transfer.id)
+ expect(movement).to be_present
+
+ Rake::Task['spree:upgrade:purge_migrated_external_receives'].tap(&:reenable).invoke
+
+ expect(movement.reload.stock_transfer_id).to be_nil
+ expect(movement.purchase_order).to be_present
+ end
+
# A transfer still owning its ledger has not been migrated.
it 'leaves a soft-deleted transfer whose movements are still its own' do
transfer = legacy_external_receive
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 5e44c12db0..60c2703bd4 100644
--- a/spree/core/spec/workflows/spree/purchase_orders/lifecycle_spec.rb
+++ b/spree/core/spec/workflows/spree/purchase_orders/lifecycle_spec.rb
@@ -31,6 +31,21 @@ describe 'purchase order lifecycle', type: :model do
expect(on_hand).to eq(0)
end
+ # See the twin note in the stock transfer lifecycle spec: the model's
+ # after_commit hook owns this announcement.
+ it 'leaves announcing a new order to the model' do
+ published = []
+ allow_any_instance_of(Spree::PurchaseOrder).
+ to receive(:publish_event) { |_instance, name, *| published << name }
+
+ Spree::PurchaseOrders::Create.call(
+ store: store, supplier: supplier, destination_location: destination,
+ items: [{ variant: variant, quantity_ordered: 1, unit_cost: 1 }]
+ )
+
+ expect(published).not_to include('purchase_order.created')
+ end
+
it 'refuses a line with no quantity' do
result = Spree::PurchaseOrders::Create.call(
store: store, supplier: supplier, destination_location: destination,
@@ -149,6 +164,16 @@ describe 'purchase order lifecycle', type: :model do
end
end
+ describe 'the supplier order count' do
+ it 'tracks purchase orders without counting them per row' do
+ expect { purchase_order }.to change { supplier.reload.purchase_orders_count }.from(0).to(1)
+
+ purchase_order.destroy
+
+ expect(supplier.reload.purchase_orders_count).to eq(0)
+ end
+ end
+
describe 'cancelling' do
# A purchase order never moved stock, so there is nothing to unwind — and
# units already received stay on the shelf, because the merchant has them.
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 8356257ede..4cfe0b22cd 100644
--- a/spree/core/spec/workflows/spree/stock_transfers/lifecycle_spec.rb
+++ b/spree/core/spec/workflows/spree/stock_transfers/lifecycle_spec.rb
@@ -38,6 +38,23 @@ describe 'stock transfer lifecycle', type: :model do
expect(transfer.stock_movements).to be_empty
end
+ # `publishes_lifecycle_events` already announces a new record, from an
+ # after_commit hook that does not run inside a transactional example — so
+ # anything seen here came from the workflow, which used to publish the
+ # same name a second time and fire every subscriber twice.
+ it 'leaves announcing a new transfer to the model' do
+ published = []
+ allow_any_instance_of(Spree::StockTransfer).
+ to receive(:publish_event) { |_instance, name, *| published << name }
+
+ Spree::StockTransfers::Create.call(
+ store: store, source_location: source, destination_location: destination,
+ items: [{ variant: variant, quantity_shipped: 1 }]
+ )
+
+ expect(published).not_to include('stock_transfer.created')
+ end
+
it 'refuses a line with no quantity' do
result = Spree::StockTransfers::Create.call(
store: store, source_location: source, destination_location: destination,