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
Give stock transfers a life, and supplier receives a purchase order
Łukasz Adamczyke76d9a012543
diff --git a/spree/core/app/models/concerns/spree/receivable.rb b/spree/core/app/models/concerns/spree/receivable.rbnew file mode 100644index 0000000000..48a3547bef--- /dev/null+++ b/spree/core/app/models/concerns/spree/receivable.rb@@ -0,0 +1,93 @@+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`.+ module Receivable+ extend 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++ included do+ scope :open, -> { where(status: OPEN_STATUSES & statuses) }+ scope :closed, -> { where(status: CLOSED_STATUSES & statuses) }++ validate :items_name_distinct_variants+ end++ # @return [Integer]+ def items_count+ items.size+ end++ # How many units the document promises in total.+ #+ # @return [Integer]+ def quantity_expected_total+ items.sum(&:quantity_expected)+ end++ # How many units have been counted in so far.+ #+ # @return [Integer]+ def quantity_received_total+ items.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.+ #+ # @return [Boolean]+ def under_received?+ items.any?(&:under_received?)+ end++ # Whether every line has arrived in full.+ #+ # @return [Boolean]+ def fully_received?+ items.any? && !under_received?+ end++ # The status a receive settles the document in: `received` once every line+ # is complete, `partially_received` while any is still owed.+ #+ # @return [String]+ def status_after_receive+ 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++ 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_variants+ variant_ids = items.reject(&:marked_for_destruction?).filter_map(&:variant_id)+ return if variant_ids.uniq.size == variant_ids.size++ errors.add(:items, :duplicate_variant, message: Spree.t('errors.messages.duplicate_variant'))+ end+ end+enddiff --git a/spree/core/app/models/concerns/spree/receivable_item.rb b/spree/core/app/models/concerns/spree/receivable_item.rbnew file mode 100644index 0000000000..a47e38c519--- /dev/null+++ b/spree/core/app/models/concerns/spree/receivable_item.rb@@ -0,0 +1,69 @@+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}.+ module ReceivableItem+ extend ActiveSupport::Concern++ class_methods do+ # @param attribute [Symbol] the column holding the promised quantity+ def expects_quantity_in(attribute)+ class_attribute :expected_quantity_attribute, default: attribute.to_sym,+ instance_writer: false+ end+ end++ included 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'++ validates :quantity_received, numericality: {+ greater_than_or_equal_to: 0, only_integer: true+ }+ validate :received_does_not_exceed_expected++ delegate :name, :sku, to: :variant, prefix: true, allow_nil: true+ end++ # How many units this line promised.+ #+ # @return [Integer]+ def quantity_expected+ public_send(self.class.expected_quantity_attribute).to_i+ end++ # How many are still owed.+ #+ # @return [Integer]+ def outstanding+ quantity_expected - quantity_received.to_i+ end++ # Whether fewer units arrived than were promised.+ #+ # @return [Boolean]+ 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? || quantity_expected.zero?+ 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))+ end+ end+enddiff --git a/spree/core/app/models/spree/purchase_order.rb b/spree/core/app/models/spree/purchase_order.rbnew file mode 100644index 0000000000..3bacb35b22--- /dev/null+++ b/spree/core/app/models/spree/purchase_order.rb@@ -0,0 +1,86 @@+module Spree+ # Goods bought from a supplier and expected at one of the merchant's own+ # warehouses (docs/plans/6.0-inventory-operations.md).+ #+ # Replaces the 5.x "external receive" — a {Spree::StockTransfer} with no+ # source location — with a record that has the things a purchase actually+ # has: a supplier, a unit cost, an expected date and a number to quote back.+ #+ # Ordered units never count toward availability. Nothing here touches+ # `count_on_hand` until {Spree::PurchaseOrders::Receive} runs, because the+ # merchant only has the goods once they land.+ #+ # Every status change is a workflow — `Spree::PurchaseOrders::Receive`, never+ # `purchase_order.receive!` — so receiving can take the quantities the+ # warehouse counted rather than assuming the order arrived intact.+ class PurchaseOrder < Spree.base_class+ has_prefix_id :po++ has_spree_number prefix: 'PO'+ include Spree::NumberIdentifier+ include Spree::SingleStoreResource+ include Spree::HasStatus+ include Spree::Receivable+ include Spree::HasCustomFields+ include Spree::Metadata++ publishes_lifecycle_events++ has_status :draft, :ordered, :partially_received, :received, :canceled,+ default: :draft++ belongs_to :supplier, class_name: 'Spree::Supplier', inverse_of: :purchase_orders+ belongs_to :destination_location, class_name: 'Spree::StockLocation'+ belongs_to :created_by, class_name: Spree.admin_user_class.to_s, optional: true++ has_many :items, class_name: 'Spree::PurchaseOrderItem',+ inverse_of: :purchase_order, dependent: :destroy+ # No `dependent:` — the ledger outlives the record that caused it, the same+ # reason Spree::Fulfillment gives for its own movements.+ has_many :stock_movements, class_name: 'Spree::StockMovement', inverse_of: :purchase_order++ accepts_nested_attributes_for :items, allow_destroy: true++ before_validation :ensure_currency++ validates :currency, presence: true+ validates :items, presence: true, unless: :draft?++ self.whitelisted_ransackable_attributes = %w[number status currency reference expected_at+ ordered_at received_at supplier_id+ destination_location_id created_at]+ self.whitelisted_ransackable_associations = %w[supplier destination_location items]++ # What the supplier will invoice for everything ordered.+ #+ # @return [BigDecimal]+ def subtotal+ items.sum(&:total_cost)+ end++ # @return [Spree::Money]+ def display_subtotal+ Spree::Money.new(subtotal, currency: currency)+ end++ # Whether the merchant may still edit the lines. Once the order is placed+ # with the supplier, what was ordered is a matter of record.+ #+ # @return [Boolean]+ def editable?+ draft?+ end++ def event_serializer_class+ 'Spree::Api::V3::PurchaseOrderEventSerializer'.safe_constantize+ end++ private++ # A foreign-currency purchase order is legitimate, so this is a default+ # rather than a derived value: pass `currency` to override it.+ def ensure_currency+ self.currency ||= store&.default_currency+ end+ end+enddiff --git a/spree/core/app/models/spree/purchase_order_item.rb b/spree/core/app/models/spree/purchase_order_item.rbnew file mode 100644index 0000000000..1eb95304e3--- /dev/null+++ b/spree/core/app/models/spree/purchase_order_item.rb@@ -0,0 +1,40 @@+module Spree+ # One SKU on a purchase order: how many were ordered, how many have arrived,+ # and what the merchant agreed to pay per unit.+ class PurchaseOrderItem < Spree.base_class+ has_prefix_id :poi++ include Spree::ReceivableItem++ expects_quantity_in :quantity_ordered++ belongs_to :purchase_order, class_name: 'Spree::PurchaseOrder', inverse_of: :items, touch: true++ validates :quantity_ordered, numericality: { greater_than: 0, only_integer: true }+ validates :unit_cost, numericality: { greater_than_or_equal_to: 0 }+ validates :variant_id, uniqueness: { scope: :purchase_order_id }++ delegate :currency, to: :purchase_order, allow_nil: true++ self.whitelisted_ransackable_attributes = %w[variant_id quantity_ordered quantity_received unit_cost]+ self.whitelisted_ransackable_associations = %w[variant]++ # What the whole line costs at the agreed unit price. Ordered rather than+ # received quantity: this is what the supplier will invoice.+ #+ # @return [BigDecimal]+ def total_cost+ unit_cost.to_d * quantity_ordered.to_i+ end++ # @return [Spree::Money]+ def display_unit_cost+ Spree::Money.new(unit_cost, currency: currency)+ end++ # @return [Spree::Money]+ def display_total_cost+ Spree::Money.new(total_cost, currency: currency)+ end+ end+enddiff --git a/spree/core/app/models/spree/stock_location.rb b/spree/core/app/models/spree/stock_location.rbindex 411545c953..41923c72a7 100644--- a/spree/core/app/models/spree/stock_location.rb+++ b/spree/core/app/models/spree/stock_location.rb@@ -158,8 +158,11 @@ module Spree# @param quantity [Integer]# @param cause [ApplicationRecord, nil] the record this is happening for# @return [Spree::StockMovement]- def restock(variant, quantity, cause = nil, persist: true)- move(variant, quantity, kind: 'received', cause: cause, persist: persist)+ # @param unit_cost [BigDecimal, nil] what each unit landed at, when the+ # goods were bought. Recorded on the movement so a rolling average cost+ # has a ledger to read; null for stock the merchant already owned.+ def restock(variant, quantity, cause = nil, unit_cost: nil)+ move(variant, quantity, kind: 'received', cause: cause, unit_cost: unit_cost)end# Goods left.@@ -168,8 +171,8 @@ module Spree# below zero. A merchant forcing a dispatch has decided the parcel left# whatever the ledger claims.# @return [Spree::StockMovement]- def unstock(variant, quantity, cause = nil, persist: true, force: false)- move(variant, quantity, kind: 'shipped', cause: cause, persist: persist, force: force)+ def unstock(variant, quantity, cause = nil, force: false)+ move(variant, quantity, kind: 'shipped', cause: cause, force: force)end# Promises stock to a placed order. The cause is the fulfillment, never@@ -200,20 +203,12 @@ module Spreemove(variant, quantity, kind: 'adjusted', reason: reason)end- def move(variant, quantity, kind:, cause: nil, reason: nil, persist: true, force: false)+ def move(variant, quantity, kind:, cause: nil, reason: nil, force: false, unit_cost: nil)stock_level = stock_level_or_create(variant)- attributes = { quantity: quantity, kind: kind, reason: reason, **cause_attributes(cause) }+ attributes = { quantity: quantity, kind: kind, reason: reason, unit_cost: unit_cost,+ **cause_attributes(cause) }- if persist- stock_level.stock_movements.create!(attributes) { |movement| movement.force = force }- else- # StockTransfer builds its movements before it is saved, so they ride- # along on its own association rather than being created here.- built = stock_level.stock_movements.build(attributes)- built.force = force- cause.stock_movements << built- built- end+ stock_level.stock_movements.create!(attributes) { |movement| movement.force = force }enddef fill_status(variant, quantity)@@ -294,6 +289,7 @@ module Spreewhen Spree::Return then { return: cause, order: cause.order }when Spree::Exchange then { exchange: cause, order: cause.order }when Spree::StockTransfer then { stock_transfer: cause }+ when Spree::PurchaseOrder then { purchase_order: cause }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 99d1e725b1..5a777d6b23 100644--- a/spree/core/app/models/spree/stock_movement.rb+++ b/spree/core/app/models/spree/stock_movement.rb@@ -31,6 +31,7 @@ module Spreebelongs_to :return, class_name: 'Spree::Return', optional: truebelongs_to :exchange, class_name: 'Spree::Exchange', optional: truebelongs_to :stock_transfer, class_name: 'Spree::StockTransfer', optional: true+ belongs_to :purchase_order, class_name: 'Spree::PurchaseOrder', optional: truealias_attribute :stock_item_id, :stock_level_id@@ -78,7 +79,8 @@ module Spree# hand a client still sending it the whole collection rather than an error.self.whitelisted_ransackable_attributes = %w[quantity kind reason created_at stock_level_idstock_item_id order_id fulfillment_id return_id- exchange_id stock_transfer_id]+ exchange_id stock_transfer_id purchase_order_id+ unit_cost]self.whitelisted_ransackable_associations = %w[stock_level]# Stored audit text for a correction nobody labelled. Deliberately@@ -100,6 +102,17 @@ module Spreepersisted? && !being_created?end+ # What the units on this row cost, when the movement was a purchase. Null+ # on everything else: moving stock a merchant already owns is not a+ # purchase, so a transfer or a return has no cost to record.+ #+ # @return [Spree::Money, nil]+ def display_unit_cost+ return nil if unit_cost.nil?++ Spree::Money.new(unit_cost, currency: purchase_order&.currency)+ end+# @deprecated Use {#stock_level}; removed in 6.1.def stock_itemSpree::Deprecation.warn('Spree::StockMovement#stock_item is deprecated and will be removed in Spree 6.1. Use #stock_level instead.')diff --git a/spree/core/app/models/spree/stock_transfer.rb b/spree/core/app/models/spree/stock_transfer.rbindex 5e59a26310..3f0409e29e 100644--- a/spree/core/app/models/spree/stock_transfer.rb+++ b/spree/core/app/models/spree/stock_transfer.rb@@ -1,121 +1,105 @@module Spree+ # Stock moving between two of the merchant's own warehouses+ # (docs/plans/6.0-inventory-operations.md).+ #+ # A transfer is a trip, not an instant. Units leave the source when+ # {Spree::StockTransfers::MarkInTransit} runs and land at the destination+ # when {Spree::StockTransfers::Receive} does — in between they are in flight,+ # physically gone from one shelf and not yet on the other. The 5.x model+ # collapsed both into one transaction, which made the destination's+ # availability wrong for the whole journey.+ #+ # Every status change is a workflow, never `transfer.receive!`, so receiving+ # can carry the quantities the warehouse actually counted and cancelling can+ # carry the merchant's restock-or-write-off choice.+ #+ # Receiving from a supplier is a {Spree::PurchaseOrder}, not a transfer with+ # no source: a purchase has a cost, a supplier and an expected date, and none+ # of those belong on internal logistics.class StockTransfer < Spree.base_classhas_prefix_id :sthas_spree_number prefix: 'T'include Spree::NumberIdentifier+ include Spree::SingleStoreResource+ include Spree::HasStatus+ include Spree::Receivableinclude Spree::HasCustomFieldsinclude Spree::Metadata+ # The upgrade task keeps a converted external receive's number readable by+ # stamping the row rather than deleting it.+ acts_as_paranoid+publishes_lifecycle_events- # No `dependent:` option, for the reason given on Spree::Fulfillment's own+ has_status :draft, :ready_to_ship, :in_transit, :partially_received, :received, :canceled,+ default: :draft++ belongs_to :source_location, class_name: 'Spree::StockLocation'+ belongs_to :destination_location, class_name: 'Spree::StockLocation'+ belongs_to :created_by, class_name: Spree.admin_user_class.to_s, optional: true++ has_many :items, class_name: 'Spree::StockTransferItem',+ inverse_of: :stock_transfer, dependent: :destroy+ # No `dependent:`, for the reason given on Spree::Fulfillment's own# movements: the ledger outlives the record that caused it.has_many :stock_movements, class_name: 'Spree::StockMovement', inverse_of: :stock_transfer- accepts_nested_attributes_for :stock_movements, reject_if: proc { |attributes|- attributes[:quantity] = attributes[:quantity].to_i- attributes[:quantity].blank? || attributes[:quantity].zero? || attributes[:stock_level_id].blank?- }- belongs_to :source_location, class_name: 'StockLocation', optional: true- belongs_to :destination_location, class_name: 'StockLocation'-- self.whitelisted_ransackable_attributes = %w[reference source_location_id destination_location_id number]+ accepts_nested_attributes_for :items, allow_destroy: true+ validates :source_location, :destination_location, presence: true+ validates :items, presence: true, unless: :draft?validate :source_location_is_not_destination_location- validate :stock_movements_not_empty+ validate :locations_belong_to_the_same_store- # Transfers have no store of their own — they belong to the warehouses- # they move stock between, and those are store-scoped. Used by- # {Spree::HasNumber} to pick up the store's numbering settings.- #- # @return [Spree::Store, nil]- def number_store- destination_location&.store || source_location&.store || super- end-- def source_movements- find_stock_location_with_location_id(source_location_id)- end+ self.whitelisted_ransackable_attributes = %w[number status reference source_location_id+ destination_location_id shipped_at received_at+ created_at]+ self.whitelisted_ransackable_associations = %w[source_location destination_location items]- def destination_movements- find_stock_location_with_location_id(destination_location_id)- end-- def transfer(source_location, destination_location, variants)- if variants.nil? || variants.empty?- errors.add(:base, :must_have_variant, message: Spree.t('stock_transfer.errors.must_have_variant'))- return false- end-- # Before the availability check, which a negative quantity would sail- # through — every count is greater than a negative number. The move would- # then write a negative in both directions and take stock off the source- # *and* the destination.- unless positive_quantities?(variants)- errors.add(:base, :invalid_quantity, message: Spree.t('stock_transfer.errors.invalid_quantity'))- return false- end-- unless variants_available_in_source_location?(source_location, variants)- errors.add(:base, :variants_unavailable, stock: source_location.name,- message: Spree.t('stock_transfer.errors.variants_unavailable', stock: source_location.name))- return false- end-- transaction do- variants.each_pair do |variant, quantity|- source_location&.unstock(variant, quantity, self, persist: false)- destination_location.restock(variant, quantity, self, persist: false)-- self.source_location = source_location- self.destination_location = destination_location- save!- end- end-- true+ # Whether the merchant may still edit the lines. Once the box is sealed and+ # marked ready, what is in it is a matter of record.+ #+ # @return [Boolean]+ def editable?+ draft?end- # receive inventory from external seller- def receive(destination_location, variants)- transfer(nil, destination_location, variants)+ # Whether the units are somewhere between the two warehouses — gone from+ # the source, not yet counted at the destination.+ #+ # @return [Boolean]+ def in_flight?+ in_transit? || partially_received?endprivate- def find_stock_location_with_location_id(location_id)- stock_movements.joins(:stock_level).- where(Spree::StockLevel.table_name => { stock_location_id: location_id })+ # The warehouse the goods are going to decides whose transfer this is,+ # which is a fact about the record rather than about the request that+ # created it. `Spree::Current.store` stays the fallback.+ def ensure_store+ self.store ||= destination_location&.store+ superenddef source_location_is_not_destination_location- return unless source_location_id.present?- return unless destination_location_id.present?+ return if source_location_id.blank? || destination_location_id.blank?return if source_location_id != destination_location_iderrors.add(:source_location, :same_location, message: Spree.t('stock_transfer.errors.same_location'))end- def stock_movements_not_empty- errors.add(:base, :must_have_variant, message: Spree.t('stock_transfer.errors.must_have_variant')) if stock_movements.empty?- end-- # Each variant needs enough available stock for the quantity being moved,- # not merely some. Checking only for a positive balance let a transfer take- # more than the shelf held and leave it negative.- def positive_quantities?(variants)- variants.all? { |_variant, quantity| quantity.to_i.positive? }- end-- def variants_available_in_source_location?(source_location, variants)- return true if source_location.nil?-- variants.all? do |variant, quantity|- stock_level = source_location.stock_level(variant)+ # A transfer moves a merchant's own stock between their own warehouses. Two+ # locations from different stores would take units out of one tenant's+ # inventory and put them into another's.+ def locations_belong_to_the_same_store+ return if source_location.blank? || destination_location.blank?+ return if source_location.store_id == destination_location.store_id- stock_level.present? && stock_level.available_count >= quantity.to_i- end+ errors.add(:destination_location, :must_belong_to_same_store,+ message: Spree.t('stock_transfer.errors.locations_in_different_stores'))endendenddiff --git a/spree/core/app/models/spree/stock_transfer_item.rb b/spree/core/app/models/spree/stock_transfer_item.rbnew file mode 100644index 0000000000..d17566695b--- /dev/null+++ b/spree/core/app/models/spree/stock_transfer_item.rb@@ -0,0 +1,19 @@+module Spree+ # One SKU on a stock transfer: how many left the source warehouse, and how+ # many the destination counted in.+ class StockTransferItem < Spree.base_class+ has_prefix_id :sti++ include Spree::ReceivableItem++ expects_quantity_in :quantity_shipped++ belongs_to :stock_transfer, class_name: 'Spree::StockTransfer', inverse_of: :items, touch: true++ validates :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_associations = %w[variant]+ end+enddiff --git a/spree/core/app/models/spree/store.rb b/spree/core/app/models/spree/store.rbindex f51c83173b..0d93f399cb 100644--- a/spree/core/app/models/spree/store.rb+++ b/spree/core/app/models/spree/store.rb@@ -244,6 +244,12 @@ module Spree# first.has_one :default_package_type, -> { where(default: true, seller_id: nil) },class_name: 'Spree::PackageType', inverse_of: :store+ # Inventory operations (docs/plans/6.0-inventory-operations.md). Transfers+ # carry their own store rather than borrowing the destination warehouse's,+ # so the admin endpoint has a scope to fetch through.+ has_many :stock_transfers, class_name: 'Spree::StockTransfer', dependent: :destroy_async, inverse_of: :store+ has_many :suppliers, class_name: 'Spree::Supplier', dependent: :destroy, inverse_of: :store+ has_many :purchase_orders, class_name: 'Spree::PurchaseOrder', dependent: :destroy_async, inverse_of: :storehas_many :promotions, class_name: 'Spree::Promotion', dependent: :nullifyhas_many :tax_categories, class_name: 'Spree::TaxCategory', dependent: :destroy, inverse_of: :storediff --git a/spree/core/app/models/spree/supplier.rb b/spree/core/app/models/spree/supplier.rbnew file mode 100644index 0000000000..6e3278b924--- /dev/null+++ b/spree/core/app/models/spree/supplier.rb@@ -0,0 +1,62 @@+module Spree+ # Somebody the merchant buys goods from. An address-book entry with a+ # purchasing history, not a party that transacts on the store — that is+ # {Spree::Seller}, the marketplace seller (decisions.md 2026-07-14).+ #+ # Suppliers belong to one store: a merchant running two storefronts keeps+ # two lists (docs/plans/6.0-inventory-operations.md, open question 2).+ class Supplier < Spree.base_class+ has_prefix_id :sup++ include Spree::SingleStoreResource+ include Spree::HasCustomFields+ include Spree::Metadata++ acts_as_paranoid++ publishes_lifecycle_events++ has_many :purchase_orders, class_name: 'Spree::PurchaseOrder', inverse_of: :supplier,+ dependent: :restrict_with_error++ validates :name, presence: true,+ uniqueness: { scope: [:store_id, *spree_base_uniqueness_scope],+ conditions: -> { where(deleted_at: nil) } }+ validates :email, email: { allow_blank: true }, length: { maximum: 254, allow_blank: true }++ normalizes :email, with: ->(email) { email.strip.downcase }+ normalizes :name, :contact_name, :phone, with: ->(value) { value.strip }++ self.whitelisted_ransackable_attributes = %w[name contact_name email phone city country_code created_at]++ # The postal address, built from this row's own columns the way+ # {Spree::StockLocation#address} does. Unsaved, and blank when nothing has+ # been filled in — check {#postable?} first.+ #+ # @return [Spree::Address]+ def address+ Spree::Address.new(+ company: name,+ address1: address1,+ address2: address2,+ city: city,+ state_code: state_code,+ state_name: state_name,+ country_code: country_code,+ postal_code: postal_code,+ phone: phone+ )+ end++ # Whether there is enough of an address to put on a purchase order.+ #+ # @return [Boolean]+ def postable?+ address1.present? && city.present? && country_code.present?+ end++ def event_serializer_class+ 'Spree::Api::V3::SupplierEventSerializer'.safe_constantize+ end+ end+enddiff --git a/spree/core/app/workflows/spree/purchase_orders/cancel.rb b/spree/core/app/workflows/spree/purchase_orders/cancel.rbnew file mode 100644index 0000000000..54753f3d04--- /dev/null+++ b/spree/core/app/workflows/spree/purchase_orders/cancel.rb@@ -0,0 +1,46 @@+module Spree+ module PurchaseOrders+ # Calls the order off.+ #+ # Nothing to unwind: a purchase order never moved stock until units were+ # received, and units already received stay on the shelf — the merchant has+ # them. Cancelling closes what is still outstanding, which is a message to+ # accounts payable rather than a stock correction.+ class Cancel < Spree::Workflow+ hooks :validate, :after_cancel++ # @param purchase_order [Spree::PurchaseOrder]+ # @param reason [String, nil] why it was called off; appended to the+ # order's notes, which is what the merchant reads afterwards+ # @param canceler [Object, nil]+ def perform(purchase_order:, reason: nil, canceler: nil)+ super++ step :ensure_cancelable+ run_hooks :validate++ ApplicationRecord.transaction do+ step :mark_canceled+ end++ run_hooks :after_cancel+ purchase_order.publish_event('purchase_order.canceled')+ success(purchase_order.reload)+ end++ private++ def ensure_cancelable+ return unless purchase_order.closed?++ failure(purchase_order, Spree.t('purchase_order.errors.already_closed'))+ end++ def mark_canceled+ notes = [purchase_order.notes, reason].compact_blank.join("\n")++ failure(purchase_order) unless purchase_order.update(status: 'canceled', notes: notes)+ end+ end+ end+enddiff --git a/spree/core/app/workflows/spree/purchase_orders/create.rb b/spree/core/app/workflows/spree/purchase_orders/create.rbnew file mode 100644index 0000000000..00b8775192--- /dev/null+++ b/spree/core/app/workflows/spree/purchase_orders/create.rb@@ -0,0 +1,67 @@+module Spree+ module PurchaseOrders+ # Drafts an order to a supplier. Nothing is on order yet and nothing+ # touches availability — a draft is what the merchant is still deciding to+ # buy.+ class Create < Spree::Workflow+ hooks :validate, :after_create++ # The created order — hook handlers read it (nil while :validate runs).+ attr_reader :purchase_order++ # @param store [Spree::Store]+ # @param supplier [Spree::Supplier]+ # @param destination_location [Spree::StockLocation] where the goods are+ # expected+ # @param items [Array<Hash>] `[{ variant:, quantity_ordered:, unit_cost: }]`+ # @param currency [String, nil] defaults to the store's; set it for a+ # foreign-currency order+ # @param expected_at [Date, nil]+ # @param reference [String, nil] the supplier's own order number+ # @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)+ super++ step :build_purchase_order+ run_hooks :validate++ ApplicationRecord.transaction do+ step :save_purchase_order+ end++ run_hooks :after_create+ purchase_order.publish_event('purchase_order.created')+ success(purchase_order.reload)+ end++ private++ def build_purchase_order+ @purchase_order = store.purchase_orders.new(+ supplier: supplier,+ destination_location: destination_location,+ currency: currency,+ expected_at: expected_at,+ reference: reference,+ notes: notes,+ created_by: created_by,+ status: Spree::PurchaseOrder.default_status+ )++ Array(items).each do |item|+ @purchase_order.items.build(+ variant: item[:variant],+ quantity_ordered: item[:quantity_ordered],+ unit_cost: item[:unit_cost]+ )+ end+ end++ def save_purchase_order+ failure(purchase_order) unless purchase_order.save+ end+ end+ end+enddiff --git a/spree/core/app/workflows/spree/purchase_orders/mark_ordered.rb b/spree/core/app/workflows/spree/purchase_orders/mark_ordered.rbnew file mode 100644index 0000000000..bd7899acb6--- /dev/null+++ b/spree/core/app/workflows/spree/purchase_orders/mark_ordered.rb@@ -0,0 +1,37 @@+module Spree+ module PurchaseOrders+ # The order has gone to the supplier. Freezes the lines and starts the+ # clock on the expected date; the goods are now "on order", which the+ # merchant can see but availability never counts.+ class MarkOrdered < Spree::Workflow+ hooks :validate, :after_mark_ordered++ # @param purchase_order [Spree::PurchaseOrder]+ def perform(purchase_order:)+ super++ step :ensure_draft+ run_hooks :validate++ ApplicationRecord.transaction do+ step :mark_ordered+ end++ run_hooks :after_mark_ordered+ purchase_order.publish_event('purchase_order.ordered')+ success(purchase_order.reload)+ end++ private++ def ensure_draft+ failure(purchase_order, Spree.t('purchase_order.errors.not_draft')) unless purchase_order.draft?+ failure(purchase_order, Spree.t('purchase_order.errors.must_have_variant')) if purchase_order.items.empty?+ end++ def mark_ordered+ failure(purchase_order) unless purchase_order.update(status: 'ordered', ordered_at: Time.current)+ end+ end+ end+enddiff --git a/spree/core/app/workflows/spree/purchase_orders/receive.rb b/spree/core/app/workflows/spree/purchase_orders/receive.rbnew file mode 100644index 0000000000..c32e730562--- /dev/null+++ b/spree/core/app/workflows/spree/purchase_orders/receive.rb@@ -0,0 +1,109 @@+module Spree+ module PurchaseOrders+ # Books in what the supplier actually delivered.+ #+ # 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.+ #+ # 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.+ class Receive < Spree::Workflow+ hooks :validate, :before_restock, :after_receive++ # @param purchase_order [Spree::PurchaseOrder]+ # @param items [Array<Hash>, nil] `[{ item:, quantity_received: }]`;+ # nil receives every line in full+ # @param received_by [Object, nil]+ def perform(purchase_order:, items: nil, received_by: nil)+ super++ step :ensure_receivable+ step :normalize_items+ run_hooks :validate++ ApplicationRecord.transaction do+ 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)+ end++ private++ def ensure_receivable+ return if purchase_order.ordered? || purchase_order.partially_received?++ failure(purchase_order, Spree.t('purchase_order.errors.not_ordered'))+ end++ 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+ 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'))+ 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 }+ end++ def record_receipt+ @normalized_items.each do |item|+ item[:item].update!(quantity_received: item[:quantity_received])+ end+ 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+ end++ 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)+ end+ end+ end+enddiff --git a/spree/core/app/workflows/spree/purchase_orders/update.rb b/spree/core/app/workflows/spree/purchase_orders/update.rbnew file mode 100644index 0000000000..581ec1021a--- /dev/null+++ b/spree/core/app/workflows/spree/purchase_orders/update.rb@@ -0,0 +1,56 @@+module Spree+ module PurchaseOrders+ # Edits a draft order. Once it has been placed with the supplier, what was+ # ordered is a matter of record between two businesses — so this refuses+ # anything past `draft`.+ class Update < Spree::Workflow+ hooks :validate, :after_update++ # @param purchase_order [Spree::PurchaseOrder]+ # @param attributes [Hash] editable columns — supplier, destination,+ # currency, expected date, reference, notes, metadata+ # @param items [Array<Hash>, nil] `[{ variant:, quantity_ordered:,+ # unit_cost: }]` replacing the current lines; nil leaves them alone+ def perform(purchase_order:, attributes: {}, items: nil)+ super++ step :ensure_editable+ run_hooks :validate++ ApplicationRecord.transaction do+ step :apply_changes+ step :save_purchase_order+ end++ run_hooks :after_update+ success(purchase_order.reload)+ end++ private++ def ensure_editable+ return if purchase_order.editable?++ failure(purchase_order, Spree.t('purchase_order.errors.not_editable'))+ end++ def apply_changes+ purchase_order.assign_attributes(attributes) if attributes.present?+ return if items.nil?++ purchase_order.items.destroy_all+ Array(items).each do |item|+ purchase_order.items.build(+ variant: item[:variant],+ quantity_ordered: item[:quantity_ordered],+ unit_cost: item[:unit_cost]+ )+ end+ end++ def save_purchase_order+ failure(purchase_order) unless purchase_order.save+ end+ end+ end+enddiff --git a/spree/core/app/workflows/spree/stock_transfers/cancel.rb b/spree/core/app/workflows/spree/stock_transfers/cancel.rbnew file mode 100644index 0000000000..912f91d0c2--- /dev/null+++ b/spree/core/app/workflows/spree/stock_transfers/cancel.rb@@ -0,0 +1,83 @@+module Spree+ module StockTransfers+ # Calls the trip off.+ #+ # Cancelling a draft or a packed transfer costs nothing — no stock has+ # moved. Cancelling one already in transit is a decision the merchant has+ # to make, because the units are physically gone from the source: either+ # they come back (`restock`, as if the box never left) or they are written+ # off (`write_off`, shrinkage). There is no silent reversal, and no+ # default: guessing would either invent stock or destroy it.+ class Cancel < Spree::Workflow+ hooks :validate, :after_cancel++ # How in-flight units are accounted for.+ IN_TRANSIT_RESOLUTIONS = %w[restock write_off].freeze++ # Recorded on every line the merchant wrote off without saying why.+ DEFAULT_WRITE_OFF_REASON = 'lost_in_transit'.freeze++ # @param stock_transfer [Spree::StockTransfer]+ # @param on_in_transit [String, nil] `'restock'` or `'write_off'`;+ # required once the units have left the source+ # @param reason [String, nil] audit text for the write-off+ # @param canceler [Object, nil]+ def perform(stock_transfer:, on_in_transit: nil, reason: nil, canceler: nil)+ super++ step :ensure_cancelable+ run_hooks :validate++ ApplicationRecord.transaction do+ step :resolve_in_flight_units+ step :mark_canceled+ end++ run_hooks :after_cancel+ stock_transfer.publish_event('stock_transfer.canceled')+ success(stock_transfer.reload)+ end++ private++ def ensure_cancelable+ failure(stock_transfer, Spree.t('stock_transfer.errors.already_closed')) if stock_transfer.closed?+ return unless stock_transfer.in_flight?+ return if IN_TRANSIT_RESOLUTIONS.include?(on_in_transit)++ failure(stock_transfer, Spree.t('stock_transfer.errors.in_transit_resolution_required'))+ end++ # Only the units still in flight are resolved: anything the destination+ # already counted in is on its shelf and stays there.+ def resolve_in_flight_units+ return unless stock_transfer.in_flight?++ stock_transfer.items.each do |item|+ next unless item.outstanding.positive?++ on_in_transit == 'restock' ? restock(item) : write_off(item)+ end+ end++ # Back onto the source's shelf, as if the box had never left. Written as+ # a `received` movement carrying this transfer, so the departure and its+ # reversal reconcile against each other in the ledger.+ def restock(item)+ stock_transfer.source_location.restock(item.variant, item.outstanding, stock_transfer)+ end++ # 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)+ end++ def mark_canceled+ failure(stock_transfer) unless stock_transfer.update(status: 'canceled')+ end+ end+ end+enddiff --git a/spree/core/app/workflows/spree/stock_transfers/create.rb b/spree/core/app/workflows/spree/stock_transfers/create.rbnew file mode 100644index 0000000000..e9c909147b--- /dev/null+++ b/spree/core/app/workflows/spree/stock_transfers/create.rb@@ -0,0 +1,61 @@+module Spree+ module StockTransfers+ # Plans a transfer. Nothing moves: a draft is a packing list the merchant+ # can still edit, and stock only leaves the source warehouse when+ # {Spree::StockTransfers::MarkInTransit} runs.+ class Create < Spree::Workflow+ hooks :validate, :after_create++ # The created transfer — hook handlers read it (nil while :validate runs).+ attr_reader :stock_transfer++ # @param store [Spree::Store]+ # @param source_location [Spree::StockLocation] where the goods leave from+ # @param destination_location [Spree::StockLocation] where they are going+ # @param items [Array<Hash>] `[{ variant:, quantity_shipped: }]`; a draft+ # may legitimately open empty and gain lines as the merchant packs+ # @param reference [String, nil] the merchant's own label for the trip+ # @param notes [String, nil]+ # @param created_by [Object, nil]+ def perform(store:, source_location:, destination_location:, items: [],+ reference: nil, notes: nil, created_by: nil)+ super++ step :build_transfer+ run_hooks :validate++ ApplicationRecord.transaction do+ step :save_transfer+ end++ run_hooks :after_create+ stock_transfer.publish_event('stock_transfer.created')+ success(stock_transfer.reload)+ end++ private++ def build_transfer+ @stock_transfer = store.stock_transfers.new(+ source_location: source_location,+ destination_location: destination_location,+ reference: reference,+ notes: notes,+ created_by: created_by,+ status: Spree::StockTransfer.default_status+ )++ Array(items).each do |item|+ @stock_transfer.items.build(variant: item[:variant], quantity_shipped: item[:quantity_shipped])+ end+ end++ # Line-level problems — a missing variant, a quantity of zero, the same+ # SKU twice — are model validations, so they answer with the field that+ # is wrong rather than one message about the whole document.+ def save_transfer+ failure(stock_transfer) unless stock_transfer.save+ end+ end+ end+enddiff --git a/spree/core/app/workflows/spree/stock_transfers/mark_in_transit.rb b/spree/core/app/workflows/spree/stock_transfers/mark_in_transit.rbnew file mode 100644index 0000000000..d7db079f28--- /dev/null+++ b/spree/core/app/workflows/spree/stock_transfers/mark_in_transit.rb@@ -0,0 +1,75 @@+module Spree+ module StockTransfers+ # The van has left. This is the moment stock leaves the source warehouse:+ # `shipped` movements are written against the source's levels, and the+ # units are in flight until the destination counts them in.+ #+ # The destination is deliberately untouched. A merchant who marked a+ # transfer in transit yesterday should see the source short and the+ # destination unchanged — that is what the 5.x one-shot transfer could not+ # express, and why availability was wrong for the whole journey.+ class MarkInTransit < Spree::Workflow+ hooks :validate, :before_unstock, :after_mark_in_transit++ # @param stock_transfer [Spree::StockTransfer]+ # @param force [Boolean] ship even if it drives the source below zero.+ # A merchant forcing a departure has decided the box left whatever the+ # ledger claims.+ def perform(stock_transfer:, force: false)+ super++ step :ensure_shippable+ step :ensure_source_has_stock unless force+ run_hooks :validate++ ApplicationRecord.transaction do+ run_hooks :before_unstock+ step :write_shipped_movements+ step :mark_in_transit+ end++ run_hooks :after_mark_in_transit+ stock_transfer.publish_event('stock_transfer.shipped')+ success(stock_transfer.reload)+ end++ private++ def ensure_shippable+ unless stock_transfer.draft? || stock_transfer.ready_to_ship?+ failure(stock_transfer, Spree.t('stock_transfer.errors.not_shippable'))+ end+ failure(stock_transfer, Spree.t('stock_transfer.errors.must_have_variant')) if stock_transfer.items.empty?+ end++ # Every line needs enough available stock for the quantity being moved,+ # not merely some: without the per-line check a transfer takes more than+ # the shelf holds and leaves it negative.+ def ensure_source_has_stock+ source = stock_transfer.source_location++ unavailable_items = stock_transfer.items.select do |item|+ level = source.stock_level(item.variant_id)+ level.nil? || level.available_count < item.quantity_shipped+ end++ return if unavailable_items.empty?++ failure(stock_transfer,+ Spree.t('stock_transfer.errors.variants_unavailable', stock: source.name))+ end++ def write_shipped_movements+ source = stock_transfer.source_location++ stock_transfer.items.each do |item|+ source.unstock(item.variant, item.quantity_shipped, stock_transfer, force: force)+ end+ end++ def mark_in_transit+ failure(stock_transfer) unless stock_transfer.update(status: 'in_transit', shipped_at: Time.current)+ end+ end+ end+enddiff --git a/spree/core/app/workflows/spree/stock_transfers/mark_ready.rb b/spree/core/app/workflows/spree/stock_transfers/mark_ready.rbnew file mode 100644index 0000000000..69e1564039--- /dev/null+++ b/spree/core/app/workflows/spree/stock_transfers/mark_ready.rb@@ -0,0 +1,36 @@+module Spree+ module StockTransfers+ # The box is packed. Freezes the lines so the warehouse and the merchant+ # are looking at the same list, without yet taking anything off the shelf.+ class MarkReady < Spree::Workflow+ hooks :validate, :after_mark_ready++ # @param stock_transfer [Spree::StockTransfer]+ def perform(stock_transfer:)+ super++ step :ensure_draft+ run_hooks :validate++ ApplicationRecord.transaction do+ step :mark_ready+ end++ run_hooks :after_mark_ready+ stock_transfer.publish_event('stock_transfer.ready_to_ship')+ success(stock_transfer.reload)+ end++ private++ def ensure_draft+ failure(stock_transfer, Spree.t('stock_transfer.errors.not_draft')) unless stock_transfer.draft?+ failure(stock_transfer, Spree.t('stock_transfer.errors.must_have_variant')) if stock_transfer.items.empty?+ end++ def mark_ready+ failure(stock_transfer) unless stock_transfer.update(status: 'ready_to_ship')+ end+ end+ end+enddiff --git a/spree/core/app/workflows/spree/stock_transfers/receive.rb b/spree/core/app/workflows/spree/stock_transfers/receive.rbnew file mode 100644index 0000000000..d296df0d86--- /dev/null+++ b/spree/core/app/workflows/spree/stock_transfers/receive.rb@@ -0,0 +1,118 @@+module Spree+ module StockTransfers+ # Records what the destination warehouse actually counted in.+ #+ # 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.+ class Receive < Spree::Workflow+ hooks :validate, :before_restock, :after_receive++ # @param stock_transfer [Spree::StockTransfer]+ # @param items [Array<Hash>, nil] `[{ item:, quantity_received:,+ # discrepancy_reason: }]`; nil receives every line in full+ # @param received_by [Object, nil]+ def perform(stock_transfer:, items: nil, received_by: nil)+ super++ step :ensure_receivable+ step :normalize_items+ run_hooks :validate++ ApplicationRecord.transaction do+ 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)+ end++ private++ def ensure_receivable+ return if stock_transfer.in_flight?++ failure(stock_transfer, Spree.t('stock_transfer.errors.not_in_transit'))+ end++ 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+ 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'))+ 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++ {+ item: line,+ quantity_received: quantity,+ discrepancy_reason: item[:discrepancy_reason],+ delta: quantity - line.quantity_received.to_i+ }+ 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)++ item[:item].update!(attributes)+ end+ 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+ end++ # `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)+ end+ end+ end+enddiff --git a/spree/core/app/workflows/spree/stock_transfers/update.rb b/spree/core/app/workflows/spree/stock_transfers/update.rbnew file mode 100644index 0000000000..b99d4da73b--- /dev/null+++ b/spree/core/app/workflows/spree/stock_transfers/update.rb@@ -0,0 +1,55 @@+module Spree+ module StockTransfers+ # Edits a draft transfer. Once the box is marked ready what is in it is a+ # matter of record, so this refuses anything past `draft` rather than+ # quietly rewriting a document the warehouse is already acting on.+ class Update < Spree::Workflow+ hooks :validate, :after_update++ # @param stock_transfer [Spree::StockTransfer]+ # @param attributes [Hash] editable columns — reference, notes, the two+ # locations, metadata+ # @param items [Array<Hash>, nil] `[{ variant:, quantity_shipped: }]`+ # replacing the current lines; nil leaves them alone+ def perform(stock_transfer:, attributes: {}, items: nil)+ super++ step :ensure_editable+ run_hooks :validate++ ApplicationRecord.transaction do+ step :apply_changes+ step :save_transfer+ end++ run_hooks :after_update+ success(stock_transfer.reload)+ end++ private++ def ensure_editable+ return if stock_transfer.editable?++ failure(stock_transfer, Spree.t('stock_transfer.errors.not_editable'))+ end++ # A whole-list replacement rather than a per-line diff: a draft's lines+ # are what the merchant is still deciding, and sending the list they+ # want is simpler for a client than working out which rows to delete.+ def apply_changes+ stock_transfer.assign_attributes(attributes) if attributes.present?+ return if items.nil?++ stock_transfer.items.destroy_all+ Array(items).each do |item|+ stock_transfer.items.build(variant: item[:variant], quantity_shipped: item[:quantity_shipped])+ end+ end++ def save_transfer+ failure(stock_transfer) unless stock_transfer.save+ end+ end+ end+enddiff --git a/spree/core/config/locales/en.yml b/spree/core/config/locales/en.ymlindex 3fe11e2908..5c9c803719 100644--- a/spree/core/config/locales/en.yml+++ b/spree/core/config/locales/en.yml@@ -558,6 +558,12 @@ en:spree/property:one: Propertyother: Properties+ spree/purchase_order:+ one: Purchase Order+ other: Purchase Orders+ spree/purchase_order_item:+ one: Purchase Order Item+ other: Purchase Order Itemsspree/refund_reason:one: Refund Reasonother: Refund Reasons@@ -591,9 +597,15 @@ en:spree/stock_transfer:one: Stock Transferother: Stock Transfers+ spree/stock_transfer_item:+ one: Stock Transfer Item+ other: Stock Transfer Itemsspree/store:one: Storeother: Stores+ spree/supplier:+ one: Supplier+ other: Suppliersspree/store_credit:one: Store Creditother: Store Credits@@ -1042,6 +1054,7 @@ en:delivery_zone_postal_definition_required: postal code member requires a prefix or a from/to rangedelivery_zone_prefix_and_range_exclusive: cannot be combined with a from/to rangedelivery_zone_range_inverted: must be greater than or equal to postal_code_from+ duplicate_variant: cannot list the same variant twicedelivery_zone_range_not_supported: postal code ranges are not supported for this country — use prefixesdiscount_has_no_effect: discount would have no effect on this orderdiscount_value_must_be_positive: discount value must be a positive number@@ -1074,6 +1087,7 @@ en:profile_does_not_accept_provider: "%{provider} deliveries cannot join the %{profile} profile"promotion_discount_not_editable: promotion discounts are managed by recalculation and cannot be editedrate_provider_requires_shipping: "%{provider} quotes shipments, so this method must ship to an address"+ received_exceeds_expected: cannot be more than the %{expected} expectedrate_provider_unavailable: is not available for this store — connect its integration firstsame_as_inviter: cannot be the same as the inviterseller_delivery_method_not_shareable: only the marketplace's own delivery methods can be shared with sellers@@ -1602,6 +1616,17 @@ en:property: Propertyprovider: Providerpublished_at: Published at+ 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+ must_have_variant: You must add at least one variant+ no_items_received: No units were received+ not_draft: Only a draft purchase order can be marked as ordered+ not_editable: Only a draft purchase order can be edited+ not_ordered: Only a purchase order that has been placed can be receivedqty: Qtyquantity: Quantityquery: Query@@ -1859,8 +1884,20 @@ en:stock_movements: Stock Movementsstock_transfer:errors:+ already_closed: This transfer has already been completed or cancelled+ in_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+ locations_in_different_stores: must belong to the same store as the source locationmust_have_variant: You must add at least one variant+ no_items_received: No units were received+ not_draft: Only a draft transfer can be marked as ready to ship+ not_editable: Only a draft transfer can be edited+ not_in_transit: Only a transfer in transit can be received+ not_shippable: Only a draft or ready-to-ship transfer can be marked in transitsame_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/20260907000001_add_inventory_operations.rb b/spree/core/db/migrate/20260907000001_add_inventory_operations.rbnew file mode 100644index 0000000000..f262f486ed--- /dev/null+++ b/spree/core/db/migrate/20260907000001_add_inventory_operations.rb@@ -0,0 +1,104 @@+class AddInventoryOperations < ActiveRecord::Migration[8.1]+ def change+ # A transfer becomes a multi-day operation with its own status, and gains+ # the store it has never carried (docs/plans/6.0-inventory-operations.md).+ # `source_location_id` stays nullable: emptying it of the external-receive+ # rows is the upgrade task's job, not a migration's.+ add_column :spree_stock_transfers, :store_id, :bigint+ add_column :spree_stock_transfers, :status, :string+ add_column :spree_stock_transfers, :shipped_at, :datetime+ add_column :spree_stock_transfers, :received_at, :datetime+ add_column :spree_stock_transfers, :notes, :text+ add_column :spree_stock_transfers, :created_by_id, :bigint+ # The upgrade task soft-deletes the external receives it converts into+ # purchase orders, so their T-… numbers stay findable without the receive+ # showing up twice.+ add_column :spree_stock_transfers, :deleted_at, :datetime+ add_index :spree_stock_transfers, :store_id+ add_index :spree_stock_transfers, :status+ add_index :spree_stock_transfers, :deleted_at++ # An STI column that never had a subclass to hold: always null, exposed by+ # nothing (docs/plans/6.0-inventory-operations.md, phase 6).+ remove_column :spree_stock_transfers, :type, :string++ create_table :spree_stock_transfer_items do |t|+ t.references :stock_transfer, null: false+ t.references :variant, null: false+ t.integer :quantity_shipped, null: false, default: 0+ t.integer :quantity_received, null: false, default: 0+ t.string :discrepancy_reason+ t.timestamps+ end+ add_index :spree_stock_transfer_items, [:stock_transfer_id, :variant_id],+ unique: true, name: 'idx_stock_transfer_items_unique'++ create_table :spree_suppliers do |t|+ t.string :name, null: false+ t.string :contact_name+ t.string :email+ t.string :phone+ t.text :notes+ t.references :store, null: false+ # Inline address columns, mirroring spree_stock_locations: a supplier is+ # a place goods come from, edited as one flat form.+ t.string :address1+ t.string :address2+ t.string :city+ t.string :state_name+ t.string :state_code+ t.string :country_code+ t.string :postal_code+ if t.respond_to?(:jsonb)+ t.jsonb :metadata+ else+ t.json :metadata+ end+ t.datetime :deleted_at+ t.timestamps+ end+ add_index :spree_suppliers, [:store_id, :name], unique: true+ add_index :spree_suppliers, :deleted_at++ create_table :spree_purchase_orders do |t|+ t.string :number, null: false+ t.string :status+ t.string :currency, null: false+ t.string :reference+ t.references :supplier, null: false+ t.references :store, null: false+ t.references :destination_location, null: false+ t.date :expected_at+ t.datetime :ordered_at+ t.datetime :received_at+ t.text :notes+ t.bigint :created_by_id+ if t.respond_to?(:jsonb)+ t.jsonb :metadata+ else+ t.json :metadata+ end+ t.timestamps+ end+ add_index :spree_purchase_orders, :number, unique: true+ add_index :spree_purchase_orders, :status++ create_table :spree_purchase_order_items do |t|+ t.references :purchase_order, null: false+ t.references :variant, null: false+ t.integer :quantity_ordered, null: false, default: 0+ t.integer :quantity_received, null: false, default: 0+ t.decimal :unit_cost, precision: 10, scale: 2, null: false, default: 0+ t.timestamps+ end+ add_index :spree_purchase_order_items, [:purchase_order_id, :variant_id],+ unique: true, name: 'idx_purchase_order_items_unique'++ # The purchase order is a new cause flavour for the `received` kind; the+ # unit cost is what those units landed at, which is what a rolling average+ # cost will be computed from.+ add_column :spree_stock_movements, :purchase_order_id, :bigint+ add_index :spree_stock_movements, :purchase_order_id+ add_column :spree_stock_movements, :unit_cost, :decimal, precision: 10, scale: 2+ end+enddiff --git a/spree/core/lib/spree/core/dependencies.rb b/spree/core/lib/spree/core/dependencies.rbindex d677ab032e..a83c41ac21 100644--- a/spree/core/lib/spree/core/dependencies.rb+++ b/spree/core/lib/spree/core/dependencies.rb@@ -96,6 +96,19 @@ module Spreedelivery_destroy_service: 'Spree::Deliveries::Destroy',return_purchase_label_workflow: 'Spree::Returns::PurchaseLabel',+ # inventory operations+ stock_transfer_create_workflow: 'Spree::StockTransfers::Create',+ stock_transfer_update_workflow: 'Spree::StockTransfers::Update',+ stock_transfer_mark_ready_workflow: 'Spree::StockTransfers::MarkReady',+ stock_transfer_mark_in_transit_workflow: 'Spree::StockTransfers::MarkInTransit',+ stock_transfer_receive_workflow: 'Spree::StockTransfers::Receive',+ stock_transfer_cancel_workflow: 'Spree::StockTransfers::Cancel',+ 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',+# returnsreturn_create_workflow: 'Spree::Returns::Create',return_approve_workflow: 'Spree::Returns::Approve',diff --git a/spree/core/lib/spree/core/permission_configuration.rb b/spree/core/lib/spree/core/permission_configuration.rbindex 413fc00f69..3461d7cce6 100644--- a/spree/core/lib/spree/core/permission_configuration.rb+++ b/spree/core/lib/spree/core/permission_configuration.rb@@ -364,7 +364,15 @@ module Spree})register_resource(:stock, group: :catalog, audiences: %i[seller], subjects: -> {[Spree::StockLevel, Spree::StockLocation, Spree::StockMovement,- Spree::StockTransfer, Spree::StockReservation]+ Spree::StockTransfer, Spree::StockTransferItem, Spree::StockReservation]+ })+ # 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+ # suppliers" (docs/plans/6.0-inventory-operations.md). Closed to the+ # 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]})register_resource(:promotions, group: :marketing, subjects: -> {diff --git a/spree/core/lib/spree/testing_support/factories/purchase_order_factory.rb b/spree/core/lib/spree/testing_support/factories/purchase_order_factory.rbnew file mode 100644index 0000000000..4ea842fcd4--- /dev/null+++ b/spree/core/lib/spree/testing_support/factories/purchase_order_factory.rb@@ -0,0 +1,49 @@+FactoryBot.define do+ factory :purchase_order, class: Spree::PurchaseOrder do+ transient do+ # Zero opens an empty draft — what a merchant sees before adding a SKU.+ quantity { 10 }+ unit_cost { 12.5 }+ end++ store { Spree::Store.default || create(:store) }+ supplier { create(:supplier, store: store) }+ destination_location { create(:stock_location, store: store) }+ status { Spree::PurchaseOrder.default_status }+ expected_at { 2.weeks.from_now.to_date }++ after(:build) do |purchase_order, evaluator|+ next if purchase_order.items.any? || evaluator.quantity.to_i.zero?++ purchase_order.items.build(+ variant: create(:variant),+ quantity_ordered: evaluator.quantity,+ unit_cost: evaluator.unit_cost+ )+ end++ trait :ordered do+ after(:create) do |purchase_order|+ Spree::PurchaseOrders::MarkOrdered.call(purchase_order: purchase_order)+ purchase_order.reload+ end+ end++ trait :received do+ ordered++ after(:create) do |purchase_order|+ Spree::PurchaseOrders::Receive.call(purchase_order: purchase_order)+ purchase_order.reload+ end+ end+ end++ factory :purchase_order_item, class: Spree::PurchaseOrderItem do+ purchase_order+ variant+ quantity_ordered { 10 }+ quantity_received { 0 }+ unit_cost { 12.5 }+ end+enddiff --git a/spree/core/lib/spree/testing_support/factories/stock_transfer_factory.rb b/spree/core/lib/spree/testing_support/factories/stock_transfer_factory.rbindex 4bc2f59af7..2fc781fd1b 100644--- a/spree/core/lib/spree/testing_support/factories/stock_transfer_factory.rb+++ b/spree/core/lib/spree/testing_support/factories/stock_transfer_factory.rb@@ -1,12 +1,59 @@FactoryBot.define dofactory :stock_transfer, class: Spree::StockTransfer do- association :source_location, factory: :stock_location- association :destination_location, factory: :stock_location+ transient do+ # Units of one variant to move; zero opens an empty draft, which is what+ # a merchant sees before they add the first SKU. Enough source stock is+ # created for the in_transit trait to actually ship.+ quantity { 5 }+ end- stock_movements { [build(:stock_movement)] }+ store { Spree::Store.default || create(:store) }+ source_location { create(:stock_location, store: store) }+ destination_location { create(:stock_location, store: store) }+ status { Spree::StockTransfer.default_status }+ reference { 'Restocking the Brooklyn shop' }- number {}- reference {}- type {}+ # A draft with one line on it: what a merchant reaches by opening the+ # new-transfer screen and adding a SKU, and the start of every lifecycle+ # spec.+ after(:build) do |stock_transfer, evaluator|+ next if stock_transfer.items.any? || evaluator.quantity.to_i.zero?++ stock_transfer.items.build(variant: create(:variant), quantity_shipped: evaluator.quantity)+ end++ trait :ready_to_ship do+ status { 'ready_to_ship' }+ end++ # Shipped through the workflow, so the source's `shipped` movements exist+ # and its shelf is genuinely short — which is what the receive specs and+ # the cancel-in-transit specs measure against.+ trait :in_transit do+ after(:create) do |stock_transfer|+ stock_transfer.items.each do |item|+ stock_transfer.source_location.restock(item.variant, item.quantity_shipped)+ end++ Spree::StockTransfers::MarkInTransit.call(stock_transfer: stock_transfer)+ stock_transfer.reload+ end+ end++ trait :received do+ in_transit++ after(:create) do |stock_transfer|+ Spree::StockTransfers::Receive.call(stock_transfer: stock_transfer)+ stock_transfer.reload+ end+ end+ end++ factory :stock_transfer_item, class: Spree::StockTransferItem do+ stock_transfer+ variant+ quantity_shipped { 5 }+ quantity_received { 0 }endenddiff --git a/spree/core/lib/spree/testing_support/factories/supplier_factory.rb b/spree/core/lib/spree/testing_support/factories/supplier_factory.rbnew file mode 100644index 0000000000..ecb182abb4--- /dev/null+++ b/spree/core/lib/spree/testing_support/factories/supplier_factory.rb@@ -0,0 +1,17 @@+FactoryBot.define do+ factory :supplier, class: Spree::Supplier do+ store { Spree::Store.default || create(:store) }+ sequence(:name) { |n| "Supplier ##{n}" }+ contact_name { 'Dana Okafor' }+ sequence(:email) { |n| "supplier#{n}@example.com" }+ phone { '555-0100' }++ trait :with_address do+ address1 { '1 Warehouse Way' }+ city { 'Brooklyn' }+ state_code { 'NY' }+ country_code { 'US' }+ postal_code { '11201' }+ end+ end+enddiff --git a/spree/core/lib/tasks/inventory_operations_migration.rake b/spree/core/lib/tasks/inventory_operations_migration.rakenew file mode 100644index 0000000000..a39e47894c--- /dev/null+++ b/spree/core/lib/tasks/inventory_operations_migration.rake@@ -0,0 +1,181 @@+module Spree+ # Turns 5.x "external receive" stock transfers into purchase orders.+ #+ # A supplier receive was never a transfer: it has a cost, a supplier and an+ # expected date, none of which moving stock between two of the merchant's own+ # warehouses has (docs/plans/6.0-inventory-operations.md). Each source-less+ # transfer becomes a Spree::PurchaseOrder against a "Migrated receives"+ # supplier, its existing movements are re-pointed at the new order, and the+ # transfer is soft-deleted so its number stays readable.+ #+ # Stock is never touched: those movements already moved it, at the time.+ class ExternalReceivesMigrator+ # Historical unit costs are unknowable — nothing recorded them.+ UNKNOWN_UNIT_COST = 0+ SUPPLIER_NAME = 'Migrated receives'.freeze++ def initialize(output: $stdout)+ @output = output+ @migrated = 0+ @skipped = 0+ end++ def call+ pending.find_each { |transfer| migrate_one(transfer) }+ backfilled = backfill_internal_transfers++ @output.puts " Migrated #{@migrated} external receive(s), skipped #{@skipped}."+ @output.puts " Backfilled store and status on #{backfilled} internal transfer(s)."+ end++ private++ # Only live, source-less rows. A previous run's output is soft-deleted, so+ # re-running picks up just what it could not reach.+ def pending+ Spree::StockTransfer.where(source_location_id: nil)+ end++ def migrate_one(transfer)+ destination = transfer.destination_location++ if destination.nil? || destination.store.nil?+ skip(transfer, 'its destination location has no store')+ return+ end++ Spree::StockTransfer.transaction do+ movements = transfer.stock_movements.to_a+ purchase_order = build_purchase_order(transfer, destination, movements)++ # A receive whose movements no longer resolve to a variant has nothing+ # to order; the transfer is left for a human to look at.+ if purchase_order.items.empty?+ skip(transfer, 'no stock movements to build lines from')+ raise ActiveRecord::Rollback+ end++ purchase_order.save!+ Spree::StockMovement.where(id: movements.map(&:id)).update_all(purchase_order_id: purchase_order.id)+ transfer.update_columns(status: 'received', deleted_at: Time.current)++ @output.puts " #{transfer.number} → #{purchase_order.number} (#{purchase_order.items.size} line(s))"+ @migrated += 1+ end+ end++ def build_purchase_order(transfer, destination, movements)+ store = destination.store++ purchase_order = store.purchase_orders.new(+ supplier: supplier_for(store),+ destination_location: destination,+ currency: store.default_currency,+ status: 'received',+ received_at: transfer.created_at,+ reference: transfer.reference.presence || transfer.number,+ notes: "Migrated from stock transfer #{transfer.number}."+ )++ lines_from(movements).each do |variant_id, quantity|+ purchase_order.items.build(+ variant_id: variant_id,+ quantity_ordered: quantity,+ quantity_received: quantity,+ unit_cost: UNKNOWN_UNIT_COST+ )+ end++ purchase_order+ 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.+ def lines_from(movements)+ movements.each_with_object({}) do |movement, lines|+ variant_id = movement.stock_level&.variant_id+ next if variant_id.nil?++ lines[variant_id] = lines.fetch(variant_id, 0) + movement.quantity.abs+ end+ end++ def supplier_for(store)+ @suppliers ||= {}+ @suppliers[store.id] ||= store.suppliers.find_or_create_by!(name: SUPPLIER_NAME) do |supplier|+ supplier.notes = 'Created by spree:upgrade:migrate_external_receives_to_purchase_orders ' \+ 'to own receives that predate purchase orders.'+ end+ end++ # Every 5.x transfer moved its stock the instant it was created, so it is+ # retroactively a completed one — which is what today's reality already is.+ def backfill_internal_transfers+ scope = Spree::StockTransfer.where(status: nil).or(Spree::StockTransfer.where(store_id: nil))+ count = 0++ scope.includes(:destination_location).find_each do |transfer|+ store_id = transfer.store_id || transfer.destination_location&.store_id+ next if store_id.nil?++ transfer.update_columns(+ store_id: store_id,+ status: transfer.status || 'received',+ received_at: transfer.received_at || transfer.created_at+ )+ count += 1+ end++ count+ end++ def skip(transfer, reason)+ @output.puts " Skipping transfer #{transfer.number}: #{reason}."+ @skipped += 1+ end+ end+end++namespace :spree do+ namespace :upgrade do+ desc <<~DESC+ Converts 5.x "external receive" stock transfers — the ones with no source+ location — into purchase orders, and gives every other transfer the store+ and status the 6.0 lifecycle expects.++ The original transfer is soft-deleted so its T-… number stays findable+ for historical reporting without the same receive appearing twice in the+ admin. Purge them with spree:upgrade:purge_migrated_external_receives+ once nobody needs the old numbers.++ Idempotent: stock is never touched, and a transfer already migrated is+ out of scope on the next run.+ DESC+ task migrate_external_receives_to_purchase_orders: :environment do+ Spree::ExternalReceivesMigrator.new.call+ end++ desc <<~DESC+ Deletes the stock transfers that+ spree:upgrade:migrate_external_receives_to_purchase_orders soft-deleted,+ once their T-… numbers are no longer needed.++ Only source-less, soft-deleted rows whose movements now belong to a+ purchase order are removed — a transfer still owning its ledger is left+ alone.+ DESC+ task purge_migrated_external_receives: :environment do+ still_owning_movements = Spree::StockMovement.where(purchase_order_id: nil).+ where.not(stock_transfer_id: nil).select(:stock_transfer_id)++ migrated = Spree::StockTransfer.only_deleted.+ where(source_location_id: nil).+ where.not(id: still_owning_movements)++ count = migrated.count+ migrated.find_each(&:really_destroy!)++ puts " Purged #{count} migrated external receive(s)."+ end+ end+enddiff --git a/spree/core/spec/models/spree/purchase_order_spec.rb b/spree/core/spec/models/spree/purchase_order_spec.rbnew file mode 100644index 0000000000..5fda92d2ce--- /dev/null+++ b/spree/core/spec/models/spree/purchase_order_spec.rb@@ -0,0 +1,85 @@+require 'spec_helper'++module Spree+ describe PurchaseOrder, type: :model do+ let(:store) { Spree::Store.default }++ it_behaves_like 'metadata'+ it_behaves_like 'lifecycle events'++ describe 'defaults' do+ subject(:purchase_order) { create(:purchase_order, store: store) }++ it 'opens as a draft with a PO number' do+ expect(purchase_order).to be_draft+ expect(purchase_order.number).to start_with('PO')+ end++ it 'takes the store currency unless told otherwise' do+ expect(purchase_order.currency).to eq(store.default_currency)+ expect(create(:purchase_order, store: store, currency: 'EUR').currency).to eq('EUR')+ end+ end++ describe 'validations' do+ it 'refuses two lines for the same variant' do+ variant = create(:variant)+ purchase_order = build(:purchase_order, store: store)+ purchase_order.items = [+ build(:purchase_order_item, purchase_order: nil, variant: variant),+ build(:purchase_order_item, purchase_order: nil, variant: variant)+ ]++ expect(purchase_order).to be_invalid+ expect(purchase_order.errors[:items]).to include(Spree.t('errors.messages.duplicate_variant'))+ end++ it 'allows an empty draft but not an empty placed order' do+ purchase_order = build(:purchase_order, store: store, quantity: 0)++ expect(purchase_order).to be_valid++ purchase_order.status = 'ordered'+ expect(purchase_order).to be_invalid+ end+ end++ describe '#subtotal' do+ it 'is what the supplier will invoice for everything ordered' do+ purchase_order = create(:purchase_order, store: store, quantity: 0)+ purchase_order.items.create!(variant: create(:variant), quantity_ordered: 10, unit_cost: 12.5)+ purchase_order.items.create!(variant: create(:variant), quantity_ordered: 3, unit_cost: 4)++ expect(purchase_order.subtotal).to eq(137)+ expect(purchase_order.display_subtotal.to_s).to eq('$137.00')+ end+ end++ describe 'items' do+ subject(:item) do+ create(:purchase_order_item, purchase_order: create(:purchase_order, store: store, quantity: 0),+ quantity_ordered: 10, quantity_received: 4, unit_cost: 12.5)+ end++ it 'reports what is still owed' do+ expect(item.quantity_expected).to eq(10)+ expect(item.outstanding).to eq(6)+ expect(item).to be_under_received+ end++ it 'costs the whole line at the agreed unit price' do+ expect(item.total_cost).to eq(125)+ expect(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+ end+ end+ end+enddiff --git a/spree/core/spec/models/spree/stock_location_spec.rb b/spree/core/spec/models/spree/stock_location_spec.rbindex 1fd6cf19ae..58bc84574c 100644--- a/spree/core/spec/models/spree/stock_location_spec.rb+++ b/spree/core/spec/models/spree/stock_location_spec.rb@@ -172,21 +172,29 @@ module Spreeit 'restocks a variant with a received movement' docause = double- expect(subject).to receive(:move).with(variant, 5, kind: 'received', cause: cause, persist: true)+ expect(subject).to receive(:move).with(variant, 5, kind: 'received', cause: cause, unit_cost: nil)subject.restock(variant, 5, cause)end+ # What the units landed at, for the rolling average cost a purchase order+ # makes possible. Null for stock the merchant already owned.+ it 'records the unit cost of a purchase when one is given' do+ cause = double+ expect(subject).to receive(:move).with(variant, 5, kind: 'received', cause: cause, unit_cost: 12.5)+ subject.restock(variant, 5, cause, unit_cost: 12.5)+ end+# The sign no longer carries the direction — the kind does — so a# departure is written positive like every other order-driven kind.it 'unstocks a variant with a shipped movement' docause = double- expect(subject).to receive(:move).with(variant, 5, kind: 'shipped', cause: cause, persist: true, force: false)+ expect(subject).to receive(:move).with(variant, 5, kind: 'shipped', cause: cause, force: false)subject.unstock(variant, 5, cause)endit 'passes force through so a merchant can record a departure the shelf cannot cover' docause = double- expect(subject).to receive(:move).with(variant, 5, kind: 'shipped', cause: cause, persist: true, force: true)+ expect(subject).to receive(:move).with(variant, 5, kind: 'shipped', cause: cause, force: true)subject.unstock(variant, 5, cause, force: true)enddiff --git a/spree/core/spec/models/spree/stock_movement_spec.rb b/spree/core/spec/models/spree/stock_movement_spec.rbindex 5d7a7e7142..2cc714974b 100644--- a/spree/core/spec/models/spree/stock_movement_spec.rb+++ b/spree/core/spec/models/spree/stock_movement_spec.rb@@ -144,7 +144,7 @@ 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]+ return_id exchange_id stock_transfer_id purchase_order_id unit_cost])enddiff --git a/spree/core/spec/models/spree/stock_transfer_spec.rb b/spree/core/spec/models/spree/stock_transfer_spec.rbindex 492bc6a607..5dfd7fe795 100644--- a/spree/core/spec/models/spree/stock_transfer_spec.rb+++ b/spree/core/spec/models/spree/stock_transfer_spec.rb@@ -2,183 +2,138 @@ require 'spec_helper'module Spreedescribe StockTransfer, type: :model do+ let(:store) { Spree::Store.default }+ let(:source_location) { create(:stock_location, store: store) }+ let(:destination_location) { create(:stock_location, store: store) }+let(:stock_transfer) do- create(- :stock_transfer,- reference: 'PO123',- source_location: source_location,- destination_location: destination_location- )+ create(:stock_transfer,+ store: store,+ reference: 'PO123',+ source_location: source_location,+ destination_location: destination_location)end- let(:destination_location) { create(:stock_location_with_items) }- let(:source_location) { create(:stock_location_with_items) }- let(:stock_level) { source_location.stock_levels.order(:id).first }- let(:variant) { stock_level.variant }-it_behaves_like 'metadata'it_behaves_like 'lifecycle events'- describe '#reference' do- subject { stock_transfer.reference }-- it { is_expected.to eq 'PO123' }- end-- describe '#transfer' do- subject { stock_transfer.transfer(source_location, destination_location, variants) }-- let(:stock_transfer) do- build(- :stock_transfer,- reference: 'PO123',- source_location: nil,- destination_location: nil,- stock_movements: []- )+ describe 'defaults' do+ it 'opens as a draft with a number' do+ expect(stock_transfer).to be_draft+ expect(stock_transfer.number).to start_with('T')+ expect(stock_transfer.reference).to eq('PO123')end- let(:variants) { { variant => 5 } }-- # A transfer moves goods, not promises: units another order is waiting- # for stay promised at the source.- it 'leaves the source location\'s promises intact' do- level = source_location.stock_level_or_create(variant)- level.update_column(:allocated_count, 3)-- subject+ # The table carried no store until 6.0, which left the admin endpoint+ # unscoped: Spree::Base.for_store falls through to `self` when the store+ # has no matching association.+ it 'takes its store from the destination warehouse when none is given' do+ transfer = described_class.create!(+ source_location: source_location,+ destination_location: destination_location,+ items: [build(:stock_transfer_item, stock_transfer: nil)]+ )- expect(level.reload.allocated_count).to eq(3)+ expect(transfer.store).to eq(destination_location.store)+ expect(described_class.for_store(store)).to include(transfer)end+ end- it 'transfers variants between 2 locations' do- subject-- expect(source_location.count_on_hand(variant)).to eq 5- expect(destination_location.count_on_hand(variant)).to eq 5-- expect(stock_transfer.source_location).to eq source_location- expect(stock_transfer.destination_location).to eq destination_location+ describe 'validations' do+ it 'refuses a transfer to the location it leaves from' do+ transfer = build(:stock_transfer, source_location: source_location,+ destination_location: source_location)- # Quantities are positive on both sides now; the kind says which way- # the goods went.- expect(stock_transfer.source_movements.first).to have_attributes(quantity: 5, kind: 'shipped')- expect(stock_transfer.destination_movements.first).to have_attributes(quantity: 5, kind: 'received')- expect(stock_transfer.source_movements.first.stock_transfer).to eq(stock_transfer)+ expect(transfer).to be_invalid+ expect(transfer.errors[:source_location]).to include(Spree.t('stock_transfer.errors.same_location'))end- # Checking only for a positive balance let a transfer take more than the- # shelf held and leave it negative.- context 'when the source holds some of the variant but not enough' do- let(:variants) { { variant => 5 } }-- before { source_location.stock_level_or_create(variant).update_column(:count_on_hand, 1) }-- it 'does not transfer the variants' do- expect(subject).to be false- expect(stock_transfer.errors[:base]).to include(- Spree.t('stock_transfer.errors.variants_unavailable', stock: source_location.name)- )- end+ # Two locations from different stores would take units out of one+ # tenant's inventory and put them into another's.+ it 'refuses two warehouses belonging to different stores' do+ other_store_location = create(:stock_location, store: create(:store))+ transfer = build(:stock_transfer, source_location: source_location,+ destination_location: other_store_location)- it 'leaves the source shelf alone' do- subject-- expect(source_location.stock_level(variant).reload.count_on_hand).to eq(1)- end+ expect(transfer).to be_invalid+ expect(transfer.errors[:destination_location]).to include(+ Spree.t('stock_transfer.errors.locations_in_different_stores')+ )end- context 'when variants are not available in the source location' do- let(:variants) { { variant => 5, other_variant => 5 } }- let(:other_variant) { create(:variant) }-- it 'does not transfer the variants' do- expect(subject).to be false- expect(stock_transfer.errors[:base]).to include(- Spree.t('stock_transfer.errors.variants_unavailable', stock: source_location.name)- )- end+ it 'refuses two lines for the same variant' do+ variant = create(:variant)+ transfer = build(:stock_transfer, source_location: source_location,+ destination_location: destination_location)+ transfer.items = [+ build(:stock_transfer_item, stock_transfer: nil, variant: variant),+ build(:stock_transfer_item, stock_transfer: nil, variant: variant)+ ]++ expect(transfer).to be_invalid+ expect(transfer.errors[:items]).to include(Spree.t('errors.messages.duplicate_variant'))end- context 'when variants are empty' do- let(:variants) { {} }+ # A draft is a packing list the merchant is still filling in; anything+ # past draft describes a box that physically exists.+ it 'allows an empty draft but not an empty shipped transfer' do+ transfer = build(:stock_transfer, source_location: source_location,+ destination_location: destination_location, quantity: 0)- it 'does not transfer the variants' do- expect(subject).to be false- expect(stock_transfer.errors[:base]).to include(Spree.t('stock_transfer.errors.must_have_variant'))- end- end+ expect(transfer).to be_valid- context 'when variants are nil' do- let(:variants) { nil }-- it 'does not transfer the variants' do- expect(subject).to be false- expect(stock_transfer.errors[:base]).to include(Spree.t('stock_transfer.errors.must_have_variant'))- end+ transfer.status = 'in_transit'+ expect(transfer).to be_invalidendend- describe 'quantity guards' do- let(:source) { create(:stock_location_with_items) }- let(:destination) { create(:stock_location) }- let(:variant) { source.stock_levels.first.variant }-- # A negative quantity sails through the availability check — every count- # is greater than a negative number — and then takes stock off the source- # *and* the destination.- it 'refuses a negative transfer quantity' do- transfer = described_class.new-- expect(transfer.transfer(source, destination, { variant => -5 })).to be false- expect(transfer.errors[:base]).to be_present+ describe 'totals' do+ subject(:transfer) do+ create(:stock_transfer, store: store, source_location: source_location,+ destination_location: destination_location, quantity: 0)end- it 'refuses a zero transfer quantity' do- transfer = described_class.new-- expect(transfer.transfer(source, destination, { variant => 0 })).to be false+ before do+ transfer.items.create!(variant: create(:variant), quantity_shipped: 10, quantity_received: 7)+ transfer.items.create!(variant: create(:variant), quantity_shipped: 5, quantity_received: 5)end- # A receive has no source, so the availability check never runs and only- # this guard stands between a typo and stock disappearing.- it 'refuses a negative receive quantity' do- transfer = described_class.new+ it 'sums what was promised and what arrived' do+ expect(transfer.items_count).to eq(2)+ expect(transfer.quantity_expected_total).to eq(15)+ expect(transfer.quantity_received_total).to eq(12)+ end- expect(transfer.receive(destination, { variant => -5 })).to be false+ it 'is under-received while any line is still owed' do+ expect(transfer).to be_under_received+ expect(transfer).not_to be_fully_received+ expect(transfer.status_after_receive).to eq('partially_received')end- end- describe '#receive' do- subject { stock_transfer.receive(destination_location, { variant => 5 }) }+ it 'is fully received once every line is complete' do+ transfer.items.each { |item| item.update!(quantity_received: item.quantity_shipped) }+ transfer.items.reset- let(:stock_transfer) do- build(- :stock_transfer,- reference: 'PO123',- source_location: nil,- destination_location: nil,- stock_movements: []- )+ expect(transfer).to be_fully_received+ expect(transfer.status_after_receive).to eq('received')end+ end- it 'receives new inventory (from a seller)' do- subject-- expect(destination_location.count_on_hand(variant)).to eq 5+ describe 'scopes' do+ it 'separates the trips still running from the ones that are over' do+ draft = create(:stock_transfer, store: store)+ received = create(:stock_transfer, :received, store: store)- expect(stock_transfer.source_location).to be_nil- expect(stock_transfer.destination_location).to eq destination_location+ expect(described_class.open).to include(draft)+ expect(described_class.open).not_to include(received)+ expect(described_class.closed).to include(received)endend- describe '#validations' do- it 'checks if source location and destination location are the same' do- stock_movements = [build(:stock_movement)]-- expect(described_class.new(source_location: source_location, destination_location: source_location, stock_movements: stock_movements)).to be_invalid- expect(described_class.new(source_location: source_location, destination_location: destination_location, stock_movements: stock_movements)).to be_valid- expect(described_class.new(destination_location: destination_location, stock_movements: stock_movements)).to be_valid+ describe '#editable?' do+ it 'is true only while the box can still be repacked' do+ expect(create(:stock_transfer, store: store)).to be_editable+ expect(create(:stock_transfer, :ready_to_ship, store: store)).not_to be_editableendendenddiff --git a/spree/core/spec/models/spree/supplier_spec.rb b/spree/core/spec/models/spree/supplier_spec.rbnew file mode 100644index 0000000000..dfd5d8e132--- /dev/null+++ b/spree/core/spec/models/spree/supplier_spec.rb@@ -0,0 +1,68 @@+require 'spec_helper'++module Spree+ describe Supplier, type: :model do+ let(:store) { Spree::Store.default }++ it_behaves_like 'metadata'+ it_behaves_like 'lifecycle events'++ describe 'validations' do+ it 'requires a name unique within the store' do+ create(:supplier, store: store, name: 'Acme Wholesale')++ expect(build(:supplier, store: store, name: 'Acme Wholesale')).to be_invalid+ expect(build(:supplier, store: create(:store), name: 'Acme Wholesale')).to be_valid+ end++ # A supplier deleted a year ago must not block the name a merchant wants+ # to use today.+ it 'frees the name again once the supplier is deleted' do+ create(:supplier, store: store, name: 'Acme Wholesale').destroy++ expect(build(:supplier, store: store, name: 'Acme Wholesale')).to be_valid+ end++ it 'refuses an email that is not one' do+ expect(build(:supplier, email: 'not-an-email')).to be_invalid+ expect(build(:supplier, email: nil)).to be_valid+ end+ end++ describe 'normalization' do+ it 'stores the email lower-cased and trimmed' do+ supplier = create(:supplier, email: ' [email protected] ')++ expect(supplier.email).to eq('[email protected]')+ end+ end++ describe '#address' do+ it 'builds an unsaved address from its own columns' do+ supplier = build(:supplier, :with_address, name: 'Acme Wholesale')++ expect(supplier).to be_postable+ expect(supplier.address).to have_attributes(+ company: 'Acme Wholesale', city: 'Brooklyn', country_code: 'US', postal_code: '11201'+ )+ expect(supplier.address).not_to be_persisted+ end++ # Every caller needs the guard: a blank supplier answers with a blank+ # address that would otherwise read as configured.+ it 'is not postable without a street, a city and a country' do+ expect(build(:supplier)).not_to be_postable+ end+ end++ describe 'deleting' do+ it 'refuses while purchase orders still point at it' do+ supplier = create(:supplier, store: store)+ create(:purchase_order, store: store, supplier: supplier)++ expect(supplier.destroy).to be false+ expect(supplier.errors[:base]).to be_present+ end+ end+ end+enddiff --git a/spree/core/spec/workflows/spree/purchase_orders/lifecycle_spec.rb b/spree/core/spec/workflows/spree/purchase_orders/lifecycle_spec.rbnew file mode 100644index 0000000000..28b54adf5a--- /dev/null+++ b/spree/core/spec/workflows/spree/purchase_orders/lifecycle_spec.rb@@ -0,0 +1,205 @@+require 'spec_helper'++# Buying stock in: nothing counts toward availability until units actually+# land, and what they cost is recorded on the movement that lands them.+describe 'purchase order lifecycle', type: :model do+ let(:store) { Spree::Store.default }+ let(:supplier) { create(:supplier, store: store) }+ let(:destination) { create(:stock_location, store: store) }+ let(:variant) { create(:variant) }++ let(:purchase_order) do+ Spree::PurchaseOrders::Create.call(+ store: store,+ supplier: supplier,+ destination_location: destination,+ expected_at: 2.weeks.from_now.to_date,+ items: [{ variant: variant, quantity_ordered: 100, unit_cost: 12.5 }]+ ).value+ end++ def on_hand+ destination.stock_level(variant.id)&.count_on_hand.to_i+ end++ describe 'creating' do+ it 'drafts the order without buying anything' do+ expect(purchase_order).to be_draft+ expect(purchase_order.supplier).to eq(supplier)+ expect(purchase_order.currency).to eq(store.default_currency)+ expect(purchase_order.items.sole).to have_attributes(quantity_ordered: 100, unit_cost: 12.5)+ expect(on_hand).to eq(0)+ end++ it 'refuses a line with no quantity' do+ result = Spree::PurchaseOrders::Create.call(+ store: store, supplier: supplier, destination_location: destination,+ items: [{ variant: variant, quantity_ordered: 0, unit_cost: 1 }]+ )++ expect(result).to be_failure+ end+ end++ describe 'placing the order' do+ it 'freezes the lines and stamps when it went out' do+ result = Spree::PurchaseOrders::MarkOrdered.call(purchase_order: purchase_order)++ expect(result).to be_success+ expect(result.value).to be_ordered+ expect(result.value.ordered_at).to be_present+ expect(result.value).not_to be_editable+ end++ # A merchant who has ordered stock does not have it.+ it 'still leaves availability alone' do+ Spree::PurchaseOrders::MarkOrdered.call(purchase_order: purchase_order)++ expect(on_hand).to eq(0)+ end++ it 'refuses an order that has already gone out' do+ Spree::PurchaseOrders::MarkOrdered.call(purchase_order: purchase_order)++ result = Spree::PurchaseOrders::MarkOrdered.call(purchase_order: purchase_order.reload)++ expect(result).to be_failure+ expect(result.error.to_s).to eq(Spree.t('purchase_order.errors.not_draft'))+ end+ end++ describe 'receiving' do+ before { 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)++ expect(result).to be_success+ expect(result.value).to be_received+ expect(result.value.received_at).to be_present+ expect(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)++ movement = purchase_order.reload.stock_movements.sole+ expect(movement).to have_attributes(kind: 'received', quantity: 100, unit_cost: 12.5)+ expect(movement.purchase_order).to eq(purchase_order)+ expect(movement.display_unit_cost.to_s).to eq('$12.50')+ 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 }]+ )++ 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)+ 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)++ Spree::PurchaseOrders::Receive.call(purchase_order: purchase_order.reload,+ items: [{ item: item.reload, quantity_received: 100 }])++ 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(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 }]+ )++ expect(result).to be_failure+ expect(on_hand).to eq(0)+ end++ it 'refuses a line belonging to another order' do+ other_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 }]+ )++ expect(result).to be_failure+ expect(result.error.to_s).to eq(Spree.t('purchase_order.errors.item_not_on_order'))+ end++ it 'refuses an order that has not been placed' do+ draft = create(:purchase_order, store: store)++ result = Spree::PurchaseOrders::Receive.call(purchase_order: draft)++ expect(result).to be_failure+ expect(result.error.to_s).to eq(Spree.t('purchase_order.errors.not_ordered'))+ end+ end++ describe 'cancelling' do+ # A purchase order never moved stock, so there is nothing to unwind — and+ # units already received stay on the shelf, because the merchant has them.+ it 'closes what is outstanding and leaves received units alone' do+ Spree::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 }])++ result = Spree::PurchaseOrders::Cancel.call(purchase_order: purchase_order.reload,+ reason: 'Supplier went under')++ expect(result).to be_success+ expect(result.value).to be_canceled+ expect(result.value.notes).to include('Supplier went under')+ expect(on_hand).to eq(60)+ end++ it 'refuses an order that is already over' do+ Spree::PurchaseOrders::MarkOrdered.call(purchase_order: purchase_order)+ Spree::PurchaseOrders::Receive.call(purchase_order: purchase_order.reload)++ result = Spree::PurchaseOrders::Cancel.call(purchase_order: purchase_order.reload)++ expect(result).to be_failure+ expect(result.error.to_s).to eq(Spree.t('purchase_order.errors.already_closed'))+ end+ end++ describe 'editing' do+ it 'replaces the lines of a draft' do+ other_variant = create(:variant)++ result = Spree::PurchaseOrders::Update.call(+ purchase_order: purchase_order,+ attributes: { reference: 'SUP-8891' },+ items: [{ variant: other_variant, quantity_ordered: 4, unit_cost: 3 }]+ )++ expect(result).to be_success+ expect(result.value.reference).to eq('SUP-8891')+ expect(result.value.items.sole).to have_attributes(variant: other_variant, quantity_ordered: 4)+ end++ it 'refuses to rewrite an order already placed with the supplier' do+ Spree::PurchaseOrders::MarkOrdered.call(purchase_order: purchase_order)++ result = Spree::PurchaseOrders::Update.call(purchase_order: purchase_order.reload,+ attributes: { reference: 'too late' })++ expect(result).to be_failure+ expect(result.error.to_s).to eq(Spree.t('purchase_order.errors.not_editable'))+ end+ end+enddiff --git a/spree/core/spec/workflows/spree/stock_transfers/lifecycle_spec.rb b/spree/core/spec/workflows/spree/stock_transfers/lifecycle_spec.rbnew file mode 100644index 0000000000..dc258a855d--- /dev/null+++ b/spree/core/spec/workflows/spree/stock_transfers/lifecycle_spec.rb@@ -0,0 +1,304 @@+require 'spec_helper'++# The whole point of the 6.0 transfer: a trip has a middle. Stock leaves the+# source when the van goes and lands at the destination when somebody counts+# it in, and in between the units belong to neither shelf.+describe 'stock transfer lifecycle', type: :model do+ let(:store) { Spree::Store.default }+ let(:source) { create(:stock_location, store: store) }+ let(:destination) { create(:stock_location, store: store) }+ let(:variant) { create(:variant) }++ let(:transfer) do+ Spree::StockTransfers::Create.call(+ store: store,+ source_location: source,+ destination_location: destination,+ items: [{ variant: variant, quantity_shipped: 10 }]+ ).value+ end++ def source_on_hand+ source.stock_level(variant.id)&.count_on_hand.to_i+ end++ def destination_on_hand+ destination.stock_level(variant.id)&.count_on_hand.to_i+ end++ before { source.restock(variant, 10) }++ describe 'creating' do+ it 'plans the trip without moving anything' do+ expect(transfer).to be_draft+ expect(transfer.items.first).to have_attributes(variant: variant, quantity_shipped: 10,+ quantity_received: 0)+ expect(source_on_hand).to eq(10)+ expect(destination_on_hand).to eq(0)+ expect(transfer.stock_movements).to be_empty+ end++ it 'refuses a line with no quantity' do+ result = Spree::StockTransfers::Create.call(+ store: store, source_location: source, destination_location: destination,+ items: [{ variant: variant, quantity_shipped: 0 }]+ )++ expect(result).to be_failure+ end+ end++ describe 'marking ready' do+ it 'freezes the list without touching stock' do+ result = Spree::StockTransfers::MarkReady.call(stock_transfer: transfer)++ expect(result).to be_success+ expect(result.value).to be_ready_to_ship+ expect(result.value).not_to be_editable+ expect(source_on_hand).to eq(10)+ end++ it 'refuses a transfer that has already shipped' do+ Spree::StockTransfers::MarkInTransit.call(stock_transfer: transfer)++ result = Spree::StockTransfers::MarkReady.call(stock_transfer: transfer.reload)++ expect(result).to be_failure+ expect(result.error.to_s).to eq(Spree.t('stock_transfer.errors.not_draft'))+ end+ end++ describe 'marking in transit' do+ subject(:result) { Spree::StockTransfers::MarkInTransit.call(stock_transfer: transfer) }++ it 'takes the units off the source shelf and nowhere else' do+ expect(result).to be_success+ expect(result.value).to be_in_transit+ expect(result.value.shipped_at).to be_present++ expect(source_on_hand).to eq(0)+ expect(destination_on_hand).to eq(0)+ end++ it 'writes a shipped movement naming the transfer' do+ result++ movement = transfer.reload.stock_movements.sole+ expect(movement).to have_attributes(kind: 'shipped', quantity: 10)+ expect(movement.stock_transfer).to eq(transfer)+ expect(movement.unit_cost).to be_nil+ end++ # A transfer moves goods, not promises: units another order is waiting for+ # stay promised at the source.+ it 'leaves the source promises intact' do+ level = source.stock_level_or_create(variant)+ level.update_column(:allocated_count, 3)++ result++ expect(level.reload.allocated_count).to eq(3)+ end++ it 'refuses to send more than the source holds' do+ source.stock_level(variant.id).update_column(:count_on_hand, 4)++ expect(result).to be_failure+ expect(result.error.to_s).to eq(+ Spree.t('stock_transfer.errors.variants_unavailable', stock: source.name)+ )+ expect(source_on_hand).to eq(4)+ end++ it 'sends anyway when the merchant forces it' do+ source.stock_level(variant.id).update_column(:count_on_hand, 4)++ forced = Spree::StockTransfers::MarkInTransit.call(stock_transfer: transfer, force: true)++ expect(forced).to be_success+ expect(source_on_hand).to eq(-6)+ end+ end++ describe 'receiving' do+ before { 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)++ expect(result).to be_success+ expect(result.value).to be_received+ expect(result.value.received_at).to be_present+ expect(destination_on_hand).to eq(10)+ end++ it 'lands only what arrived and stays open when it is short' do+ item = transfer.reload.items.sole++ 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(result.value).to be_partially_received+ expect(result.value.received_at).to be_nil+ expect(destination_on_hand).to eq(8)+ expect(item.reload).to have_attributes(quantity_received: 8, outstanding: 2,+ discrepancy_reason: 'damaged_in_transit')+ 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 }])++ result = Spree::StockTransfers::Receive.call(stock_transfer: transfer.reload,+ items: [{ item: item.reload, quantity_received: 10 }])++ expect(result).to be_success+ expect(result.value).to be_received+ expect(destination_on_hand).to eq(10)+ expect(transfer.reload.stock_movements.received.sum(:quantity)).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 }]+ )++ expect(result).to be_failure+ expect(destination_on_hand).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 }])++ expect(result).to be_failure+ expect(destination_on_hand).to eq(8)+ end++ 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: other_item, quantity_received: 1 }]+ )++ expect(result).to be_failure+ expect(result.error.to_s).to eq(Spree.t('stock_transfer.errors.item_not_on_transfer'))+ end++ it 'refuses a transfer that has not shipped' do+ draft = create(:stock_transfer, store: store)++ expect(Spree::StockTransfers::Receive.call(stock_transfer: draft)).to be_failure+ end+ end++ describe 'cancelling' do+ it 'is a no-op for stock while the transfer is still a draft' do+ result = Spree::StockTransfers::Cancel.call(stock_transfer: transfer)++ expect(result).to be_success+ expect(result.value).to be_canceled+ expect(source_on_hand).to eq(10)+ expect(transfer.reload.stock_movements).to be_empty+ end++ # The units are physically gone from the source, so guessing would either+ # invent stock or destroy it.+ it 'refuses to cancel an in-transit transfer without a decision' do+ Spree::StockTransfers::MarkInTransit.call(stock_transfer: transfer)++ result = Spree::StockTransfers::Cancel.call(stock_transfer: transfer.reload)++ expect(result).to be_failure+ expect(result.error.to_s).to eq(Spree.t('stock_transfer.errors.in_transit_resolution_required'))+ expect(transfer.reload).to be_in_transit+ end++ it 'puts the units back when the merchant says they came home' do+ Spree::StockTransfers::MarkInTransit.call(stock_transfer: transfer)++ result = Spree::StockTransfers::Cancel.call(stock_transfer: transfer.reload, on_in_transit: 'restock')++ expect(result).to be_success+ expect(source_on_hand).to eq(10)+ expect(destination_on_hand).to eq(0)+ expect(transfer.reload.stock_movements.received.sum(:quantity)).to eq(10)+ end++ # The loss is already in the ledger — the units left when the transfer+ # shipped. What is missing is why.+ it 'records the reason and moves no stock when the units are written off' do+ Spree::StockTransfers::MarkInTransit.call(stock_transfer: transfer)++ result = Spree::StockTransfers::Cancel.call(stock_transfer: transfer.reload,+ on_in_transit: 'write_off', reason: 'stolen')++ expect(result).to be_success+ expect(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.stock_movements.received).to be_empty+ end++ # Anything the destination already counted in is on its shelf and stays.+ it 'only resolves the units still in flight' do+ Spree::StockTransfers::MarkInTransit.call(stock_transfer: transfer)+ Spree::StockTransfers::Receive.call(stock_transfer: transfer.reload,+ items: [{ item: transfer.items.sole, quantity_received: 6 }])++ Spree::StockTransfers::Cancel.call(stock_transfer: transfer.reload, on_in_transit: 'restock')++ expect(destination_on_hand).to eq(6)+ expect(source_on_hand).to eq(4)+ end++ it 'refuses a transfer that is already over' do+ Spree::StockTransfers::MarkInTransit.call(stock_transfer: transfer)+ Spree::StockTransfers::Receive.call(stock_transfer: transfer.reload)++ result = Spree::StockTransfers::Cancel.call(stock_transfer: transfer.reload)++ expect(result).to be_failure+ expect(result.error.to_s).to eq(Spree.t('stock_transfer.errors.already_closed'))+ end+ end++ describe 'editing' do+ it 'replaces the lines of a draft' do+ other_variant = create(:variant)++ result = Spree::StockTransfers::Update.call(+ stock_transfer: transfer,+ attributes: { reference: 'Second attempt' },+ items: [{ variant: other_variant, quantity_shipped: 2 }]+ )++ expect(result).to be_success+ expect(result.value.reference).to eq('Second attempt')+ expect(result.value.items.sole).to have_attributes(variant: other_variant, quantity_shipped: 2)+ end++ it 'refuses to rewrite a transfer the warehouse is already acting on' do+ Spree::StockTransfers::MarkReady.call(stock_transfer: transfer)++ result = Spree::StockTransfers::Update.call(stock_transfer: transfer.reload,+ attributes: { reference: 'too late' })++ expect(result).to be_failure+ expect(result.error.to_s).to eq(Spree.t('stock_transfer.errors.not_editable'))+ end+ end+end