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
Record each delivery as a stock receipt
Damian Legawiec2d76ce784cca
diff --git a/spree/core/app/models/concerns/spree/receivable.rb b/spree/core/app/models/concerns/spree/receivable.rbindex 48a3547bef..bb56219c19 100644--- a/spree/core/app/models/concerns/spree/receivable.rb+++ b/spree/core/app/models/concerns/spree/receivable.rb@@ -1,88 +1,85 @@module Spree- # A document whose line items expect goods to arrive at a stock location: a- # stock transfer, a purchase order (docs/plans/6.0-inventory-operations.md).- #- # Owns the reads both share — the running totals a list page shows and the- # question "did everything arrive?". The writes stay in the workflows, which- # is what lets a receive carry the quantities the warehouse counted.- #- # Including classes provide an `items` association of {Spree::ReceivableItem}- # rows and a `destination_location`.+ # What a purchase order and a stock transfer have in common: lines that+ # promise a quantity, deliveries that bring some of it, and a status that+ # says how far along that is.module Receivableextend ActiveSupport::Concern- # The statuses a document sits in while goods are still expected.OPEN_STATUSES = %w[draft ready_to_ship ordered in_transit partially_received].freeze- # The statuses nothing more will arrive in.- CLOSED_STATUSES = %w[received canceled].freeze+ CLOSED_STATUSES = %w[received over_received canceled].freezeincluded do+ has_many :stock_receipts, as: :receivable, class_name: 'Spree::StockReceipt',+ inverse_of: :receivable, dependent: :destroy+scope :open, -> { where(status: OPEN_STATUSES & statuses) }scope :closed, -> { where(status: CLOSED_STATUSES & statuses) }validate :items_name_distinct_variantsend- # @return [Integer]def items_countitems.sizeend- # How many units the document promises in total.- #- # @return [Integer]def quantity_expected_totalitems.sum(&:quantity_expected)end- # How many units have been counted in so far.- #- # @return [Integer]def quantity_received_totalitems.sum { |item| item.quantity_received.to_i }end- # Whether any line is still owed units — the opposite of- # {#fully_received?} for a document that has lines at all.+ def quantity_rejected_total+ items.sum { |item| item.quantity_rejected.to_i }+ end++ # Whether any line is still owed units.## @return [Boolean]- def under_received?+ def short?items.any?(&:under_received?)end- # Whether every line has arrived in full.+ # Whether any line took in more than it expected.## @return [Boolean]+ def over?+ items.any?(&:over_received?)+ end+def fully_received?- items.any? && !under_received?+ items.any? && !short?end- # The status a receive settles the document in: `received` once every line- # is complete, `partially_received` while any is still owed.+ # Where a delivery leaves the document: over-receipt outranks a shortfall+ # elsewhere, because the extra units are already on the shelf and nothing+ # further can be expected once the supplier has sent more than was asked.## @return [String]def status_after_receive+ return 'over_received' if over?+fully_received? ? 'received' : 'partially_received'end- # Whether the document is still expecting goods.- #- # @return [Boolean]def open?OPEN_STATUSES.include?(status)end- # @return [Boolean]def closed?CLOSED_STATUSES.include?(status)end+ # Closed by the merchant with units still owed, rather than by a delivery.+ #+ # @return [Boolean]+ def closed_short?+ closed_short_at.present?+ end+private- # Two lines for the same SKU make "how many are we sending?" ambiguous,- # and would race the unique index besides. Checked here rather than as a- # uniqueness validation on the line, which queries the database and so- # cannot see its own unsaved siblings.def items_name_distinct_variantsvariant_ids = items.reject(&:marked_for_destruction?).filter_map(&:variant_id)return if variant_ids.uniq.size == variant_ids.sizediff --git a/spree/core/app/models/concerns/spree/receivable_item.rb b/spree/core/app/models/concerns/spree/receivable_item.rbindex 23a811d13e..604987565b 100644--- a/spree/core/app/models/concerns/spree/receivable_item.rb+++ b/spree/core/app/models/concerns/spree/receivable_item.rb@@ -1,17 +1,12 @@module Spree- # A line on a document that expects goods to arrive: how many were promised,- # and how many the warehouse actually counted.- #- # The promised quantity has a different name on each document —- # `quantity_shipped` on a stock transfer, `quantity_ordered` on a purchase- # order — because the merchant's own vocabulary differs. Including classes- # name their column once in `expected_quantity_attribute` and everything- # here reads through {#quantity_expected}.+ # A line on a purchase order or a stock transfer: one variant, a promised+ # quantity, and the running totals of what deliveries have brought.module ReceivableItemextend ActiveSupport::Concernclass_methods do- # @param attribute [Symbol] the column holding the promised quantity+ # Names the column holding what the line promised: `quantity_ordered` on+ # a purchase order line, `quantity_shipped` on a transfer line.def expects_quantity_in(attribute)class_attribute :expected_quantity_attribute, default: attribute.to_sym,instance_writer: false@@ -19,15 +14,13 @@ module Spreeendincluded do- # `with_deleted`: a line outlives the variant it names, the same way the- # movement ledger outlives the level it describes. Without this a- # discontinued SKU takes the whole document out of the API with it.belongs_to :variant, -> { with_deleted }, class_name: 'Spree::Variant'+ has_many :stock_receipt_items, as: :line, class_name: 'Spree::StockReceiptItem',+ inverse_of: :line, dependent: :destroy- validates :quantity_received, numericality: {+ validates :quantity_received, :quantity_rejected, numericality: {greater_than_or_equal_to: 0, only_integer: true}- validate :received_does_not_exceed_expecteddelegate :name, :sku, to: :variant, prefix: true, allow_nil: trueend@@ -47,31 +40,37 @@ module Spreevariant&.primary_media || variant&.product&.primary_mediaend- # How many are still owed.+ # Units that count against the promise. A supplier's promise is met by+ # units the dock accepts — refused goods go back and are still owed. A+ # transfer overrides this: its promise is met by units that arrived at+ # all, since the damaged ones are not in the van any more.+ #+ # @return [Integer]+ def quantity_settled+ quantity_received.to_i+ end++ # Units still owed. Never below zero: anything above the promise is+ # `quantity_over`, not a negative debt.## @return [Integer]def outstanding- quantity_expected - quantity_received.to_i+ [quantity_expected - quantity_settled, 0].maxend- # Whether fewer units arrived than were promised.+ # Units that arrived beyond what was promised.#- # @return [Boolean]+ # @return [Integer]+ def quantity_over+ [quantity_settled - quantity_expected, 0].max+ end+def under_received?outstanding.positive?end- private-- # The error goes on `quantity_received` because that is the value the- # caller sent: a receive of twelve against ten shipped is a miscount at- # the receiving dock, not a retrospective error in what left.- def received_does_not_exceed_expected- return if quantity_received.blank?- return if quantity_received.to_i <= quantity_expected-- errors.add(:quantity_received, :cannot_exceed_expected,- message: Spree.t('errors.messages.received_exceeds_expected', expected: quantity_expected))+ def over_received?+ quantity_over.positive?endendenddiff --git a/spree/core/app/models/spree/exports/purchase_orders.rb b/spree/core/app/models/spree/exports/purchase_orders.rbnew file mode 100644index 0000000000..8cf99c4185--- /dev/null+++ b/spree/core/app/models/spree/exports/purchase_orders.rb@@ -0,0 +1,39 @@+module Spree+ module Exports+ # Purchase orders as a supplier reads them: one row per line, the order's+ # header repeated on each. Filtered to one order, it is the file a merchant+ # sends to that supplier.+ class PurchaseOrders < Spree::Export+ def self.required_scope+ :purchasing+ end++ def self.model_class+ Spree::PurchaseOrder+ end++ def model_class+ Spree::PurchaseOrder+ end++ def scope_includes+ [:supplier, :destination_location, { items: { variant: :product } }]+ end++ def csv_headers+ Spree::CSV::PurchaseOrderItemPresenter::HEADERS+ end++ def generate_csv+ ::CSV.open(export_tmp_file_path, 'wb', encoding: 'UTF-8', col_sep: ',', row_sep: "\r\n") do |csv|+ csv << csv_headers+ records_to_export.includes(scope_includes).find_each do |purchase_order|+ purchase_order.items.each do |item|+ csv << Spree::CSV::FormulaSanitizer.row(Spree::CSV::PurchaseOrderItemPresenter.new(item).call)+ end+ end+ end+ end+ end+ end+enddiff --git a/spree/core/app/models/spree/import_schemas/purchase_orders.rb b/spree/core/app/models/spree/import_schemas/purchase_orders.rbnew file mode 100644index 0000000000..c0eda967fd--- /dev/null+++ b/spree/core/app/models/spree/import_schemas/purchase_orders.rb@@ -0,0 +1,19 @@+module Spree+ module ImportSchemas+ # One row per line; rows sharing a reference become one draft order.+ class PurchaseOrders < Spree::ImportSchema+ FIELDS = [+ { name: 'reference', label: 'Reference', required: true },+ { name: 'supplier', label: 'Supplier', required: true },+ { name: 'destination', label: 'Destination', required: true },+ { name: 'sku', label: 'SKU', required: true },+ { name: 'quantity', label: 'Quantity', required: true },+ { name: 'unit_cost', label: 'Unit cost', required: true },+ { name: 'currency', label: 'Currency' },+ { name: 'expected_at', label: 'Expected on' },+ { name: 'cancel_by', label: 'Cancel by' },+ { name: 'notes', label: 'Notes' }+ ].freeze+ end+ end+enddiff --git a/spree/core/app/models/spree/imports/purchase_orders.rb b/spree/core/app/models/spree/imports/purchase_orders.rbnew file mode 100644index 0000000000..4ba1e5714a--- /dev/null+++ b/spree/core/app/models/spree/imports/purchase_orders.rb@@ -0,0 +1,28 @@+module Spree+ module Imports+ # Draft purchase orders from a supplier's line sheet. Rows sharing a+ # `reference` are one order; every order this import creates is a draft,+ # to be checked and placed from its own screen.+ class PurchaseOrders < Spree::Import+ def row_processor_class+ Spree::Imports::RowProcessors::PurchaseOrder+ end++ def group_column+ 'reference'+ end++ def model_class+ Spree::PurchaseOrder+ end++ def self.model_class+ Spree::PurchaseOrder+ end++ def self.required_scope+ :purchasing+ end+ end+ end+enddiff --git a/spree/core/app/models/spree/purchase_order.rb b/spree/core/app/models/spree/purchase_order.rbindex 1319bbf3e8..298e939e20 100644--- a/spree/core/app/models/spree/purchase_order.rb+++ b/spree/core/app/models/spree/purchase_order.rb@@ -27,7 +27,7 @@ module Spreepublishes_lifecycle_events- has_status :draft, :ordered, :partially_received, :received, :canceled,+ has_status :draft, :ordered, :partially_received, :received, :over_received, :canceled,default: :draftbelongs_to :supplier, class_name: 'Spree::Supplier', inverse_of: :purchase_orders,@@ -48,9 +48,16 @@ module Spreevalidates :currency, presence: truevalidates :items, presence: true, unless: -> { draft? || canceled? }+ # Overdue and past-cancel-by read the calendar date in the server's zone;+ # a supplier's promise is a day, and a few hours either side of midnight+ # is not what a merchant is filtering for.+ scope :overdue, -> { open.where(arel_table[:expected_at].lt(Date.current)) }+ scope :past_cancel_by, -> { open.where(arel_table[:cancel_by].lt(Date.current)) }+self.whitelisted_ransackable_attributes = %w[number status currency reference expected_at- ordered_at received_at supplier_id- destination_location_id created_at]+ cancel_by ordered_at received_at closed_short_at+ supplier_id destination_location_id created_at]+ self.whitelisted_ransackable_scopes = %w[open closed overdue past_cancel_by]self.whitelisted_ransackable_associations = %w[supplier destination_location items]# What the supplier will invoice for everything ordered.diff --git a/spree/core/app/models/spree/purchase_order_item.rb b/spree/core/app/models/spree/purchase_order_item.rbindex 1eb95304e3..551f7ee7b5 100644--- a/spree/core/app/models/spree/purchase_order_item.rb+++ b/spree/core/app/models/spree/purchase_order_item.rb@@ -16,7 +16,7 @@ module Spreedelegate :currency, to: :purchase_order, allow_nil: true- self.whitelisted_ransackable_attributes = %w[variant_id quantity_ordered quantity_received unit_cost]+ self.whitelisted_ransackable_attributes = %w[variant_id quantity_ordered quantity_received quantity_rejected unit_cost]self.whitelisted_ransackable_associations = %w[variant]# What the whole line costs at the agreed unit price. Ordered rather thandiff --git a/spree/core/app/models/spree/stock_location.rb b/spree/core/app/models/spree/stock_location.rbindex 41923c72a7..2215cc7e24 100644--- a/spree/core/app/models/spree/stock_location.rb+++ b/spree/core/app/models/spree/stock_location.rb@@ -290,6 +290,8 @@ module Spreewhen Spree::Exchange then { exchange: cause, order: cause.order }when Spree::StockTransfer then { stock_transfer: cause }when Spree::PurchaseOrder then { purchase_order: cause }+ # A delivery names the document it was against as well as itself.+ when Spree::StockReceipt then { stock_receipt: cause, **cause_attributes(cause.receivable) }when Spree::Order then { order: cause }else {}enddiff --git a/spree/core/app/models/spree/stock_movement.rb b/spree/core/app/models/spree/stock_movement.rbindex 5a777d6b23..d6b5d74cc5 100644--- a/spree/core/app/models/spree/stock_movement.rb+++ b/spree/core/app/models/spree/stock_movement.rb@@ -32,6 +32,7 @@ module Spreebelongs_to :exchange, class_name: 'Spree::Exchange', optional: truebelongs_to :stock_transfer, class_name: 'Spree::StockTransfer', optional: truebelongs_to :purchase_order, class_name: 'Spree::PurchaseOrder', optional: true+ belongs_to :stock_receipt, class_name: 'Spree::StockReceipt', optional: true, inverse_of: :stock_movementsalias_attribute :stock_item_id, :stock_level_id@@ -80,7 +81,7 @@ module Spreeself.whitelisted_ransackable_attributes = %w[quantity kind reason created_at stock_level_idstock_item_id order_id fulfillment_id return_idexchange_id stock_transfer_id purchase_order_id- unit_cost]+ stock_receipt_id unit_cost]self.whitelisted_ransackable_associations = %w[stock_level]# Stored audit text for a correction nobody labelled. Deliberatelydiff --git a/spree/core/app/models/spree/stock_receipt.rb b/spree/core/app/models/spree/stock_receipt.rbnew file mode 100644index 0000000000..d2c333b14a--- /dev/null+++ b/spree/core/app/models/spree/stock_receipt.rb@@ -0,0 +1,56 @@+module Spree+ # One delivery against a purchase order or a stock transfer: what the dock+ # counted in on one day, under one packing slip. Lines on the document keep+ # the running totals; the receipt is the record of each arrival, and every+ # `received` movement it caused names it.+ #+ # A *stock* receipt on purpose — a customer-facing sales receipt will want+ # the plain word.+ class StockReceipt < Spree.base_class+ has_prefix_id :sr++ include Spree::SingleStoreResource+ has_spree_number prefix: 'SR'+ include Spree::NumberIdentifier+ include Spree::Metadata++ publishes_lifecycle_events++ belongs_to :receivable, polymorphic: true, inverse_of: :stock_receipts+ belongs_to :received_by, class_name: Spree.admin_user_class.to_s, optional: true++ has_many :items, class_name: 'Spree::StockReceiptItem', inverse_of: :stock_receipt,+ dependent: :destroy+ has_many :stock_movements, class_name: 'Spree::StockMovement', inverse_of: :stock_receipt,+ dependent: :nullify++ validates :received_at, presence: true+ validates :items, presence: true++ normalizes :reference, with: ->(value) { value.strip.presence }++ self.whitelisted_ransackable_attributes = %w[number reference received_at receivable_type+ receivable_id received_by_id created_at]++ # @return [Integer] units this delivery put on the shelf+ def quantity_accepted_total+ items.sum { |item| item.quantity_accepted.to_i }+ end++ # @return [Integer] units this delivery refused+ def quantity_rejected_total+ items.sum { |item| item.quantity_rejected.to_i }+ end++ def event_serializer_class+ 'Spree::Api::V3::StockReceiptEventSerializer'.safe_constantize+ end++ private++ def ensure_store+ self.store ||= receivable&.store+ super+ end+ end+enddiff --git a/spree/core/app/models/spree/stock_receipt_item.rb b/spree/core/app/models/spree/stock_receipt_item.rbnew file mode 100644index 0000000000..c161ab5035--- /dev/null+++ b/spree/core/app/models/spree/stock_receipt_item.rb@@ -0,0 +1,35 @@+module Spree+ # One line of a delivery: how many of a document's line arrived, how many of+ # those were refused, and why. Accepted units reach the shelf; rejected ones+ # exist only here.+ class StockReceiptItem < Spree.base_class+ has_prefix_id :sri++ REJECTION_REASONS = %w[damaged wrong_item expired other].freeze++ belongs_to :stock_receipt, class_name: 'Spree::StockReceipt', inverse_of: :items+ # A purchase order item or a stock transfer item.+ belongs_to :line, polymorphic: true, inverse_of: :stock_receipt_items++ validates :quantity_accepted, :quantity_rejected,+ numericality: { greater_than_or_equal_to: 0, only_integer: true }+ validates :rejection_reason, inclusion: { in: REJECTION_REASONS },+ if: -> { quantity_rejected.to_i.positive? }+ validate :counts_something++ delegate :variant, :variant_name, :variant_sku, to: :line, allow_nil: true++ # @return [Integer] everything the dock counted, accepted or not+ def quantity_counted+ quantity_accepted.to_i + quantity_rejected.to_i+ end++ private++ def counts_something+ return if quantity_counted.positive?++ errors.add(:base, :nothing_counted, message: Spree.t('stock_receipt.errors.nothing_counted'))+ end+ end+enddiff --git a/spree/core/app/models/spree/stock_transfer.rb b/spree/core/app/models/spree/stock_transfer.rbindex 080113aa6e..3321ca7bbf 100644--- a/spree/core/app/models/spree/stock_transfer.rb+++ b/spree/core/app/models/spree/stock_transfer.rb@@ -37,7 +37,7 @@ module Spreepublishes_lifecycle_events- has_status :draft, :ready_to_ship, :in_transit, :partially_received, :received, :canceled,+ has_status :draft, :ready_to_ship, :in_transit, :partially_received, :received, :over_received, :canceled,default: :draftbelongs_to :source_location, class_name: 'Spree::StockLocation'@@ -63,7 +63,8 @@ module Spreeself.whitelisted_ransackable_attributes = %w[number status reference source_location_iddestination_location_id shipped_at received_at- created_at]+ closed_short_at created_at]+ self.whitelisted_ransackable_scopes = %w[open closed]self.whitelisted_ransackable_associations = %w[source_location destination_location items]# Whether the merchant may still edit the lines. Once the box is sealed anddiff --git a/spree/core/app/models/spree/stock_transfer_item.rb b/spree/core/app/models/spree/stock_transfer_item.rbindex d17566695b..04f6465709 100644--- a/spree/core/app/models/spree/stock_transfer_item.rb+++ b/spree/core/app/models/spree/stock_transfer_item.rb@@ -13,7 +13,13 @@ module Spreevalidates :quantity_shipped, numericality: { greater_than: 0, only_integer: true }validates :variant_id, uniqueness: { scope: :stock_transfer_id }- self.whitelisted_ransackable_attributes = %w[variant_id quantity_shipped quantity_received discrepancy_reason]+ self.whitelisted_ransackable_attributes = %w[variant_id quantity_shipped quantity_received quantity_rejected]++ # Everything that arrived, whatever state it was in: a crushed unit is+ # not still on the road.+ def quantity_settled+ quantity_received.to_i + quantity_rejected.to_i+ endself.whitelisted_ransackable_associations = %w[variant]endenddiff --git a/spree/core/app/presenters/spree/csv/purchase_order_item_presenter.rb b/spree/core/app/presenters/spree/csv/purchase_order_item_presenter.rbnew file mode 100644index 0000000000..03ac0cc288--- /dev/null+++ b/spree/core/app/presenters/spree/csv/purchase_order_item_presenter.rb@@ -0,0 +1,48 @@+module Spree+ module CSV+ # One purchase order line as a CSV row, with its order's header alongside.+ # The first columns match the import schema, so an exported file re-imports.+ class PurchaseOrderItemPresenter+ HEADERS = %w[+ reference supplier destination sku quantity unit_cost currency expected_at cancel_by notes+ number status product_name received rejected+ ].freeze++ def initialize(item)+ @item = item+ end++ attr_reader :item++ def call+ order = item.purchase_order++ [+ order.reference,+ order.supplier&.name,+ order.destination_location&.name,+ item.variant&.sku,+ item.quantity_ordered,+ amount_string(item.unit_cost, order.currency),+ order.currency,+ order.expected_at&.iso8601,+ order.cancel_by&.iso8601,+ order.notes,+ order.number,+ order.status,+ item.variant&.product&.name,+ item.quantity_received,+ item.quantity_rejected+ ]+ end++ private++ def amount_string(amount, currency)+ return nil if amount.nil?++ format("%.#{Spree::Money::Rounding.precision(currency)}f", amount)+ end+ end+ end+enddiff --git a/spree/core/app/services/spree/imports/row_processors/purchase_order.rb b/spree/core/app/services/spree/imports/row_processors/purchase_order.rbnew file mode 100644index 0000000000..8825a9308a--- /dev/null+++ b/spree/core/app/services/spree/imports/row_processors/purchase_order.rb@@ -0,0 +1,157 @@+module Spree+ module Imports+ module RowProcessors+ # One line of a purchase order. The first row carrying a reference opens+ # a draft for it through the same workflow the screen uses; every later+ # row with that reference adds its line. Suppliers, warehouses and SKUs+ # are named, not created: a typo must fail the row, not spawn a record.+ class PurchaseOrder < Base+ QUANTITY_FORMAT = /\A\d+\z/+ AMOUNT_FORMAT = /\A\d+(\.\d+)?\z/++ def initialize(row, **)+ super+ @store = import.store+ end++ attr_reader :store++ def process!+ reference = attributes['reference'].to_s.strip+ raise ArgumentError, Spree.t(:purchase_order_import_reference_required) if reference.blank?++ line = {+ variant: find_variant,+ quantity_ordered: quantity_for(attributes['quantity']),+ unit_cost: amount_for(attributes['unit_cost'])+ }++ cache = import.row_lookup_cache+ key = [:purchase_order_import_order, reference]+ if cache.key?(key)+ add_line(cache[key], line)+ else+ cache[key] = open_draft(reference, line)+ end+ end++ private++ def open_draft(reference, line)+ result = Spree::PurchaseOrders::Create.call(+ store: store,+ supplier: find_supplier,+ destination_location: find_destination,+ items: [line],+ currency: currency_for(attributes['currency']),+ expected_at: date_for(attributes['expected_at'], 'expected_at'),+ cancel_by: date_for(attributes['cancel_by'], 'cancel_by'),+ reference: reference,+ notes: attributes['notes'].to_s.strip.presence,+ created_by: import.user+ )+ raise ArgumentError, failure_message(result) unless result.success?++ result.value+ end++ # The update replaces the lines wholesale, so the ones already on the+ # draft go back with the new one. A SKU repeated under one reference+ # is one line with the quantities added, the way a picker would total+ # two cartons of the same thing.+ def add_line(purchase_order, line)+ lines = purchase_order.items.map do |item|+ { variant: item.variant, quantity_ordered: item.quantity_ordered, unit_cost: item.unit_cost }+ end+ existing = lines.find { |entry| entry[:variant].id == line[:variant].id }+ if existing+ existing[:quantity_ordered] += line[:quantity_ordered]+ else+ lines << line+ end++ result = Spree::PurchaseOrders::Update.call(purchase_order: purchase_order, items: lines)+ raise ArgumentError, failure_message(result) unless result.success?++ result.value+ end++ def find_supplier+ name = attributes['supplier'].to_s.strip+ raise ArgumentError, Spree.t(:purchase_order_import_supplier_required) if name.blank?++ cached_lookup(:purchase_order_import_supplier, name.downcase) do+ store.suppliers.find_by(Spree::Supplier.arel_table[:name].lower.eq(name.downcase))+ end || raise(ArgumentError, Spree.t(:purchase_order_import_unknown_supplier, name: name))+ end++ def find_destination+ name = attributes['destination'].to_s.strip+ raise ArgumentError, Spree.t(:purchase_order_import_destination_required) if name.blank?++ cached_lookup(:purchase_order_import_destination, name.downcase) do+ store.stock_locations.find_by(Spree::StockLocation.arel_table[:name].lower.eq(name.downcase))+ end || raise(ArgumentError, Spree.t(:purchase_order_import_unknown_destination, name: name))+ end++ def find_variant+ sku = attributes['sku'].to_s.strip+ raise ArgumentError, Spree.t(:purchase_order_import_sku_required) if sku.blank?++ variants = cached_lookup(:purchase_order_import_variant, sku.downcase) do+ store.variants.where(Spree::Variant.arel_table[:sku].lower.eq(sku.downcase)).limit(2).to_a+ end+ raise ArgumentError, Spree.t(:purchase_order_import_unknown_sku, sku: sku) if variants.empty?+ raise ArgumentError, Spree.t(:purchase_order_import_ambiguous_sku, sku: sku) if variants.many?++ variants.first+ end++ def quantity_for(value)+ text = value.to_s.strip+ unless text.match?(QUANTITY_FORMAT) && text.to_i.positive?+ raise ArgumentError, Spree.t(:purchase_order_import_invalid_quantity, value: text)+ end++ text.to_i+ end++ def amount_for(value)+ text = value.to_s.strip+ raise ArgumentError, Spree.t(:purchase_order_import_invalid_cost, value: text) unless text.match?(AMOUNT_FORMAT)++ BigDecimal(text)+ end++ def currency_for(value)+ currency = value.to_s.strip.upcase.presence || store.default_currency+ return currency if supported_currencies.include?(currency)++ raise ArgumentError, Spree.t(:purchase_order_import_unsupported_currency, currency: currency)+ end++ def supported_currencies+ cached_lookup(:purchase_order_import_currencies) { store.supported_currencies_list.map(&:iso_code) }+ end++ # A complete date only: `Date.parse` would take "March" and guess the+ # rest, and a guessed delivery date is worse than none.+ def date_for(value, column)+ text = value.to_s.strip+ return nil if text.blank?++ Date.iso8601(text)+ rescue Date::Error+ raise ArgumentError, Spree.t(:purchase_order_import_invalid_date, column: column, value: text)+ end++ def failure_message(result)+ error = result.error+ return error.full_messages.to_sentence if error.respond_to?(:full_messages)++ error.to_s.presence || Spree.t(:purchase_order_import_failed)+ end+ end+ end+ end+enddiff --git a/spree/core/app/workflows/spree/purchase_orders/close.rb b/spree/core/app/workflows/spree/purchase_orders/close.rbnew file mode 100644index 0000000000..fb2cd19818--- /dev/null+++ b/spree/core/app/workflows/spree/purchase_orders/close.rb@@ -0,0 +1,47 @@+module Spree+ module PurchaseOrders+ # Ends an order the supplier will not complete.+ #+ # Eight of ten arrived and the last two are not coming. Cancelling would+ # deny the eight, and waiting leaves the order open forever; closing short+ # keeps what was received, records that the rest never came and why, and+ # lets the outstanding count stand on each line as the record of the gap.+ # No stock moves — the units were never here.+ class Close < Spree::Workflow+ hooks :validate, :after_close++ attr_reader :purchase_order, :reason++ # @param purchase_order [Spree::PurchaseOrder]+ # @param reason [String, nil] why the balance is not expected+ def perform(purchase_order:, reason: nil)+ super++ purchase_order.with_lock do+ step :ensure_closable+ run_hooks :validate+ step :close_short+ end++ run_hooks :after_close+ purchase_order.publish_event('purchase_order.received')+ success(purchase_order.reload)+ end++ private++ def ensure_closable+ return if purchase_order.partially_received?++ failure(purchase_order, Spree.t('purchase_order.errors.not_partially_received'))+ end++ def close_short+ now = Time.current+ attributes = { status: 'received', received_at: now, closed_short_at: now, close_reason: reason.presence }++ failure(purchase_order) unless purchase_order.update(attributes)+ end+ end+ end+enddiff --git a/spree/core/app/workflows/spree/purchase_orders/create.rb b/spree/core/app/workflows/spree/purchase_orders/create.rbindex c6c6c8b67a..4c7526cfe3 100644--- a/spree/core/app/workflows/spree/purchase_orders/create.rb+++ b/spree/core/app/workflows/spree/purchase_orders/create.rb@@ -21,7 +21,7 @@ module Spree# @param notes [String, nil]# @param created_by [Object, nil]def perform(store:, supplier:, destination_location:, items: [], currency: nil,- expected_at: nil, reference: nil, notes: nil, created_by: nil)+ expected_at: nil, cancel_by: nil, reference: nil, notes: nil, created_by: nil)superstep :build_purchase_order@@ -44,6 +44,7 @@ module Spreedestination_location: destination_location,currency: currency,expected_at: expected_at,+ cancel_by: cancel_by,reference: reference,notes: notes,created_by: created_by,diff --git a/spree/core/app/workflows/spree/purchase_orders/mark_draft.rb b/spree/core/app/workflows/spree/purchase_orders/mark_draft.rbnew file mode 100644index 0000000000..09fc52f312--- /dev/null+++ b/spree/core/app/workflows/spree/purchase_orders/mark_draft.rb@@ -0,0 +1,41 @@+module Spree+ module PurchaseOrders+ # Takes a placed order back to the drawing board.+ #+ # Only while nothing has arrived: once a delivery has been booked the+ # lines are a record of what was received against, and can no longer be+ # rewritten. The order's `ordered_at` is cleared, because it is no longer+ # ordered.+ class MarkDraft < Spree::Workflow+ hooks :validate, :after_mark_draft++ attr_reader :purchase_order++ # @param purchase_order [Spree::PurchaseOrder]+ def perform(purchase_order:)+ super++ purchase_order.with_lock do+ step :ensure_returnable+ run_hooks :validate+ step :return_to_draft+ end++ run_hooks :after_mark_draft+ purchase_order.publish_event('purchase_order.draft')+ success(purchase_order.reload)+ end++ private++ def ensure_returnable+ failure(purchase_order, Spree.t('purchase_order.errors.already_receiving')) if purchase_order.stock_receipts.exists?+ failure(purchase_order, Spree.t('purchase_order.errors.not_ordered_for_draft')) unless purchase_order.ordered?+ end++ def return_to_draft+ failure(purchase_order) unless purchase_order.update(status: 'draft', ordered_at: nil)+ end+ end+ end+enddiff --git a/spree/core/app/workflows/spree/purchase_orders/receive.rb b/spree/core/app/workflows/spree/purchase_orders/receive.rbindex 8b030b61e5..4dc7b1bfb0 100644--- a/spree/core/app/workflows/spree/purchase_orders/receive.rb+++ b/spree/core/app/workflows/spree/purchase_orders/receive.rb@@ -1,135 +1,64 @@module Spreemodule PurchaseOrders- # Books in what the supplier actually delivered.+ # Books in one delivery from the supplier, as a stock receipt.## This is the moment purchased goods first exist as far as availability is# concerned: nothing before it touched `count_on_hand`, because a merchant# who has ordered stock does not have it. Suppliers under-ship and- # back-order routinely, so `quantity_received` is the running total for the- # line and only the difference from last time reaches the shelf.+ # back-order routinely, so a delivery is booked as its own receipt and adds+ # to the line's running total; over-shipments are booked as they come and+ # close the order as `over_received`.## Each `received` movement carries the line's `unit_cost`, which is what a- # rolling average cost is computed from — including across two partial- # deliveries agreed at different prices.+ # rolling average cost is computed from — including across two deliveries+ # agreed at different prices.class Receive < Spree::Workflow+ include Spree::StockReceipts::Recording+hooks :validate, :before_restock, :after_receive+ attr_reader :purchase_order, :items, :received_at, :reference, :notes, :received_by,+ :stock_receipt+# @param purchase_order [Spree::PurchaseOrder]- # @param items [Array<Hash>, nil] `[{ item:, quantity_received: }]`;- # nil receives every line in full+ # @param items [Array<Hash>, nil] `[{ item:, quantity_accepted:,+ # quantity_rejected:, rejection_reason:, notes: }]` — this delivery's+ # counts; nil books everything still outstanding, intact+ # @param received_at [Time, nil] defaults to now+ # @param reference [String, nil] the supplier's delivery note+ # @param notes [String, nil]# @param received_by [Object, nil]- def perform(purchase_order:, items: nil, received_by: nil)+ def perform(purchase_order:, items: nil, received_at: nil, reference: nil, notes: nil, received_by: nil)super-- # One receive at a time per document. Each line's delta is measured- # against its running total, so two callers reading the same total both- # credit the whole delivery — three concurrent receives of ten units put- # thirty on the shelf and leave the line saying ten. The lock also opens- # the transaction the writes below need, and it is always taken- # document-then-level, never the other way, so it cannot cross with the- # lock `StockLevel#adjust_count_on_hand` takes underneath.- purchase_order.with_lock do- # The caller resolved these before the lock, so their running totals- # may predate a receive that has since committed.- items&.each { |item| item[:item]&.reload }-- step :ensure_receivable- step :normalize_items- run_hooks :validate-- step :record_receipt- run_hooks :before_restock- step :restock_deltas- step :settle_status- end-- run_hooks :after_receive- purchase_order.publish_event("purchase_order.#{purchase_order.status}")- success(purchase_order.reload)+ record_deliveryendprivate- def ensure_receivable- return if purchase_order.ordered? || purchase_order.partially_received?-- failure(purchase_order, Spree.t('purchase_order.errors.not_ordered'))+ def receivable+ purchase_orderend- def normalize_items- @normalized_items =- if items.nil?- purchase_order.items.map do |line|- { item: line, quantity_received: line.quantity_ordered, delta: line.outstanding }- end- else- reject_repeated_lines- Array(items).map { |item| normalize_item(item) }- end-- return if @normalized_items.any? { |item| item[:delta].positive? }-- failure(purchase_order, Spree.t('purchase_order.errors.no_items_received'))+ def event_prefix+ 'purchase_order'end- # The running total may only go up: taking units back off the shelf is a- # correction, which is what a manual adjustment is for.- def normalize_item(item)- line = item[:item]- failure(purchase_order, Spree.t('purchase_order.errors.item_not_on_order')) unless- line&.purchase_order_id == purchase_order.id-- quantity = item[:quantity_received].to_i- if quantity.negative? || quantity > line.quantity_ordered || quantity < line.quantity_received- failure(purchase_order, Spree.t('purchase_order.errors.invalid_received_quantity',- variant: line.variant_name, ordered: line.quantity_ordered))- end-- { item: line, quantity_received: quantity, delta: quantity - line.quantity_received.to_i }+ def error_scope+ 'purchase_order'end- # Every delta is measured against the line's running total before any of- # them is written, so a line named twice contributes its delta once per- # entry: entries of four and six against a fresh line put ten on the- # shelf while the line records six. Refused rather than merged, because- # those two entries are genuinely ambiguous — ten in total, or six- # correcting four? A scanner that appends an entry per carton has to send- # the total instead.- def reject_repeated_lines- lines = Array(items).map { |item| item[:item] }.compact- repeated = lines.group_by(&:id).values.find { |group| group.length > 1 }- return if repeated.nil?-- failure(purchase_order, Spree.t('purchase_order.errors.repeated_item', variant: repeated.first.variant_name))- end+ def ensure_receivable+ return if purchase_order.ordered? || purchase_order.partially_received?- def record_receipt- @normalized_items.each do |item|- item[:item].update!(quantity_received: item[:quantity_received])- end+ failure(purchase_order, Spree.t('purchase_order.errors.not_ordered'))end- def restock_deltas- destination = purchase_order.destination_location-- @normalized_items.each do |item|- next unless item[:delta].positive?-- destination.restock(item[:item].variant, item[:delta], purchase_order,- unit_cost: item[:item].unit_cost)- end+ def line_belongs?(line)+ line&.purchase_order_id == purchase_order.idend- def settle_status- # The caller's lines are freshly-loaded instances, not the ones the- # association is holding, so the totals have to be re-read before they- # can decide the status.- purchase_order.items.reset- status = purchase_order.status_after_receive- attributes = { status: status }- attributes[:received_at] = Time.current if status == 'received'-- failure(purchase_order) unless purchase_order.update(attributes)+ def unit_cost_for(line)+ line.unit_costendendenddiff --git a/spree/core/app/workflows/spree/stock_receipts/recording.rb b/spree/core/app/workflows/spree/stock_receipts/recording.rbnew file mode 100644index 0000000000..f3ddcb7791--- /dev/null+++ b/spree/core/app/workflows/spree/stock_receipts/recording.rb@@ -0,0 +1,143 @@+module Spree+ module StockReceipts+ # The steps every delivery takes, whichever document it is against. The+ # workflow including this names the document (`receivable`), says when it+ # may be received (`ensure_receivable`), which lines are its own+ # (`line_belongs?`) and what a line's units cost (`unit_cost_for`).+ #+ # Quantities are this delivery's counts, not running totals: "forty+ # arrived, two of them crushed" is what the dock writes down, and what a+ # second delivery of the same line adds to rather than restates. Accepted+ # units reach the shelf; rejected ones exist only on the receipt.+ module Recording+ private++ def record_delivery+ # One delivery at a time per document. Each line's running total is+ # read and then written, so two deliveries booked at once would both+ # add to the same starting figure. The lock also opens the transaction+ # the writes need, and is always taken document-then-level, never the+ # other way, so it cannot cross with the lock+ # `StockLevel#adjust_count_on_hand` takes underneath.+ receivable.with_lock do+ # The caller resolved these before the lock, so their running totals+ # may predate a delivery that has since committed.+ items&.each { |item| item[:item]&.reload }++ step :ensure_receivable+ step :normalize_items+ run_hooks :validate++ step :build_receipt+ step :update_lines+ run_hooks :before_restock+ step :restock_accepted+ step :settle_status+ end++ run_hooks :after_receive+ receivable.publish_event("#{event_prefix}.#{receivable.status}")+ success(stock_receipt.reload)+ end++ # Nothing named means the whole outstanding balance arrived intact.+ def normalize_items+ @normalized_items =+ if items.nil?+ receivable.items.select { |line| line.outstanding.positive? }.map do |line|+ { line: line, quantity_accepted: line.outstanding, quantity_rejected: 0 }+ end+ else+ reject_repeated_lines+ Array(items).filter_map { |item| normalize_item(item) }+ end++ return if @normalized_items.any?++ failure(receivable, Spree.t("#{error_scope}.errors.no_items_received"))+ end++ # A line the payload names but counts nothing on is left out rather than+ # refused: a receive screen submits every row, most of them untouched.+ def normalize_item(item)+ line = item[:item]+ failure(receivable, Spree.t("#{error_scope}.errors.item_not_on_document")) unless line_belongs?(line)++ accepted = item[:quantity_accepted].to_i+ rejected = item[:quantity_rejected].to_i+ if accepted.negative? || rejected.negative?+ failure(receivable, Spree.t("#{error_scope}.errors.invalid_receipt_quantity", variant: line.variant_name))+ end+ return nil if accepted.zero? && rejected.zero?++ {+ line: line,+ quantity_accepted: accepted,+ quantity_rejected: rejected,+ rejection_reason: item[:rejection_reason].presence,+ notes: item[:notes].presence+ }+ end++ # Two entries for one line are genuinely ambiguous — two cartons, or a+ # correction of the first? — so they are refused rather than merged.+ def reject_repeated_lines+ lines = Array(items).map { |item| item[:item] }.compact+ repeated = lines.group_by(&:id).values.find { |group| group.length > 1 }+ return if repeated.nil?++ failure(receivable, Spree.t("#{error_scope}.errors.repeated_item", variant: repeated.first.variant_name))+ end++ def build_receipt+ @stock_receipt = receivable.stock_receipts.build(+ store: receivable.store,+ received_at: received_at.presence || Time.current,+ reference: reference,+ notes: notes,+ received_by: received_by+ )+ @normalized_items.each { |entry| @stock_receipt.items.build(entry) }++ failure(@stock_receipt) unless @stock_receipt.save+ end++ def update_lines+ @normalized_items.each do |entry|+ line = entry[:line]+ line.update!(+ quantity_received: line.quantity_received.to_i + entry[:quantity_accepted],+ quantity_rejected: line.quantity_rejected.to_i + entry[:quantity_rejected]+ )+ end+ end++ # Only accepted units land. The receipt is the cause, and brings the+ # document's own foreign key with it.+ def restock_accepted+ destination = receivable.destination_location++ @normalized_items.each do |entry|+ next unless entry[:quantity_accepted].positive?++ destination.restock(entry[:line].variant, entry[:quantity_accepted], stock_receipt,+ unit_cost: unit_cost_for(entry[:line]))+ end+ end++ # `received_at` is stamped only when the document actually closes, in+ # full or over — a partial delivery leaves it open.+ def settle_status+ # The caller's lines are freshly-loaded instances, not the ones the+ # association is holding, so the totals have to be re-read before they+ # can decide the status.+ receivable.items.reset+ status = receivable.status_after_receive+ attributes = { status: status }+ attributes[:received_at] = Time.current if Spree::Receivable::CLOSED_STATUSES.include?(status)++ failure(receivable) unless receivable.update(attributes)+ end+ end+ end+enddiff --git a/spree/core/app/workflows/spree/stock_transfers/cancel.rb b/spree/core/app/workflows/spree/stock_transfers/cancel.rbindex 01731b8fd9..a2c6d3bf9a 100644--- a/spree/core/app/workflows/spree/stock_transfers/cancel.rb+++ b/spree/core/app/workflows/spree/stock_transfers/cancel.rb@@ -61,10 +61,12 @@ module Spree# Read the running totals under the lock: an association loaded before# it holds the quantities as they were before any receive that has# since committed, and those are what `outstanding` subtracts from.+ return write_off if on_in_transit == 'write_off'+stock_transfer.items.reload.each do |item|next unless item.outstanding.positive?- on_in_transit == 'restock' ? restock(item) : write_off(item)+ restock(item)endend@@ -77,14 +79,15 @@ module Spree# Nothing to write to the shelf: the units left the source when the# transfer was marked in transit and never arrived anywhere, so the loss- # is already in the ledger. What is missing is why, and that goes on the- # line the merchant is looking at.- def write_off(item)- item.update!(discrepancy_reason: reason.presence || DEFAULT_WRITE_OFF_REASON)+ # is already in the ledger. What is missing is why, and that is recorded+ # as the reason the transfer closed — the same place a short close puts+ # it.+ def write_off+ @close_reason = reason.presence || DEFAULT_WRITE_OFF_REASONenddef mark_canceled- failure(stock_transfer) unless stock_transfer.update(status: 'canceled')+ failure(stock_transfer) unless stock_transfer.update(status: 'canceled', close_reason: @close_reason)endendenddiff --git a/spree/core/app/workflows/spree/stock_transfers/close.rb b/spree/core/app/workflows/spree/stock_transfers/close.rbnew file mode 100644index 0000000000..72bc45a71b--- /dev/null+++ b/spree/core/app/workflows/spree/stock_transfers/close.rb@@ -0,0 +1,47 @@+module Spree+ module StockTransfers+ # Ends a transfer whose missing units are not going to turn up.+ #+ # Eight of ten arrived and the box is not coming back for the other two.+ # The units already left the source when the transfer went in transit, so+ # nothing is written to any shelf: closing short keeps what the+ # destination counted in, records why the rest never arrived, and leaves+ # the outstanding count on each line as the record of the loss.+ class Close < Spree::Workflow+ hooks :validate, :after_close++ attr_reader :stock_transfer, :reason++ # @param stock_transfer [Spree::StockTransfer]+ # @param reason [String, nil] what happened to the balance+ def perform(stock_transfer:, reason: nil)+ super++ stock_transfer.with_lock do+ step :ensure_closable+ run_hooks :validate+ step :close_short+ end++ run_hooks :after_close+ stock_transfer.publish_event('stock_transfer.received')+ success(stock_transfer.reload)+ end++ private++ def ensure_closable+ return if stock_transfer.partially_received?++ failure(stock_transfer, Spree.t('stock_transfer.errors.not_partially_received'))+ end++ def close_short+ now = Time.current+ attributes = { status: 'received', received_at: now, closed_short_at: now, close_reason: reason.presence }++ failure(stock_transfer) unless stock_transfer.update(attributes)+ end+ end+ end+enddiff --git a/spree/core/app/workflows/spree/stock_transfers/mark_draft.rb b/spree/core/app/workflows/spree/stock_transfers/mark_draft.rbnew file mode 100644index 0000000000..5eda730669--- /dev/null+++ b/spree/core/app/workflows/spree/stock_transfers/mark_draft.rb@@ -0,0 +1,41 @@+module Spree+ module StockTransfers+ # Unfreezes a packed transfer so its lines can be changed again.+ #+ # Only from `ready_to_ship`: nothing has left the source yet, so there is+ # nothing to undo. Once the van has gone, what is in the box is a matter+ # of record.+ class MarkDraft < Spree::Workflow+ hooks :validate, :after_mark_draft++ attr_reader :stock_transfer++ # @param stock_transfer [Spree::StockTransfer]+ def perform(stock_transfer:)+ super++ stock_transfer.with_lock do+ step :ensure_returnable+ run_hooks :validate+ step :return_to_draft+ end++ run_hooks :after_mark_draft+ stock_transfer.publish_event('stock_transfer.draft')+ success(stock_transfer.reload)+ end++ private++ def ensure_returnable+ return if stock_transfer.ready_to_ship?++ failure(stock_transfer, Spree.t('stock_transfer.errors.not_ready_to_ship'))+ end++ def return_to_draft+ failure(stock_transfer) unless stock_transfer.update(status: 'draft')+ end+ end+ end+enddiff --git a/spree/core/app/workflows/spree/stock_transfers/receive.rb b/spree/core/app/workflows/spree/stock_transfers/receive.rbindex f409be32e1..298f15f7df 100644--- a/spree/core/app/workflows/spree/stock_transfers/receive.rb+++ b/spree/core/app/workflows/spree/stock_transfers/receive.rb@@ -1,148 +1,61 @@module Spreemodule StockTransfers- # Records what the destination warehouse actually counted in.+ # Records one delivery the destination warehouse counted in, as a stock+ # receipt.## Partial receipt is the normal case, not an edge case: ten left, eight- # arrived, two were crushed in transit. Quantities therefore come from the- # caller — `quantity_received` is the running total for the line, so a- # second receive of the same box tops it up rather than starting over — and- # only the difference from last time is written to the shelf.+ # arrived, two were crushed in transit. A delivery is booked as its own+ # receipt — what was accepted, what was refused and why — and adds to the+ # line's running total, so a second box tops it up rather than restating+ # it. Only accepted units reach the shelf.class Receive < Spree::Workflow+ include Spree::StockReceipts::Recording+hooks :validate, :before_restock, :after_receive+ attr_reader :stock_transfer, :items, :received_at, :reference, :notes, :received_by,+ :stock_receipt+# @param stock_transfer [Spree::StockTransfer]- # @param items [Array<Hash>, nil] `[{ item:, quantity_received:,- # discrepancy_reason: }]`; nil receives every line in full+ # @param items [Array<Hash>, nil] `[{ item:, quantity_accepted:,+ # quantity_rejected:, rejection_reason:, notes: }]` — this delivery's+ # counts; nil books everything still outstanding, intact+ # @param received_at [Time, nil] defaults to now+ # @param reference [String, nil] the carrier's or packer's note+ # @param notes [String, nil]# @param received_by [Object, nil]- def perform(stock_transfer:, items: nil, received_by: nil)+ def perform(stock_transfer:, items: nil, received_at: nil, reference: nil, notes: nil, received_by: nil)super-- # One receive at a time per document. Each line's delta is measured- # against its running total, so two callers reading the same total both- # credit the whole delivery — three concurrent receives of ten units put- # thirty on the shelf and leave the line saying ten. The lock also opens- # the transaction the writes below need, and it is always taken- # document-then-level, never the other way, so it cannot cross with the- # lock `StockLevel#adjust_count_on_hand` takes underneath.- stock_transfer.with_lock do- # The caller resolved these before the lock, so their running totals- # may predate a receive that has since committed.- items&.each { |item| item[:item]&.reload }-- step :ensure_receivable- step :normalize_items- run_hooks :validate-- step :record_receipt- run_hooks :before_restock- step :restock_deltas- step :settle_status- end-- run_hooks :after_receive- stock_transfer.publish_event("stock_transfer.#{stock_transfer.status}")- success(stock_transfer.reload)+ record_deliveryendprivate- def ensure_receivable- return if stock_transfer.in_flight?-- failure(stock_transfer, Spree.t('stock_transfer.errors.not_in_transit'))+ def receivable+ stock_transferend- def normalize_items- @normalized_items =- if items.nil?- stock_transfer.items.map do |line|- { item: line, quantity_received: line.quantity_shipped,- delta: line.outstanding }- end- else- reject_repeated_lines- Array(items).map { |item| normalize_item(item) }- end-- return if @normalized_items.any? { |item| item[:delta].positive? }-- failure(stock_transfer, Spree.t('stock_transfer.errors.no_items_received'))+ def event_prefix+ 'stock_transfer'end- # The running total may only go up: un-receiving units already put on- # the shelf is a correction, which is what a manual adjustment is for.- def normalize_item(item)- line = item[:item]- failure(stock_transfer, Spree.t('stock_transfer.errors.item_not_on_transfer')) unless- line&.stock_transfer_id == stock_transfer.id-- quantity = item[:quantity_received].to_i- if quantity.negative? || quantity > line.quantity_shipped || quantity < line.quantity_received- failure(stock_transfer, Spree.t('stock_transfer.errors.invalid_received_quantity',- variant: line.variant_name, shipped: line.quantity_shipped))- end-- normalized = {- item: line,- quantity_received: quantity,- 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-- # Every delta is measured against the line's running total before any of- # them is written, so a line named twice contributes its delta once per- # entry: entries of four and six against a fresh line put ten on the- # shelf while the line records six. Refused rather than merged, because- # those two entries are genuinely ambiguous — ten in total, or six- # correcting four? A scanner that appends an entry per carton has to send- # the total instead.- def reject_repeated_lines- lines = Array(items).map { |item| item[:item] }.compact- repeated = lines.group_by(&:id).values.find { |group| group.length > 1 }- return if repeated.nil?-- failure(stock_transfer, Spree.t('stock_transfer.errors.repeated_item', variant: repeated.first.variant_name))+ def error_scope+ 'stock_transfer'end- def record_receipt- @normalized_items.each do |item|- attributes = { quantity_received: item[:quantity_received] }- attributes[:discrepancy_reason] = item[:discrepancy_reason] if item.key?(:discrepancy_reason)+ def ensure_receivable+ return if stock_transfer.in_flight?- item[:item].update!(attributes)- end+ failure(stock_transfer, Spree.t('stock_transfer.errors.not_in_transit'))end- # Only the difference lands on the shelf. A second receive that tops a- # line up from eight to ten adds two, not ten.- def restock_deltas- destination = stock_transfer.destination_location-- @normalized_items.each do |item|- next unless item[:delta].positive?-- destination.restock(item[:item].variant, item[:delta], stock_transfer)- end+ def line_belongs?(line)+ line&.stock_transfer_id == stock_transfer.idend- # `received` once every line is complete, `partially_received` while any- # is still owed — and `received_at` is stamped only when the trip is- # actually over.- def settle_status- # The caller's lines are freshly-loaded instances, not the ones the- # association is holding, so the totals have to be re-read before they- # can decide the status.- stock_transfer.items.reset- status = stock_transfer.status_after_receive- attributes = { status: status }- attributes[:received_at] = Time.current if status == 'received'-- failure(stock_transfer) unless stock_transfer.update(attributes)+ # Moving stock a merchant already owns is not a purchase.+ def unit_cost_for(_line)+ nilendendenddiff --git a/spree/core/config/locales/en.yml b/spree/core/config/locales/en.ymlindex 8a2cc1a177..5a4a4738d3 100644--- a/spree/core/config/locales/en.yml+++ b/spree/core/config/locales/en.yml@@ -1623,15 +1623,31 @@ en:purchase_order:errors:already_closed: This purchase order has already been received or cancelled- invalid_received_quantity: Received quantity for %{variant} must be between what was already received and the %{ordered} ordered- item_not_on_order: One of the lines does not belong to this purchase order+ already_receiving: A delivery has already been booked against this purchase order, so it cannot go back to draft+ invalid_receipt_quantity: The quantities for %{variant} cannot be negative+ item_not_on_document: One of the lines does not belong to this purchase ordermust_have_variant: You must add at least one variantno_items_received: No units were receivednot_draft: Only a draft purchase order can be marked as orderednot_editable: Only a draft purchase order can be editednot_ordered: Only a purchase order that has been placed can be received+ not_ordered_for_draft: Only a placed purchase order can go back to draft+ not_partially_received: Only a partially received purchase order can be closed shortonly_draft_can_be_deleted: Only a draft purchase order can be deleted — cancel it instead- repeated_item: "%{variant} was listed more than once. Send one entry per line, with the total received so far"+ repeated_item: "%{variant} was listed more than once. Send one entry per line, with what this delivery brought"+ purchase_order_import_ambiguous_sku: More than one product in this store has the SKU %{sku}. Give each a SKU of its own before importing an order for it.+ purchase_order_import_destination_required: Destination is required.+ purchase_order_import_failed: The purchase order could not be written.+ purchase_order_import_invalid_cost: unit_cost must be a number like 16.50, got %{value}.+ purchase_order_import_invalid_date: "%{column} must be a full date like 2026-03-31, got %{value}."+ purchase_order_import_invalid_quantity: quantity must be a whole number above zero, got %{value}.+ purchase_order_import_reference_required: Reference is required — it is what groups a file's rows into orders.+ purchase_order_import_sku_required: SKU is required.+ purchase_order_import_supplier_required: Supplier is required.+ purchase_order_import_unknown_destination: This store has no warehouse named %{name}.+ purchase_order_import_unknown_sku: No product in this store has the SKU %{sku}.+ purchase_order_import_unknown_supplier: This store has no supplier named %{name}. Add them first.+ purchase_order_import_unsupported_currency: This store does not buy in %{currency}.qty: Qtyquantity: Quantityquery: Query@@ -1887,22 +1903,32 @@ en:reasons:manual_adjustment: Manual adjustmentstock_movements: Stock Movements+ stock_receipt:+ errors:+ nothing_counted: A line on a delivery must count at least one unit, accepted or rejected+ rejection_reasons:+ damaged: Damaged+ expired: Expired+ other: Other+ wrong_item: Wrong itemstock_transfer:errors:already_closed: This transfer has already been completed or cancelledin_transit_resolution_required: Choose whether the units come back to the source warehouse or are written offinvalid_quantity: Every variant must move a quantity above zero- invalid_received_quantity: Received quantity for %{variant} must be between what was already received and the %{shipped} shipped- item_not_on_transfer: One of the lines does not belong to this transfer+ invalid_receipt_quantity: The quantities for %{variant} cannot be negative+ item_not_on_document: One of the lines does not belong to this transferlocations_in_different_stores: must belong to the same store as the source locationmust_have_variant: You must add at least one variantno_items_received: No units were receivednot_draft: Only a draft transfer can be marked as ready to shipnot_editable: Only a draft transfer can be editednot_in_transit: Only a transfer in transit can be received+ not_partially_received: Only a partially received transfer can be closed short+ not_ready_to_ship: Only a transfer that is ready to ship can go back to draftnot_shippable: Only a draft or ready-to-ship transfer can be marked in transitonly_draft_can_be_deleted: Only a draft transfer can be deleted — cancel it instead- repeated_item: "%{variant} was listed more than once. Send one entry per line, with the total received so far"+ repeated_item: "%{variant} was listed more than once. Send one entry per line, with what this delivery brought"same_location: cannot be the same as the destination locationvariants_unavailable: Some variants are not available on %{stock}stop: Stopdiff --git a/spree/core/db/migrate/20260910000001_add_stock_receipts.rb b/spree/core/db/migrate/20260910000001_add_stock_receipts.rbnew file mode 100644index 0000000000..4e385e5186--- /dev/null+++ b/spree/core/db/migrate/20260910000001_add_stock_receipts.rb@@ -0,0 +1,44 @@+class AddStockReceipts < ActiveRecord::Migration[8.1]+ def change+ create_table :spree_stock_receipts do |t|+ t.string :number, null: false+ t.references :store, null: false+ t.references :receivable, polymorphic: true, null: false+ t.string :reference+ t.datetime :received_at, null: false+ t.bigint :received_by_id+ t.text :notes+ if t.respond_to?(:jsonb)+ t.jsonb :metadata+ else+ t.json :metadata+ end+ t.timestamps+ end+ add_index :spree_stock_receipts, :number, unique: true+ add_index :spree_stock_receipts, :received_by_id++ create_table :spree_stock_receipt_items do |t|+ t.references :stock_receipt, null: false+ t.references :line, polymorphic: true, null: false+ t.integer :quantity_accepted, null: false, default: 0+ t.integer :quantity_rejected, null: false, default: 0+ t.string :rejection_reason+ t.text :notes+ t.timestamps+ end++ add_column :spree_purchase_order_items, :quantity_rejected, :integer, null: false, default: 0+ add_column :spree_stock_transfer_items, :quantity_rejected, :integer, null: false, default: 0+ remove_column :spree_stock_transfer_items, :discrepancy_reason, :string++ add_column :spree_purchase_orders, :cancel_by, :date+ add_column :spree_purchase_orders, :closed_short_at, :datetime+ add_column :spree_purchase_orders, :close_reason, :text+ add_column :spree_stock_transfers, :closed_short_at, :datetime+ add_column :spree_stock_transfers, :close_reason, :text++ add_column :spree_stock_movements, :stock_receipt_id, :bigint+ add_index :spree_stock_movements, :stock_receipt_id+ end+enddiff --git a/spree/core/lib/spree/core/dependencies.rb b/spree/core/lib/spree/core/dependencies.rbindex a83c41ac21..3204cbdd3a 100644--- a/spree/core/lib/spree/core/dependencies.rb+++ b/spree/core/lib/spree/core/dependencies.rb@@ -103,11 +103,15 @@ module Spreestock_transfer_mark_in_transit_workflow: 'Spree::StockTransfers::MarkInTransit',stock_transfer_receive_workflow: 'Spree::StockTransfers::Receive',stock_transfer_cancel_workflow: 'Spree::StockTransfers::Cancel',+ stock_transfer_mark_draft_workflow: 'Spree::StockTransfers::MarkDraft',+ stock_transfer_close_workflow: 'Spree::StockTransfers::Close',purchase_order_create_workflow: 'Spree::PurchaseOrders::Create',purchase_order_update_workflow: 'Spree::PurchaseOrders::Update',purchase_order_mark_ordered_workflow: 'Spree::PurchaseOrders::MarkOrdered',purchase_order_receive_workflow: 'Spree::PurchaseOrders::Receive',purchase_order_cancel_workflow: 'Spree::PurchaseOrders::Cancel',+ purchase_order_mark_draft_workflow: 'Spree::PurchaseOrders::MarkDraft',+ purchase_order_close_workflow: 'Spree::PurchaseOrders::Close',# returnsreturn_create_workflow: 'Spree::Returns::Create',diff --git a/spree/core/lib/spree/core/engine.rb b/spree/core/lib/spree/core/engine.rbindex 13546f3e76..4d011d0cbb 100644--- a/spree/core/lib/spree/core/engine.rb+++ b/spree/core/lib/spree/core/engine.rb@@ -458,14 +458,16 @@ module SpreeSpree::Exports::GiftCards,Spree::Exports::NewsletterSubscribers,Spree::Exports::CouponCodes,- Spree::Exports::PriceListPrices+ Spree::Exports::PriceListPrices,+ Spree::Exports::PurchaseOrders]Rails.application.config.spree.import_types = [Spree::Imports::Products,Spree::Imports::ProductTranslations,Spree::Imports::Customers,- Spree::Imports::PriceListPrices+ Spree::Imports::PriceListPrices,+ Spree::Imports::PurchaseOrders]Rails.application.config.spree.taxon_rules = [diff --git a/spree/core/lib/spree/core/permission_configuration.rb b/spree/core/lib/spree/core/permission_configuration.rbindex 3461d7cce6..db240da364 100644--- a/spree/core/lib/spree/core/permission_configuration.rb+++ b/spree/core/lib/spree/core/permission_configuration.rb@@ -364,7 +364,8 @@ module Spree})register_resource(:stock, group: :catalog, audiences: %i[seller], subjects: -> {[Spree::StockLevel, Spree::StockLocation, Spree::StockMovement,- Spree::StockTransfer, Spree::StockTransferItem, Spree::StockReservation]+ Spree::StockTransfer, Spree::StockTransferItem, Spree::StockReservation,+ Spree::StockReceipt, Spree::StockReceiptItem]})# Buying goods in, which is a different job from moving the goods you# already have: `write_stock` must not also mean "may place orders with@@ -372,7 +373,8 @@ module Spree# seller audience — a marketplace seller does not purchase on the# operator's account.register_resource(:purchasing, group: :catalog, subjects: -> {- [Spree::Supplier, Spree::PurchaseOrder, Spree::PurchaseOrderItem]+ [Spree::Supplier, Spree::PurchaseOrder, Spree::PurchaseOrderItem,+ Spree::StockReceipt, Spree::StockReceiptItem]})register_resource(:promotions, group: :marketing, subjects: -> {diff --git a/spree/core/lib/spree/testing_support/factories/import_factory.rb b/spree/core/lib/spree/testing_support/factories/import_factory.rbindex b64fccad79..3e1644a5ed 100644--- a/spree/core/lib/spree/testing_support/factories/import_factory.rb+++ b/spree/core/lib/spree/testing_support/factories/import_factory.rb@@ -49,6 +49,18 @@ FactoryBot.define doendend+ factory :purchase_orders_import, class: 'Spree::Imports::PurchaseOrders', parent: :import do+ type { 'Spree::Imports::PurchaseOrders' }++ after(:build) do |import|+ import.attachment.attach(+ io: StringIO.new(Spree::ImportSchemas::PurchaseOrders.new.headers.join(',') + "\n"),+ filename: 'purchase_orders_import.csv',+ content_type: 'text/csv'+ )+ end+ end+factory :customer_import, class: 'Spree::Imports::Customers', parent: :import dotype { 'Spree::Imports::Customers' }diff --git a/spree/core/lib/spree/testing_support/factories/stock_receipt_factory.rb b/spree/core/lib/spree/testing_support/factories/stock_receipt_factory.rbnew file mode 100644index 0000000000..bd02801e76--- /dev/null+++ b/spree/core/lib/spree/testing_support/factories/stock_receipt_factory.rb@@ -0,0 +1,37 @@+FactoryBot.define do+ # The record only. Building one here books nothing: line totals and stock+ # movements are written by the receive workflows, which is what a spec that+ # needs a real delivery should call.+ factory :stock_receipt, class: Spree::StockReceipt do+ transient do+ quantity_accepted { nil }+ quantity_rejected { 0 }+ rejection_reason { nil }+ end++ receivable { create(:purchase_order, :ordered) }+ store { receivable.store }+ received_at { Time.current }+ reference { 'Delivery note 4471' }++ after(:build) do |receipt, evaluator|+ next if receipt.items.any?++ receipt.receivable.items.each do |line|+ receipt.items.build(+ line: line,+ quantity_accepted: evaluator.quantity_accepted || line.outstanding,+ quantity_rejected: evaluator.quantity_rejected,+ rejection_reason: evaluator.rejection_reason+ )+ end+ end+ end++ factory :stock_receipt_item, class: Spree::StockReceiptItem do+ stock_receipt+ line { create(:purchase_order_item) }+ quantity_accepted { 5 }+ quantity_rejected { 0 }+ end+enddiff --git a/spree/core/lib/tasks/inventory_operations_migration.rake b/spree/core/lib/tasks/inventory_operations_migration.rakeindex 22650ab941..66d21bd79c 100644--- a/spree/core/lib/tasks/inventory_operations_migration.rake+++ b/spree/core/lib/tasks/inventory_operations_migration.rake@@ -62,7 +62,11 @@ module Spreeraise ActiveRecord::Rollbackend- Spree::StockMovement.where(id: movements.map(&:id)).update_all(purchase_order_id: purchase_order.id)+ receipt = mint_receipt(purchase_order, transfer)+ Spree::StockMovement.where(id: movements.map(&:id)).update_all(+ purchase_order_id: purchase_order.id,+ stock_receipt_id: receipt.id+ )transfer.update_columns(status: 'received', deleted_at: Time.current)@output.puts " #{transfer.number} → #{purchase_order.number} (#{purchase_order.items.size} line(s))"@@ -95,6 +99,22 @@ module Spreepurchase_orderend+ # The receive itself, as the record every later delivery gets: one+ # receipt, dated when the transfer was, accepting every line in full.+ def mint_receipt(purchase_order, transfer)+ receipt = purchase_order.stock_receipts.build(+ store: purchase_order.store,+ received_at: transfer.created_at,+ reference: transfer.number,+ notes: "Migrated from stock transfer #{transfer.number}."+ )+ purchase_order.items.each do |item|+ receipt.items.build(line: item, quantity_accepted: item.quantity_received)+ end+ receipt.save!+ receipt+ end+# One line per variant, summing the movements that named it: a 5.x receive# of five SKUs is five movement rows whose only link is the transfer.#diff --git a/spree/core/spec/lib/tasks/inventory_operations_migration_spec.rb b/spree/core/spec/lib/tasks/inventory_operations_migration_spec.rbindex b351978beb..e7e74dbca4 100644--- a/spree/core/spec/lib/tasks/inventory_operations_migration_spec.rb+++ b/spree/core/spec/lib/tasks/inventory_operations_migration_spec.rb@@ -53,13 +53,28 @@ describe 'spree:upgrade inventory operations' doexpect(Spree::PurchaseOrder.last.items.sole.unit_cost).to eq(0)end- it 're-points the existing movements at the purchase order' do+ it 're-points the existing movements at the purchase order and its receipt' dotransfer = legacy_external_receive(quantity: 7)movement = transfer.stock_movements.solerun_task- expect(movement.reload.purchase_order).to eq(Spree::PurchaseOrder.last)+ purchase_order = Spree::PurchaseOrder.last+ expect(movement.reload.purchase_order).to eq(purchase_order)+ expect(movement.stock_receipt).to eq(purchase_order.stock_receipts.sole)+ end++ # The receive reads the way every later delivery will: one receipt, dated+ # when the transfer was, accepting every line in full.+ it 'records the receive as a stock receipt' do+ transfer = legacy_external_receive(quantity: 7)++ run_task++ receipt = Spree::PurchaseOrder.last.stock_receipts.sole+ expect(receipt.reference).to eq(transfer.number)+ expect(receipt.received_at).to be_within(1.second).of(transfer.created_at)+ expect(receipt.items.sole).to have_attributes(quantity_accepted: 7, quantity_rejected: 0)end# The number has to stay findable for historical reporting, without thediff --git a/spree/core/spec/models/spree/exports/purchase_orders_spec.rb b/spree/core/spec/models/spree/exports/purchase_orders_spec.rbnew file mode 100644index 0000000000..69662073b8--- /dev/null+++ b/spree/core/spec/models/spree/exports/purchase_orders_spec.rb@@ -0,0 +1,60 @@+require 'spec_helper'++RSpec.describe Spree::Exports::PurchaseOrders, type: :model do+ let(:store) { @default_store }+ let(:user) { create(:admin_user) }+ let(:supplier) { create(:supplier, store: store, name: 'Acme Wholesale') }+ let(:destination) { create(:stock_location, store: store, name: 'Brooklyn') }+ let(:product) { create(:product, name: 'Denim Shirt', store: store) }+ let(:variant) { create(:variant, product: product, sku: 'DENIM-M') }++ let!(:purchase_order) do+ create(:purchase_order, store: store, supplier: supplier, destination_location: destination, quantity: 0).tap do |order|+ order.items.create!(variant: variant, quantity_ordered: 24, quantity_received: 20, quantity_rejected: 2, unit_cost: 12.5)+ order.update!(reference: 'ACME-0042', expected_at: Date.new(2026, 10, 1), cancel_by: Date.new(2026, 10, 15))+ end+ end++ def build_export(search_params: nil, record_selection: 'all')+ described_class.new(store: store, user: user, search_params: search_params, record_selection: record_selection)+ end++ describe '#generate_csv' do+ it 'writes one row per line with the order alongside, importable as it stands' do+ export = build_export+ export.save!+ export.generate++ rows = CSV.parse(export.attachment.download, headers: true)+ expect(rows.headers).to eq(Spree::CSV::PurchaseOrderItemPresenter::HEADERS)+ expect(rows.headers.first(Spree::ImportSchemas::PurchaseOrders.new.headers.size)).to eq(+ Spree::ImportSchemas::PurchaseOrders.new.headers+ )++ row = rows.sole.to_h+ expect(row).to include(+ 'reference' => 'ACME-0042', 'supplier' => 'Acme Wholesale', 'destination' => 'Brooklyn',+ 'sku' => 'DENIM-M', 'quantity' => '24', 'unit_cost' => '12.50', 'currency' => store.default_currency,+ 'expected_at' => '2026-10-01', 'cancel_by' => '2026-10-15',+ 'number' => purchase_order.number, 'status' => 'draft', 'product_name' => 'Denim Shirt',+ 'received' => '20', 'rejected' => '2'+ )+ end++ it 'narrows to the orders a filter names' do+ other = create(:purchase_order, store: store)++ export = build_export(search_params: { number_eq: other.number }, record_selection: 'filtered')+ export.save!+ export.generate++ rows = CSV.parse(export.attachment.download, headers: true)+ expect(rows.map { |row| row['number'] }).to eq([other.number])+ end+ end++ it 'is gated by the purchasing scope, like the purchase order endpoints' do+ expect(described_class.required_scope).to eq(:purchasing)+ expect(described_class.model_class).to eq(Spree::PurchaseOrder)+ end+enddiff --git a/spree/core/spec/models/spree/purchase_order_spec.rb b/spree/core/spec/models/spree/purchase_order_spec.rbindex 4f96fcc8ab..7a3a88749b 100644--- a/spree/core/spec/models/spree/purchase_order_spec.rb+++ b/spree/core/spec/models/spree/purchase_order_spec.rb@@ -84,13 +84,14 @@ module Spreeexpect(item.display_unit_cost.to_s).to eq('$12.50')end- # A receive of twelve against ten ordered is a miscount at the dock, so- # the error belongs on the value the caller sent.- it 'refuses to receive more than was ordered' do- item.quantity_received = 11-- expect(item).to be_invalid- expect(item.errors[:quantity_received]).to be_present+ # Twelve against ten ordered is what the supplier sent, so the line+ # reports it rather than refusing it.+ it 'reports units above the order as over-received, and owes nothing' do+ item.quantity_received = 12++ expect(item).to be_valid+ expect(item).to have_attributes(quantity_over: 2, outstanding: 0)+ expect(item).to be_over_receivedendendenddiff --git a/spree/core/spec/models/spree/stock_movement_spec.rb b/spree/core/spec/models/spree/stock_movement_spec.rbindex 2cc714974b..c97ae632a5 100644--- a/spree/core/spec/models/spree/stock_movement_spec.rb+++ b/spree/core/spec/models/spree/stock_movement_spec.rb@@ -144,7 +144,8 @@ describe Spree::StockMovement, type: :model doit 'exposes the kind and every cause key' doexpect(Spree::StockMovement.whitelisted_ransackable_attributes).to eq(%w[quantity kind reason created_at stock_level_id stock_item_id order_id fulfillment_id- return_id exchange_id stock_transfer_id purchase_order_id unit_cost]+ return_id exchange_id stock_transfer_id purchase_order_id stock_receipt_id+ unit_cost])enddiff --git a/spree/core/spec/models/spree/stock_receipt_spec.rb b/spree/core/spec/models/spree/stock_receipt_spec.rbnew file mode 100644index 0000000000..59a312a34f--- /dev/null+++ b/spree/core/spec/models/spree/stock_receipt_spec.rb@@ -0,0 +1,80 @@+require 'spec_helper'++describe Spree::StockReceipt, type: :model do+ let(:store) { @default_store }+ let(:purchase_order) { create(:purchase_order, :ordered, store: store, quantity: 10) }++ describe 'a delivery' do+ it 'is numbered, dated and owned by its document\'s store' do+ receipt = create(:stock_receipt, receivable: purchase_order)++ expect(receipt.number).to start_with('SR')+ expect(receipt.store).to eq(store)+ expect(receipt.received_at).to be_present+ expect(receipt.items.sole).to have_attributes(line: purchase_order.items.sole, quantity_accepted: 10)+ end++ it 'has to bring something' do+ receipt = build(:stock_receipt, receivable: purchase_order)+ receipt.items.clear++ expect(receipt).to be_invalid+ expect(receipt.errors[:items]).to be_present+ end++ it 'totals what it accepted and what it refused' do+ receipt = build(:stock_receipt, receivable: purchase_order, quantity_accepted: 7,+ quantity_rejected: 3, rejection_reason: 'damaged')++ expect(receipt.quantity_accepted_total).to eq(7)+ expect(receipt.quantity_rejected_total).to eq(3)+ end++ it 'is found from the document it was booked against' do+ receipt = create(:stock_receipt, receivable: purchase_order)++ expect(purchase_order.reload.stock_receipts).to eq([receipt])+ end+ end++ describe 'a line on it' do+ let(:line) { purchase_order.items.sole }+ let(:receipt) { create(:stock_receipt, receivable: purchase_order) }++ it 'counts accepted and rejected units together' do+ item = build(:stock_receipt_item, stock_receipt: receipt, line: line, quantity_accepted: 4,+ quantity_rejected: 1, rejection_reason: 'wrong_item')++ expect(item).to be_valid+ expect(item.quantity_counted).to eq(5)+ expect(item.variant).to eq(line.variant)+ end++ it 'must count something' do+ item = build(:stock_receipt_item, stock_receipt: receipt, line: line, quantity_accepted: 0)++ expect(item).to be_invalid+ expect(item.errors[:base]).to include(Spree.t('stock_receipt.errors.nothing_counted'))+ end++ it 'needs a known reason for whatever it refused' do+ item = build(:stock_receipt_item, stock_receipt: receipt, line: line, quantity_accepted: 4,+ quantity_rejected: 1)++ expect(item).to be_invalid+ expect(item.errors[:rejection_reason]).to be_present++ item.rejection_reason = 'crushed'+ expect(item).to be_invalid++ item.rejection_reason = 'damaged'+ expect(item).to be_valid+ end++ it 'refuses a negative count' do+ item = build(:stock_receipt_item, stock_receipt: receipt, line: line, quantity_accepted: -1)++ expect(item).to be_invalid+ end+ end+enddiff --git a/spree/core/spec/models/spree/stock_transfer_spec.rb b/spree/core/spec/models/spree/stock_transfer_spec.rbindex 5dfd7fe795..17fb5362dc 100644--- a/spree/core/spec/models/spree/stock_transfer_spec.rb+++ b/spree/core/spec/models/spree/stock_transfer_spec.rb@@ -105,7 +105,7 @@ module Spreeendit 'is under-received while any line is still owed' do- expect(transfer).to be_under_received+ expect(transfer).to be_shortexpect(transfer).not_to be_fully_receivedexpect(transfer.status_after_receive).to eq('partially_received')enddiff --git a/spree/core/spec/services/spree/imports/row_processors/purchase_order_spec.rb b/spree/core/spec/services/spree/imports/row_processors/purchase_order_spec.rbnew file mode 100644index 0000000000..41d2f9206d--- /dev/null+++ b/spree/core/spec/services/spree/imports/row_processors/purchase_order_spec.rb@@ -0,0 +1,100 @@+require 'spec_helper'++RSpec.describe Spree::Imports::RowProcessors::PurchaseOrder, type: :service do+ let(:store) { @default_store }+ let(:import) { create(:purchase_orders_import, store: store) }+ let(:csv_row_headers) { Spree::ImportSchemas::PurchaseOrders.new.headers }++ let!(:supplier) { create(:supplier, store: store, name: 'Acme Wholesale') }+ let!(:destination) { create(:stock_location, store: store, name: 'Brooklyn') }+ let(:product) { create(:product, store: store) }+ let!(:variant) { create(:variant, product: product, sku: 'DENIM-M') }+ let!(:other_variant) { create(:variant, product: product, sku: 'DENIM-L') }++ before do+ Spree.import_start_mapping_workflow.call(import: import)+ end++ def csv_row_hash(attrs = {})+ csv_row_headers.index_with { |header| attrs[header] }+ end++ def process(attrs)+ row = create(:import_row, import: import, data: csv_row_hash(attrs).to_json)+ described_class.new(row).process!+ end++ let(:line) do+ { 'reference' => 'ACME-0042', 'supplier' => 'acme wholesale', 'destination' => 'Brooklyn',+ 'sku' => 'DENIM-M', 'quantity' => '24', 'unit_cost' => '12.50' }+ end++ it 'opens a draft order for the row through the same workflow the screen uses' do+ purchase_order = process(line.merge('currency' => 'usd', 'expected_at' => '2026-10-01',+ 'cancel_by' => '2026-10-15', 'notes' => 'Autumn buy'))++ expect(purchase_order).to be_a(Spree::PurchaseOrder)+ expect(purchase_order).to be_draft+ expect(purchase_order).to have_attributes(+ supplier: supplier, destination_location: destination, reference: 'ACME-0042', currency: 'USD',+ expected_at: Date.new(2026, 10, 1), cancel_by: Date.new(2026, 10, 15), notes: 'Autumn buy'+ )+ expect(purchase_order.created_by).to eq(import.user)+ expect(purchase_order.items.sole).to have_attributes(variant: variant, quantity_ordered: 24, unit_cost: 12.5)+ end++ it 'adds later rows with the same reference to that order, totalling a repeated SKU' do+ first = process(line)+ process(line.merge('sku' => 'DENIM-L', 'quantity' => '6', 'unit_cost' => '13.00'))+ second = process(line.merge('quantity' => '12'))++ expect(second).to eq(first)+ expect(Spree::PurchaseOrder.count).to eq(1)+ lines = first.reload.items.map { |item| [item.variant.sku, item.quantity_ordered, item.unit_cost] }+ expect(lines).to contain_exactly(['DENIM-M', 36, 12.5], ['DENIM-L', 6, 13.0])+ end++ it 'opens a separate order for each reference' do+ process(line)+ process(line.merge('reference' => 'ACME-0043'))++ expect(Spree::PurchaseOrder.pluck(:reference)).to contain_exactly('ACME-0042', 'ACME-0043')+ end++ it 'names suppliers and warehouses rather than creating them' do+ expect { process(line.merge('supplier' => 'Nobody')) }.+ to raise_error(ArgumentError, Spree.t(:purchase_order_import_unknown_supplier, name: 'Nobody'))+ expect { process(line.merge('destination' => 'Mars')) }.+ to raise_error(ArgumentError, Spree.t(:purchase_order_import_unknown_destination, name: 'Mars'))+ expect(Spree::Supplier.count).to eq(1)+ expect(Spree::PurchaseOrder.count).to eq(0)+ end++ it 'needs the SKU to exist, once' do+ expect { process(line.merge('sku' => 'NOPE')) }.+ to raise_error(ArgumentError, Spree.t(:purchase_order_import_unknown_sku, sku: 'NOPE'))++ # Past the SKU validation, the way a legacy catalogue can be.+ create(:variant, product: create(:product, store: store)).update_columns(sku: 'denim-m')+ expect { process(line) }.+ to raise_error(ArgumentError, Spree.t(:purchase_order_import_ambiguous_sku, sku: 'DENIM-M'))+ end++ it 'refuses a reference-less row, since nothing could group it' do+ expect { process(line.merge('reference' => ' ')) }.+ to raise_error(ArgumentError, Spree.t(:purchase_order_import_reference_required))+ end++ it 'refuses quantities, costs, currencies and dates it cannot read' do+ expect { process(line.merge('quantity' => '0')) }.+ to raise_error(ArgumentError, Spree.t(:purchase_order_import_invalid_quantity, value: '0'))+ expect { process(line.merge('quantity' => 'ten')) }.+ to raise_error(ArgumentError, Spree.t(:purchase_order_import_invalid_quantity, value: 'ten'))+ expect { process(line.merge('unit_cost' => '')) }.+ to raise_error(ArgumentError, Spree.t(:purchase_order_import_invalid_cost, value: ''))+ expect { process(line.merge('currency' => 'XXX')) }.+ to raise_error(ArgumentError, Spree.t(:purchase_order_import_unsupported_currency, currency: 'XXX'))+ expect { process(line.merge('expected_at' => 'March')) }.+ to raise_error(ArgumentError, Spree.t(:purchase_order_import_invalid_date, column: 'expected_at', value: 'March'))+ end+enddiff --git a/spree/core/spec/workflows/spree/purchase_orders/lifecycle_spec.rb b/spree/core/spec/workflows/spree/purchase_orders/lifecycle_spec.rbindex acf5917310..647e7ac921 100644--- a/spree/core/spec/workflows/spree/purchase_orders/lifecycle_spec.rb+++ b/spree/core/spec/workflows/spree/purchase_orders/lifecycle_spec.rb@@ -86,94 +86,119 @@ describe 'purchase order lifecycle', type: :model dodescribe 'receiving' dobefore { Spree::PurchaseOrders::MarkOrdered.call(purchase_order: purchase_order) }- it 'books the whole delivery in and closes the order' do- result = Spree::PurchaseOrders::Receive.call(purchase_order: purchase_order.reload)+ def receive(items = nil, **attributes)+ Spree::PurchaseOrders::Receive.call(purchase_order: purchase_order.reload, items: items, **attributes)+ end++ def line+ purchase_order.reload.items.sole+ end++ it 'books the whole delivery in as a receipt and closes the order' do+ result = receiveexpect(result).to be_success- expect(result.value).to be_received- expect(result.value.received_at).to be_present+ receipt = result.value+ expect(receipt).to be_a(Spree::StockReceipt)+ expect(receipt.number).to start_with('SR')+ expect(receipt.items.sole).to have_attributes(line: line, quantity_accepted: 100, quantity_rejected: 0)+ expect(purchase_order.reload).to be_received+ expect(purchase_order.received_at).to be_presentexpect(on_hand).to eq(100)end- it 'records what the units cost on the movement that landed them' do- Spree::PurchaseOrders::Receive.call(purchase_order: purchase_order.reload)+ it 'records what the units cost on the movement that landed them, and which delivery' do+ receipt = receive.valuemovement = purchase_order.reload.stock_movements.soleexpect(movement).to have_attributes(kind: 'received', quantity: 100, unit_cost: 12.5)expect(movement.purchase_order).to eq(purchase_order)+ expect(movement.stock_receipt).to eq(receipt)expect(movement.display_unit_cost.to_s).to eq('$12.50')end- # Two receivers booking the same pallet in at once: both resolve the line,- # both compute a delta from the total they read, and both credit the whole- # delivery. The workflow re-reads the line under its lock, so the second- # caller measures against what actually committed.- # Every delta is measured before any of them is written, so a line named- # twice would contribute its delta once per entry — the shape a scanner- # app produces when it appends an entry per pallet.- it 'refuses a payload that names the same line twice' do- item = purchase_order.reload.items.sole+ it 'adds each delivery to the line and keeps the order open until it is whole' do+ first = receive([{ item: line, quantity_accepted: 60 }], reference: 'DN-1')+ expect(purchase_order.reload).to be_partially_received+ expect(line).to have_attributes(quantity_received: 60, outstanding: 40)- result = Spree::PurchaseOrders::Receive.call(- purchase_order: purchase_order,- items: [{ item: item, quantity_received: 40 }, { item: item, quantity_received: 60 }]- )+ second = receive([{ item: line, quantity_accepted: 40 }], reference: 'DN-2')++ expect(purchase_order.reload).to be_received+ expect(purchase_order.stock_receipts.order(:id).map(&:reference)).to eq(%w[DN-1 DN-2])+ expect(first.value.quantity_accepted_total).to eq(60)+ expect(second.value.quantity_accepted_total).to eq(40)+ expect(on_hand).to eq(100)+ end++ it 'records each delivery at the cost agreed when it landed' do+ receive([{ item: line, quantity_accepted: 60 }])+ line.update!(unit_cost: 14.0)+ receive([{ item: line, quantity_accepted: 40 }])++ costs = purchase_order.reload.stock_movements.order(:id).map { |movement| [movement.quantity, movement.unit_cost] }+ expect(costs).to eq([[60, 12.5], [40, 14.0]])+ end++ it 'keeps rejected units off the shelf and on the receipt' do+ result = receive([{ item: line, quantity_accepted: 8, quantity_rejected: 2, rejection_reason: 'damaged' }])++ expect(result).to be_success+ expect(result.value.items.sole).to have_attributes(quantity_rejected: 2, rejection_reason: 'damaged')+ expect(line).to have_attributes(quantity_received: 8, quantity_rejected: 2, outstanding: 92)+ expect(on_hand).to eq(8)+ end++ it 'refuses a rejection that gives no reason' do+ result = receive([{ item: line, quantity_accepted: 8, quantity_rejected: 2 }])expect(result).to be_failure- expect(result.error.to_s).to eq(- Spree.t('purchase_order.errors.repeated_item', variant: item.variant_name)- )expect(on_hand).to eq(0)- expect(item.reload.quantity_received).to eq(0)end- it 'ignores a running total that was read before another receive committed' do- stale_line = purchase_order.reload.items.sole- Spree::PurchaseOrders::Receive.call(purchase_order: purchase_order,- items: [{ item: purchase_order.items.sole, quantity_received: 60 }])+ it 'books an over-shipment in and closes the order as over-received' do+ result = receive([{ item: line, quantity_accepted: 110 }])++ expect(result).to be_success+ expect(purchase_order.reload).to be_over_received+ expect(purchase_order).to be_closed+ expect(line).to have_attributes(quantity_received: 110, quantity_over: 10, outstanding: 0)+ expect(on_hand).to eq(110)+ end- result = Spree::PurchaseOrders::Receive.call(purchase_order: purchase_order.reload,- items: [{ item: stale_line, quantity_received: 60 }])+ it 'refuses a delivery that counts nothing' do+ result = receive([{ item: line, quantity_accepted: 0, quantity_rejected: 0 }])expect(result).to be_failureexpect(result.error.to_s).to eq(Spree.t('purchase_order.errors.no_items_received'))- expect(on_hand).to eq(60)end- it 'stays open when the supplier under-ships' do- item = purchase_order.reload.items.sole-- result = Spree::PurchaseOrders::Receive.call(- purchase_order: purchase_order, items: [{ item: item, quantity_received: 60 }]- )+ # Two entries for one line are genuinely ambiguous — two cartons, or a+ # correction of the first? — the shape a scanner app produces when it+ # appends an entry per pallet.+ it 'refuses a payload that names the same line twice' do+ result = receive([{ item: line, quantity_accepted: 40 }, { item: line, quantity_accepted: 60 }])- expect(result).to be_success- expect(result.value).to be_partially_received- expect(on_hand).to eq(60)- expect(item.reload.outstanding).to eq(40)+ expect(result).to be_failure+ expect(result.error.to_s).to eq(Spree.t('purchase_order.errors.repeated_item', variant: line.variant_name))+ expect(on_hand).to eq(0)end- # Two deliveries agreed at different prices are two movements, each- # carrying its own cost — which is the whole reason the column exists.- it 'records each delivery at the price it was agreed' do- item = purchase_order.reload.items.sole- Spree::PurchaseOrders::Receive.call(purchase_order: purchase_order,- items: [{ item: item, quantity_received: 60 }])- item.reload.update!(unit_cost: 14)+ # Two receivers booking two pallets at once: each adds its own count to+ # the total it reads, and the lock makes the second read the first's write.+ it 'adds a delivery to the total another delivery just committed' do+ stale_line = line+ receive([{ item: line, quantity_accepted: 60 }])- Spree::PurchaseOrders::Receive.call(purchase_order: purchase_order.reload,- items: [{ item: item.reload, quantity_received: 100 }])+ result = receive([{ item: stale_line, quantity_accepted: 40 }])- costs = purchase_order.reload.stock_movements.order(:id).map { |m| [m.quantity, m.unit_cost.to_f] }- expect(costs).to eq([[60, 12.5], [40, 14.0]])+ expect(result).to be_success+ expect(line.quantity_received).to eq(100)expect(on_hand).to eq(100)end- it 'refuses to receive more than was ordered' do- result = Spree::PurchaseOrders::Receive.call(- purchase_order: purchase_order.reload,- items: [{ item: purchase_order.items.sole, quantity_received: 101 }]- )+ it 'refuses a negative count' do+ result = receive([{ item: line, quantity_accepted: -1 }])expect(result).to be_failureexpect(on_hand).to eq(0)@@ -182,12 +207,10 @@ describe 'purchase order lifecycle', type: :model doit 'refuses a line belonging to another order' doother_item = create(:purchase_order, store: store).items.first- result = Spree::PurchaseOrders::Receive.call(- purchase_order: purchase_order.reload, items: [{ item: other_item, quantity_received: 1 }]- )+ result = receive([{ item: other_item, quantity_accepted: 1 }])expect(result).to be_failure- expect(result.error.to_s).to eq(Spree.t('purchase_order.errors.item_not_on_order'))+ expect(result.error.to_s).to eq(Spree.t('purchase_order.errors.item_not_on_document'))endit 'refuses an order that has not been placed' do@@ -200,6 +223,55 @@ describe 'purchase order lifecycle', type: :model doendend+ describe 'closing short' do+ before { Spree::PurchaseOrders::MarkOrdered.call(purchase_order: purchase_order) }++ it 'ends a partially received order and records why' do+ Spree::PurchaseOrders::Receive.call(purchase_order: purchase_order.reload,+ items: [{ item: purchase_order.items.sole, quantity_accepted: 60 }])++ result = Spree::PurchaseOrders::Close.call(purchase_order: purchase_order.reload,+ reason: 'Supplier out of stock')++ expect(result).to be_success+ expect(result.value).to be_received+ expect(result.value).to be_closed_short+ expect(result.value.close_reason).to eq('Supplier out of stock')+ expect(result.value.items.sole.outstanding).to eq(40)+ expect(on_hand).to eq(60)+ end++ it 'refuses an order nothing has arrived on' do+ result = Spree::PurchaseOrders::Close.call(purchase_order: purchase_order.reload)++ expect(result).to be_failure+ expect(result.error.to_s).to eq(Spree.t('purchase_order.errors.not_partially_received'))+ end+ end++ describe 'going back to draft' do+ before { Spree::PurchaseOrders::MarkOrdered.call(purchase_order: purchase_order) }++ it 'reopens a placed order nothing has arrived on' do+ result = Spree::PurchaseOrders::MarkDraft.call(purchase_order: purchase_order.reload)++ expect(result).to be_success+ expect(result.value).to be_draft+ expect(result.value.ordered_at).to be_nil+ expect(result.value).to be_editable+ end++ it 'refuses once a delivery has been booked' do+ Spree::PurchaseOrders::Receive.call(purchase_order: purchase_order.reload,+ items: [{ item: purchase_order.items.sole, quantity_accepted: 1 }])++ result = Spree::PurchaseOrders::MarkDraft.call(purchase_order: purchase_order.reload)++ expect(result).to be_failure+ expect(result.error.to_s).to eq(Spree.t('purchase_order.errors.already_receiving'))+ end+ end+describe 'the supplier order count' doit 'tracks purchase orders without counting them per row' doexpect { purchase_order }.to change { supplier.reload.purchase_orders_count }.from(0).to(1)@@ -216,7 +288,7 @@ describe 'purchase order lifecycle', type: :model doit 'closes what is outstanding and leaves received units alone' doSpree::PurchaseOrders::MarkOrdered.call(purchase_order: purchase_order)Spree::PurchaseOrders::Receive.call(purchase_order: purchase_order.reload,- items: [{ item: purchase_order.items.sole, quantity_received: 60 }])+ items: [{ item: purchase_order.items.sole, quantity_accepted: 60 }])result = Spree::PurchaseOrders::Cancel.call(purchase_order: purchase_order.reload,reason: 'Supplier went under')diff --git a/spree/core/spec/workflows/spree/stock_transfers/lifecycle_spec.rb b/spree/core/spec/workflows/spree/stock_transfers/lifecycle_spec.rbindex 81832fddc0..9a59a435be 100644--- a/spree/core/spec/workflows/spree/stock_transfers/lifecycle_spec.rb+++ b/spree/core/spec/workflows/spree/stock_transfers/lifecycle_spec.rb@@ -140,137 +140,172 @@ describe 'stock transfer lifecycle', type: :model dodescribe 'receiving' dobefore { Spree::StockTransfers::MarkInTransit.call(stock_transfer: transfer) }- it 'lands everything and closes the trip when the count matches' do- result = Spree::StockTransfers::Receive.call(stock_transfer: transfer.reload)+ def receive(items = nil, **attributes)+ Spree::StockTransfers::Receive.call(stock_transfer: transfer.reload, items: items, **attributes)+ end++ def line+ transfer.reload.items.sole+ end++ it 'lands everything as a receipt and closes the trip when the count matches' do+ result = receive(reference: 'Van 3, morning run')expect(result).to be_success- expect(result.value).to be_received- expect(result.value.received_at).to be_present+ receipt = result.value+ expect(receipt).to be_a(Spree::StockReceipt)+ expect(receipt.reference).to eq('Van 3, morning run')+ expect(receipt.items.sole).to have_attributes(line: line, quantity_accepted: 10)+ expect(transfer.reload).to be_received+ expect(transfer.received_at).to be_presentexpect(destination_on_hand).to eq(10)+ expect(transfer.stock_movements.received.sole.stock_receipt).to eq(receipt)end- it 'lands only what arrived and stays open when it is short' do- item = transfer.reload.items.sole+ it 'lands only what arrived and stays open while units are still on the road' do+ result = receive([{ item: line, quantity_accepted: 8 }])- result = Spree::StockTransfers::Receive.call(- stock_transfer: transfer,- items: [{ item: item, quantity_received: 8, discrepancy_reason: 'damaged_in_transit' }]- )+ expect(result).to be_success+ expect(transfer.reload).to be_partially_received+ expect(transfer.received_at).to be_nil+ expect(destination_on_hand).to eq(8)+ expect(line).to have_attributes(quantity_received: 8, outstanding: 2)+ end++ # Two crushed units arrived all the same: nothing is left in the van, so+ # the trip is over — with the damage on record and off the shelf.+ it 'records what was refused and closes the trip once everything has arrived' do+ result = receive([{ item: line, quantity_accepted: 8, quantity_rejected: 2, rejection_reason: 'damaged' }])expect(result).to be_success- expect(result.value).to be_partially_received- expect(result.value.received_at).to be_nil+ expect(result.value.items.sole).to have_attributes(quantity_accepted: 8, quantity_rejected: 2,+ rejection_reason: 'damaged')+ expect(transfer.reload).to be_received+ expect(transfer.received_at).to be_presentexpect(destination_on_hand).to eq(8)- expect(item.reload).to have_attributes(quantity_received: 8, outstanding: 2,- discrepancy_reason: 'damaged_in_transit')+ expect(line).to have_attributes(quantity_received: 8, quantity_rejected: 2, outstanding: 0)end- # The line's quantity_received is a running total, so a second delivery- # tops it up rather than landing the whole amount again.- it 'adds only the difference on a second receive' do- item = transfer.reload.items.sole- Spree::StockTransfers::Receive.call(stock_transfer: transfer,- items: [{ item: item, quantity_received: 8 }])+ # Each delivery adds what it brought; the second box does not restate the+ # first.+ it 'adds a second delivery to the first' do+ receive([{ item: line, quantity_accepted: 8 }])- result = Spree::StockTransfers::Receive.call(stock_transfer: transfer.reload,- items: [{ item: item.reload, quantity_received: 10 }])+ result = receive([{ item: line, quantity_accepted: 2 }])expect(result).to be_success- expect(result.value).to be_received+ expect(transfer.reload).to be_received+ expect(transfer.stock_receipts.count).to eq(2)expect(destination_on_hand).to eq(10)- expect(transfer.reload.stock_movements.received.sum(:quantity)).to eq(10)+ expect(transfer.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' }]- )+ it 'books more than was shipped and closes the trip as over-received' do+ result = receive([{ item: line, quantity_accepted: 11 }])- Spree::StockTransfers::Receive.call(stock_transfer: transfer.reload,- items: [{ item: item.reload, quantity_received: 9 }])+ expect(result).to be_success+ expect(transfer.reload).to be_over_received+ expect(line).to have_attributes(quantity_received: 11, quantity_over: 1, outstanding: 0)+ expect(destination_on_hand).to eq(11)+ end++ # Two operators receiving two boxes at once, which the destination's+ # tablet makes as easy as a double-tap: each adds its own count to the+ # total it reads, and the lock makes the second read the first's write.+ it 'adds a delivery to the total another delivery just committed' do+ stale_line = line+ receive([{ item: line, quantity_accepted: 6 }])++ result = receive([{ item: stale_line, quantity_accepted: 4 }])- expect(item.reload.discrepancy_reason).to eq('damaged_in_transit')+ expect(result).to be_success+ expect(transfer.reload).to be_received+ expect(destination_on_hand).to eq(10)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 }]- )+ # Two entries for one line are genuinely ambiguous — two cartons, or a+ # correction of the first? — the shape a scanner app produces when it+ # appends an entry per carton.+ it 'refuses a payload that names the same line twice' do+ result = receive([{ item: line, quantity_accepted: 4 }, { item: line, quantity_accepted: 6 }])expect(result).to be_failure+ expect(result.error.to_s).to eq(Spree.t('stock_transfer.errors.repeated_item', variant: line.variant_name))expect(destination_on_hand).to eq(0)+ expect(line.quantity_received).to eq(0)end- # Taking units back off the shelf is a correction, which is what a manual- # adjustment is for.- it 'refuses to lower a quantity already received' do- item = transfer.reload.items.sole- Spree::StockTransfers::Receive.call(stock_transfer: transfer,- items: [{ item: item, quantity_received: 8 }])-- result = Spree::StockTransfers::Receive.call(stock_transfer: transfer.reload,- items: [{ item: item.reload, quantity_received: 5 }])+ it 'refuses a delivery that counts nothing' do+ result = receive([{ item: line, quantity_accepted: 0 }])expect(result).to be_failure- expect(destination_on_hand).to eq(8)+ expect(result.error.to_s).to eq(Spree.t('stock_transfer.errors.no_items_received'))end- # Two operators receiving the same box at once, which the destination's- # tablet makes as easy as a double-tap: both resolve the line, both compute- # a delta from the total they read, and both credit the whole delivery. The- # workflow re-reads the line under its lock, so the second caller measures- # against what actually committed and finds nothing left to receive.- it 'ignores a running total that was read before another receive committed' do- stale_line = transfer.reload.items.sole- Spree::StockTransfers::Receive.call(stock_transfer: transfer,- items: [{ item: transfer.items.sole, quantity_received: 6 }])+ it 'refuses a line belonging to another transfer' do+ other_item = create(:stock_transfer, store: store).items.first- result = Spree::StockTransfers::Receive.call(stock_transfer: transfer.reload,- items: [{ item: stale_line, quantity_received: 6 }])+ result = receive([{ item: other_item, quantity_accepted: 1 }])expect(result).to be_failure- expect(result.error.to_s).to eq(Spree.t('stock_transfer.errors.no_items_received'))- expect(destination_on_hand).to eq(6)+ expect(result.error.to_s).to eq(Spree.t('stock_transfer.errors.item_not_on_document'))end- # Every delta is measured before any of them is written, so a line named- # twice would contribute its delta once per entry — the shape a scanner- # app produces when it appends an entry per carton.- it 'refuses a payload that names the same line twice' do- item = transfer.reload.items.sole+ it 'refuses a transfer that is not on the road' do+ draft = create(:stock_transfer, store: store)- result = Spree::StockTransfers::Receive.call(- stock_transfer: transfer,- items: [{ item: item, quantity_received: 4 }, { item: item, quantity_received: 6 }]- )+ result = Spree::StockTransfers::Receive.call(stock_transfer: draft)expect(result).to be_failure- expect(result.error.to_s).to eq(- Spree.t('stock_transfer.errors.repeated_item', variant: item.variant_name)- )- expect(destination_on_hand).to eq(0)- expect(item.reload.quantity_received).to eq(0)+ expect(result.error.to_s).to eq(Spree.t('stock_transfer.errors.not_in_transit'))end+ end- it 'refuses a line belonging to another transfer' do- other_item = create(:stock_transfer, store: store).items.first+ describe 'closing short' do+ before { Spree::StockTransfers::MarkInTransit.call(stock_transfer: transfer) }- result = Spree::StockTransfers::Receive.call(- stock_transfer: transfer.reload, items: [{ item: other_item, quantity_received: 1 }]- )+ it 'ends a partially received trip and records what happened to the rest' do+ Spree::StockTransfers::Receive.call(stock_transfer: transfer.reload,+ items: [{ item: transfer.items.sole, quantity_accepted: 8 }])++ result = Spree::StockTransfers::Close.call(stock_transfer: transfer.reload, reason: 'Two fell off the van')++ expect(result).to be_success+ expect(result.value).to be_received+ expect(result.value).to be_closed_short+ expect(result.value.close_reason).to eq('Two fell off the van')+ expect(result.value.items.sole.outstanding).to eq(2)+ expect(source_on_hand).to eq(0)+ expect(destination_on_hand).to eq(8)+ end++ it 'refuses a trip nothing has arrived on' do+ result = Spree::StockTransfers::Close.call(stock_transfer: transfer.reload)expect(result).to be_failure- expect(result.error.to_s).to eq(Spree.t('stock_transfer.errors.item_not_on_transfer'))+ expect(result.error.to_s).to eq(Spree.t('stock_transfer.errors.not_partially_received'))end+ end- it 'refuses a transfer that has not shipped' do- draft = create(:stock_transfer, store: store)+ describe 'going back to draft' do+ it 'unfreezes a packed transfer' do+ Spree::StockTransfers::MarkReady.call(stock_transfer: transfer)++ result = Spree::StockTransfers::MarkDraft.call(stock_transfer: transfer.reload)- expect(Spree::StockTransfers::Receive.call(stock_transfer: draft)).to be_failure+ expect(result).to be_success+ expect(result.value).to be_draft+ expect(result.value).to be_editable+ expect(source_on_hand).to eq(10)+ end++ it 'refuses once the van has left' do+ Spree::StockTransfers::MarkInTransit.call(stock_transfer: transfer)++ result = Spree::StockTransfers::MarkDraft.call(stock_transfer: transfer.reload)++ expect(result).to be_failure+ expect(result.error.to_s).to eq(Spree.t('stock_transfer.errors.not_ready_to_ship'))endend@@ -330,7 +365,7 @@ describe 'stock transfer lifecycle', type: :model doexpect(result).to be_successexpect(source_on_hand).to eq(0)expect(destination_on_hand).to eq(0)- expect(transfer.reload.items.sole.discrepancy_reason).to eq('stolen')+ expect(transfer.reload.close_reason).to eq('stolen')expect(transfer.stock_movements.received).to be_emptyend@@ -338,7 +373,7 @@ describe 'stock transfer lifecycle', type: :model doit 'only resolves the units still in flight' doSpree::StockTransfers::MarkInTransit.call(stock_transfer: transfer)Spree::StockTransfers::Receive.call(stock_transfer: transfer.reload,- items: [{ item: transfer.items.sole, quantity_received: 6 }])+ items: [{ item: transfer.items.sole, quantity_accepted: 6 }])Spree::StockTransfers::Cancel.call(stock_transfer: transfer.reload, on_in_transit: 'restock')