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.

Ship part of a fulfillment, with tracking and an email switch

Damian Legawiec2396474fd2bc
diff --git a/packages/admin-sdk/src/admin-client.ts b/packages/admin-sdk/src/admin-client.ts
index c950390271..4707918faf 100644
--- a/packages/admin-sdk/src/admin-client.ts
+++ b/packages/admin-sdk/src/admin-client.ts
@@ -137,6 +137,7 @@ import type {
ExchangeUpdateParams,
ExportCreateParams,
FulfillmentCreateParams,
+ FulfillmentFulfillParams,
FulfillmentSplitParams,
FulfillmentUpdateParams,
GiftCardApplyParams,
@@ -1055,12 +1056,19 @@ export class AdminClient {
body: params,
}),
- fulfill: (orderId: string, id: string, options?: RequestOptions): Promise<Fulfillment> =>
- this.request<Fulfillment>(
- 'PATCH',
- `/orders/${orderId}/fulfillments/${id}/fulfill`,
- options,
- ),
+ // Passing `items` ships only those quantities: they are split into a new
+ // fulfillment, which is what comes back — the addressed fulfillment keeps
+ // the remainder and stays open.
+ fulfill: (
+ orderId: string,
+ id: string,
+ params?: FulfillmentFulfillParams,
+ options?: RequestOptions,
+ ): Promise<Fulfillment> =>
+ this.request<Fulfillment>('PATCH', `/orders/${orderId}/fulfillments/${id}/fulfill`, {
+ ...options,
+ body: params,
+ }),
cancel: (orderId: string, id: string, options?: RequestOptions): Promise<Fulfillment> =>
this.request<Fulfillment>('PATCH', `/orders/${orderId}/fulfillments/${id}/cancel`, options),
diff --git a/packages/admin-sdk/src/params.ts b/packages/admin-sdk/src/params.ts
index 83d8c85a9a..63760bd8c3 100644
--- a/packages/admin-sdk/src/params.ts
+++ b/packages/admin-sdk/src/params.ts
@@ -137,6 +137,26 @@ export interface FulfillmentUpdateParams {
stock_location_id?: string
}
+/**
+ * Ships some or all of a fulfillment. A fulfillment has one origin, one
+ * carrier and one tracking number, so shipping a subset splits it first: the
+ * chosen quantities move into a new fulfillment which is the one that ships,
+ * and the remainder stays behind, still open.
+ */
+export interface FulfillmentFulfillParams {
+ /** Line item quantities to ship; omit to ship everything the fulfillment holds */
+ items?: Array<{ item_id: string; quantity: number }>
+ /** Carrier tracking number or a full `https://` tracking link, stored on the fulfillment that ships */
+ tracking?: string
+ /**
+ * Whether the customer gets the shipment email. Defaults to true; pass false
+ * to suppress it for this dispatch only (a correction, a re-ship, goods
+ * handed over in person). The store's own transactional-email preference
+ * still applies on top.
+ */
+ notify_customer?: boolean
+}
+
/**
* Moves `quantity` units of one variant out of a fulfillment into a new one.
* Splitting is per variant — a fulfillment holding several variants needs one
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 fc9c60c69b..4ebfecb4f2 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
@@ -56,32 +56,50 @@ module Spree
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
- @resource.fulfill!
- render json: serialize_resource(@resource.reload)
- rescue StateMachines::InvalidTransition => e
- render_service_error(e.message)
+ result = Spree.fulfillment_fulfill_workflow.call(
+ fulfillment: @resource,
+ items: items_for_fulfill,
+ tracking: fulfill_params[:tracking],
+ notify_customer: notify_customer_for_fulfill
+ )
+
+ 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/cancel
def cancel
with_order_lock do
- @resource.cancel!
- render json: serialize_resource(@resource.reload)
- rescue StateMachines::InvalidTransition => e
- render_service_error(e.message)
+ 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 /api/v3/admin/orders/:order_id/fulfillments/:id/resume
def resume
with_order_lock do
- @resource.resume!
- render json: serialize_resource(@resource.reload)
- rescue StateMachines::InvalidTransition => e
- render_service_error(e.message)
+ result = Spree.fulfillment_resume_workflow.call(fulfillment: @resource)
+
+ if result.success?
+ render json: serialize_resource(result.value)
+ else
+ render_result_error(result)
+ end
end
end
@@ -158,6 +176,27 @@ module Spree
}
end
end
+
+ def fulfill_params
+ @fulfill_params ||= params.permit(:tracking, :notify_customer, items: [:item_id, :quantity])
+ end
+
+ # Only an explicit false suppresses the email — an omitted flag, and
+ # anything unparseable, keeps the historic behavior of sending it.
+ def notify_customer_for_fulfill
+ !ActiveModel::Type::Boolean.new.cast(fulfill_params[:notify_customer]).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/spec/controllers/spree/api/v3/admin/orders/fulfillments_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/orders/fulfillments_controller_spec.rb
index 616aa71881..abff3b2483 100644
--- a/spree/api/spec/controllers/spree/api/v3/admin/orders/fulfillments_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/admin/orders/fulfillments_controller_spec.rb
@@ -199,6 +199,94 @@ RSpec.describe Spree::Api::V3::Admin::Orders::FulfillmentsController, type: :con
expect(response).to have_http_status(:ok)
expect(json_response['status']).to eq('fulfilled')
end
+
+ it 'stores the tracking number passed with the shipment' do
+ patch :fulfill, params: {
+ order_id: order.prefixed_id,
+ id: shipment.prefixed_id,
+ tracking: '1Z999'
+ }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(shipment.reload.tracking).to eq('1Z999')
+ end
+
+ it 'passes the notification flag through to the workflow' do
+ expect(Spree.fulfillment_fulfill_workflow).to receive(:call).
+ with(hash_including(notify_customer: false)).
+ and_call_original
+
+ patch :fulfill, params: {
+ order_id: order.prefixed_id,
+ id: shipment.prefixed_id,
+ notify_customer: false
+ }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ end
+
+ it 'notifies by default when the flag is omitted' do
+ expect(Spree.fulfillment_fulfill_workflow).to receive(:call).
+ with(hash_including(notify_customer: true)).
+ and_call_original
+
+ patch :fulfill, params: {
+ order_id: order.prefixed_id,
+ id: shipment.prefixed_id
+ }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ end
+
+ context 'with a subset of items' do
+ let!(:order) do
+ create(:order_ready_to_ship, store: store, line_items_count: 2).tap do |placed|
+ placed.line_items.each { |line_item| line_item.update_columns(quantity: 2) }
+ placed.fulfillments.first.fulfillment_items.update_all(quantity: 2)
+ placed.reload
+ end
+ end
+
+ # The response is the newly split fulfillment, not the one addressed in
+ # the URL — that one keeps the remainder and stays open.
+ it 'ships only the requested quantity and returns the shipped fulfillment' do
+ patch :fulfill, params: {
+ order_id: order.prefixed_id,
+ id: shipment.prefixed_id,
+ items: [{ item_id: order.line_items.first.prefixed_id, quantity: 1 }]
+ }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(json_response['status']).to eq('fulfilled')
+ expect(json_response['id']).not_to eq(shipment.prefixed_id)
+
+ expect(shipment.reload).not_to be_fulfilled
+ expect(order.reload.fulfillment_status).to eq('partial')
+ end
+
+ it 'rejects a quantity the fulfillment does not hold' do
+ patch :fulfill, params: {
+ order_id: order.prefixed_id,
+ id: shipment.prefixed_id,
+ items: [{ item_id: order.line_items.first.prefixed_id, quantity: 99 }]
+ }, as: :json
+
+ expect(response).to have_http_status(:unprocessable_content)
+ expect(shipment.reload).not_to be_fulfilled
+ end
+
+ it '404s on a line item belonging to another order' do
+ other_item = create(:order_with_line_items, store: store).line_items.first
+
+ patch :fulfill, params: {
+ order_id: order.prefixed_id,
+ id: shipment.prefixed_id,
+ items: [{ item_id: other_item.prefixed_id, quantity: 1 }]
+ }, as: :json
+
+ expect(response).to have_http_status(:not_found)
+ end
+ end
end
describe 'PATCH #cancel' do
diff --git a/spree/core/app/models/spree/fulfillment/custom_events.rb b/spree/core/app/models/spree/fulfillment/custom_events.rb
index 9d809bddae..b8b28354f6 100644
--- a/spree/core/app/models/spree/fulfillment/custom_events.rb
+++ b/spree/core/app/models/spree/fulfillment/custom_events.rb
@@ -25,12 +25,27 @@ module Spree
publish_event('fulfillment.ready')
end
+ # Whether the customer should be told this fulfillment shipped. Set by
+ # the caller (see Spree::Fulfillments::Fulfill) and carried in the event
+ # metadata rather than the payload — it is an instruction to subscribers
+ # about this one dispatch, not a property of the fulfillment.
+ #
+ # Defaults to true: anything fulfilling a shipment without expressing an
+ # opinion gets the historic behavior.
+ attr_writer :notify_customer
+
+ def notify_customer?
+ @notify_customer.nil? ? true : !!@notify_customer
+ end
+
def publish_fulfillment_fulfilled_event
return unless Spree::Events.enabled?
- publish_event('fulfillment.fulfilled')
+ metadata = { notify_customer: notify_customer? }
+
+ publish_event('fulfillment.fulfilled', nil, metadata)
# Legacy name — removed in 6.1
- publish_event('shipment.shipped')
+ publish_event('shipment.shipped', nil, metadata)
# Force reload of fulfillments association to see the new status
order.fulfillments.reset
diff --git a/spree/core/app/workflows/spree/fulfillments/fulfill.rb b/spree/core/app/workflows/spree/fulfillments/fulfill.rb
new file mode 100644
index 0000000000..dde0c4f944
--- /dev/null
+++ b/spree/core/app/workflows/spree/fulfillments/fulfill.rb
@@ -0,0 +1,169 @@
+module Spree
+ module Fulfillments
+ # Marks a fulfillment as fulfilled, optionally only for some of the units
+ # it holds.
+ #
+ # A fulfillment is the unit of shipping: it has one origin, one carrier and
+ # one tracking number, so "half of it shipped" is not a state it can be in.
+ # Shipping a subset therefore splits first — the chosen quantities move into
+ # a new fulfillment which is the one that ships, and the remainder stays
+ # behind, still open. That is what a merchant means by a partial shipment,
+ # and it keeps every fulfillment honest about what is actually in the box.
+ #
+ # Passing no +items+ fulfills the whole thing, which is the common case and
+ # the historic behavior.
+ #
+ # In the workflow tier because the split and the fulfillment have to happen
+ # together or not at all: a split that succeeded while the fulfillment
+ # failed would leave the order carrying a phantom fulfillment nobody asked
+ # for. The state machine stays the low-level mechanic underneath — this
+ # workflow decides *what* ships, the machine still decides whether the
+ # transition is legal.
+ class Fulfill < Spree::Workflow
+ hooks :validate, :after_fulfill
+
+ # The fulfillment that actually shipped. For a partial shipment this is
+ # the newly split fulfillment, NOT the one passed in — callers rendering
+ # a response want the shipped one.
+ attr_reader :fulfillment
+
+ # @param fulfillment [Spree::Fulfillment] the fulfillment to ship from
+ # @param items [Array<Hash>, nil] `[{ line_item: Spree::LineItem, quantity: Integer }]`
+ # to ship; nil or empty fulfills every unit the fulfillment holds
+ # @param tracking [String, nil] carrier tracking number or full tracking URL,
+ # stored on the fulfillment that ships
+ # @param notify_customer [Boolean] whether the shipment email goes out;
+ # false suppresses it for this dispatch only
+ # @return [Spree::ServiceModule::Result] the fulfilled fulfillment on success
+ def perform(fulfillment:, items: nil, tracking: nil, notify_customer: true)
+ super
+
+ @source = fulfillment
+ @requested = normalize_requested(items)
+
+ # Veto point — cut-off windows, 3PL capacity, per-location policy.
+ # Before anything is written: a rejection touches nothing.
+ run_hooks :validate
+
+ step :ensure_fulfillable
+
+ ApplicationRecord.transaction do
+ step :split_off_requested_units
+ step :unstock_if_resuming_from_canceled
+ step :apply_tracking
+ step :mark_fulfilled
+ end
+
+ run_hooks :after_fulfill
+ success(@fulfillment.reload)
+ end
+
+ private
+
+ # Drops entries asking for nothing, so `[{quantity: 0}]` means "ship
+ # everything" the same way an omitted list does rather than splitting off
+ # an empty fulfillment.
+ def normalize_requested(items)
+ return [] if items.blank?
+
+ items.filter_map do |item|
+ quantity = item[:quantity].to_i
+ { line_item: item[:line_item], quantity: quantity } if quantity.positive?
+ end
+ end
+
+ def ensure_fulfillable
+ failure(@source, Spree.t('fulfillments.errors.cannot_fulfill')) unless @source.can_fulfill?
+
+ ensure_requested_units_available
+ end
+
+ # Each requested quantity has to exist in *this* fulfillment. Without
+ # this the split would silently pull units out of a sibling fulfillment,
+ # shipping goods the merchant did not select.
+ def ensure_requested_units_available
+ return if @requested.empty?
+
+ available = @source.fulfillment_items.group(:line_item_id).sum(:quantity)
+
+ @requested.each do |item|
+ held = available[item[:line_item].id].to_i
+ next if item[:quantity] <= held
+
+ failure(
+ @source,
+ Spree.t('fulfillments.errors.not_in_fulfillment',
+ item: item[:line_item].prefixed_id, requested: item[:quantity], available: held)
+ )
+ end
+ end
+
+ # Reuses the create workflow rather than re-implementing unit moving:
+ # creating a fulfillment at the same origin with the requested items is
+ # exactly a split, and Create already handles the stock bookkeeping,
+ # partial-quantity moves and draining of emptied sources.
+ def split_off_requested_units
+ @fulfillment = @source
+ return if @requested.empty? || ships_everything?
+
+ result = Spree.fulfillment_create_workflow.call(
+ order: @source.order,
+ stock_location: @source.stock_location,
+ items: @requested,
+ delivery_method: @source.delivery_method
+ )
+
+ failure(@source, result.error) unless result.success?
+
+ @fulfillment = result.value
+ end
+
+ # Requesting every unit the fulfillment holds is a whole shipment wearing
+ # a partial shipment's clothes. Splitting there would drain the source
+ # and destroy it, which needlessly changes the fulfillment's number.
+ def ships_everything?
+ held = @source.fulfillment_items.group(:line_item_id).sum(:quantity)
+ requested = @requested.to_h { |item| [item[:line_item].id, item[:quantity]] }
+
+ held.all? { |line_item_id, quantity| requested[line_item_id].to_i >= quantity }
+ end
+
+ # A canceled fulfillment already put its units back on the shelf, so
+ # shipping it directly has to take them off again — the state machine
+ # allows canceled -> fulfilled precisely so goods that went out anyway
+ # can be recorded. Previously the resume callback covered this; it is an
+ # explicit step now that the callbacks are gone.
+ def unstock_if_resuming_from_canceled
+ return unless @source.canceled?
+
+ @fulfillment.manifest.each do |item|
+ next unless item.variant.track_inventory?
+
+ @fulfillment.stock_location.unstock(item.variant, item.quantity, @fulfillment)
+ end
+ end
+
+ # Written before the transition so the provider's own tracking lookup
+ # (run_provider_create_fulfillment) sees an admin-entered number and
+ # leaves it alone, and so the shipment email carries it.
+ #
+ # update_columns, not update! — Fulfillment#update! is a legacy override
+ # taking the order and recomputing status, which would fire after_fulfill
+ # ahead of the transition.
+ def apply_tracking
+ return if tracking.blank?
+
+ @fulfillment.update_columns(tracking: tracking.to_s.squish, updated_at: Time.current)
+ end
+
+ # The suppression flag rides on the record because the event is published
+ # from an after_transition callback, which takes no arguments.
+ def mark_fulfilled
+ @fulfillment.notify_customer = notify_customer
+ @fulfillment.fulfill!
+ rescue StateMachines::InvalidTransition => e
+ failure(@fulfillment, e.message)
+ end
+ end
+ end
+end
diff --git a/spree/core/config/locales/en.yml b/spree/core/config/locales/en.yml
index dac31f3ad8..6e608047de 100644
--- a/spree/core/config/locales/en.yml
+++ b/spree/core/config/locales/en.yml
@@ -958,11 +958,15 @@ en:
track_link: 'Tracking Link: %{url}'
fulfillments:
errors:
+ cannot_cancel: This fulfillment cannot be canceled in its current status
+ cannot_fulfill: This fulfillment cannot be fulfilled in its current status
+ cannot_resume: This fulfillment cannot be resumed in its current status
insufficient_quantity: Requested quantity (%{requested}) for item %{item} exceeds its unfulfilled quantity (%{available})
invalid_cost: cost must be a non-negative number
invalid_quantity: Quantity for item %{item} must be a positive integer
invalid_status: status must be 'shipped' when provided
no_items_to_fulfill: Order has no unfulfilled items
+ not_in_fulfillment: Requested quantity (%{requested}) for item %{item} exceeds the %{available} held by this fulfillment
order_canceled: Fulfillments cannot be created on a canceled order
order_not_completed: Fulfillments can only be created manually on completed orders
gateway: Gateway
diff --git a/spree/core/lib/spree/core/dependencies.rb b/spree/core/lib/spree/core/dependencies.rb
index 3e3208ad6c..327fe65d34 100644
--- a/spree/core/lib/spree/core/dependencies.rb
+++ b/spree/core/lib/spree/core/dependencies.rb
@@ -71,6 +71,7 @@ module Spree
# fulfillment
fulfillment_create_workflow: 'Spree::Fulfillments::Create',
fulfillment_update_workflow: 'Spree::Fulfillments::Update',
+ fulfillment_fulfill_workflow: 'Spree::Fulfillments::Fulfill',
# returns
return_create_workflow: 'Spree::Returns::Create',
diff --git a/spree/core/spec/workflows/spree/fulfillments/fulfill_spec.rb b/spree/core/spec/workflows/spree/fulfillments/fulfill_spec.rb
new file mode 100644
index 0000000000..d5c6bea152
--- /dev/null
+++ b/spree/core/spec/workflows/spree/fulfillments/fulfill_spec.rb
@@ -0,0 +1,240 @@
+require 'spec_helper'
+
+module Spree
+ describe Fulfillments::Fulfill do
+ subject { described_class }
+
+ let(:store) { @default_store }
+ let(:order) { create(:order_ready_to_ship, store: store, line_items_count: 2) }
+ let(:fulfillment) { order.fulfillments.first }
+ let(:line_items) { order.line_items.sort_by(&:id) }
+
+ describe 'fulfilling everything (items omitted)' do
+ let(:execute) { subject.call(fulfillment: fulfillment) }
+
+ it 'fulfills the fulfillment in place without splitting' do
+ expect(execute.success?).to eq(true)
+ expect(execute.value).to eq(fulfillment)
+ expect(fulfillment.reload).to be_fulfilled
+ expect(order.reload.fulfillments.count).to eq(1)
+ end
+
+ it 'rolls the order up to fulfilled' do
+ execute
+ expect(order.reload.fulfillment_status).to eq('fulfilled')
+ end
+ end
+
+ describe 'fulfilling a subset' do
+ # Two units of each line item, so shipping one unit leaves a remainder
+ # both within that line item and across the order.
+ let(:partial_order) do
+ create(:order_ready_to_ship, store: store, line_items_count: 2).tap do |order|
+ order.line_items.each { |line_item| line_item.update_columns(quantity: 2) }
+ order.fulfillments.first.fulfillment_items.update_all(quantity: 2)
+ order.reload
+ end
+ end
+ let(:source) { partial_order.fulfillments.first }
+ let(:first_item) { partial_order.line_items.sort_by(&:id).first }
+
+ let(:execute) do
+ subject.call(fulfillment: source, items: [{ line_item: first_item, quantity: 1 }])
+ end
+
+ it 'splits the requested units into a new fulfillment and ships that one' do
+ shipped = execute.value
+
+ expect(execute.success?).to eq(true)
+ expect(shipped).not_to eq(source)
+ expect(shipped).to be_fulfilled
+ expect(shipped.fulfillment_items.sum(:quantity)).to eq(1)
+ end
+
+ it 'leaves the remainder open on the source fulfillment' do
+ execute
+
+ expect(source.reload).not_to be_fulfilled
+ # 2 of the first line item + 2 of the second, minus the 1 shipped.
+ expect(source.fulfillment_items.sum(:quantity)).to eq(3)
+ end
+
+ it 'reports the order as partially fulfilled' do
+ execute
+ expect(partial_order.reload.fulfillment_status).to eq('partial')
+ end
+
+ it 'does not split when the requested items cover everything held' do
+ items = partial_order.line_items.map { |line_item| { line_item: line_item, quantity: 2 } }
+
+ result = subject.call(fulfillment: source, items: items)
+
+ expect(result.value).to eq(source)
+ expect(partial_order.reload.fulfillments.count).to eq(1)
+ expect(source.reload).to be_fulfilled
+ end
+
+ it 'treats zero quantities as no selection and fulfills everything' do
+ result = subject.call(fulfillment: source, items: [{ line_item: first_item, quantity: 0 }])
+
+ expect(result.value).to eq(source)
+ expect(source.reload).to be_fulfilled
+ end
+ end
+
+ describe 'guards' do
+ it 'refuses a quantity the fulfillment does not hold' do
+ result = subject.call(
+ fulfillment: fulfillment,
+ items: [{ line_item: line_items.first, quantity: 99 }]
+ )
+
+ expect(result.success?).to eq(false)
+ expect(result.error.to_s).to match(/exceeds the .* held by this fulfillment/)
+ expect(fulfillment.reload).not_to be_fulfilled
+ end
+
+ # The state machine offers `fulfill` from ready, ready_for_pickup and
+ # canceled — shipping a canceled fulfillment is a deliberate transition
+ # (the goods went out anyway), so the workflow must not second-guess it.
+ it 'fulfills a canceled fulfillment, which the state machine allows' do
+ fulfillment.cancel!
+
+ result = subject.call(fulfillment: fulfillment)
+
+ expect(result.success?).to eq(true)
+ expect(fulfillment.reload).to be_fulfilled
+ end
+
+ it 'refuses a fulfillment already fulfilled' do
+ fulfillment.fulfill!
+
+ result = subject.call(fulfillment: fulfillment)
+
+ expect(result.success?).to eq(false)
+ expect(result.error.to_s).to eq(Spree.t('fulfillments.errors.cannot_fulfill'))
+ end
+
+ # The split and the fulfillment share a transaction, so a fulfillment
+ # that cannot ship must not leave a stray split behind.
+ it 'creates no fulfillment when the split succeeds but shipping fails' do
+ allow_any_instance_of(Spree::Fulfillment).to receive(:fulfill!).
+ and_raise(StateMachines::InvalidTransition.new(fulfillment, fulfillment.class.state_machine, :fulfill))
+
+ expect {
+ subject.call(fulfillment: fulfillment, items: [{ line_item: line_items.first, quantity: 1 }])
+ }.not_to change { order.reload.fulfillments.count }
+ end
+ end
+
+ # A canceled fulfillment already restocked its units, so shipping it
+ # directly has to take them off the shelf again. This used to ride on the
+ # resume transition callback.
+ describe 'fulfilling a canceled fulfillment' do
+ before { fulfillment.cancel! }
+
+ it 'takes the units back off the shelf' do
+ variant = fulfillment.fulfillment_items.first.variant
+ stock_item = fulfillment.stock_location.stock_item(variant)
+
+ expect { subject.call(fulfillment: fulfillment) }.
+ to change { stock_item.reload.count_on_hand }.by(
+ -fulfillment.fulfillment_items.where(variant_id: variant.id).sum(:quantity)
+ )
+ expect(fulfillment.reload).to be_fulfilled
+ end
+
+ it 'does not unstock when the fulfillment was open' do
+ fulfillment.resume!
+ variant = fulfillment.fulfillment_items.first.variant
+ stock_item = fulfillment.stock_location.stock_item(variant)
+
+ expect { subject.call(fulfillment: fulfillment) }.
+ not_to change { stock_item.reload.count_on_hand }
+ end
+ end
+
+ describe 'tracking' do
+ it 'stores the tracking number on the fulfillment that ships' do
+ subject.call(fulfillment: fulfillment, tracking: '1Z999')
+
+ expect(fulfillment.reload.tracking).to eq('1Z999')
+ end
+
+ it 'puts tracking on the split fulfillment, not the remainder' do
+ partial = create(:order_ready_to_ship, store: store, line_items_count: 1).tap do |order|
+ order.line_items.each { |line_item| line_item.update_columns(quantity: 2) }
+ order.fulfillments.first.fulfillment_items.update_all(quantity: 2)
+ order.reload
+ end
+ source = partial.fulfillments.first
+ source_tracking = source.tracking
+
+ shipped = subject.call(
+ fulfillment: source,
+ items: [{ line_item: partial.line_items.first, quantity: 1 }],
+ tracking: '1Z999'
+ ).value
+
+ expect(shipped).not_to eq(source)
+ expect(shipped.tracking).to eq('1Z999')
+ expect(source.reload.tracking).to eq(source_tracking)
+ end
+ end
+
+ # The email rides on the fulfillment.fulfilled event's metadata, so the
+ # flag is asserted where it is published rather than by reaching into the
+ # mailer (which lives in a different gem).
+ describe 'customer notification' do
+ before do
+ allow(Spree::Events).to receive(:enabled?).and_return(true)
+ allow(Spree::Events).to receive(:publish)
+ end
+
+ it 'asks subscribers to notify by default' do
+ subject.call(fulfillment: fulfillment)
+
+ expect(Spree::Events).to have_received(:publish).
+ with('fulfillment.fulfilled', anything, hash_including(notify_customer: true))
+ end
+
+ it 'suppresses the notification when asked' do
+ subject.call(fulfillment: fulfillment, notify_customer: false)
+
+ expect(Spree::Events).to have_received(:publish).
+ with('fulfillment.fulfilled', anything, hash_including(notify_customer: false))
+ end
+
+ it 'carries the flag on the legacy shipment.shipped twin too' do
+ subject.call(fulfillment: fulfillment, notify_customer: false)
+
+ expect(Spree::Events).to have_received(:publish).
+ with('shipment.shipped', anything, hash_including(notify_customer: false))
+ end
+ end
+
+ describe 'hooks' do
+ before { Spree.hooks.clear! }
+ after { Spree.hooks.clear! }
+
+ it 'lets a validate handler veto before anything is written' do
+ Spree.hooks.register('fulfillments.fulfill.validate') { |flow| flow.reject!('past the cut-off') }
+
+ result = subject.call(fulfillment: fulfillment)
+
+ expect(result.success?).to eq(false)
+ expect(result.error.to_s).to eq('past the cut-off')
+ expect(fulfillment.reload).not_to be_fulfilled
+ end
+
+ it 'runs after_fulfill with the shipped fulfillment' do
+ seen = nil
+ Spree.hooks.register('fulfillments.fulfill.after_fulfill') { |flow| seen = flow.fulfillment }
+
+ subject.call(fulfillment: fulfillment)
+
+ expect(seen).to eq(fulfillment)
+ end
+ end
+ end
+end
diff --git a/spree/emails/app/subscribers/spree/fulfillment_email_subscriber.rb b/spree/emails/app/subscribers/spree/fulfillment_email_subscriber.rb
index aa34c65ae0..5f89fe444c 100644
--- a/spree/emails/app/subscribers/spree/fulfillment_email_subscriber.rb
+++ b/spree/emails/app/subscribers/spree/fulfillment_email_subscriber.rb
@@ -5,6 +5,8 @@ module Spree
subscribes_to 'fulfillment.fulfilled'
def handle(event)
+ return unless notify_customer?(event)
+
fulfillment = find_fulfillment(event)
return unless fulfillment
@@ -16,6 +18,14 @@ module Spree
private
+ # An admin shipping from the backoffice can suppress the shipment email for
+ # this one dispatch (a correction, a re-ship, goods handed over in person).
+ # Absent metadata means send, so events published by anything unaware of
+ # the flag keep the historic behavior.
+ def notify_customer?(event)
+ event.metadata.fetch('notify_customer', true) != false
+ end
+
def find_fulfillment(event)
fulfillment_id = event.payload['id']
Spree::Fulfillment.find_by_prefix_id(fulfillment_id)
diff --git a/spree/emails/spec/models/spree/shipment_spec.rb b/spree/emails/spec/models/spree/shipment_spec.rb
index 0d6b77cb3a..e31b02cae6 100644
--- a/spree/emails/spec/models/spree/shipment_spec.rb
+++ b/spree/emails/spec/models/spree/shipment_spec.rb
@@ -23,8 +23,9 @@ describe Spree::Shipment, type: :model do
end
it 'publishes shipment.shipped event when fulfilling', events: true do
- expect(shipment).to receive(:publish_event).with('shipment.shipped')
- allow(shipment).to receive(:publish_event).with(anything)
+ expect(shipment).to receive(:publish_event).
+ with('shipment.shipped', nil, hash_including(notify_customer: true))
+ allow(shipment).to receive(:publish_event).with(any_args)
shipment.fulfill!
end
diff --git a/spree/emails/spec/subscribers/spree/fulfillment_email_subscriber_spec.rb b/spree/emails/spec/subscribers/spree/fulfillment_email_subscriber_spec.rb
index 265a1c4582..9b10d4f281 100644
--- a/spree/emails/spec/subscribers/spree/fulfillment_email_subscriber_spec.rb
+++ b/spree/emails/spec/subscribers/spree/fulfillment_email_subscriber_spec.rb
@@ -8,8 +8,8 @@ RSpec.describe Spree::FulfillmentEmailSubscriber do
let(:fulfillment) { order.fulfillments.first }
let(:subscriber) { described_class.new }
- def mock_event(fulfillment)
- double('Event', payload: { 'id' => fulfillment.prefixed_id })
+ def mock_event(fulfillment, metadata = {})
+ double('Event', payload: { 'id' => fulfillment.prefixed_id }, metadata: metadata.stringify_keys)
end
before do
@@ -42,5 +42,23 @@ RSpec.describe Spree::FulfillmentEmailSubscriber do
expect { subscriber.handle(mock_event(fulfillment)) }.not_to raise_error
end
end
+
+ # An admin shipping from the backoffice can suppress the email for one
+ # dispatch — a correction, a re-ship, or goods handed over in person.
+ context 'when the event suppresses the notification' do
+ it 'does not send the fulfilled email' do
+ expect(Spree::FulfillmentMailer).not_to receive(:fulfilled_email)
+
+ subscriber.handle(mock_event(fulfillment, notify_customer: false))
+ end
+ end
+
+ context 'when the event asks for the notification' do
+ it 'sends the fulfilled email' do
+ expect(Spree::FulfillmentMailer).to receive(:fulfilled_email).with(fulfillment.id).and_return(double(deliver_later: true))
+
+ subscriber.handle(mock_event(fulfillment, notify_customer: true))
+ end
+ end
end
end