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.

Share the order sub-resource controllers between admin and seller

Damian Legawiec2c50ca6f0408
diff --git a/packages/dashboard/src/lib/fulfillment-items.test.ts b/packages/dashboard-core/src/lib/fulfillment-items.test.ts
similarity index 100%
rename from packages/dashboard/src/lib/fulfillment-items.test.ts
rename to packages/dashboard-core/src/lib/fulfillment-items.test.ts
diff --git a/packages/dashboard/src/lib/fulfillment-items.ts b/packages/dashboard-core/src/lib/fulfillment-items.ts
similarity index 100%
rename from packages/dashboard/src/lib/fulfillment-items.ts
rename to packages/dashboard-core/src/lib/fulfillment-items.ts
diff --git a/spree/api/app/controllers/concerns/spree/api/v3/orders/claim_actions.rb b/spree/api/app/controllers/concerns/spree/api/v3/orders/claim_actions.rb
new file mode 100644
index 0000000000..1998e57a02
--- /dev/null
+++ b/spree/api/app/controllers/concerns/spree/api/v3/orders/claim_actions.rb
@@ -0,0 +1,112 @@
+module Spree
+ module Api
+ module V3
+ module Orders
+ # Something went wrong with a delivery, and the merchant makes it
+ # right — money back, a replacement, or both — without necessarily
+ # asking for the goods back.
+ #
+ # See {PostSaleActions} for why the lookups a payload's ids resolve
+ # through are deliberately left to the including controller.
+ module ClaimActions
+ extend ActiveSupport::Concern
+ include PostSaleActions
+
+ # POST .../claims
+ def create
+ create_post_sale_record(Spree.claim_create_workflow, Spree::Claim)
+ end
+
+ # PATCH .../claims/:id/approve
+ def approve
+ run_workflow(Spree.claim_approve_workflow, approver: try_spree_current_user)
+ end
+
+ # PATCH .../claims/:id/resolve — a refund, a replacement, or both.
+ def resolve
+ run_workflow(Spree.claim_resolve_workflow,
+ resolution: params[:resolution],
+ refund_method: params[:refund_method] || 'store_credit',
+ amount: params[:amount],
+ replacement_line_item_ids: replacement_line_item_ids,
+ resolver: try_spree_current_user)
+ end
+
+ # PATCH .../claims/:id/deny
+ def deny
+ run_workflow(Spree.claim_deny_workflow, reason: params[:reason])
+ end
+
+ # PATCH .../claims/:id/cancel
+ def cancel
+ run_workflow(Spree.claim_cancel_workflow, reason: params[:reason])
+ end
+
+ protected
+
+ def model_class
+ Spree::Claim
+ end
+
+ def parent_association
+ :claims
+ end
+
+ def workflow_record_key
+ :claim
+ end
+
+ private
+
+ def create_params
+ @create_params ||= params.permit(
+ :memo, :reason_id,
+ items: [:line_item_id, :quantity, :description, :send_replacement,
+ :replacement_variant_id, :refund_amount]
+ )
+ end
+
+ # Every claimed line is resolved through the order itself, so a line
+ # item from another order cannot be claimed against this one.
+ def items_for_create
+ Array(create_params[:items]).map do |item|
+ {
+ line_item: @order.line_items.find_by_prefix_id!(item[:line_item_id]),
+ quantity: item[:quantity].to_i,
+ description: item[:description],
+ send_replacement: item[:send_replacement].to_b,
+ replacement_variant: replacement_variant_for(item[:replacement_variant_id]),
+ refund_amount: item[:refund_amount]
+ }
+ end
+ end
+
+ # Which lines to replace, decided at resolution time. Absent means
+ # "leave whatever the claim was opened with".
+ def replacement_line_item_ids
+ return nil unless params.key?(:replacement_line_item_ids)
+
+ Array(params[:replacement_line_item_ids]).map do |id|
+ @resource.claim_line_items.find_by_prefix_id!(id).id
+ end
+ end
+
+ def reason_for_create
+ return nil if create_params[:reason_id].blank?
+
+ current_store.claim_reasons.find_by_prefix_id!(create_params[:reason_id])
+ end
+
+ # The catalogue a replacement may be promised from. Left to the
+ # including controller precisely because getting it wrong would let
+ # one seller ship another's stock.
+ #
+ # @return [Spree::Variant, nil]
+ def replacement_variant_for(_variant_id)
+ raise NotImplementedError, "#{self.class} must implement #replacement_variant_for"
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/spree/api/app/controllers/concerns/spree/api/v3/orders/delivery_actions.rb b/spree/api/app/controllers/concerns/spree/api/v3/orders/delivery_actions.rb
new file mode 100644
index 0000000000..5047722a6d
--- /dev/null
+++ b/spree/api/app/controllers/concerns/spree/api/v3/orders/delivery_actions.rb
@@ -0,0 +1,105 @@
+module Spree
+ module Api
+ module V3
+ module Orders
+ # The consignments of one fulfillment — a parcel each, or a freight
+ # PRO number covering several pallets.
+ #
+ # A delivery is born when a tracking number is attached, days before
+ # anything arrives, so POST means "this went out as another
+ # consignment"; arrival is a transition on an existing row.
+ #
+ # Shared by the operator's branch and the seller's. `@parent` (the
+ # fulfillment) and `@resource` arrive already fetched and authorized,
+ # so including this concern cannot widen what a caller reaches.
+ module DeliveryActions
+ extend ActiveSupport::Concern
+
+ # POST .../deliveries
+ def create
+ authorize!(:create, Spree::Delivery)
+
+ with_order_lock do
+ # Every key is passed whether or not the request carried it, so
+ # the service sees a missing tracking number as a blank one to
+ # reject rather than a keyword it was never given.
+ result = Spree.delivery_create_service.call(
+ owner: @parent,
+ **resource_permitted_attributes.index_with { |key| delivery_params[key] }
+ )
+
+ if result.success?
+ render json: serialize_resource(result.value), status: :created
+ else
+ render_result_error(result)
+ end
+ end
+ end
+
+ # PATCH .../deliveries/:id — correcting the number, carrier or link.
+ #
+ # A corrected number is a different parcel as far as the carrier is
+ # concerned: its journey starts over, and the carrier and link that
+ # belonged to the old number go with it unless this request supplies
+ # new ones. A consignment that started over may also have been the
+ # one holding the fulfillment at delivered.
+ def update
+ with_order_lock do
+ if @resource.update(@resource.correction_attributes(delivery_params.to_h))
+ recalculate_fulfillment_delivery
+ render json: serialize_resource(@resource.reload)
+ else
+ render_validation_error(@resource.errors)
+ end
+ end
+ end
+
+ # DELETE .../deliveries/:id — 422 when a label minted it.
+ def destroy
+ with_order_lock do
+ result = Spree.delivery_destroy_service.call(delivery: @resource)
+
+ if result.success?
+ head :no_content
+ else
+ render_result_error(result)
+ end
+ end
+ end
+
+ protected
+
+ def model_class
+ Spree::Delivery
+ end
+
+ def parent_association
+ :deliveries
+ end
+
+ def collection_includes
+ [:shipping_label]
+ end
+
+ def resource_permitted_attributes
+ [:tracking_number, :carrier, :service, :tracking_url]
+ end
+
+ private
+
+ def delivery_params
+ @delivery_params ||= params.permit(*resource_permitted_attributes)
+ end
+
+ # Deliveries can hang off something other than a fulfillment, which
+ # has no delivered state to roll up.
+ def recalculate_fulfillment_delivery
+ return unless @parent.is_a?(Spree::Fulfillment)
+
+ Spree.fulfillment_recalculate_delivery_service.call(fulfillment: @parent)
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/spree/api/app/controllers/concerns/spree/api/v3/orders/exchange_actions.rb b/spree/api/app/controllers/concerns/spree/api/v3/orders/exchange_actions.rb
new file mode 100644
index 0000000000..a3fe1acc3b
--- /dev/null
+++ b/spree/api/app/controllers/concerns/spree/api/v3/orders/exchange_actions.rb
@@ -0,0 +1,118 @@
+module Spree
+ module Api
+ module V3
+ module Orders
+ # Swapping goods on an order — a different size, colour or product —
+ # and the four moves that settle it.
+ #
+ # See {PostSaleActions} for why the lookups a payload's ids resolve
+ # through are deliberately left to the including controller.
+ module ExchangeActions
+ extend ActiveSupport::Concern
+ include PostSaleActions
+
+ # POST .../exchanges
+ def create
+ create_post_sale_record(
+ Spree.exchange_create_workflow, Spree::Exchange,
+ stock_location: stock_location_for_create
+ )
+ end
+
+ # PATCH .../exchanges/:id/approve
+ def approve
+ run_workflow(Spree.exchange_approve_workflow, approver: try_spree_current_user)
+ end
+
+ # PATCH .../exchanges/:id/receive
+ def receive
+ run_workflow(Spree.exchange_receive_workflow,
+ items: items_for_receive,
+ received_by: try_spree_current_user)
+ end
+
+ # PATCH .../exchanges/:id/fulfill — sends the replacement, settling
+ # any price difference, which is why it takes a refund method.
+ def fulfill
+ run_workflow(Spree.exchange_fulfill_workflow,
+ refund_method: params[:refund_method] || 'store_credit',
+ refunder: try_spree_current_user)
+ end
+
+ # PATCH .../exchanges/:id/cancel
+ def cancel
+ run_workflow(Spree.exchange_cancel_workflow, reason: params[:reason])
+ end
+
+ protected
+
+ def model_class
+ Spree::Exchange
+ end
+
+ def parent_association
+ :exchanges
+ end
+
+ def workflow_record_key
+ :exchange
+ end
+
+ private
+
+ def create_params
+ @create_params ||= params.permit(
+ :memo, :reason_id, :stock_location_id,
+ items: [:fulfillment_item_id, :new_variant_id, :quantity]
+ )
+ end
+
+ # The units going back are resolved through the order; what comes
+ # out instead is resolved through {#replacement_variant_for}.
+ def items_for_create
+ Array(create_params[:items]).map do |item|
+ {
+ fulfillment_item: @order.fulfillment_items.find_by_prefix_id!(item[:fulfillment_item_id]),
+ new_variant: replacement_variant_for(item[:new_variant_id]),
+ quantity: item[:quantity].to_i
+ }
+ end
+ end
+
+ def items_for_receive
+ # `nil` means "receive it all as requested"; an empty list means
+ # the caller named no units, which must not fall through to that.
+ return nil unless params.key?(:items)
+
+ params.permit(items: [:exchange_line_item_id, :quantity, :resellable])[:items].map do |item|
+ {
+ exchange_line_item: @resource.exchange_line_items.find_by_prefix_id!(item[:exchange_line_item_id]),
+ quantity: item[:quantity].to_i,
+ resellable: item.key?(:resellable) ? item[:resellable].to_b : true
+ }
+ end
+ end
+
+ def reason_for_create
+ return nil if create_params[:reason_id].blank?
+
+ current_store.return_reasons.find_by_prefix_id!(create_params[:reason_id])
+ end
+
+ # The catalogue the replacement comes out of, and the shelf the
+ # returned goods go back to. Both are left to the including
+ # controller: an operator exchanges into the whole store, a seller
+ # only into their own goods, and getting this wrong would put one
+ # seller's stock on another's order.
+ def replacement_variant_for(_variant_id)
+ raise NotImplementedError, "#{self.class} must implement #replacement_variant_for"
+ end
+
+ def stock_location_for_create
+ raise NotImplementedError, "#{self.class} must implement #stock_location_for_create"
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/spree/api/app/controllers/concerns/spree/api/v3/orders/fulfillment_actions.rb b/spree/api/app/controllers/concerns/spree/api/v3/orders/fulfillment_actions.rb
new file mode 100644
index 0000000000..3c700a5d9a
--- /dev/null
+++ b/spree/api/app/controllers/concerns/spree/api/v3/orders/fulfillment_actions.rb
@@ -0,0 +1,157 @@
+module Spree
+ module Api
+ module V3
+ module Orders
+ # Dispatching what is owed on an order: shipping a parcel, cancelling
+ # one, and splitting goods that leave separately.
+ #
+ # Shared by the operator's branch and the seller's, which run the same
+ # workflows. What differs is only *whose records a payload may name*,
+ # and that stays in the including controller: this concern never
+ # fetches an order, a variant or a stock location. `@order` and
+ # `@resource` arrive already fetched and authorized — through
+ # `current_store` on one branch, `current_seller_orders` on the other
+ # — and this code never learns which.
+ module FulfillmentActions
+ extend ActiveSupport::Concern
+
+ # PATCH .../fulfillments/:id
+ def update
+ with_order_lock do
+ result = Spree.fulfillment_update_workflow.call(
+ fulfillment: @resource, fulfillment_attributes: update_attributes
+ )
+
+ if result.success?
+ render json: serialize_resource(@resource.reload)
+ else
+ render_result_error(result)
+ end
+ end
+ end
+
+ # PATCH .../fulfillments/:id/fulfill
+ #
+ # Ships the parcel. `items` narrows it to part of what the
+ # fulfillment holds, which splits the rest onto a new one.
+ def fulfill
+ with_order_lock do
+ result = Spree.fulfillment_fulfill_workflow.call(
+ fulfillment: @resource,
+ items: items_for_fulfill,
+ tracking: fulfill_params[:tracking],
+ tracking_carrier: fulfill_params[:tracking_carrier],
+ notify_customer: notify_customer?(fulfill_params[:notify_customer]),
+ **fulfill_workflow_options
+ )
+
+ if result.success?
+ render json: serialize_resource(result.value)
+ else
+ render_result_error(result)
+ end
+ end
+ end
+
+ # PATCH .../fulfillments/:id/cancel
+ #
+ # Restocking and standing the carrier down happen in the workflow.
+ def cancel
+ with_order_lock do
+ result = Spree.fulfillment_cancel_workflow.call(fulfillment: @resource)
+
+ if result.success?
+ render json: serialize_resource(result.value)
+ else
+ render_result_error(result)
+ end
+ end
+ end
+
+ # PATCH .../fulfillments/:id/split
+ #
+ # Moves part of what this parcel holds onto one of its own, for
+ # goods leaving separately. Answers with every fulfillment on the
+ # order, since splitting rewrites more than one.
+ def split
+ with_order_lock do
+ changer = @resource.transfer_to_location(
+ variant_for_split, params[:quantity].to_i, stock_location_for_split
+ )
+
+ if changer.run!
+ render json: {
+ data: @order.reload.fulfillments.map { |fulfillment| serialize_resource(fulfillment) }
+ }
+ else
+ render_validation_error(changer.errors)
+ end
+ end
+ end
+
+ protected
+
+ def model_class
+ Spree::Fulfillment
+ end
+
+ def parent_association
+ :fulfillments
+ end
+
+ private
+
+ def fulfill_params
+ @fulfill_params ||= params.permit(*fulfill_permitted_keys)
+ end
+
+ def fulfill_permitted_keys
+ [:tracking, :tracking_carrier, :notify_customer, { items: [:item_id, :quantity] }]
+ end
+
+ # Extra keywords the branch's own fulfil accepts — forcing past a
+ # guard is the operator's call, so the seller adds nothing.
+ def fulfill_workflow_options
+ {}
+ end
+
+ # The workflow addresses what to ship by line item, and the lookup
+ # runs through the order so an id from elsewhere cannot be shipped.
+ def items_for_fulfill
+ return if fulfill_params[:items].nil?
+
+ fulfill_params[:items].map do |item|
+ {
+ line_item: @order.line_items.find_by_prefix_id!(item[:item_id]),
+ quantity: Integer(item[:quantity].to_s, exception: false)
+ }
+ end
+ end
+
+ # Only an explicit false suppresses the email; an omitted flag keeps
+ # sending it.
+ def notify_customer?(value)
+ !ActiveModel::Type::Boolean.new.cast(value).equal?(false)
+ end
+
+ # The attributes handed to the update workflow. The workflow assigns
+ # ids raw, so a branch that must narrow one resolves it here first.
+ def update_attributes
+ permitted_params.to_h
+ end
+
+ # What may be split out of this parcel, and where the split half
+ # ships from. Both are left to the including controller: they decide
+ # whose catalogue and whose shelves are reachable.
+ def variant_for_split
+ raise NotImplementedError, "#{self.class} must implement #variant_for_split"
+ end
+
+ def stock_location_for_split
+ raise NotImplementedError, "#{self.class} must implement #stock_location_for_split"
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/spree/api/app/controllers/concerns/spree/api/v3/orders/post_sale_actions.rb b/spree/api/app/controllers/concerns/spree/api/v3/orders/post_sale_actions.rb
new file mode 100644
index 0000000000..018b3e0393
--- /dev/null
+++ b/spree/api/app/controllers/concerns/spree/api/v3/orders/post_sale_actions.rb
@@ -0,0 +1,66 @@
+module Spree
+ module Api
+ module V3
+ module Orders
+ # What every post-sale record on an order has in common: it is opened
+ # against the order, and then moved through its statuses one named
+ # action at a time.
+ #
+ # Shared by the operator's branch and the seller's, which run the same
+ # workflows with the same arguments. What differs between them is only
+ # *whose records a payload may name*, and that stays in the including
+ # controller: this concern never fetches an order, a variant or a
+ # stock location, so including it cannot widen what a caller reaches.
+ # `@order` and `@resource` arrive already fetched and authorized —
+ # through `current_store` on one branch, `current_seller_orders` on
+ # the other — and this code never learns which.
+ module PostSaleActions
+ extend ActiveSupport::Concern
+
+ protected
+
+ # Runs one of the record's status workflows and renders the result.
+ #
+ # The keyword the workflow expects for the record itself differs per
+ # entity (+return_record:+, +exchange:+, +claim:+), so each concern
+ # names its own.
+ def run_workflow(workflow, **arguments)
+ result = workflow.call(workflow_record_key => @resource, **arguments)
+
+ if result.success?
+ render json: serialize_resource(result.value)
+ else
+ render_result_error(result)
+ end
+ end
+
+ # @return [Symbol] the keyword this entity's workflows take it under
+ def workflow_record_key
+ raise NotImplementedError, "#{self.class} must implement #workflow_record_key"
+ end
+
+ # Opens the record against the order, through the entity's create
+ # workflow.
+ def create_post_sale_record(workflow, subject, **arguments)
+ authorize!(:create, subject)
+
+ result = workflow.call(
+ order: @order,
+ items: items_for_create,
+ reason: reason_for_create,
+ memo: create_params[:memo],
+ created_by: try_spree_current_user,
+ **arguments
+ )
+
+ if result.success?
+ render json: serialize_resource(result.value), status: :created
+ else
+ render_result_error(result)
+ end
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/spree/api/app/controllers/concerns/spree/api/v3/orders/return_actions.rb b/spree/api/app/controllers/concerns/spree/api/v3/orders/return_actions.rb
new file mode 100644
index 0000000000..40389efcbf
--- /dev/null
+++ b/spree/api/app/controllers/concerns/spree/api/v3/orders/return_actions.rb
@@ -0,0 +1,117 @@
+module Spree
+ module Api
+ module V3
+ module Orders
+ # Goods coming back on an order: opening the return, and the four
+ # moves that settle it.
+ #
+ # See {PostSaleActions} for why the lookups a payload's ids resolve
+ # through are deliberately left to the including controller.
+ module ReturnActions
+ extend ActiveSupport::Concern
+ include PostSaleActions
+
+ # POST .../returns
+ def create
+ create_post_sale_record(
+ Spree.return_create_workflow, Spree::Return,
+ stock_location: stock_location_for_create
+ )
+ end
+
+ # PATCH .../returns/:id/approve
+ def approve
+ run_workflow(Spree.return_approve_workflow, approver: try_spree_current_user)
+ end
+
+ # PATCH .../returns/:id/receive — what the warehouse actually counted.
+ def receive
+ run_workflow(Spree.return_receive_workflow,
+ items: items_for_receive,
+ received_by: try_spree_current_user)
+ end
+
+ # PATCH .../returns/:id/refund
+ def refund
+ run_workflow(Spree.return_refund_workflow,
+ amount: params[:amount],
+ refund_method: params[:refund_method] || 'original_payment',
+ refunder: try_spree_current_user)
+ end
+
+ # PATCH .../returns/:id/cancel
+ def cancel
+ run_workflow(Spree.return_cancel_workflow, reason: params[:reason])
+ end
+
+ protected
+
+ def model_class
+ Spree::Return
+ end
+
+ def parent_association
+ :returns
+ end
+
+ def workflow_record_key
+ :return_record
+ end
+
+ private
+
+ def create_params
+ @create_params ||= params.permit(
+ :memo, :reason_id, :stock_location_id,
+ items: [:fulfillment_item_id, :quantity]
+ )
+ end
+
+ # The units coming back, resolved through the order itself, so a
+ # fulfillment item from another order cannot be returned against
+ # this one.
+ def items_for_create
+ Array(create_params[:items]).map do |item|
+ {
+ fulfillment_item: @order.fulfillment_items.find_by_prefix_id!(item[:fulfillment_item_id]),
+ quantity: item[:quantity].to_i
+ }
+ end
+ end
+
+ # What the warehouse counted, resolved through the return itself.
+ def items_for_receive
+ # `nil` means "receive it all as requested"; an empty list means
+ # the caller named no units, which must not fall through to that.
+ return nil unless params.key?(:items)
+
+ params.permit(items: [:return_line_item_id, :quantity, :resellable])[:items].map do |item|
+ {
+ return_line_item: @resource.return_line_items.find_by_prefix_id!(item[:return_line_item_id]),
+ quantity: item[:quantity].to_i,
+ resellable: item.key?(:resellable) ? item[:resellable].to_b : true
+ }
+ end
+ end
+
+ # The merchant's own vocabulary either way: a seller picks a reason,
+ # the operator decides what the reasons are.
+ def reason_for_create
+ return nil if create_params[:reason_id].blank?
+
+ current_store.return_reasons.find_by_prefix_id!(create_params[:reason_id])
+ end
+
+ # The shelf the goods go back to — the store's warehouses for an
+ # operator, only their own for a seller. Left to the including
+ # controller because it decides whose stock this restocks.
+ #
+ # @return [Spree::StockLocation, nil]
+ def stock_location_for_create
+ raise NotImplementedError, "#{self.class} must implement #stock_location_for_create"
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/spree/api/app/controllers/concerns/spree/api/v3/orders/shipping_label_actions.rb b/spree/api/app/controllers/concerns/spree/api/v3/orders/shipping_label_actions.rb
new file mode 100644
index 0000000000..1c7824903a
--- /dev/null
+++ b/spree/api/app/controllers/concerns/spree/api/v3/orders/shipping_label_actions.rb
@@ -0,0 +1,128 @@
+module Spree
+ module Api
+ module V3
+ module Orders
+ # The postage on a parcel: recording a label, printing it back, and
+ # removing one that was uploaded by mistake.
+ #
+ # Shared by the operator's branch and the seller's. Buying a label is
+ # NOT here: it needs a carrier account, which is the operator's, so
+ # that action lives on the admin controller alone.
+ #
+ # `@parent` (the label's owner) and `@resource` arrive already fetched
+ # and authorized, so including this concern cannot widen what a caller
+ # reaches.
+ module ShippingLabelActions
+ extend ActiveSupport::Concern
+
+ included do
+ include ActiveStorage::SetCurrent
+ include Spree::Api::V3::StreamsShippingLabel
+
+ rescue_from ActiveSupport::MessageVerifier::InvalidSignature,
+ with: :render_invalid_signature
+ end
+
+ # GET .../labels/:id/download
+ #
+ # Streamed rather than redirected to storage, so the credentials
+ # that reached the action are what protects the file.
+ def download
+ stream_shipping_label(@resource) do
+ render_error(
+ code: Spree::Api::V3::ErrorHandler::ERROR_CODES[:validation_error],
+ message: Spree.t('shipping_labels.errors.no_file_url'),
+ status: :unprocessable_content
+ )
+ end
+ end
+
+ # DELETE .../labels/:id
+ #
+ # Only an uploaded label: a purchased one has postage to refund, so
+ # it goes through the refund action instead.
+ def destroy
+ unless @resource.uploaded?
+ return render_error(
+ code: Spree::Api::V3::ErrorHandler::ERROR_CODES[:validation_error],
+ message: Spree.t('shipping_labels.errors.purchased_not_deletable'),
+ status: :unprocessable_content
+ )
+ end
+
+ with_order_lock do
+ # The consignment goes with the label only while the parcel
+ # never moved — a journey that happened is a fact. Once it has,
+ # the delivery stays and is simply unlinked, so a wrong PDF can
+ # still be removed and replaced.
+ @resource.release_unmoved_delivery
+ @resource.destroy!
+ head :no_content
+ end
+ end
+
+ protected
+
+ def model_class
+ Spree::ShippingLabel
+ end
+
+ def parent_association
+ :shipping_labels
+ end
+
+ def collection_includes
+ [{ file_attachment: :blob }]
+ end
+
+ # Downloading is reading, so it must not demand write access to the
+ # parcel the label belongs to.
+ def read_actions
+ %w[index show download]
+ end
+
+ private
+
+ def label_permitted_keys
+ [:file, :tracking_number, :carrier, :service,
+ :cost, :currency, :file_format, :tracking_url]
+ end
+
+ def label_params
+ @label_params ||= params.permit(*label_permitted_keys)
+ end
+
+ # Records a label bought outside Spree.
+ #
+ # Every key is passed whether or not the request carried it, so the
+ # workflow sees a missing tracking number as a blank one to reject
+ # rather than a keyword it was never given.
+ def record_uploaded_label
+ with_order_lock do
+ result = Spree.shipping_label_record_workflow.call(
+ owner: @parent,
+ **label_permitted_keys.index_with { |key| label_params[key] }
+ )
+
+ if result.success?
+ render json: serialize_resource(result.value), status: :created
+ else
+ render_result_error(result)
+ end
+ end
+ end
+
+ # A tampered or expired direct-upload signature is a bad parameter,
+ # not a server fault.
+ def render_invalid_signature
+ render_error(
+ code: Spree::Api::V3::ErrorHandler::ERROR_CODES[:parameter_invalid],
+ message: Spree.t('shipping_labels.errors.file_required'),
+ status: :unprocessable_content
+ )
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/spree/api/app/controllers/spree/api/v3/admin/orders/claims_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/orders/claims_controller.rb
index fb90d38a21..10c55ee35f 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/orders/claims_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/orders/claims_controller.rb
@@ -5,6 +5,8 @@ module Spree
module Orders
# Claims on a completed order.
class ClaimsController < BaseController
+ include Spree::Api::V3::Orders::ClaimActions
+
# Claims are a subject of the `orders` catalog resource, so
# `read_orders`/`write_orders` gate these endpoints. `:claims`
# would name a key no catalog knows.
@@ -12,26 +14,9 @@ module Spree
before_action :set_resource, only: [:show, :update, :approve, :resolve, :deny, :cancel]
- # POST /api/v3/admin/orders/:order_id/claims
- def create
- authorize!(:create, Spree::Claim)
-
- result = Spree.claim_create_workflow.call(
- order: @order,
- items: items_for_create,
- reason: reason_for_create,
- memo: create_params[:memo],
- created_by: try_spree_current_user
- )
-
- if result.success?
- render json: serialize_resource(result.value), status: :created
- else
- render_result_error(result)
- end
- end
-
# PATCH /api/v3/admin/orders/:order_id/claims/:id
+ #
+ # Editable fields only — status moves through the member actions.
def update
if @resource.update(permitted_params)
render json: serialize_resource(@resource.reload)
@@ -40,49 +25,12 @@ module Spree
end
end
- # PATCH /api/v3/admin/orders/:order_id/claims/:id/approve
- def approve
- run_workflow(Spree.claim_approve_workflow, approver: try_spree_current_user)
- end
-
- # PATCH /api/v3/admin/orders/:order_id/claims/:id/resolve
- #
- # The resolution is chosen here rather than at claim creation, so
- # an admin decides how to make things right once they have the
- # facts.
- def resolve
- run_workflow(Spree.claim_resolve_workflow,
- resolution: params[:resolution],
- refund_method: params[:refund_method] || 'store_credit',
- amount: params[:amount],
- replacement_line_item_ids: replacement_line_item_ids,
- resolver: try_spree_current_user)
- end
-
- # PATCH /api/v3/admin/orders/:order_id/claims/:id/deny
- def deny
- run_workflow(Spree.claim_deny_workflow, reason: params[:reason])
- end
-
- # PATCH /api/v3/admin/orders/:order_id/claims/:id/cancel
- def cancel
- run_workflow(Spree.claim_cancel_workflow, reason: params[:reason])
- end
-
protected
- def model_class
- Spree::Claim
- end
-
def serializer_class
Spree.api.admin_claim_serializer
end
- def parent_association
- :claims
- end
-
def collection_includes
[:reason, { claim_line_items: [:variant, :replacement_variant] }]
end
@@ -91,59 +39,14 @@ module Spree
params.permit(:memo, :reason_id, metadata: {})
end
- def create_params
- @create_params ||= params.permit(
- :memo, :reason_id,
- items: [:line_item_id, :quantity, :description, :send_replacement,
- :replacement_variant_id, :refund_amount]
- )
- end
-
private
- # Which lines to replace, decided at resolution time. Absent means
- # "leave whatever the claim was opened with".
- def replacement_line_item_ids
- return nil unless params.key?(:replacement_line_item_ids)
-
- Array(params[:replacement_line_item_ids]).map do |id|
- @resource.claim_line_items.find_by_prefix_id!(id).id
- end
- end
-
- def run_workflow(workflow, **arguments)
- result = workflow.call(claim: @resource, **arguments)
-
- if result.success?
- render json: serialize_resource(result.value)
- else
- render_result_error(result)
- end
- end
-
- def items_for_create
- Array(create_params[:items]).map do |item|
- {
- line_item: @order.line_items.find_by_prefix_id!(item[:line_item_id]),
- quantity: item[:quantity].to_i,
- description: item[:description],
- send_replacement: item[:send_replacement].to_b,
- replacement_variant: replacement_variant_for(item),
- refund_amount: item[:refund_amount]
- }
- end
- end
-
- def replacement_variant_for(item)
- return nil if item[:replacement_variant_id].blank?
-
- current_store.variants.find_by_prefix_id!(item[:replacement_variant_id])
- end
-
- def reason_for_create
- return nil if create_params[:reason_id].blank?
+ # The whole store's catalogue: an operator may promise anything
+ # the store sells as a replacement.
+ def replacement_variant_for(variant_id)
+ return nil if variant_id.blank?
- current_store.claim_reasons.find_by_prefix_id!(create_params[:reason_id])
+ current_store.variants.find_by_prefix_id!(variant_id)
end
end
end
diff --git a/spree/api/app/controllers/spree/api/v3/admin/orders/deliveries_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/orders/deliveries_controller.rb
index 23c49518ca..5430163ac7 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/orders/deliveries_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/orders/deliveries_controller.rb
@@ -3,59 +3,17 @@ module Spree
module V3
module Admin
module Orders
- # The consignments of one fulfillment — a parcel each, or a freight
- # PRO number covering several pallets — under
+ # The consignments of one fulfillment, under
# /orders/:order_id/fulfillments/:fulfillment_id/deliveries.
#
- # A delivery is born when a tracking number is attached, days before
- # anything arrives, so POST means "this fulfillment went out as
- # another consignment"; arrival is the mark_delivered transition on
- # an existing row. The fulfillment-level mark_delivered stays beside
- # it for parcels that have no delivery row at all.
+ # CRUD lives in the shared concern; what is here is the store-wide
+ # scope and the one action only an operator has. The
+ # fulfillment-level mark_delivered stays beside it for parcels that
+ # have no delivery row at all.
class DeliveriesController < BaseController
- before_action :set_resource, only: [:show, :update, :destroy, :mark_delivered]
-
- # POST .../deliveries
- def create
- authorize!(:create, Spree::Delivery)
-
- with_order_lock do
- result = Spree.delivery_create_service.call(owner: @parent, **create_arguments)
-
- if result.success?
- render json: serialize_resource(result.value), status: :created
- else
- render_result_error(result)
- end
- end
- end
-
- # PATCH .../deliveries/:id — correcting the number, carrier or link.
- # A corrected number is a different parcel to the carrier, so its
- # journey starts over.
- def update
- with_order_lock do
- if @resource.update(@resource.correction_attributes(update_params.to_h))
- recalculate_delivery
- render json: serialize_resource(@resource.reload)
- else
- render_validation_error(@resource.errors)
- end
- end
- end
+ include Spree::Api::V3::Orders::DeliveryActions
- # DELETE .../deliveries/:id — 422 when a label minted it.
- def destroy
- with_order_lock do
- result = Spree.delivery_destroy_service.call(delivery: @resource)
-
- if result.success?
- head :no_content
- else
- render_result_error(result)
- end
- end
- end
+ before_action :set_resource, only: [:show, :update, :destroy, :mark_delivered]
# PATCH .../deliveries/:id/mark_delivered — staff saying this one
# consignment arrived; the fulfillment follows once every
@@ -79,56 +37,18 @@ module Spree
protected
- # A corrected number is a different parcel as far as the carrier
- # is concerned: its journey starts over, and the carrier and link
- # that belonged to the old number go with it unless this request
- # supplies new ones.
- # A consignment that started over may have been the one holding
- # the fulfillment at delivered.
- def recalculate_delivery
- return unless @parent.is_a?(Spree::Fulfillment)
-
- Spree.fulfillment_recalculate_delivery_service.call(fulfillment: @parent)
- end
-
- def model_class
- Spree::Delivery
- end
-
def serializer_class
Spree.api.admin_delivery_serializer
end
- def parent_association
- :deliveries
- end
-
- def collection_includes
- [:shipping_label]
- end
-
+ # The consignments hang off the fulfillment, not the order, so
+ # the parent is narrowed one step past the base's.
def set_parent
- @order = current_store.orders.find_by_prefix_id!(params[:order_id])
+ super
@parent = @order.fulfillments.find_by_prefix_id!(params[:fulfillment_id])
end
- def resource_permitted_attributes
- [:tracking_number, :carrier, :service, :tracking_url]
- end
-
- def update_params
- params.permit(*resource_permitted_attributes)
- end
-
- def create_arguments
- permitted = params.permit(*resource_permitted_attributes)
- {
- tracking_number: permitted[:tracking_number],
- carrier: permitted[:carrier],
- service: permitted[:service],
- tracking_url: permitted[:tracking_url]
- }
- end
+ private
def mark_delivered_params
@mark_delivered_params ||= params.permit(:delivered_at, :notify_customer)
diff --git a/spree/api/app/controllers/spree/api/v3/admin/orders/exchanges_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/orders/exchanges_controller.rb
index 46102fff8e..b2f46ca5e3 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/orders/exchanges_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/orders/exchanges_controller.rb
@@ -6,6 +6,8 @@ module Spree
# Exchanges on a completed order. Each status change is its own
# member action, because each carries different arguments.
class ExchangesController < BaseController
+ include Spree::Api::V3::Orders::ExchangeActions
+
# Exchanges are a subject of the `orders` catalog resource, so
# `read_orders`/`write_orders` gate these endpoints. `:exchanges`
# would name a key no catalog knows.
@@ -13,27 +15,9 @@ module Spree
before_action :set_resource, only: [:show, :update, :approve, :receive, :fulfill, :cancel]
- # POST /api/v3/admin/orders/:order_id/exchanges
- def create
- authorize!(:create, Spree::Exchange)
-
- result = Spree.exchange_create_workflow.call(
- order: @order,
- items: items_for_create,
- stock_location: stock_location_for_create,
- reason: reason_for_create,
- memo: create_params[:memo],
- created_by: try_spree_current_user
- )
-
- if result.success?
- render json: serialize_resource(result.value), status: :created
- else
- render_result_error(result)
- end
- end
-
# PATCH /api/v3/admin/orders/:order_id/exchanges/:id
+ #
+ # Editable fields only — status moves through the member actions.
def update
if @resource.update(permitted_params)
render json: serialize_resource(@resource.reload)
@@ -42,44 +26,12 @@ module Spree
end
end
- # PATCH /api/v3/admin/orders/:order_id/exchanges/:id/approve
- def approve
- run_workflow(Spree.exchange_approve_workflow, approver: try_spree_current_user)
- end
-
- # PATCH /api/v3/admin/orders/:order_id/exchanges/:id/receive
- def receive
- run_workflow(Spree.exchange_receive_workflow,
- items: items_for_receive,
- received_by: try_spree_current_user)
- end
-
- # PATCH /api/v3/admin/orders/:order_id/exchanges/:id/fulfill
- def fulfill
- run_workflow(Spree.exchange_fulfill_workflow,
- refund_method: params[:refund_method] || 'store_credit',
- refunder: try_spree_current_user)
- end
-
- # PATCH /api/v3/admin/orders/:order_id/exchanges/:id/cancel
- def cancel
- run_workflow(Spree.exchange_cancel_workflow, reason: params[:reason])
- end
-
protected
- def model_class
- Spree::Exchange
- end
-
def serializer_class
Spree.api.admin_exchange_serializer
end
- def parent_association
- :exchanges
- end
-
def collection_includes
[:reason, :stock_location, { exchange_line_items: [:original_variant, :new_variant] }]
end
@@ -88,43 +40,12 @@ module Spree
params.permit(:memo, :reason_id, :stock_location_id, metadata: {})
end
- def create_params
- @create_params ||= params.permit(:memo, :reason_id, :stock_location_id,
- items: [:fulfillment_item_id, :new_variant_id, :quantity])
- end
-
private
- def run_workflow(workflow, **arguments)
- result = workflow.call(exchange: @resource, **arguments)
-
- if result.success?
- render json: serialize_resource(result.value)
- else
- render_result_error(result)
- end
- end
-
- def items_for_create
- Array(create_params[:items]).map do |item|
- {
- fulfillment_item: @order.fulfillment_items.find_by_prefix_id!(item[:fulfillment_item_id]),
- new_variant: current_store.variants.find_by_prefix_id!(item[:new_variant_id]),
- quantity: item[:quantity].to_i
- }
- end
- end
-
- def items_for_receive
- return nil if params[:items].blank?
-
- params.permit(items: [:exchange_line_item_id, :quantity, :resellable])[:items].map do |item|
- {
- exchange_line_item: @resource.exchange_line_items.find_by_prefix_id!(item[:exchange_line_item_id]),
- quantity: item[:quantity].to_i,
- resellable: item.key?(:resellable) ? item[:resellable].to_b : true
- }
- end
+ # The whole store's catalogue, and any warehouse the caller may
+ # see: an operator exchanges into anything the store sells.
+ def replacement_variant_for(variant_id)
+ current_store.variants.find_by_prefix_id!(variant_id)
end
def stock_location_for_create
@@ -133,12 +54,6 @@ module Spree
current_store.stock_locations.accessible_by(current_ability, :show).
find_by_prefix_id!(create_params[:stock_location_id])
end
-
- def reason_for_create
- return nil if create_params[:reason_id].blank?
-
- current_store.return_reasons.find_by_prefix_id!(create_params[:reason_id])
- end
end
end
end
diff --git a/spree/api/app/controllers/spree/api/v3/admin/orders/fulfillments_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/orders/fulfillments_controller.rb
index 7b1f6422af..45d00b2439 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/orders/fulfillments_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/orders/fulfillments_controller.rb
@@ -3,7 +3,15 @@ module Spree
module V3
module Admin
module Orders
+ # The parcels owed on an order.
+ #
+ # Shipping, cancelling and splitting live in the shared concern;
+ # what is here is what makes them the operator's — the store-wide
+ # scope every id in a payload resolves through, and the two actions
+ # only an operator has.
class FulfillmentsController < BaseController
+ include Spree::Api::V3::Orders::FulfillmentActions
+
scoped_resource :fulfillments
before_action :set_resource, only: [:show, :update, :fulfill, :mark_delivered, :cancel, :split]
@@ -39,51 +47,10 @@ module Spree
end
end
- # PATCH /api/v3/admin/orders/:order_id/fulfillments/:id
- def update
- with_order_lock do
- result = Spree.fulfillment_update_workflow.call(
- fulfillment: @resource,
- fulfillment_attributes: permitted_params.to_h
- )
-
- if result.success?
- render json: serialize_resource(@resource.reload)
- else
- render_result_error(result)
- end
- end
- end
-
- # PATCH /api/v3/admin/orders/:order_id/fulfillments/:id/fulfill
- #
- # Marks the fulfillment as fulfilled. Passing `items` ships only
- # those quantities: they are split into a new fulfillment which is
- # the one that ships and is returned, leaving the remainder open.
- def fulfill
- with_order_lock do
- result = Spree.fulfillment_fulfill_workflow.call(
- fulfillment: @resource,
- items: items_for_fulfill,
- tracking: fulfill_params[:tracking],
- tracking_carrier: fulfill_params[:tracking_carrier],
- notify_customer: notify_customer?(fulfill_params[:notify_customer]),
- force: fulfill_params[:force].to_b
- )
-
- if result.success?
- render json: serialize_resource(result.value)
- else
- render_result_error(result)
- end
- end
- end
-
# PATCH /api/v3/admin/orders/:order_id/fulfillments/:id/mark_delivered
#
- # Confirms the customer received the goods. Staff can record this
- # by hand — a merchant with no carrier integration still needs a
- # delivered state.
+ # Staff confirming the parcel arrived. Deliberately the operator's
+ # alone: that goods arrived is the buyer's word, not the sender's.
def mark_delivered
with_order_lock do
result = Spree.fulfillment_mark_delivered_workflow.call(
@@ -100,75 +67,51 @@ module Spree
end
end
- # PATCH /api/v3/admin/orders/:order_id/fulfillments/:id/cancel
- def cancel
- with_order_lock do
- result = Spree.fulfillment_cancel_workflow.call(fulfillment: @resource)
+ protected
- if result.success?
- render json: serialize_resource(result.value)
- else
- render_result_error(result)
- end
- end
+ def serializer_class
+ Spree.api.admin_fulfillment_serializer
end
- # PATCH /api/v3/admin/orders/:order_id/fulfillments/:id/split
- def split
- with_order_lock do
- variant = current_store.variants.find_by_prefix_id!(params[:variant_id])
- quantity = params[:quantity].to_i
-
- stock_location = if params[:stock_location_id].present?
- find_stock_location!(params[:stock_location_id])
- else
- @resource.stock_location
- end
-
- fulfilment_changer = @resource.transfer_to_location(variant, quantity, stock_location)
-
- if fulfilment_changer.run!
- fulfillments = @order.reload.fulfillments
- render json: {
- data: fulfillments.map { |s| serialize_resource(s) }
- }
- else
- render_validation_error(fulfilment_changer.errors)
- end
- end
+ def collection_includes
+ [:deliveries, { shipping_labels: { file_attachment: :blob } }]
end
- protected
-
- def model_class
- Spree::Shipment
+ def permitted_params
+ params.permit(:tracking, :tracking_carrier, :selected_delivery_rate_id, :stock_location_id)
end
- def serializer_class
- Spree.api.admin_fulfillment_serializer
+ private
+
+ # Forcing past a stock or payment guard is the operator's call.
+ def fulfill_permitted_keys
+ super + [:force]
end
- def parent_association
- :shipments
+ def fulfill_workflow_options
+ { force: fulfill_params[:force].to_b }
end
- # The serializer embeds both, and the tracking summary reads the
- # first consignment.
- def collection_includes
- [:deliveries, { shipping_labels: { file_attachment: :blob } }]
+ # The whole catalogue, and any warehouse this staff member may
+ # see: an operator ships anything the store sells.
+ def variant_for_split
+ current_store.variants.find_by_prefix_id!(params[:variant_id])
end
- # State changes go through the dedicated `fulfill`/`cancel` member
- # actions, not mass assignment. `tracking` and `tracking_carrier`
- # are the one-parcel shortcut onto the primary delivery.
- def permitted_params
- params.permit(:tracking, :tracking_carrier, :selected_delivery_rate_id, :stock_location_id)
+ def stock_location_for_split
+ return @resource.stock_location if params[:stock_location_id].blank?
+
+ find_stock_location!(params[:stock_location_id])
end
def create_params
@create_params ||= params.permit(:stock_location_id, :tracking, :delivery_method_id, :cost, :status, metadata: {}, items: [:item_id, :quantity])
end
+ def mark_delivered_params
+ @mark_delivered_params ||= params.permit(:delivered_at, :notify_customer)
+ end
+
def find_stock_location!(id)
Spree::StockLocation.accessible_by(current_ability, :show).find_by_prefix_id!(id)
end
@@ -193,31 +136,6 @@ module Spree
}
end
end
-
- def fulfill_params
- @fulfill_params ||= params.permit(:tracking, :tracking_carrier, :notify_customer, :force, items: [:item_id, :quantity])
- end
-
- def mark_delivered_params
- @mark_delivered_params ||= params.permit(:delivered_at, :notify_customer)
- end
-
- # Only an explicit false suppresses the email — an omitted flag, and
- # anything unparseable, keeps the historic behavior of sending it.
- def notify_customer?(value)
- !ActiveModel::Type::Boolean.new.cast(value).equal?(false)
- end
-
- def items_for_fulfill
- return if fulfill_params[:items].nil?
-
- fulfill_params[:items].map do |item|
- {
- line_item: @order.line_items.find_by_prefix_id!(item[:item_id]),
- quantity: Integer(item[:quantity].to_s, exception: false)
- }
- end
- end
end
end
end
diff --git a/spree/api/app/controllers/spree/api/v3/admin/orders/labels_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/orders/labels_controller.rb
index 72a2a198dc..a9b564f410 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/orders/labels_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/orders/labels_controller.rb
@@ -3,35 +3,27 @@ module Spree
module V3
module Admin
module Orders
- # Shipping labels on one parcel — a fulfillment's outbound label
- # under /orders/:order_id/fulfillments/:fulfillment_id/labels, a
- # return's inbound label under /orders/:order_id/returns/:return_id/labels
- # (docs/plans/6.0-shipping-labels-and-deliveries.md).
+ # The postage on a parcel or a return.
#
- # Creating one either buys it through the parcel's provider, or —
- # when a +file+ is given — records a label the merchant bought
- # elsewhere. A refund is a transition, so it is a PATCH member
- # action; the only destroy is for an uploaded label, which has
- # nothing to refund.
+ # Recording, printing and deleting live in the shared concern. What
+ # is here is what needs the operator's carrier account: buying a
+ # label, and refunding one that was bought and not used.
class LabelsController < BaseController
- include ActiveStorage::SetCurrent
- include Spree::Api::V3::StreamsShippingLabel
+ include Spree::Api::V3::Orders::ShippingLabelActions
before_action :set_resource, only: [:show, :download, :refund, :destroy]
- # A tampered signed id would otherwise surface as a 500.
- rescue_from ActiveSupport::MessageVerifier::InvalidSignature, with: :render_invalid_signature
-
# POST .../labels
+ #
+ # Buys the label through the parcel's provider, or — when a `file`
+ # is given — records one the merchant bought elsewhere.
def create
authorize!(:create, Spree::ShippingLabel)
+ return record_uploaded_label if label_params[:file].present?
+
with_order_lock do
- result = if label_params[:file].present?
- Spree.shipping_label_record_workflow.call(owner: @parent, **record_arguments)
- else
- Spree.shipping_label_purchase_workflow.call(owner: @parent)
- end
+ result = Spree.shipping_label_purchase_workflow.call(owner: @parent)
if result.success?
render json: serialize_resource(result.value), status: :created
@@ -41,20 +33,7 @@ module Spree
end
end
- # GET .../labels/:id/download — streamed rather than redirected, so
- # the label is never reachable without admin credentials. The
- # carrier's copy is proxied only while the fetch is still pending.
- def download
- stream_shipping_label(@resource) do
- render_error(
- code: ERROR_CODES[:validation_error],
- message: Spree.t('shipping_labels.errors.no_file_url'),
- status: :unprocessable_content
- )
- end
- end
-
- # PATCH .../labels/:id/refund
+ # PATCH .../labels/:id/refund — a transition, so a member action.
def refund
with_order_lock do
result = Spree.shipping_label_refund_workflow.call(shipping_label: @resource)
@@ -67,84 +46,27 @@ module Spree
end
end
- # DELETE .../labels/:id — uploaded labels only; a purchased label
- # is refunded, never deleted, so the postage history stays honest.
- def destroy
- unless @resource.uploaded?
- return render_error(
- code: ERROR_CODES[:validation_error],
- message: Spree.t('shipping_labels.errors.purchased_not_deletable'),
- status: :unprocessable_content
- )
- end
-
- with_order_lock do
- # The consignment goes with the label only while the parcel
- # never moved — a journey that happened is a fact. Once it has,
- # the delivery stays and is simply unlinked, so a wrong PDF can
- # still be removed and replaced.
- @resource.release_unmoved_delivery
- @resource.destroy!
- head :no_content
- end
- end
-
protected
- def model_class
- Spree::ShippingLabel
- end
-
def serializer_class
Spree.api.admin_shipping_label_serializer
end
- def parent_association
- :shipping_labels
- end
-
def collection_includes
[:integration, :delivery, { file_attachment: :blob }]
end
- # The owner — fulfillment or return — is the parent the labels hang
- # off; the order is fetched first so an owner id from another
- # order can never resolve.
+ # The owner — fulfillment or return — is the parent the labels
+ # hang off; the base fetches the order first, so an owner id from
+ # another order can never resolve.
def set_parent
- @order = current_store.orders.find_by_prefix_id!(params[:order_id])
+ super
@parent = if params[:return_id].present?
@order.returns.find_by_prefix_id!(params[:return_id])
else
@order.fulfillments.find_by_prefix_id!(params[:fulfillment_id])
end
end
-
- READ_ACTIONS = %w[index show download].freeze
-
- def read_actions
- READ_ACTIONS
- end
-
- def label_params
- @label_params ||= params.permit(:file, :tracking_number, :carrier, :service, :cost, :currency, :file_format, :tracking_url)
- end
-
- def record_arguments
- {
- file: label_params[:file],
- tracking_number: label_params[:tracking_number],
- carrier: label_params[:carrier],
- service: label_params[:service],
- cost: label_params[:cost],
- currency: label_params[:currency],
- file_format: label_params[:file_format],
- tracking_url: label_params[:tracking_url]
- }
- end
-
- def render_invalid_signature
- render_error(code: ERROR_CODES[:parameter_invalid], message: Spree.t('shipping_labels.errors.file_required'), status: :unprocessable_content)
- end
end
end
end
diff --git a/spree/api/app/controllers/spree/api/v3/admin/orders/returns_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/orders/returns_controller.rb
index 8fb55f1d37..ff76667399 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/orders/returns_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/orders/returns_controller.rb
@@ -9,6 +9,8 @@ module Spree
# quantities the warehouse counted, refunding carries a method and
# an amount.
class ReturnsController < BaseController
+ include Spree::Api::V3::Orders::ReturnActions
+
# Returns are a subject of the `orders` catalog resource (see
# Spree::PermissionConfiguration), so `read_orders`/`write_orders`
# gate these endpoints — matching the cross-order ReturnsController.
@@ -19,26 +21,6 @@ module Spree
before_action :set_resource, only: [:show, :update, :approve, :receive, :refund, :cancel]
- # POST /api/v3/admin/orders/:order_id/returns
- def create
- authorize!(:create, Spree::Return)
-
- result = Spree.return_create_workflow.call(
- order: @order,
- items: items_for_create,
- stock_location: stock_location_for_create,
- reason: reason_for_create,
- memo: create_params[:memo],
- created_by: try_spree_current_user
- )
-
- if result.success?
- render json: serialize_resource(result.value), status: :created
- else
- render_result_error(result)
- end
- end
-
# PATCH /api/v3/admin/orders/:order_id/returns/:id
#
# Editable fields only — status moves through the member actions.
@@ -50,48 +32,12 @@ module Spree
end
end
- # PATCH /api/v3/admin/orders/:order_id/returns/:id/approve
- def approve
- run_workflow(Spree.return_approve_workflow, approver: try_spree_current_user)
- end
-
- # PATCH /api/v3/admin/orders/:order_id/returns/:id/receive
- #
- # `items` carries what actually arrived; omitting it receives
- # everything as requested and resellable.
- def receive
- run_workflow(Spree.return_receive_workflow,
- items: items_for_receive,
- received_by: try_spree_current_user)
- end
-
- # PATCH /api/v3/admin/orders/:order_id/returns/:id/refund
- def refund
- run_workflow(Spree.return_refund_workflow,
- amount: params[:amount],
- refund_method: params[:refund_method] || 'original_payment',
- refunder: try_spree_current_user)
- end
-
- # PATCH /api/v3/admin/orders/:order_id/returns/:id/cancel
- def cancel
- run_workflow(Spree.return_cancel_workflow, reason: params[:reason])
- end
-
protected
- def model_class
- Spree::Return
- end
-
def serializer_class
Spree.api.admin_return_serializer
end
- def parent_association
- :returns
- end
-
# `documents` resolves the provider through the returned units and
# reads the labels it produced, so both are preloaded: without them
# a page of returns is a query per row.
@@ -107,56 +53,15 @@ module Spree
params.permit(:memo, :reason_id, :stock_location_id, metadata: {})
end
- def create_params
- @create_params ||= params.permit(:memo, :reason_id, :stock_location_id,
- items: [:fulfillment_item_id, :quantity])
- end
-
private
- def run_workflow(workflow, **arguments)
- result = workflow.call(return_record: @resource, **arguments)
-
- if result.success?
- render json: serialize_resource(result.value)
- else
- render_result_error(result)
- end
- end
-
- def items_for_create
- Array(create_params[:items]).map do |item|
- {
- fulfillment_item: @order.fulfillment_items.find_by_prefix_id!(item[:fulfillment_item_id]),
- quantity: item[:quantity].to_i
- }
- end
- end
-
- def items_for_receive
- return nil if params[:items].blank?
-
- params.permit(items: [:return_line_item_id, :quantity, :resellable])[:items].map do |item|
- {
- return_line_item: @resource.return_line_items.find_by_prefix_id!(item[:return_line_item_id]),
- quantity: item[:quantity].to_i,
- resellable: item.key?(:resellable) ? item[:resellable].to_b : true
- }
- end
- end
-
+ # Any of the store's warehouses the caller may see.
def stock_location_for_create
return nil if create_params[:stock_location_id].blank?
current_store.stock_locations.accessible_by(current_ability, :show).
find_by_prefix_id!(create_params[:stock_location_id])
end
-
- def reason_for_create
- return nil if create_params[:reason_id].blank?
-
- current_store.return_reasons.find_by_prefix_id!(create_params[:reason_id])
- end
end
end
end
diff --git a/spree/api/app/controllers/spree/api/v3/seller/orders/base_controller.rb b/spree/api/app/controllers/spree/api/v3/seller/orders/base_controller.rb
new file mode 100644
index 0000000000..661a51c37e
--- /dev/null
+++ b/spree/api/app/controllers/spree/api/v3/seller/orders/base_controller.rb
@@ -0,0 +1,44 @@
+module Spree
+ module Api
+ module V3
+ module Seller
+ module Orders
+ # Anchor for everything nested under one of this seller's orders.
+ #
+ # Mirrors Admin::Orders::BaseController: the parent order is fetched
+ # once here rather than in each controller. The difference is the
+ # root — `current_seller_orders`, which is the seller's own orders
+ # minus drafts, since neither an in-flight checkout nor the
+ # operator's working document is this seller's to act on.
+ #
+ # Deliberately not a subclass of the admin base: that one resolves
+ # through `current_store`, and inheriting its lookups is precisely
+ # how a seller would come to read the whole marketplace.
+ class BaseController < Seller::ResourceController
+ include Spree::Api::V3::OrderLock
+
+ before_action :authorize_order_access!
+
+ scoped_resource :orders
+
+ protected
+
+ def set_parent
+ @parent = current_seller_orders.find_by_prefix_id!(params[:order_id])
+ @order = @parent
+ end
+
+ # Reads need only `:show` on the order; every write needs
+ # `:update`, so a seller who may only view an order cannot ship,
+ # refund or cancel against it. Derived from +read_actions+ rather
+ # than a hand-kept list, so a new write action is a write by
+ # default instead of silently unauthorized.
+ def authorize_order_access!
+ authorize_parent!(@parent)
+ end
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/spree/api/app/controllers/spree/api/v3/seller/orders/claims_controller.rb b/spree/api/app/controllers/spree/api/v3/seller/orders/claims_controller.rb
index 86fa4224b3..aa3bf1d7eb 100644
--- a/spree/api/app/controllers/spree/api/v3/seller/orders/claims_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/seller/orders/claims_controller.rb
@@ -4,148 +4,38 @@ module Spree
module Seller
module Orders
# Something went wrong with a delivery on one of this seller's
- # orders, and the seller makes it right — money back, a replacement,
- # or both — without necessarily asking for the goods back.
+ # orders, and the seller makes it right.
#
- # Rooted at the order fetched through `current_seller_orders`, with
- # the claimed lines and any replacement variant resolved through the
- # order and the seller's own catalogue.
- class ClaimsController < Seller::ResourceController
- # Claims are a subject of the `orders` catalog resource.
- scoped_resource :orders
+ # The workflows are the operator's, shared through the concern, so a
+ # claim settled here credits and restocks exactly as it does when
+ # the marketplace handles it. What is here is what makes it the
+ # seller's: the order comes from `current_seller_orders`, so a claim
+ # on somebody else's order reads as missing rather than denied, and
+ # a replacement may only be promised out of this seller's catalogue.
+ class ClaimsController < BaseController
+ include Spree::Api::V3::Orders::ClaimActions
- before_action :set_order
before_action :set_resource, only: [:show, :approve, :resolve, :deny, :cancel]
- # POST /api/v3/seller/orders/:order_id/claims
- def create
- authorize!(:create, Spree::Claim)
-
- result = Spree.claim_create_workflow.call(
- order: @order,
- items: items_for_create,
- reason: reason_for_create,
- memo: create_params[:memo],
- created_by: try_spree_current_user
- )
-
- if result.success?
- render json: serialize_resource(result.value), status: :created
- else
- render_result_error(result)
- end
- end
-
- # PATCH /api/v3/seller/orders/:order_id/claims/:id/approve
- def approve
- run_workflow(Spree.claim_approve_workflow, approver: try_spree_current_user)
- end
-
- # PATCH /api/v3/seller/orders/:order_id/claims/:id/resolve
- #
- # Settles the claim: a refund, a replacement shipment, or both.
- def resolve
- run_workflow(Spree.claim_resolve_workflow,
- resolution: params[:resolution],
- refund_method: params[:refund_method] || 'store_credit',
- amount: params[:amount],
- replacement_line_item_ids: replacement_line_item_ids,
- resolver: try_spree_current_user)
- end
-
- # PATCH /api/v3/seller/orders/:order_id/claims/:id/deny
- def deny
- run_workflow(Spree.claim_deny_workflow, reason: params[:reason])
- end
-
- # PATCH /api/v3/seller/orders/:order_id/claims/:id/cancel
- def cancel
- run_workflow(Spree.claim_cancel_workflow, reason: params[:reason])
- end
-
protected
- def model_class
- Spree::Claim
- end
-
def serializer_class
Spree.api.seller_claim_serializer
end
- def parent_association
- :claims
- end
-
- def read_actions
- %w[index show]
- end
-
def collection_includes
[:reason, { claim_line_items: [:variant, :line_item, :replacement_variant] }]
end
private
- def set_order
- @order = @parent = current_seller_orders.find_by_prefix_id!(params[:order_id])
- authorize! :show, @order
- end
-
- def run_workflow(workflow, **arguments)
- result = workflow.call(claim: @resource, **arguments)
-
- if result.success?
- render json: serialize_resource(result.value)
- else
- render_result_error(result)
- end
- end
-
- def create_params
- @create_params ||= params.permit(
- :memo, :reason_id,
- items: [:line_item_id, :quantity, :description, :send_replacement,
- :replacement_variant_id, :refund_amount]
- )
- end
-
- def items_for_create
- Array(create_params[:items]).map do |item|
- {
- line_item: @order.line_items.find_by_prefix_id!(item[:line_item_id]),
- quantity: item[:quantity].to_i,
- description: item[:description],
- send_replacement: item[:send_replacement].to_b,
- replacement_variant: replacement_variant_for(item),
- refund_amount: item[:refund_amount]
- }
- end
- end
-
# The seller's own catalogue: a replacement is stock this seller
# sends, so a variant belonging to another seller is not theirs to
# promise.
- def replacement_variant_for(item)
- return nil if item[:replacement_variant_id].blank?
-
- current_seller.variants.find_by_prefix_id!(item[:replacement_variant_id])
- end
-
- # Which lines to replace, decided at resolution time. Absent means
- # "leave whatever the claim was opened with".
- def replacement_line_item_ids
- return nil unless params.key?(:replacement_line_item_ids)
-
- Array(params[:replacement_line_item_ids]).map do |id|
- @resource.claim_line_items.find_by_prefix_id!(id).id
- end
- end
-
- def reason_for_create
- return nil if create_params[:reason_id].blank?
+ def replacement_variant_for(variant_id)
+ return nil if variant_id.blank?
- current_store.claim_reasons.find_by_prefix_id!(create_params[:reason_id])
+ current_seller.variants.find_by_prefix_id!(variant_id)
end
end
end
diff --git a/spree/api/app/controllers/spree/api/v3/seller/orders/deliveries_controller.rb b/spree/api/app/controllers/spree/api/v3/seller/orders/deliveries_controller.rb
index b039ba5c45..1eac8af4d0 100644
--- a/spree/api/app/controllers/spree/api/v3/seller/orders/deliveries_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/seller/orders/deliveries_controller.rb
@@ -3,104 +3,32 @@ module Spree
module V3
module Seller
module Orders
- # The consignments on a parcel the seller ships themselves. Rooted
- # at the order fetched through `current_seller_orders`, so a
- # fulfillment on somebody else's order reads as missing.
- class DeliveriesController < Seller::BaseController
- include Spree::Api::V3::OrderLock
-
- scoped_resource :fulfillments
-
- before_action :set_fulfillment
- before_action :set_delivery, only: [:show, :update, :destroy]
-
- def index
- render json: { data: @fulfillment.deliveries.map { |delivery| serialize(delivery) } }
- end
-
- def show
- render json: serialize(@delivery)
- end
-
- # POST /api/v3/seller/orders/:order_id/fulfillments/:fulfillment_id/deliveries
- def create
- authorize! :update, @fulfillment
-
- with_order_lock do
- result = Spree.delivery_create_service.call(
- owner: @fulfillment,
- tracking_number: delivery_params[:tracking_number],
- carrier: delivery_params[:carrier],
- service: delivery_params[:service],
- tracking_url: delivery_params[:tracking_url]
- )
-
- if result.success?
- render json: serialize(result.value), status: :created
- else
- render_result_error(result)
- end
- end
- end
-
- # PATCH .../deliveries/:id
- def update
- authorize! :update, @fulfillment
-
- with_order_lock do
- if @delivery.update(@delivery.correction_attributes(delivery_params.to_h))
- Spree.fulfillment_recalculate_delivery_service.call(fulfillment: @fulfillment)
- render json: serialize(@delivery.reload)
- else
- render_validation_error(@delivery.errors)
- end
- end
- end
-
- # DELETE .../deliveries/:id — 422 when a label minted it.
- def destroy
- authorize! :update, @fulfillment
-
- with_order_lock do
- result = Spree.delivery_destroy_service.call(delivery: @delivery)
-
- if result.success?
- head :no_content
- else
- render_result_error(result)
- end
- end
- end
+ # The consignments on a parcel the seller ships themselves.
+ #
+ # CRUD is shared with the operator's branch through the concern.
+ # What is here is what makes it the seller's: the order comes from
+ # `current_seller_orders`, so a fulfillment on somebody else's order
+ # reads as missing rather than denied.
+ #
+ # No `mark_delivered`: that a parcel arrived is the buyer's word,
+ # not the sender's, so confirming receipt stays with the operator
+ # and the carrier feed.
+ class DeliveriesController < BaseController
+ include Spree::Api::V3::Orders::DeliveryActions
+
+ before_action :set_resource, only: [:show, :update, :destroy]
protected
- def read_actions
- %w[index show]
- end
-
- private
-
- # A corrected number is a different parcel as far as the carrier
- # is concerned: its journey starts over, and the carrier and link
- # that belonged to the old number go with it unless this request
- # supplies new ones.
-
- def set_fulfillment
- @order = current_seller_orders.find_by_prefix_id!(params[:order_id])
- authorize! :show, @order
- @fulfillment = @order.fulfillments.find_by_prefix_id!(params[:fulfillment_id])
- end
-
- def set_delivery
- @delivery = @fulfillment.deliveries.find_by_prefix_id!(params[:id])
- end
-
- def delivery_params
- @delivery_params ||= params.permit(:tracking_number, :carrier, :service, :tracking_url)
+ def serializer_class
+ Spree.api.seller_delivery_serializer
end
- def serialize(delivery)
- Spree.api.seller_delivery_serializer.new(delivery, params: { store: current_store }).to_h
+ # The labels and consignments hang off the fulfillment, not the
+ # order, so the parent is narrowed one step past the base's.
+ def set_parent
+ super
+ @parent = @order.fulfillments.find_by_prefix_id!(params[:fulfillment_id])
end
end
end
diff --git a/spree/api/app/controllers/spree/api/v3/seller/orders/exchanges_controller.rb b/spree/api/app/controllers/spree/api/v3/seller/orders/exchanges_controller.rb
index a7d95efeed..1912e1918b 100644
--- a/spree/api/app/controllers/spree/api/v3/seller/orders/exchanges_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/seller/orders/exchanges_controller.rb
@@ -6,131 +6,35 @@ module Spree
# Swapping goods on one of this seller's orders — a different size,
# colour or product.
#
- # Rooted at the order fetched through `current_seller_orders`. The
- # replacement variant is resolved through `current_seller.variants`
- # rather than the store's: a seller exchanges into their own
- # catalogue, and reaching a rival's variant here would put that
- # seller's stock on this seller's order.
- class ExchangesController < Seller::ResourceController
- # Exchanges are a subject of the `orders` catalog resource.
- scoped_resource :orders
+ # The workflows are the operator's, shared through the concern. What
+ # is here is what makes it the seller's: the order comes from
+ # `current_seller_orders`, and the replacement variant is resolved
+ # through `current_seller.variants` rather than the store's, because
+ # a seller exchanges into their own catalogue and reaching a rival's
+ # variant here would put that seller's stock on this seller's order.
+ class ExchangesController < BaseController
+ include Spree::Api::V3::Orders::ExchangeActions
- before_action :set_order
before_action :set_resource, only: [:show, :approve, :receive, :fulfill, :cancel]
- # POST /api/v3/seller/orders/:order_id/exchanges
- def create
- authorize!(:create, Spree::Exchange)
-
- result = Spree.exchange_create_workflow.call(
- order: @order,
- items: items_for_create,
- stock_location: stock_location_for_create,
- reason: reason_for_create,
- memo: create_params[:memo],
- created_by: try_spree_current_user
- )
-
- if result.success?
- render json: serialize_resource(result.value), status: :created
- else
- render_result_error(result)
- end
- end
-
- # PATCH /api/v3/seller/orders/:order_id/exchanges/:id/approve
- def approve
- run_workflow(Spree.exchange_approve_workflow, approver: try_spree_current_user)
- end
-
- # PATCH /api/v3/seller/orders/:order_id/exchanges/:id/receive
- def receive
- run_workflow(Spree.exchange_receive_workflow,
- items: items_for_receive,
- received_by: try_spree_current_user)
- end
-
- # PATCH /api/v3/seller/orders/:order_id/exchanges/:id/fulfill
- #
- # Sends the replacement. Settles a price difference at the same
- # time, which is why it takes a refund method.
- def fulfill
- run_workflow(Spree.exchange_fulfill_workflow,
- refund_method: params[:refund_method] || 'store_credit',
- refunder: try_spree_current_user)
- end
-
- # PATCH /api/v3/seller/orders/:order_id/exchanges/:id/cancel
- def cancel
- run_workflow(Spree.exchange_cancel_workflow, reason: params[:reason])
- end
-
protected
- def model_class
- Spree::Exchange
- end
-
def serializer_class
Spree.api.seller_exchange_serializer
end
- def parent_association
- :exchanges
- end
-
- def read_actions
- %w[index show]
- end
-
def collection_includes
- [:reason, :stock_location, { exchange_line_items: [:original_variant, :new_variant, :line_item] }]
+ [:reason, :stock_location,
+ { exchange_line_items: [:original_variant, :new_variant, :line_item] }]
end
private
- def set_order
- @order = @parent = current_seller_orders.find_by_prefix_id!(params[:order_id])
- authorize! :show, @order
- end
-
- def run_workflow(workflow, **arguments)
- result = workflow.call(exchange: @resource, **arguments)
-
- if result.success?
- render json: serialize_resource(result.value)
- else
- render_result_error(result)
- end
- end
-
- def create_params
- @create_params ||= params.permit(:memo, :reason_id, :stock_location_id,
- items: [:fulfillment_item_id, :new_variant_id, :quantity])
- end
-
- def items_for_create
- Array(create_params[:items]).map do |item|
- {
- fulfillment_item: @order.fulfillment_items.find_by_prefix_id!(item[:fulfillment_item_id]),
- new_variant: current_seller.variants.find_by_prefix_id!(item[:new_variant_id]),
- quantity: item[:quantity].to_i
- }
- end
- end
-
- def items_for_receive
- # `nil` means "receive it all as requested"; an empty list means the
- # caller named no units, which must not fall through to that.
- return nil unless params.key?(:items)
-
- params.permit(items: [:exchange_line_item_id, :quantity, :resellable])[:items].map do |item|
- {
- exchange_line_item: @resource.exchange_line_items.find_by_prefix_id!(item[:exchange_line_item_id]),
- quantity: item[:quantity].to_i,
- resellable: item.key?(:resellable) ? item[:resellable].to_b : true
- }
- end
+ # The seller's own catalogue and their own shelves — a rival's
+ # variant is not theirs to send, nor a marketplace warehouse
+ # theirs to restock.
+ def replacement_variant_for(variant_id)
+ current_seller.variants.find_by_prefix_id!(variant_id)
end
def stock_location_for_create
@@ -138,12 +42,6 @@ module Spree
current_seller.stock_locations.find_by_prefix_id!(create_params[:stock_location_id])
end
-
- def reason_for_create
- return nil if create_params[:reason_id].blank?
-
- current_store.return_reasons.find_by_prefix_id!(create_params[:reason_id])
- end
end
end
end
diff --git a/spree/api/app/controllers/spree/api/v3/seller/orders/fulfillments_controller.rb b/spree/api/app/controllers/spree/api/v3/seller/orders/fulfillments_controller.rb
index 3747575c6c..583f177632 100644
--- a/spree/api/app/controllers/spree/api/v3/seller/orders/fulfillments_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/seller/orders/fulfillments_controller.rb
@@ -3,209 +3,73 @@ module Spree
module V3
module Seller
module Orders
- # Dispatching what a seller owes on one of their orders.
+ # The parcels this seller owes on one of their orders.
#
- # Rooted at the order fetched through `current_seller_orders`, so a
- # fulfillment on somebody else's order reads as missing rather than
- # denied — and a seller can never ship against an order that is not
- # theirs, whatever id they send.
+ # Shipping, cancelling and splitting are the operator's workflows,
+ # shared through the concern, so the customer email, the label
+ # purchase and the extension hooks all happen exactly as they do
+ # when the marketplace ships on the seller's behalf.
#
- # Fulfilling reuses the operator's workflow, so the customer email,
- # the label purchase and the extension hooks all happen exactly as
- # they do when the marketplace ships on the seller's behalf.
- class FulfillmentsController < Seller::BaseController
- include Spree::Api::V3::OrderLock
-
- scoped_resource :fulfillments
-
- before_action :set_order
- before_action :set_fulfillment,
- only: [:show, :update, :fulfill, :cancel, :split]
-
- def index
- # This action builds its own collection rather than going through
- # the base controller, so it preloads what the serializer reads —
- # otherwise every parcel costs a query for its consignments and
- # another for its labels.
- fulfillments = @order.fulfillments.
- includes(:deliveries, :shipping_labels, :fulfillment_items).
- preload_associations_lazily
-
- render json: { data: fulfillments.map { |fulfillment| serialize(fulfillment) } }
- end
-
- def show
- render json: serialize(@fulfillment)
- end
-
- # PATCH /api/v3/seller/orders/:order_id/fulfillments/:id/fulfill
- #
- # Ships the parcel. `items` narrows it to part of what the
- # fulfillment holds, which splits the rest onto a new one.
- def fulfill
- with_order_lock do
- result = Spree.fulfillment_fulfill_workflow.call(
- fulfillment: @fulfillment,
- items: items_for_fulfill,
- tracking: fulfill_params[:tracking],
- tracking_carrier: fulfill_params[:tracking_carrier],
- notify_customer: notify_customer?(fulfill_params[:notify_customer])
- )
-
- if result.success?
- render json: serialize(result.value)
- else
- render_service_error(@fulfillment.errors.presence || result.error)
- end
- end
- end
-
- # PATCH /api/v3/seller/orders/:order_id/fulfillments/:id
- #
- # The tracking pair, which of the seller's own shelves the parcel
- # ships from, and which quoted service carries it — a seller who
- # picks from a different warehouse than the split assumed needs to
- # say so, and the rates are requoted from there.
- #
- # The origin is resolved through `current_seller.stock_locations`,
- # so a marketplace warehouse is unreachable however the id arrives.
- def update
- with_order_lock do
- render_workflow_result(
- Spree.fulfillment_update_workflow.call(
- fulfillment: @fulfillment, fulfillment_attributes: update_attributes
- )
- )
- end
- end
-
- # PATCH /api/v3/seller/orders/:order_id/fulfillments/:id/cancel
- #
- # A parcel this seller is not going to send after all. Restocking
- # and standing the carrier down happen inside the workflow.
- def cancel
- run_workflow(Spree.fulfillment_cancel_workflow)
- end
-
- # PATCH /api/v3/seller/orders/:order_id/fulfillments/:id/split
- #
- # Moves part of what this parcel holds onto one of its own, for
- # goods leaving separately. The variant is resolved through the
- # order rather than the catalogue: what may be split is what this
- # parcel is actually carrying.
- def split
- with_order_lock do
- variant = @order.variants.find_by_prefix_id!(params[:variant_id])
-
- changer = @fulfillment.transfer_to_location(
- variant, params[:quantity].to_i, split_stock_location
- )
+ # What is here is what makes them the seller's: the order comes from
+ # `current_seller_orders`, so a fulfillment on somebody else's order
+ # reads as missing rather than denied, and both the goods that may
+ # be split and the shelves they ship from are the seller's own.
+ #
+ # No `mark_delivered` and no `create`: that goods arrived is the
+ # buyer's word rather than the sender's, and a parcel comes into
+ # being from the order, not from the seller.
+ class FulfillmentsController < BaseController
+ include Spree::Api::V3::Orders::FulfillmentActions
- if changer.run!
- render json: {
- data: @order.reload.fulfillments.map { |fulfillment| serialize(fulfillment) }
- }
- else
- render_validation_error(changer.errors)
- end
- end
- end
+ before_action :set_resource, only: [:show, :update, :fulfill, :cancel, :split]
protected
- def read_actions
- %w[index show]
+ def serializer_class
+ Spree.api.seller_fulfillment_serializer
end
- private
-
- def set_order
- @order = current_seller_orders.find_by_prefix_id!(params[:order_id])
- authorize! :show, @order
- end
-
- WRITE_ACTIONS = %w[update fulfill cancel split].freeze
-
- def set_fulfillment
- @fulfillment = @order.fulfillments.find_by_prefix_id!(params[:id])
- authorize! :update, @fulfillment if WRITE_ACTIONS.include?(action_name)
+ def collection_includes
+ [:deliveries, :shipping_labels, :fulfillment_items]
end
- def fulfill_params
- @fulfill_params ||= params.permit(
- :tracking, :tracking_carrier, :notify_customer, items: [:item_id, :quantity]
- )
- end
-
- def update_params
+ def permitted_params
params.permit(:tracking, :tracking_carrier, :stock_location_id,
:selected_delivery_rate_id)
end
- # The payload the workflow gets. The workflow assigns the origin
- # raw, so the prefixed id is resolved through the seller's own
- # shelves first — a marketplace warehouse 404s here rather than
- # reaching the assignment. The rate needs no such resolution: the
- # model's own writer takes the prefixed id and looks it up among
- # this parcel's quotes, so a rate belonging to another package is
- # already unreachable.
- def update_attributes
- attributes = update_params.to_h
-
- if update_params[:stock_location_id].present?
- location = current_seller.stock_locations.
- find_by_prefix_id!(update_params[:stock_location_id])
- attributes['stock_location_id'] = location.id
- end
-
- attributes
- end
-
- # Where the split half ships from. The seller's own shelves only —
- # defaulting to where this parcel already sits.
- def split_stock_location
- return @fulfillment.stock_location if params[:stock_location_id].blank?
+ private
- current_seller.stock_locations.find_by_prefix_id!(params[:stock_location_id])
+ # What may be split out is what this parcel is actually carrying,
+ # resolved through the order rather than the catalogue.
+ def variant_for_split
+ @order.variants.find_by_prefix_id!(params[:variant_id])
end
- def run_workflow(workflow)
- with_order_lock do
- render_workflow_result(workflow.call(fulfillment: @fulfillment))
- end
- end
+ # The seller's own shelves only — defaulting to where this parcel
+ # already sits.
+ def stock_location_for_split
+ return @resource.stock_location if params[:stock_location_id].blank?
- def render_workflow_result(result)
- if result.success?
- render json: serialize(result.value)
- else
- render_result_error(result)
- end
+ seller_stock_location!(params[:stock_location_id])
end
- # The workflow addresses what to ship by line item, and the lookup
- # runs through the order so an id from elsewhere cannot be shipped.
- def items_for_fulfill
- return if fulfill_params[:items].nil?
+ # The workflow assigns the origin raw, so the prefixed id is
+ # resolved through the seller's own shelves first — a marketplace
+ # warehouse 404s here rather than reaching the assignment.
+ def update_attributes
+ attributes = permitted_params.to_h
- fulfill_params[:items].map do |item|
- {
- line_item: @order.line_items.find_by_prefix_id!(item[:item_id]),
- quantity: Integer(item[:quantity].to_s, exception: false)
- }
+ if permitted_params[:stock_location_id].present?
+ attributes['stock_location_id'] =
+ seller_stock_location!(permitted_params[:stock_location_id]).id
end
- end
- # Only an explicit false suppresses the email; an omitted flag
- # keeps sending it, as the operator's endpoint does.
- def notify_customer?(value)
- !ActiveModel::Type::Boolean.new.cast(value).equal?(false)
+ attributes
end
- def serialize(fulfillment)
- Spree.api.seller_fulfillment_serializer.new(
- fulfillment, params: { store: current_store }
- ).to_h
+ def seller_stock_location!(id)
+ current_seller.stock_locations.find_by_prefix_id!(id)
end
end
end
diff --git a/spree/api/app/controllers/spree/api/v3/seller/orders/labels_controller.rb b/spree/api/app/controllers/spree/api/v3/seller/orders/labels_controller.rb
index b940e19415..26cfc0f6b7 100644
--- a/spree/api/app/controllers/spree/api/v3/seller/orders/labels_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/seller/orders/labels_controller.rb
@@ -3,36 +3,26 @@ module Spree
module V3
module Seller
module Orders
- # Labels on a parcel the seller ships themselves. Sellers fulfill on
- # manual methods only, so they upload a label bought elsewhere and
- # print it back — never purchase or refund, which need the
- # operator's carrier account.
- class LabelsController < Seller::BaseController
- include Spree::Api::V3::OrderLock
- include ActiveStorage::SetCurrent
- include Spree::Api::V3::StreamsShippingLabel
-
- scoped_resource :fulfillments
-
- before_action :set_fulfillment
- before_action :set_label, only: [:show, :download, :destroy]
-
- rescue_from ActiveSupport::MessageVerifier::InvalidSignature, with: :render_invalid_signature
-
- def index
- render json: { data: @fulfillment.shipping_labels.map { |label| serialize(label) } }
- end
-
- def show
- render json: serialize(@label)
- end
-
- # POST /api/v3/seller/orders/:order_id/fulfillments/:fulfillment_id/labels
+ # Labels on a parcel the seller ships themselves.
+ #
+ # Recording, printing and deleting are shared with the operator's
+ # branch through the concern. Buying and refunding are not: they
+ # need the operator's carrier account, so a seller uploads a label
+ # bought elsewhere and prints it back.
+ #
+ # Rooted at the order fetched through `current_seller_orders`, so a
+ # fulfillment on somebody else's order reads as missing.
+ class LabelsController < BaseController
+ include Spree::Api::V3::Orders::ShippingLabelActions
+
+ before_action :set_resource, only: [:show, :download, :destroy]
+
+ # POST .../labels
#
# Records an uploaded label; a request without a file is refused,
# since purchase is the operator's.
def create
- authorize! :update, @fulfillment
+ authorize!(:create, Spree::ShippingLabel)
if label_params[:file].blank?
return render_error(
@@ -42,88 +32,20 @@ module Spree
)
end
- with_order_lock do
- result = Spree.shipping_label_record_workflow.call(
- owner: @fulfillment,
- file: label_params[:file],
- tracking_number: label_params[:tracking_number],
- carrier: label_params[:carrier],
- service: label_params[:service],
- cost: label_params[:cost],
- currency: label_params[:currency],
- file_format: label_params[:file_format],
- tracking_url: label_params[:tracking_url]
- )
-
- if result.success?
- render json: serialize(result.value), status: :created
- else
- render_result_error(result)
- end
- end
- end
-
- # GET .../labels/:id/download
- def download
- stream_shipping_label(@label) do
- render_error(
- code: ERROR_CODES[:validation_error],
- message: Spree.t('shipping_labels.errors.no_file_url'),
- status: :unprocessable_content
- )
- end
- end
-
- # DELETE .../labels/:id — uploaded labels only.
- def destroy
- authorize! :update, @fulfillment
-
- unless @label.uploaded?
- return render_error(
- code: ERROR_CODES[:validation_error],
- message: Spree.t('shipping_labels.errors.purchased_not_deletable'),
- status: :unprocessable_content
- )
- end
-
- with_order_lock do
- # The consignment goes with the label only while the parcel
- # never moved — a journey that happened is a fact. Once it has,
- # the delivery stays and is simply unlinked.
- @label.release_unmoved_delivery
- @label.destroy!
- head :no_content
- end
+ record_uploaded_label
end
protected
- def read_actions
- %w[index show download]
- end
-
- private
-
- def set_fulfillment
- @order = current_seller_orders.find_by_prefix_id!(params[:order_id])
- authorize! :show, @order
- @fulfillment = @order.fulfillments.find_by_prefix_id!(params[:fulfillment_id])
- end
-
- def set_label
- @label = @fulfillment.shipping_labels.find_by_prefix_id!(params[:id])
- end
-
- def label_params
- @label_params ||= params.permit(:file, :tracking_number, :carrier, :service, :cost, :currency, :file_format, :tracking_url)
- end
-
- def serialize(label)
- Spree.api.seller_shipping_label_serializer.new(label, params: { store: current_store }).to_h
+ def serializer_class
+ Spree.api.seller_shipping_label_serializer
end
- def render_invalid_signature
- render_error(code: ERROR_CODES[:parameter_invalid], message: Spree.t('shipping_labels.errors.file_required'), status: :unprocessable_content)
+ # The labels and consignments hang off the fulfillment, not the
+ # order, so the parent is narrowed one step past the base's.
+ def set_parent
+ super
+ @parent = @order.fulfillments.find_by_prefix_id!(params[:fulfillment_id])
end
end
end
diff --git a/spree/api/app/controllers/spree/api/v3/seller/orders/returns_controller.rb b/spree/api/app/controllers/spree/api/v3/seller/orders/returns_controller.rb
index a04949bee8..fc7cf82e6a 100644
--- a/spree/api/app/controllers/spree/api/v3/seller/orders/returns_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/seller/orders/returns_controller.rb
@@ -5,159 +5,37 @@ module Spree
module Orders
# Goods coming back on one of this seller's orders.
#
- # Rooted at the order fetched through `current_seller_orders`, so a
+ # Every status move reuses the operator's workflow, shared through
+ # the concern, so restocking, the tax credit, the refund and the
+ # ledger reversal all happen exactly as they do when the marketplace
+ # handles the return itself. What is here is what makes it the
+ # seller's: the order comes from `current_seller_orders`, so a
# return on somebody else's order reads as missing rather than
- # denied, and every id the payload names — the units returned, the
- # shelf they go back to, the reason — is resolved through the
- # seller's own records.
- #
- # Every status move reuses the operator's workflow, so restocking,
- # the tax credit, the refund and the ledger reversal all happen
- # exactly as they do when the marketplace handles the return itself.
- class ReturnsController < Seller::ResourceController
- # Returns are a subject of the `orders` catalog resource, so
- # `read_orders`/`write_orders` gate these endpoints. Naming
- # `:returns` here would name a key no catalog knows.
- scoped_resource :orders
+ # denied, and the goods go back onto the seller's own shelf.
+ class ReturnsController < BaseController
+ include Spree::Api::V3::Orders::ReturnActions
- before_action :set_order
before_action :set_resource, only: [:show, :approve, :receive, :refund, :cancel]
- # POST /api/v3/seller/orders/:order_id/returns
- def create
- authorize!(:create, Spree::Return)
-
- result = Spree.return_create_workflow.call(
- order: @order,
- items: items_for_create,
- stock_location: stock_location_for_create,
- reason: reason_for_create,
- memo: create_params[:memo],
- created_by: try_spree_current_user
- )
-
- if result.success?
- render json: serialize_resource(result.value), status: :created
- else
- render_result_error(result)
- end
- end
-
- # PATCH /api/v3/seller/orders/:order_id/returns/:id/approve
- def approve
- run_workflow(Spree.return_approve_workflow, approver: try_spree_current_user)
- end
-
- # PATCH /api/v3/seller/orders/:order_id/returns/:id/receive
- #
- # `items` carries what actually arrived; omitting it receives
- # everything as requested and resellable.
- def receive
- run_workflow(Spree.return_receive_workflow,
- items: items_for_receive,
- received_by: try_spree_current_user)
- end
-
- # PATCH /api/v3/seller/orders/:order_id/returns/:id/refund
- #
- # The seller took the money for their own child order, so giving it
- # back is theirs. What can be given back is bounded by the return
- # itself and, on a split checkout, by this order's share of the
- # group's payment — never a sibling's.
- def refund
- run_workflow(Spree.return_refund_workflow,
- amount: params[:amount],
- refund_method: params[:refund_method] || 'original_payment',
- refunder: try_spree_current_user)
- end
-
- # PATCH /api/v3/seller/orders/:order_id/returns/:id/cancel
- def cancel
- run_workflow(Spree.return_cancel_workflow, reason: params[:reason])
- end
-
protected
- def model_class
- Spree::Return
- end
-
def serializer_class
Spree.api.seller_return_serializer
end
- def parent_association
- :returns
- end
-
- def read_actions
- %w[index show]
- end
-
def collection_includes
[:reason, :stock_location, { return_line_items: [:variant, :line_item] }]
end
private
- def set_order
- @order = @parent = current_seller_orders.find_by_prefix_id!(params[:order_id])
- authorize! :show, @order
- end
-
- def run_workflow(workflow, **arguments)
- result = workflow.call(return_record: @resource, **arguments)
-
- if result.success?
- render json: serialize_resource(result.value)
- else
- render_result_error(result)
- end
- end
-
- def create_params
- @create_params ||= params.permit(:memo, :reason_id, :stock_location_id,
- items: [:fulfillment_item_id, :quantity])
- end
-
- # Addressed by fulfillment item and resolved through the order, so
- # units belonging to another seller's order cannot be returned here.
- def items_for_create
- Array(create_params[:items]).map do |item|
- {
- fulfillment_item: @order.fulfillment_items.find_by_prefix_id!(item[:fulfillment_item_id]),
- quantity: item[:quantity].to_i
- }
- end
- end
-
- def items_for_receive
- # `nil` means "receive it all as requested"; an empty list means the
- # caller named no units, which must not fall through to that.
- return nil unless params.key?(:items)
-
- params.permit(items: [:return_line_item_id, :quantity, :resellable])[:items].map do |item|
- {
- return_line_item: @resource.return_line_items.find_by_prefix_id!(item[:return_line_item_id]),
- quantity: item[:quantity].to_i,
- resellable: item.key?(:resellable) ? item[:resellable].to_b : true
- }
- end
- end
-
- # The seller's own shelves only — goods coming back to a
- # marketplace warehouse is not this endpoint's business.
+ # The seller's own shelves: returned goods go back into the stock
+ # the seller sells from, never a marketplace warehouse.
def stock_location_for_create
return nil if create_params[:stock_location_id].blank?
current_seller.stock_locations.find_by_prefix_id!(create_params[:stock_location_id])
end
-
- def reason_for_create
- return nil if create_params[:reason_id].blank?
-
- current_store.return_reasons.find_by_prefix_id!(create_params[:reason_id])
- end
end
end
end
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/orders/returns_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/orders/returns_controller_spec.rb
index e3e253cea2..08cba5edca 100644
--- a/spree/api/spec/controllers/spree/api/v3/admin/orders/returns_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/admin/orders/returns_controller_spec.rb
@@ -103,6 +103,19 @@ RSpec.describe Spree::Api::V3::Admin::Orders::ReturnsController, type: :controll
expect(json_response['status']).to eq('received')
end
+ # Omitting `items` means "everything as requested"; naming an empty list
+ # means the caller named no units, which must not fall through to that.
+ it 'refuses an explicitly empty item list rather than receiving everything' do
+ line = return_record.return_line_items.first
+
+ patch :receive, params: {
+ order_id: order.prefixed_id, id: return_record.prefixed_id, items: []
+ }, as: :json
+
+ expect(response).to have_http_status(:unprocessable_content)
+ expect(line.reload.received_quantity).to eq(0)
+ end
+
it 'records a partial, non-resellable receipt' do
line = return_record.return_line_items.first