Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
Fix what review found on tracking, labels and partial returns
Damian Legawiecd6348092c80c
diff --git a/packages/dashboard-core/src/tables/stock-locations.tsx b/packages/dashboard-core/src/tables/stock-locations.tsxindex 3826d35879..6334e8a6a1 100644--- a/packages/dashboard-core/src/tables/stock-locations.tsx+++ b/packages/dashboard-core/src/tables/stock-locations.tsx@@ -83,7 +83,7 @@ defineTable<PanelStockLocation>('stock-locations', {filterType: 'boolean',render: (sl) => (<ActiveBadge- active={sl.returns_enabled}+ active={sl.returns_enabled ?? true}activeLabel={i18n.t('admin.stock_locations.badges.enabled')}dashWhenInactive/>diff --git a/packages/dashboard/src/components/spree/post-sale-create-dialogs.tsx b/packages/dashboard/src/components/spree/post-sale-create-dialogs.tsxindex f18a7f6984..de5e2b5767 100644--- a/packages/dashboard/src/components/spree/post-sale-create-dialogs.tsx+++ b/packages/dashboard/src/components/spree/post-sale-create-dialogs.tsx@@ -132,12 +132,15 @@ export function CreateReturnDialog({// somewhere even when no location is flagged.const locationOptions = (stockLocationData?.data ?? []).filter((location) => location.active)- .sort((a, b) => Number(b.returns_enabled) - Number(a.returns_enabled))+ // A location that predates the flag accepts returns, which is how goods+ // behaved before it existed — the same default the form applies.+ .sort((a, b) => Number(b.returns_enabled ?? true) - Number(a.returns_enabled ?? true)).map((location) => ({value: location.id,- label: location.returns_enabled- ? location.name- : t('admin.pages.orders.detail.returns.location_no_returns', { name: location.name }),+ label:+ (location.returns_enabled ?? true)+ ? location.name+ : t('admin.pages.orders.detail.returns.location_no_returns', { name: location.name }),}))const chosen = selectedItems(selection)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.rbindex 5c2bd80336..23c49518ca 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@@ -35,7 +35,8 @@ module Spree# journey starts over.def updatewith_order_lock do- if @resource.update(corrected_attributes(update_params.to_h, @resource))+ if @resource.update(@resource.correction_attributes(update_params.to_h))+ recalculate_deliveryrender json: serialize_resource(@resource.reload)elserender_validation_error(@resource.errors)@@ -82,14 +83,12 @@ module Spree# 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 corrected_attributes(attributes, delivery)- number = attributes[:tracking_number]- return attributes if number.blank? || number.squish == delivery.tracking_number-- corrected = attributes.merge(status: 'pending')- corrected[:carrier] = nil if corrected[:carrier].blank?- corrected[:tracking_url] = nil if corrected[:tracking_url].blank?- corrected+ # 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)enddef model_classdiff --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.rbindex 9eeaf6ce26..d51022eb60 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@@ -79,10 +79,20 @@ module Spreeendwith_order_lock do- ApplicationRecord.transaction do- @resource.delivery&.destroy!- @resource.destroy!+ # The label's own consignment goes with it, but only while the+ # parcel never moved: a journey that happened is a fact, and+ # Deliveries::Destroy is what knows that and rolls the+ # fulfillment up afterwards.+ delivery = @resource.delivery+ if delivery && [email protected]_unmoved_delivery+ return render_error(+ code: ERROR_CODES[:validation_error],+ message: Spree.t('shipping_labels.errors.delivery_has_moved'),+ status: :unprocessable_content+ )end++ @resource.destroy!head :no_contentendenddiff --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.rbindex 921cd4fb18..b039ba5c45 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@@ -48,7 +48,8 @@ module Spreeauthorize! :update, @fulfillmentwith_order_lock do- if @delivery.update(corrected_attributes(delivery_params.to_h, @delivery))+ if @delivery.update(@delivery.correction_attributes(delivery_params.to_h))+ Spree.fulfillment_recalculate_delivery_service.call(fulfillment: @fulfillment)render json: serialize(@delivery.reload)elserender_validation_error(@delivery.errors)@@ -83,15 +84,6 @@ module Spree# 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 corrected_attributes(attributes, delivery)- number = attributes[:tracking_number]- return attributes if number.blank? || number.squish == delivery.tracking_number-- corrected = attributes.merge(status: 'pending')- corrected[:carrier] = nil if corrected[:carrier].blank?- corrected[:tracking_url] = nil if corrected[:tracking_url].blank?- corrected- enddef set_fulfillment@order = current_seller_orders.find_by_prefix_id!(params[:order_id])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.rbindex ab310a40c3..6bf71841bf 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@@ -87,10 +87,17 @@ module Spreeendwith_order_lock do- ApplicationRecord.transaction do- @label.delivery&.destroy!- @label.destroy!+ # The label's own consignment goes with it, but only while the+ # parcel never moved: a journey that happened is a fact.+ if @label.delivery && [email protected]_unmoved_delivery+ return render_error(+ code: ERROR_CODES[:validation_error],+ message: Spree.t('shipping_labels.errors.delivery_has_moved'),+ status: :unprocessable_content+ )end++ @label.destroy!head :no_contentendenddiff --git a/spree/api/app/controllers/spree/api/v3/webhooks/fulfillments_controller.rb b/spree/api/app/controllers/spree/api/v3/webhooks/fulfillments_controller.rbindex 52665b6ebe..755c385e7f 100644--- a/spree/api/app/controllers/spree/api/v3/webhooks/fulfillments_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/webhooks/fulfillments_controller.rb@@ -70,11 +70,15 @@ module Spreedef find_delivery(tracking_code)return if tracking_code.blank?+ # Paged rather than capped: a tracking number reused across+ # canceled owners would otherwise fill the window and hide the+ # live delivery behind them, and the webhook would be+ # acknowledged without applying the carrier's update.current_store.deliveries.where(tracking_number: tracking_code).order(created_at: :desc, id: :desc).- limit(CANDIDATE_LIMIT).includes(:owner).+ find_each(batch_size: CANDIDATE_LIMIT, order: :desc).find { |delivery| delivery.owner.present? && !delivery.owner.canceled? }endenddiff --git a/spree/api/spec/controllers/spree/api/v3/admin/orders/labels_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/orders/labels_controller_spec.rbindex 18b921e9ed..2d4462f994 100644--- a/spree/api/spec/controllers/spree/api/v3/admin/orders/labels_controller_spec.rb+++ b/spree/api/spec/controllers/spree/api/v3/admin/orders/labels_controller_spec.rb@@ -147,6 +147,21 @@ RSpec.describe Spree::Api::V3::Admin::Orders::LabelsController, type: :controlleexpect(response).to have_http_status(:unprocessable_content)end++ # A journey that happened is a fact: deleting the label a parcel shipped+ # under must not erase where that parcel went.+ it 'keeps the consignment once the parcel has shipped' do+ label = create(:shipping_label, :uploaded, :with_delivery, owner: fulfillment)+ fulfillment.update!(status: 'fulfilled', fulfilled_at: Time.current)++ delete :destroy, params: {+ order_id: order.prefixed_id, fulfillment_id: fulfillment.prefixed_id, id: label.prefixed_id+ }, as: :json++ expect(response).to have_http_status(:unprocessable_content)+ expect(Spree::ShippingLabel.exists?(label.id)).to be(true)+ expect(fulfillment.reload.deliveries).to be_present+ endenddescribe 'return labels' dodiff --git a/spree/core/app/models/spree/delivery.rb b/spree/core/app/models/spree/delivery.rbindex 76a4b14c6d..4c7281f6ee 100644--- a/spree/core/app/models/spree/delivery.rb+++ b/spree/core/app/models/spree/delivery.rb@@ -58,6 +58,25 @@ module Spreestatus == 'delivered'end+ # What changes when a merchant corrects the tracking number: to the+ # carrier a different number is a different parcel, so the journey starts+ # over and everything belonging to the old number goes with it — its+ # status, its arrival, and the carrier and link that described it.+ # Otherwise a UPS badge and a UPS page survive onto a FedEx number, and a+ # stale arrival keeps dating the returns window.+ #+ # @param attributes [Hash] the merchant's edit+ # @return [Hash] the edit, widened when the number really changed+ def correction_attributes(attributes)+ number = attributes[:tracking_number] || attributes['tracking_number']+ return attributes if number.blank? || number.to_s.squish == tracking_number++ corrected = attributes.merge(status: 'pending', delivered_at: nil)+ corrected[:carrier] = nil if corrected[:carrier].blank? && corrected['carrier'].blank?+ corrected[:tracking_url] = nil if corrected[:tracking_url].blank? && corrected['tracking_url'].blank?+ corrected+ end+self.whitelisted_ransackable_attributes = %w[tracking_number carrier status]# The public page where this consignment can be followed, best answerdiff --git a/spree/core/app/models/spree/fulfillment.rb b/spree/core/app/models/spree/fulfillment.rbindex 490c902b30..89a114eb4b 100644--- a/spree/core/app/models/spree/fulfillment.rb+++ b/spree/core/app/models/spree/fulfillment.rb@@ -564,6 +564,10 @@ module Spree# Reload associations to pick up the new selected shipping ratedelivery_rates.resetassociation(:selected_delivery_rate).reset+ # A different rate can be a different carrier, and the provider is+ # derived from the method behind it — a stale one buys, tracks or+ # cancels through the account the parcel is no longer shipping on.+ @provider = nil# Update shipment cost and owner totals only during checkout.# For completed orders, totals are managed separately (e.g., in tests or admin adjustments)return if owner.nil? || owner.completed?diff --git a/spree/core/app/models/spree/return.rb b/spree/core/app/models/spree/return.rbindex 4042257dc1..1649b33f52 100644--- a/spree/core/app/models/spree/return.rb+++ b/spree/core/app/models/spree/return.rb@@ -85,11 +85,31 @@ module Spreedef to_packagepackage = Spree::Stock::Package.new(stock_location)package.owner = order- units = return_line_items.includes(:fulfillment_item).filter_map(&:fulfillment_item)+ units = returned_unitsunits.group_by(&:status).each { |status, items| package.add_multiple(items, status.to_sym) }packageend+ # The units as the parcel coming back holds them: a partial return sends+ # back what the customer is returning, not everything that shipped. The+ # copies are never saved — the shipment's own record of what left is not+ # ours to rewrite, and it is what a second return is measured against.+ #+ # @return [Array<Spree::FulfillmentItem>]+ def returned_units+ return_line_items.includes(:fulfillment_item).filter_map do |return_line_item|+ unit = return_line_item.fulfillment_item+ next if unit.nil?++ quantity = return_line_item.quantity.to_i+ next unit if quantity <= 0 || quantity == unit.quantity.to_i++ # `dup` rather than a new record: the packer reads variant, line item+ # and status off the unit, and a copy carries all of it.+ unit.dup.tap { |returned| returned.quantity = quantity }+ end+ end+# What the customer is owed for the items being returned.def refund_totalreturn_line_items.sum(&:pre_tax_amount)diff --git a/spree/core/app/services/spree/deliveries/upsert_primary.rb b/spree/core/app/services/spree/deliveries/upsert_primary.rbindex 16cc40920c..5801c62534 100644--- a/spree/core/app/services/spree/deliveries/upsert_primary.rb+++ b/spree/core/app/services/spree/deliveries/upsert_primary.rb@@ -27,13 +27,16 @@ module Spree# A corrected number is a different parcel: its journey starts over,# and the carrier and link belonging to the old number go with it —# otherwise a UPS badge and a UPS page survive onto a FedEx number.- if number != primary.tracking_number- attributes[:status] = 'pending'- attributes[:carrier] = nil if carrier.blank?- attributes[:tracking_url] = nil- end+ corrected = number != primary.tracking_number+ attributes = primary.correction_attributes(attributes)- primary.update(attributes) ? success(primary) : failure(primary)+ return failure(primary) unless primary.update(attributes)++ # A consignment that started over may have been the one holding the+ # fulfillment at delivered.+ Spree.fulfillment_recalculate_delivery_service.call(fulfillment: fulfillment) if corrected++ success(primary)endendenddiff --git a/spree/core/app/workflows/spree/shipping_labels/refund.rb b/spree/core/app/workflows/spree/shipping_labels/refund.rbindex 3a21af65c7..b2d18763b0 100644--- a/spree/core/app/workflows/spree/shipping_labels/refund.rb+++ b/spree/core/app/workflows/spree/shipping_labels/refund.rb@@ -63,7 +63,13 @@ module Spreeshipping_label.update!(attributes)end+ # Only once the carrier has actually refunded. A refund the carrier is+ # still deciding on may never settle, and the parcel keeps travelling+ # under this tracking number meanwhile — ShippingLabels::ConfirmRefund+ # releases it when the answer arrives.def remove_delivery_if_never_moved+ return unless shipping_label.refunded?+shipping_label.release_unmoved_deliveryendenddiff --git a/spree/core/config/locales/en.yml b/spree/core/config/locales/en.ymlindex 992e807492..f2500b0f1b 100644--- a/spree/core/config/locales/en.yml+++ b/spree/core/config/locales/en.yml@@ -1730,6 +1730,7 @@ en:shipping_labels:errors:already_purchased: This parcel already has an active shipping label+ delivery_has_moved: This label's parcel is already on its way, so its tracking cannot be removed with the label.file_fetch_failed: The label file could not be fetched from the carrier (HTTP %{status})file_required: An uploaded label needs a fileno_file_url: The carrier did not provide a file for this labeldiff --git a/spree/core/lib/tasks/deliveries_migration.rake b/spree/core/lib/tasks/deliveries_migration.rakeindex af57cecc99..b9104e3aba 100644--- a/spree/core/lib/tasks/deliveries_migration.rake+++ b/spree/core/lib/tasks/deliveries_migration.rake@@ -33,7 +33,7 @@ namespace :spree do# still has the column; anywhere else it never existed.carrier = fulfillment.has_attribute?(:tracking_carrier) ? fulfillment.read_attribute(:tracking_carrier) : nil- result = Spree::Deliveries::Create.new.call(+ result = Spree.delivery_create_service.call(owner: fulfillment, tracking_number: tracking, carrier: carrier)diff --git a/spree/core/spec/models/spree/delivery_spec.rb b/spree/core/spec/models/spree/delivery_spec.rbindex bcf52f5cd3..be636719b0 100644--- a/spree/core/spec/models/spree/delivery_spec.rb+++ b/spree/core/spec/models/spree/delivery_spec.rb@@ -135,4 +135,37 @@ RSpec.describe Spree::Delivery, type: :model doexpect(fulfillment.deliveries.undelivered).to eq([first])endend+ describe '#correction_attributes' do+ let(:delivery) do+ create(:delivery, owner: fulfillment, store: store, tracking_number: '1Z_OLD',+ carrier: 'ups', tracking_url: 'https://ups.example/1Z_OLD',+ status: 'delivered', delivered_at: 2.days.ago)+ end++ # To a carrier a different number is a different parcel, so nothing about+ # the old one may survive onto it — least of all an arrival, which is what+ # the returns window counts from.+ it 'starts the journey over and drops the old parcel arrival' do+ corrected = delivery.correction_attributes(tracking_number: '9400_NEW')++ expect(corrected[:status]).to eq('pending')+ expect(corrected[:delivered_at]).to be_nil+ expect(corrected[:carrier]).to be_nil+ expect(corrected[:tracking_url]).to be_nil+ end++ it 'leaves an edit that is not a correction alone' do+ expect(delivery.correction_attributes(carrier: 'fedex')).to eq(carrier: 'fedex')+ end++ it 'keeps a carrier the merchant supplied with the new number' do+ corrected = delivery.correction_attributes(tracking_number: '9400_NEW', carrier: 'fedex')++ expect(corrected[:carrier]).to eq('fedex')+ end++ it 'treats the same number with stray whitespace as no correction' do+ expect(delivery.correction_attributes(tracking_number: ' 1Z_OLD ')).not_to have_key(:status)+ end+ endenddiff --git a/spree/core/spec/models/spree/return_spec.rb b/spree/core/spec/models/spree/return_spec.rbindex 8c0c9ef6a8..f4047e06bd 100644--- a/spree/core/spec/models/spree/return_spec.rb+++ b/spree/core/spec/models/spree/return_spec.rb@@ -65,4 +65,22 @@ RSpec.describe Spree::Return doexpect(line.received_quantity).to eq(0)endend+ describe '#to_package' do+ let(:order) { create(:shipped_order, store: store) }+ let(:return_record) { create(:return, order: order, store: store) }+ let(:fulfillment_item) { return_record.return_line_items.first.fulfillment_item }++ # The factory returns one unit; the shipment carried three.+ before { fulfillment_item.update_columns(quantity: 3) }++ # A partial return ships back what the customer is returning. Rating the+ # whole shipment buys the wrong postage and declares the wrong goods.+ it 'weighs only the units coming back' do+ expect(return_record.reload.to_package.contents.sum(&:quantity)).to eq(1)+ end++ it 'never rewrites what the shipment recorded as sent' do+ expect { return_record.reload.to_package }.not_to change { fulfillment_item.reload.quantity }+ end+ endend