Skip to content

armgit / spree

Public Imported from GitHub
0

Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.

Merged near-identical post-sale, receivable and product membership code

Claude7498c29cee08
diff --git a/spree/core/app/services/spree/categories/add_products.rb b/spree/core/app/services/spree/categories/add_products.rb
index ed3c5648e1..141d47892b 100644
--- a/spree/core/app/services/spree/categories/add_products.rb
+++ b/spree/core/app/services/spree/categories/add_products.rb
@@ -2,8 +2,9 @@ module Spree
module Categories
class AddProducts
prepend Spree::ServiceModule::Base
+ include Spree::ProductMemberships
- # Creates product-category links for the given categories and products in bulk.
+ # Adds the given products to the given categories, in bulk.
#
# @param categories [Array<Spree::Category>]
# @param products [Array<Spree::Product>]
@@ -11,38 +12,21 @@ module Spree
def call(categories:, products:)
return if categories.blank? || products.blank?
- # build the params for the insert_all
- product_categories_params = categories.pluck(:id).flat_map do |category_id|
- position = Spree::ProductCategory.where(category_id: category_id).count
-
- products.pluck(:id).map do |product_id|
- {
- category_id: category_id,
- product_id: product_id,
- position: (position += 1)
- }
- end
- end
- # doing a quick insert_all here to avoid the overhead of instantiating
- Spree::ProductCategory.insert_all(product_categories_params)
+ add_memberships(categories, products)
+ success(true)
+ end
- # update counter caches
- category_ids = categories.pluck(:id)
- product_ids = products.pluck(:id)
- product_ids.each { |id| Spree::Product.reset_counters(id, :product_categories) }
- # Recompute the descendant-inclusive products_count for the categories and
- # their ancestors (bulk insert skips ProductCategory callbacks).
- Spree::Category.recalculate_products_count(category_ids)
+ private
- # clear cache & index products
- Spree::Product.where(id: product_ids).touch_all
- products.each(&:enqueue_search_index)
+ def membership_class = Spree::ProductCategory
+ def group_class = Spree::Category
- Spree::Category.where(id: category_ids).touch_all
- # Optional external hook (e.g. storefront featured sections); namespace owned by that gem.
+ # Recomputes the descendant-inclusive products_count for the categories
+ # and their ancestors, and lets an optional storefront extension refresh
+ # its featured sections.
+ def refresh_group_counters(category_ids)
+ Spree::Category.recalculate_products_count(category_ids)
Spree::Taxons::TouchFeaturedSections.call(taxon_ids: category_ids) if defined?(Spree::Taxons::TouchFeaturedSections)
-
- success(true)
end
end
end
diff --git a/spree/core/app/services/spree/categories/remove_products.rb b/spree/core/app/services/spree/categories/remove_products.rb
index dd09bf3050..bb029a8068 100644
--- a/spree/core/app/services/spree/categories/remove_products.rb
+++ b/spree/core/app/services/spree/categories/remove_products.rb
@@ -2,8 +2,9 @@ module Spree
module Categories
class RemoveProducts
prepend Spree::ServiceModule::Base
+ include Spree::ProductMemberships
- # Removes the given products from the given categories.
+ # Removes the given products from the given categories and re-packs positions.
#
# @param categories [Array<Spree::Category>]
# @param products [Array<Spree::Product>]
@@ -11,61 +12,21 @@ module Spree
def call(categories:, products:)
return if categories.blank? || products.blank?
- category_ids = categories.pluck(:id)
- product_ids = products.pluck(:id)
-
- ApplicationRecord.transaction do
- category_ids.each do |category_id|
- Spree::ProductCategory.where(category_id: category_id, product_id: product_ids).delete_all
- end
-
- product_categories_params = category_ids.flat_map do |category_id|
- position = 0
- existing_product_ids = Spree::ProductCategory.where(category_id: category_id).pluck(:product_id)
-
- existing_product_ids.map do |product_id|
- {
- category_id: category_id,
- product_id: product_id,
- position: (position += 1),
- created_at: Time.current,
- updated_at: Time.current
- }
- end
- end
-
- if product_categories_params.any?
- opts = {}
- opts[:unique_by] = %i[product_id category_id] unless mysql_adapter?
-
- Spree::ProductCategory.upsert_all(
- product_categories_params,
- **opts
- )
- end
- end
-
- # update counter caches
- product_ids.each { |id| Spree::Product.reset_counters(id, :product_categories) }
- # Recompute the descendant-inclusive products_count for the categories and
- # their ancestors (delete_all skips ProductCategory callbacks).
- Spree::Category.recalculate_products_count(category_ids)
-
- # clear cache & index products
- Spree::Product.where(id: product_ids).touch_all
- products.each(&:enqueue_search_index)
-
- Spree::Category.where(id: category_ids).touch_all
- # Optional external hook (e.g. storefront featured sections); namespace owned by that gem.
- Spree::Taxons::TouchFeaturedSections.call(taxon_ids: category_ids) if defined?(Spree::Taxons::TouchFeaturedSections)
-
+ remove_memberships(categories, products)
success(true)
end
private
- def mysql_adapter?
- Spree.mysql?
+ def membership_class = Spree::ProductCategory
+ def group_class = Spree::Category
+
+ # Recomputes the descendant-inclusive products_count for the categories
+ # and their ancestors, and lets an optional storefront extension refresh
+ # its featured sections.
+ def refresh_group_counters(category_ids)
+ Spree::Category.recalculate_products_count(category_ids)
+ Spree::Taxons::TouchFeaturedSections.call(taxon_ids: category_ids) if defined?(Spree::Taxons::TouchFeaturedSections)
end
end
end
diff --git a/spree/core/app/services/spree/collections/add_products.rb b/spree/core/app/services/spree/collections/add_products.rb
index 877b563628..5dc906a3dd 100644
--- a/spree/core/app/services/spree/collections/add_products.rb
+++ b/spree/core/app/services/spree/collections/add_products.rb
@@ -2,8 +2,9 @@ module Spree
module Collections
class AddProducts
prepend Spree::ServiceModule::Base
+ include Spree::ProductMemberships
- # Adds the given products to the given collections (manual curation), in bulk.
+ # Adds the given products to the given collections, in bulk.
#
# @param collections [Array<Spree::Collection>]
# @param products [Array<Spree::Product>]
@@ -11,29 +12,17 @@ module Spree
def call(collections:, products:)
return if collections.blank? || products.blank?
- product_collections_params = collections.pluck(:id).flat_map do |collection_id|
- position = Spree::ProductCollection.where(collection_id: collection_id).count
-
- products.pluck(:id).map do |product_id|
- {
- collection_id: collection_id,
- product_id: product_id,
- position: (position += 1)
- }
- end
- end
- Spree::ProductCollection.insert_all(product_collections_params)
+ add_memberships(collections, products)
+ success(true)
+ end
- collection_ids = collections.pluck(:id)
- product_ids = products.pluck(:id)
- collection_ids.each { |id| Spree::Collection.reset_counters(id, :product_collections) }
- product_ids.each { |id| Spree::Product.reset_counters(id, :product_collections) }
+ private
- Spree::Product.where(id: product_ids).touch_all
- products.each(&:enqueue_search_index)
- Spree::Collection.where(id: collection_ids).touch_all
+ def membership_class = Spree::ProductCollection
+ def group_class = Spree::Collection
- success(true)
+ def refresh_group_counters(collection_ids)
+ collection_ids.each { |id| Spree::Collection.reset_counters(id, :product_collections) }
end
end
end
diff --git a/spree/core/app/services/spree/collections/remove_products.rb b/spree/core/app/services/spree/collections/remove_products.rb
index 566e8fb71b..554188032e 100644
--- a/spree/core/app/services/spree/collections/remove_products.rb
+++ b/spree/core/app/services/spree/collections/remove_products.rb
@@ -2,6 +2,7 @@ module Spree
module Collections
class RemoveProducts
prepend Spree::ServiceModule::Base
+ include Spree::ProductMemberships
# Removes the given products from the given collections and re-packs positions.
#
@@ -11,54 +12,17 @@ module Spree
def call(collections:, products:)
return if collections.blank? || products.blank?
- collection_ids = collections.pluck(:id)
- product_ids = products.pluck(:id)
-
- ApplicationRecord.transaction do
- collection_ids.each do |collection_id|
- Spree::ProductCollection.where(collection_id: collection_id, product_id: product_ids).delete_all
- end
-
- product_collections_params = collection_ids.flat_map do |collection_id|
- position = 0
- existing_product_ids = Spree::ProductCollection.where(collection_id: collection_id).pluck(:product_id)
-
- existing_product_ids.map do |product_id|
- {
- collection_id: collection_id,
- product_id: product_id,
- position: (position += 1),
- created_at: Time.current,
- updated_at: Time.current
- }
- end
- end
-
- if product_collections_params.any?
- opts = {}
- # Column list rather than the index name — the composite unique index is named
- # index_product_collections_on_collection_and_product (shortened to fit the
- # identifier limit), so match by columns to stay name-independent.
- opts[:unique_by] = %i[collection_id product_id] unless mysql_adapter?
-
- Spree::ProductCollection.upsert_all(product_collections_params, **opts)
- end
- end
-
- collection_ids.each { |id| Spree::Collection.reset_counters(id, :product_collections) }
- product_ids.each { |id| Spree::Product.reset_counters(id, :product_collections) }
-
- Spree::Product.where(id: product_ids).touch_all
- products.each(&:enqueue_search_index)
- Spree::Collection.where(id: collection_ids).touch_all
-
+ remove_memberships(collections, products)
success(true)
end
private
- def mysql_adapter?
- Spree.mysql?
+ def membership_class = Spree::ProductCollection
+ def group_class = Spree::Collection
+
+ def refresh_group_counters(collection_ids)
+ collection_ids.each { |id| Spree::Collection.reset_counters(id, :product_collections) }
end
end
end
diff --git a/spree/core/app/services/spree/product_memberships.rb b/spree/core/app/services/spree/product_memberships.rb
new file mode 100644
index 0000000000..ba2b59a1de
--- /dev/null
+++ b/spree/core/app/services/spree/product_memberships.rb
@@ -0,0 +1,55 @@
+module Spree
+ # Bulk adding and removing products on categories or collections. The
+ # including service names the join model (`membership_class`), the grouping
+ # it belongs to (`group_class`, `group_key`) and refreshes the grouping's
+ # own counters in `refresh_group_counters`.
+ module ProductMemberships
+ private
+
+ def add_memberships(groups, products)
+ rows = groups.pluck(:id).flat_map do |group_id|
+ position = membership_class.where(group_key => group_id).count
+ products.pluck(:id).map do |product_id|
+ { group_key => group_id, product_id: product_id, position: (position += 1) }
+ end
+ end
+ membership_class.insert_all(rows)
+
+ refresh_after_membership_change(groups.pluck(:id), products)
+ end
+
+ # Removes the products, then re-packs the remaining positions from 1.
+ def remove_memberships(groups, products)
+ group_ids = groups.pluck(:id)
+
+ ApplicationRecord.transaction do
+ membership_class.where(group_key => group_ids, product_id: products.pluck(:id)).delete_all
+
+ rows = group_ids.flat_map do |group_id|
+ membership_class.where(group_key => group_id).order(:position).pluck(:product_id).map.with_index(1) do |product_id, position|
+ { group_key => group_id, product_id: product_id, position: position }
+ end
+ end
+ membership_class.upsert_all(rows, unique_by: ([group_key, :product_id] unless Spree.mysql?)) if rows.any?
+ end
+
+ refresh_after_membership_change(group_ids, products)
+ end
+
+ # Bulk writes skip the join model's callbacks, so counters, caches and the
+ # search index are refreshed here.
+ def refresh_after_membership_change(group_ids, products)
+ product_ids = products.pluck(:id)
+ product_ids.each { |id| Spree::Product.reset_counters(id, membership_class.model_name.element.pluralize.to_sym) }
+ refresh_group_counters(group_ids)
+
+ Spree::Product.where(id: product_ids).touch_all
+ products.each(&:enqueue_search_index)
+ group_class.where(id: group_ids).touch_all
+ end
+
+ def group_key
+ group_class.model_name.element.foreign_key.to_sym
+ end
+ end
+end
diff --git a/spree/core/app/workflows/spree/claims/approve.rb b/spree/core/app/workflows/spree/claims/approve.rb
index d3c0d4dfea..21c687c472 100644
--- a/spree/core/app/workflows/spree/claims/approve.rb
+++ b/spree/core/app/workflows/spree/claims/approve.rb
@@ -1,38 +1,21 @@
module Spree
module Claims
class Approve < Spree::Workflow
+ include Spree::PostSale::Approval
+
hooks :validate, :after_approve
# @param claim [Spree::Claim]
# @param approver [Object, nil]
def perform(claim:, approver: nil)
super
-
- step :ensure_approvable
- run_hooks :validate
-
- ApplicationRecord.transaction do
- step :mark_approved
- end
-
- run_hooks :after_approve
- claim.publish_event('claim.approved')
- success(claim.reload)
+ approve
end
private
- def ensure_approvable
- failure(claim, :not_open) unless claim.open?
- end
-
- def mark_approved
- claim.update!(
- status: 'approved',
- approved_at: Time.current,
- created_by: claim.created_by || approver
- )
- end
+ def post_sale_record = claim
+ def approvable_status = 'open'
end
end
end
diff --git a/spree/core/app/workflows/spree/claims/cancel.rb b/spree/core/app/workflows/spree/claims/cancel.rb
index 3048680973..48762574cb 100644
--- a/spree/core/app/workflows/spree/claims/cancel.rb
+++ b/spree/core/app/workflows/spree/claims/cancel.rb
@@ -1,7 +1,7 @@
module Spree
module Claims
class Cancel < Spree::Workflow
- include Spree::Refunds::TaxCredit
+ include Spree::PostSale::Cancellation
hooks :validate, :after_cancel
@@ -9,36 +9,13 @@ module Spree
# @param reason [String, nil]
def perform(claim:, reason: nil)
super
-
- step :ensure_cancellable
- run_hooks :validate
-
- ApplicationRecord.transaction do
- step :mark_canceled
- step :clear_tax
- end
-
- run_hooks :after_cancel
- claim.publish_event('claim.canceled')
- success(claim.reload)
+ cancel
end
private
- def ensure_cancellable
- return if claim.open? || claim.approved?
-
- failure(claim, :not_cancellable)
- end
-
- def mark_canceled
- memo = [claim.memo, reason].compact_blank.join("\n")
- claim.update!(status: 'canceled', canceled_at: Time.current, memo: memo.presence)
- end
-
- def clear_tax
- clear_tax_credit(claim)
- end
+ def post_sale_record = claim
+ def cancellable_statuses = %w[open approved]
end
end
end
diff --git a/spree/core/app/workflows/spree/exchanges/approve.rb b/spree/core/app/workflows/spree/exchanges/approve.rb
index b13404d8c0..bea3819eac 100644
--- a/spree/core/app/workflows/spree/exchanges/approve.rb
+++ b/spree/core/app/workflows/spree/exchanges/approve.rb
@@ -1,38 +1,21 @@
module Spree
module Exchanges
class Approve < Spree::Workflow
+ include Spree::PostSale::Approval
+
hooks :validate, :after_approve
# @param exchange [Spree::Exchange]
# @param approver [Object, nil]
def perform(exchange:, approver: nil)
super
-
- step :ensure_approvable
- run_hooks :validate
-
- ApplicationRecord.transaction do
- step :mark_approved
- end
-
- run_hooks :after_approve
- exchange.publish_event('exchange.approved')
- success(exchange.reload)
+ approve
end
private
- def ensure_approvable
- failure(exchange, :not_requested) unless exchange.requested?
- end
-
- def mark_approved
- exchange.update!(
- status: 'approved',
- approved_at: Time.current,
- created_by: exchange.created_by || approver
- )
- end
+ def post_sale_record = exchange
+ def approvable_status = 'requested'
end
end
end
diff --git a/spree/core/app/workflows/spree/exchanges/cancel.rb b/spree/core/app/workflows/spree/exchanges/cancel.rb
index eebe757e01..e3c5c8c1d5 100644
--- a/spree/core/app/workflows/spree/exchanges/cancel.rb
+++ b/spree/core/app/workflows/spree/exchanges/cancel.rb
@@ -4,7 +4,7 @@ module Spree
# merchant holds the customer's items and must either fulfill the
# replacement or refund.
class Cancel < Spree::Workflow
- include Spree::Refunds::TaxCredit
+ include Spree::PostSale::Cancellation
hooks :validate, :after_cancel
@@ -12,36 +12,13 @@ module Spree
# @param reason [String, nil]
def perform(exchange:, reason: nil)
super
-
- step :ensure_cancellable
- run_hooks :validate
-
- ApplicationRecord.transaction do
- step :mark_canceled
- step :clear_tax
- end
-
- run_hooks :after_cancel
- exchange.publish_event('exchange.canceled')
- success(exchange.reload)
+ cancel
end
private
- def ensure_cancellable
- return if exchange.requested? || exchange.approved?
-
- failure(exchange, :not_cancellable)
- end
-
- def mark_canceled
- memo = [exchange.memo, reason].compact_blank.join("\n")
- exchange.update!(status: 'canceled', canceled_at: Time.current, memo: memo.presence)
- end
-
- def clear_tax
- clear_tax_credit(exchange)
- end
+ def post_sale_record = exchange
+ def cancellable_statuses = %w[requested approved]
end
end
end
diff --git a/spree/core/app/workflows/spree/exchanges/receive.rb b/spree/core/app/workflows/spree/exchanges/receive.rb
index 9fe5cf2a18..bb110ae4b0 100644
--- a/spree/core/app/workflows/spree/exchanges/receive.rb
+++ b/spree/core/app/workflows/spree/exchanges/receive.rb
@@ -3,6 +3,8 @@ module Spree
# Records what came back. Same partial-receipt shape as returns: the
# warehouse enters actual quantities and flags anything unsellable.
class Receive < Spree::Workflow
+ include Spree::PostSale::Receipt
+
hooks :validate, :before_restock, :after_receive
# @param exchange [Spree::Exchange]
@@ -10,76 +12,15 @@ module Spree
# @param received_by [Object, nil]
def perform(exchange:, 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_resellable_items
- step :mark_received
- end
-
- run_hooks :after_receive
- exchange.publish_event('exchange.received')
- success(exchange.reload)
+ receive
end
private
- def ensure_receivable
- failure(exchange, :not_approved) unless exchange.approved?
- end
-
- def normalize_items
- @normalized_items =
- if items.nil?
- exchange.exchange_line_items.map do |line|
- { exchange_line_item: line, quantity: line.quantity, resellable: true }
- end
- else
- items.map { |item| normalize_item(item) }
- end
-
- failure(exchange, :no_items_received) if @normalized_items.sum { |item| item[:quantity] }.zero?
- end
-
- def normalize_item(item)
- line = item[:exchange_line_item]
- quantity = item[:quantity].to_i
-
- failure(exchange, :item_not_on_exchange) unless line&.exchange_id == exchange.id
- failure(exchange, :invalid_quantity) if quantity.negative? || quantity > line.quantity
-
- { exchange_line_item: line, quantity: quantity, resellable: item.fetch(:resellable, true) }
- end
-
- def record_receipt
- @normalized_items.each do |item|
- item[:exchange_line_item].update!(
- received_quantity: item[:quantity],
- resellable: item[:resellable]
- )
- end
- end
-
- def restock_resellable_items
- @normalized_items.each do |item|
- next unless item[:resellable]
- next unless item[:quantity].positive?
-
- exchange.stock_location.restock(
- item[:exchange_line_item].original_variant,
- item[:quantity],
- exchange
- )
- end
- end
+ def post_sale_record = exchange
- def mark_received
- exchange.update!(status: 'received', received_at: Time.current)
+ def restock_variant(line)
+ line.original_variant
end
end
end
diff --git a/spree/core/app/workflows/spree/post_sale/approval.rb b/spree/core/app/workflows/spree/post_sale/approval.rb
new file mode 100644
index 0000000000..50edae412f
--- /dev/null
+++ b/spree/core/app/workflows/spree/post_sale/approval.rb
@@ -0,0 +1,35 @@
+module Spree
+ module PostSale
+ # Approval shared by returns, exchanges and claims. The including
+ # workflow names the record it approves (`post_sale_record`) and the
+ # status that record must be in (`approvable_status`).
+ module Approval
+ private
+
+ def approve
+ step :ensure_approvable
+ run_hooks :validate
+
+ ApplicationRecord.transaction do
+ step :mark_approved
+ end
+
+ run_hooks :after_approve
+ post_sale_record.publish_event("#{post_sale_record.event_prefix}.approved")
+ success(post_sale_record.reload)
+ end
+
+ def ensure_approvable
+ failure(post_sale_record, :"not_#{approvable_status}") unless post_sale_record.status == approvable_status
+ end
+
+ def mark_approved
+ post_sale_record.update!(
+ status: 'approved',
+ approved_at: Time.current,
+ created_by: post_sale_record.created_by || approver
+ )
+ end
+ end
+ end
+end
diff --git a/spree/core/app/workflows/spree/post_sale/cancellation.rb b/spree/core/app/workflows/spree/post_sale/cancellation.rb
new file mode 100644
index 0000000000..7dbb392c82
--- /dev/null
+++ b/spree/core/app/workflows/spree/post_sale/cancellation.rb
@@ -0,0 +1,44 @@
+module Spree
+ module PostSale
+ # Cancellation shared by returns, exchanges and claims. The including
+ # workflow names the record it cancels (`post_sale_record`) and the
+ # statuses it may be cancelled from (`cancellable_statuses`). A block
+ # runs after the cancellation commits, for work outside the database.
+ module Cancellation
+ include Spree::Refunds::TaxCredit
+
+ private
+
+ def cancel
+ step :ensure_cancellable
+ run_hooks :validate
+
+ ApplicationRecord.transaction do
+ step :mark_canceled
+ step :clear_tax
+ end
+
+ yield if block_given?
+
+ run_hooks :after_cancel
+ post_sale_record.publish_event("#{post_sale_record.event_prefix}.canceled")
+ success(post_sale_record.reload)
+ end
+
+ def ensure_cancellable
+ return if post_sale_record.status.in?(cancellable_statuses)
+
+ failure(post_sale_record, :not_cancellable)
+ end
+
+ def mark_canceled
+ memo = [post_sale_record.memo, reason].compact_blank.join("\n")
+ post_sale_record.update!(status: 'canceled', canceled_at: Time.current, memo: memo.presence)
+ end
+
+ def clear_tax
+ clear_tax_credit(post_sale_record)
+ end
+ end
+ end
+end
diff --git a/spree/core/app/workflows/spree/post_sale/receipt.rb b/spree/core/app/workflows/spree/post_sale/receipt.rb
new file mode 100644
index 0000000000..f977b7e338
--- /dev/null
+++ b/spree/core/app/workflows/spree/post_sale/receipt.rb
@@ -0,0 +1,92 @@
+module Spree
+ module PostSale
+ # Records what the warehouse actually received for a return or an
+ # exchange. The including workflow names the record (`post_sale_record`);
+ # its lines, the item key callers pass (`return_line_item:` or
+ # `exchange_line_item:`) and the error codes follow from the record's
+ # event prefix. `restock_variant` says which variant a line puts back.
+ #
+ # Partial and damaged receipt is the normal case, not an edge case: the
+ # customer said three items were coming, two arrived, one of those is not
+ # resellable. Quantities and resellable flags therefore come from the
+ # caller rather than from the request.
+ module Receipt
+ private
+
+ def receive
+ step :ensure_receivable
+ step :normalize_items
+ run_hooks :validate
+
+ ApplicationRecord.transaction do
+ step :record_receipt
+ run_hooks :before_restock
+ step :restock_resellable_items
+ step :mark_received
+ end
+
+ run_hooks :after_receive
+ post_sale_record.publish_event("#{post_sale_kind}.received")
+ success(post_sale_record.reload)
+ end
+
+ def post_sale_kind
+ post_sale_record.event_prefix
+ end
+
+ def restock_variant(line)
+ line.variant
+ end
+
+ def ensure_receivable
+ failure(post_sale_record, :not_approved) unless post_sale_record.approved?
+ end
+
+ def normalize_items
+ @normalized_items =
+ if items.nil?
+ post_sale_record.public_send(:"#{post_sale_kind}_line_items").map do |line|
+ { line: line, quantity: line.quantity, resellable: true }
+ end
+ else
+ items.map { |item| normalize_item(item) }
+ end
+
+ failure(post_sale_record, :no_items_received) if @normalized_items.sum { |item| item[:quantity] }.zero?
+ end
+
+ def normalize_item(item)
+ line = item[:"#{post_sale_kind}_line_item"]
+ quantity = item[:quantity].to_i
+
+ unless line&.public_send(:"#{post_sale_kind}_id") == post_sale_record.id
+ failure(post_sale_record, :"item_not_on_#{post_sale_kind}")
+ end
+ failure(post_sale_record, :invalid_quantity) if quantity.negative? || quantity > line.quantity
+
+ { line: line, quantity: quantity, resellable: item.fetch(:resellable, true) }
+ end
+
+ def record_receipt
+ @normalized_items.each do |item|
+ item[:line].update!(received_quantity: item[:quantity], resellable: item[:resellable])
+ end
+ end
+
+ # Only resellable goods go back into sellable stock — a damaged item
+ # is received but never restocked.
+ def restock_resellable_items
+ @normalized_items.each do |item|
+ next unless item[:resellable]
+ next unless item[:quantity].positive?
+
+ post_sale_record.stock_location.restock(restock_variant(item[:line]), item[:quantity], post_sale_record)
+ end
+ end
+
+ def mark_received
+ post_sale_record.update!(status: 'received', received_at: Time.current)
+ end
+ end
+ end
+end
diff --git a/spree/core/app/workflows/spree/purchase_orders/close.rb b/spree/core/app/workflows/spree/purchase_orders/close.rb
index 3e2f33e572..ad00cc93c7 100644
--- a/spree/core/app/workflows/spree/purchase_orders/close.rb
+++ b/spree/core/app/workflows/spree/purchase_orders/close.rb
@@ -8,7 +8,7 @@ module Spree
# lets the outstanding count stand on each line as the record of the gap.
# No stock moves — the units were never here.
class Close < Spree::Workflow
- include Spree::Receivables::IncomingCounter
+ include Spree::Receivables::ClosingShort
hooks :validate, :after_close
@@ -18,40 +18,12 @@ module Spree
# @param reason [String, nil] why the balance is not expected
def perform(purchase_order:, reason: nil)
super
-
- purchase_order.with_lock do
- step :ensure_closable
- run_hooks :validate
- step :uncount_awaited_units
- step :close_short
- end
-
- run_hooks :after_close
- purchase_order.publish_event('purchase_order.received')
- success(purchase_order.reload)
+ close
end
private
- def ensure_closable
- return if purchase_order.partially_received?
-
- failure(purchase_order, Spree.t('purchase_order.errors.not_partially_received'))
- end
-
- # The merchant has just said the balance is not coming, so it leaves
- # the destination's incoming figure; the outstanding count on each line
- # keeps the record of what never arrived.
- def uncount_awaited_units
- uncount_incoming(purchase_order)
- end
-
- def close_short
- now = Time.current
- attributes = { status: 'received', received_at: now, closed_short_at: now, close_reason: reason.presence }
-
- failure(purchase_order) unless purchase_order.update(attributes)
- end
+ def receivable = purchase_order
end
end
end
diff --git a/spree/core/app/workflows/spree/purchase_orders/update.rb b/spree/core/app/workflows/spree/purchase_orders/update.rb
index 581ec1021a..ad892dbc87 100644
--- a/spree/core/app/workflows/spree/purchase_orders/update.rb
+++ b/spree/core/app/workflows/spree/purchase_orders/update.rb
@@ -4,6 +4,8 @@ module Spree
# ordered is a matter of record between two businesses — so this refuses
# anything past `draft`.
class Update < Spree::Workflow
+ include Spree::Receivables::DraftEditing
+
hooks :validate, :after_update
# @param purchase_order [Spree::PurchaseOrder]
@@ -13,44 +15,13 @@ module Spree
# 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)
+ edit
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
+ def receivable = purchase_order
+ def item_attributes = %i[quantity_ordered unit_cost]
end
end
end
diff --git a/spree/core/app/workflows/spree/receivables/closing_short.rb b/spree/core/app/workflows/spree/receivables/closing_short.rb
new file mode 100644
index 0000000000..096c84a71d
--- /dev/null
+++ b/spree/core/app/workflows/spree/receivables/closing_short.rb
@@ -0,0 +1,46 @@
+module Spree
+ module Receivables
+ # Ends a purchase order or transfer whose missing units are not going to
+ # turn up. Nothing is written to any shelf: closing short keeps what was
+ # received, records why the rest never arrived, and leaves the outstanding
+ # count on each line as the record of the gap. The including workflow
+ # names the document (`receivable`).
+ module ClosingShort
+ include IncomingCounter
+
+ private
+
+ def close
+ receivable.with_lock do
+ step :ensure_closable
+ run_hooks :validate
+ step :uncount_awaited_units
+ step :close_short
+ end
+
+ run_hooks :after_close
+ receivable.publish_event("#{receivable.event_prefix}.received")
+ success(receivable.reload)
+ end
+
+ def ensure_closable
+ return if receivable.partially_received?
+
+ failure(receivable, Spree.t("#{receivable.event_prefix}.errors.not_partially_received"))
+ end
+
+ # The balance is not coming, so it leaves the destination's incoming
+ # figure; each line's outstanding count keeps the record.
+ def uncount_awaited_units
+ uncount_incoming(receivable)
+ end
+
+ def close_short
+ now = Time.current
+ attributes = { status: 'received', received_at: now, closed_short_at: now, close_reason: reason.presence }
+
+ failure(receivable) unless receivable.update(attributes)
+ end
+ end
+ end
+end
diff --git a/spree/core/app/workflows/spree/receivables/draft_editing.rb b/spree/core/app/workflows/spree/receivables/draft_editing.rb
new file mode 100644
index 0000000000..40f17d67af
--- /dev/null
+++ b/spree/core/app/workflows/spree/receivables/draft_editing.rb
@@ -0,0 +1,48 @@
+module Spree
+ module Receivables
+ # Edits a draft purchase order or transfer. Past `draft` the document is a
+ # matter of record, so the edit is refused rather than quietly rewriting
+ # something a supplier or warehouse is already acting on. The including
+ # workflow names the document (`receivable`) and the line columns callers
+ # may set (`item_attributes`).
+ module DraftEditing
+ private
+
+ def edit
+ step :ensure_editable
+ run_hooks :validate
+
+ ApplicationRecord.transaction do
+ step :apply_changes
+ step :save_document
+ end
+
+ run_hooks :after_update
+ success(receivable.reload)
+ end
+
+ def ensure_editable
+ return if receivable.editable?
+
+ failure(receivable, Spree.t("#{receivable.event_prefix}.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
+ receivable.assign_attributes(attributes) if attributes.present?
+ return if items.nil?
+
+ receivable.items.destroy_all
+ Array(items).each do |item|
+ receivable.items.build(variant: item[:variant], **item_attributes.index_with { |key| item[key] })
+ end
+ end
+
+ def save_document
+ failure(receivable) unless receivable.save
+ end
+ end
+ end
+end
diff --git a/spree/core/app/workflows/spree/returns/approve.rb b/spree/core/app/workflows/spree/returns/approve.rb
index a94a0d8290..1b4ec0e642 100644
--- a/spree/core/app/workflows/spree/returns/approve.rb
+++ b/spree/core/app/workflows/spree/returns/approve.rb
@@ -10,38 +10,21 @@ module Spree
# 6.0-delivery-rate-provider.md; a store needing one before then can put
# the URL in the return's `metadata`.
class Approve < Spree::Workflow
+ include Spree::PostSale::Approval
+
hooks :validate, :after_approve
# @param return_record [Spree::Return]
# @param approver [Object, nil] who is approving it (see Spree.actor_classes)
def perform(return_record:, approver: nil)
super
-
- step :ensure_approvable
- run_hooks :validate
-
- ApplicationRecord.transaction do
- step :mark_approved
- end
-
- run_hooks :after_approve
- return_record.publish_event('return.approved')
- success(return_record.reload)
+ approve
end
private
- def ensure_approvable
- failure(return_record, :not_requested) unless return_record.requested?
- end
-
- def mark_approved
- return_record.update!(
- status: 'approved',
- approved_at: Time.current,
- created_by: return_record.created_by || approver
- )
- end
+ def post_sale_record = return_record
+ def approvable_status = 'requested'
end
end
end
diff --git a/spree/core/app/workflows/spree/returns/cancel.rb b/spree/core/app/workflows/spree/returns/cancel.rb
index aae3fd34e1..fe8c634014 100644
--- a/spree/core/app/workflows/spree/returns/cancel.rb
+++ b/spree/core/app/workflows/spree/returns/cancel.rb
@@ -7,7 +7,7 @@ module Spree
# holding the customer's items, and the way out is a refund, not a
# cancellation.
class Cancel < Spree::Workflow
- include Spree::Refunds::TaxCredit
+ include Spree::PostSale::Cancellation
hooks :validate, :after_cancel
@@ -16,44 +16,20 @@ module Spree
def perform(return_record:, reason: nil)
super
- step :ensure_cancellable
- run_hooks :validate
-
- ApplicationRecord.transaction do
- step :mark_canceled
- step :clear_tax
- end
-
# Carrier I/O, after the status is committed: a customer who abandons
# a return must not be left holding live prepaid postage the merchant
# is still paying for.
- external_step :refund_prepaid_label
-
- run_hooks :after_cancel
- return_record.publish_event('return.canceled')
- success(return_record.reload)
+ cancel { external_step :refund_prepaid_label }
end
private
- def ensure_cancellable
- return if return_record.requested? || return_record.approved?
-
- failure(return_record, :not_cancellable)
- end
+ def post_sale_record = return_record
+ def cancellable_statuses = %w[requested approved]
def refund_prepaid_label
Spree::Fulfillments::StandDownProvider.refund_labels(return_record)
end
-
- def mark_canceled
- memo = [return_record.memo, reason].compact_blank.join("\n")
- return_record.update!(status: 'canceled', canceled_at: Time.current, memo: memo.presence)
- end
-
- def clear_tax
- clear_tax_credit(return_record)
- end
end
end
end
diff --git a/spree/core/app/workflows/spree/returns/receive.rb b/spree/core/app/workflows/spree/returns/receive.rb
index f34db6f6fa..9a3d15dc3c 100644
--- a/spree/core/app/workflows/spree/returns/receive.rb
+++ b/spree/core/app/workflows/spree/returns/receive.rb
@@ -1,13 +1,9 @@
module Spree
module Returns
- # Records what the warehouse actually received.
- #
- # Partial and damaged receipt is the normal case, not an edge case: the
- # customer said three items were coming, two arrived, one of those is not
- # resellable. Quantities and resellable flags therefore come from the
- # caller rather than from the request, which is precisely what a state
- # machine transition could not express.
+ # Records what the warehouse actually received (see Spree::PostSale::Receipt).
class Receive < Spree::Workflow
+ include Spree::PostSale::Receipt
+
hooks :validate, :before_restock, :after_receive
# @param return_record [Spree::Return]
@@ -16,79 +12,12 @@ module Spree
# @param received_by [Object, nil]
def perform(return_record:, 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_resellable_items
- step :mark_received
- end
-
- run_hooks :after_receive
- return_record.publish_event('return.received')
- success(return_record.reload)
+ receive
end
private
- def ensure_receivable
- failure(return_record, :not_approved) unless return_record.approved?
- end
-
- def normalize_items
- @normalized_items =
- if items.nil?
- return_record.return_line_items.map do |line|
- { return_line_item: line, quantity: line.quantity, resellable: true }
- end
- else
- items.map { |item| normalize_item(item) }
- end
-
- failure(return_record, :no_items_received) if @normalized_items.sum { |item| item[:quantity] }.zero?
- end
-
- def normalize_item(item)
- line = item[:return_line_item]
- quantity = item[:quantity].to_i
-
- failure(return_record, :item_not_on_return) unless line&.return_id == return_record.id
- failure(return_record, :invalid_quantity) if quantity.negative? || quantity > line.quantity
-
- { return_line_item: line, quantity: quantity, resellable: item.fetch(:resellable, true) }
- end
-
- def record_receipt
- @normalized_items.each do |item|
- item[:return_line_item].update!(
- received_quantity: item[:quantity],
- resellable: item[:resellable]
- )
- end
- end
-
- # Only resellable goods go back into sellable stock — a damaged return
- # is received but never restocked.
- def restock_resellable_items
- @normalized_items.each do |item|
- next unless item[:resellable]
- next unless item[:quantity].positive?
-
- return_record.stock_location.restock(
- item[:return_line_item].variant,
- item[:quantity],
- return_record
- )
- end
- end
-
- def mark_received
- return_record.update!(status: 'received', received_at: Time.current)
- end
+ def post_sale_record = return_record
end
end
end
diff --git a/spree/core/app/workflows/spree/stock_transfers/close.rb b/spree/core/app/workflows/spree/stock_transfers/close.rb
index 390036d36a..3ad9381354 100644
--- a/spree/core/app/workflows/spree/stock_transfers/close.rb
+++ b/spree/core/app/workflows/spree/stock_transfers/close.rb
@@ -8,7 +8,7 @@ module Spree
# destination counted in, records why the rest never arrived, and leaves
# the outstanding count on each line as the record of the loss.
class Close < Spree::Workflow
- include Spree::Receivables::IncomingCounter
+ include Spree::Receivables::ClosingShort
hooks :validate, :after_close
@@ -18,39 +18,12 @@ module Spree
# @param reason [String, nil] what happened to the balance
def perform(stock_transfer:, reason: nil)
super
-
- stock_transfer.with_lock do
- step :ensure_closable
- run_hooks :validate
- step :uncount_awaited_units
- step :close_short
- end
-
- run_hooks :after_close
- stock_transfer.publish_event('stock_transfer.received')
- success(stock_transfer.reload)
+ close
end
private
- def ensure_closable
- return if stock_transfer.partially_received?
-
- failure(stock_transfer, Spree.t('stock_transfer.errors.not_partially_received'))
- end
-
- # The missing units are not going to turn up, so the destination stops
- # expecting them; each line's outstanding count keeps the record.
- def uncount_awaited_units
- uncount_incoming(stock_transfer)
- end
-
- def close_short
- now = Time.current
- attributes = { status: 'received', received_at: now, closed_short_at: now, close_reason: reason.presence }
-
- failure(stock_transfer) unless stock_transfer.update(attributes)
- end
+ def receivable = stock_transfer
end
end
end
diff --git a/spree/core/app/workflows/spree/stock_transfers/update.rb b/spree/core/app/workflows/spree/stock_transfers/update.rb
index b99d4da73b..b663ff8aae 100644
--- a/spree/core/app/workflows/spree/stock_transfers/update.rb
+++ b/spree/core/app/workflows/spree/stock_transfers/update.rb
@@ -4,6 +4,8 @@ module Spree
# 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
+ include Spree::Receivables::DraftEditing
+
hooks :validate, :after_update
# @param stock_transfer [Spree::StockTransfer]
@@ -13,43 +15,13 @@ module Spree
# 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)
+ edit
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
+ def receivable = stock_transfer
+ def item_attributes = %i[quantity_shipped]
end
end
end