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.

Address PR review findings

Damian Legawiecb6e6218f7dd9
diff --git a/docs/plans/decisions.md b/docs/plans/decisions.md
index 21ae217323..ed9da40d72 100644
--- a/docs/plans/decisions.md
+++ b/docs/plans/decisions.md
@@ -5,8 +5,10 @@
two stores can each have their own "Damaged" or "Order Canceled".
This is what makes the controller rule enforceable: every reason lookup
-reads `current_store.return_reasons` rather than the model constant, so a
-prefixed id from another store is a 404 instead of a silent success — the
+reads its matching association — `current_store.return_reasons`,
+`current_store.claim_reasons`, `current_store.refund_reasons` — rather
+than the model constant, so a prefixed id from another store is a 404
+instead of a silent success — the
cheapest defence against IDOR, and now uniform across the returns surface
alongside `current_store.stock_locations`.
diff --git a/docs/v6/user/returns/returns-processing.mdx b/docs/v6/user/returns/returns-processing.mdx
index 4dd3d15d3a..7eaf62d1a0 100644
--- a/docs/v6/user/returns/returns-processing.mdx
+++ b/docs/v6/user/returns/returns-processing.mdx
@@ -73,12 +73,12 @@ Returns, exchanges, and claims each have their own section in the dashboard, so
## Reasons
-Spree keeps two separate lists of reasons, managed under **Settings → Returns** and seeded when your store is created:
+Spree keeps two separate lists of reasons, managed under **Settings → Returns & reasons** and seeded when your store is created:
- **Return reasons** explain why a customer is sending something back — "wrong size", "changed my mind", "no longer needed". These apply to both returns and exchanges.
- **Claim reasons** explain what went wrong on your end — "arrived damaged", "never arrived", "wrong item sent".
-They are kept separate because they answer different questions, and mixing them makes reporting less useful. See [Settings → Returns Configuration](https://spreecommerce.org/docs/user/settings/returns-configuration) for how to manage them.
+They are kept separate because they answer different questions, and mixing them makes reporting less useful. See [Settings → Returns Configuration](/v6/user/settings/returns-configuration) for how to manage them.
## Return policy
diff --git a/docs/v6/user/settings/returns-configuration.mdx b/docs/v6/user/settings/returns-configuration.mdx
index eb2843ae4e..c22c528f03 100644
--- a/docs/v6/user/settings/returns-configuration.mdx
+++ b/docs/v6/user/settings/returns-configuration.mdx
@@ -44,7 +44,7 @@ Refund reasons have an extra setting:
## Managing reasons
-All three lists live together under **Settings → Returns**. Spree seeds a starting set when your store is created, so returns, claims, and refunds work out of the box, and you can add, rename, deactivate, or delete entries from there.
+All three lists live together under **Settings → Returns & reasons**. Spree seeds a starting set when your store is created, so returns, claims, and refunds work out of the box, and you can add, rename, deactivate, or delete entries from there.
Each reason has two fields: its **name**, and whether it is **available on new records**. Turning that switch off retires a reason — it stops appearing when staff open a new return, claim, or refund, while every record that already used it keeps its explanation.
@@ -64,4 +64,4 @@ Rather than guessing, Spree gives your developers a place to attach your own pol
Once your reasons are set up, you are ready to handle returns, exchanges, and claims.
-To learn how, see [Returns → Returns Processing](https://spreecommerce.org/docs/user/returns/returns-processing).
+To learn how, see [Returns → Returns Processing](/v6/user/returns/returns-processing).
diff --git a/packages/admin-sdk/src/admin-client.ts b/packages/admin-sdk/src/admin-client.ts
index 89fd9ba6d4..b19815102b 100644
--- a/packages/admin-sdk/src/admin-client.ts
+++ b/packages/admin-sdk/src/admin-client.ts
@@ -2756,6 +2756,7 @@ export class AdminClient {
// Reasons — why a return, claim or refund happened
// ============================================
+ /** Why a customer sent something back. Shared by returns and exchanges. */
readonly returnReasons = {
list: (
params?: ListParams & Record<string, unknown>,
@@ -2783,6 +2784,7 @@ export class AdminClient {
this.request<void>('DELETE', `/return_reasons/${id}`, options),
}
+ /** What went wrong with a delivery — damaged, missing, wrong item. */
readonly claimReasons = {
list: (
params?: ListParams & Record<string, unknown>,
@@ -2810,6 +2812,10 @@ export class AdminClient {
this.request<void>('DELETE', `/claim_reasons/${id}`, options),
}
+ /**
+ * Why money went back. Some rows are seeded and immutable: core looks
+ * them up by name, so `can_be_deleted` is false and renaming is refused.
+ */
readonly refundReasons = {
list: (
params?: ListParams & Record<string, unknown>,
diff --git a/packages/dashboard/src/locales/ar.json b/packages/dashboard/src/locales/ar.json
index 5f0bac49c9..c703aae3eb 100644
--- a/packages/dashboard/src/locales/ar.json
+++ b/packages/dashboard/src/locales/ar.json
@@ -2964,7 +2964,7 @@
}
},
"reasons": {
- "title": "المرتجعات",
+ "title": "المرتجعات والأسباب",
"description": "القوائم التي يختار منها فريقك عند معالجة المرتجعات والمطالبات والمبالغ المستردة.",
"add_cta": "إضافة سبب",
"add_sheet_title": "إضافة سبب",
@@ -3031,7 +3031,7 @@
"payment_methods": "طرق الدفع",
"product_types": "أنواع المنتجات",
"profile": "الملف الشخصي",
- "reasons": "المرتجعات",
+ "reasons": "المرتجعات والأسباب",
"staff": "الموظفون",
"stock_locations": "مواقع المخزون",
"store": "المتجر",
diff --git a/packages/dashboard/src/locales/de.json b/packages/dashboard/src/locales/de.json
index c220d010d3..8bbe8e03b7 100644
--- a/packages/dashboard/src/locales/de.json
+++ b/packages/dashboard/src/locales/de.json
@@ -2964,7 +2964,7 @@
}
},
"reasons": {
- "title": "Rücksendungen",
+ "title": "Rücksendungen & Gründe",
"description": "Die Auswahllisten, aus denen Ihr Team bei Rücksendungen, Reklamationen und Rückerstattungen wählt.",
"add_cta": "Grund hinzufügen",
"add_sheet_title": "Grund hinzufügen",
@@ -3031,7 +3031,7 @@
"payment_methods": "Zahlungsmethoden",
"product_types": "Produkttypen",
"profile": "Profil",
- "reasons": "Rücksendungen",
+ "reasons": "Rücksendungen & Gründe",
"staff": "Mitarbeiter",
"stock_locations": "Lagerstandorte",
"store": "Shop",
diff --git a/packages/dashboard/src/locales/en.json b/packages/dashboard/src/locales/en.json
index 92ac0600e1..e58c11a081 100644
--- a/packages/dashboard/src/locales/en.json
+++ b/packages/dashboard/src/locales/en.json
@@ -2964,7 +2964,7 @@
}
},
"reasons": {
- "title": "Returns",
+ "title": "Returns & reasons",
"description": "The vocabularies your team picks from when handling returns, claims and refunds.",
"add_cta": "Add reason",
"add_sheet_title": "Add reason",
@@ -3031,7 +3031,7 @@
"payment_methods": "Payment methods",
"product_types": "Product types",
"profile": "Profile",
- "reasons": "Returns",
+ "reasons": "Returns & reasons",
"staff": "Staff",
"stock_locations": "Stock locations",
"store": "Store",
diff --git a/packages/dashboard/src/locales/fr.json b/packages/dashboard/src/locales/fr.json
index d5663f78fc..94b40f7a72 100644
--- a/packages/dashboard/src/locales/fr.json
+++ b/packages/dashboard/src/locales/fr.json
@@ -2964,7 +2964,7 @@
}
},
"reasons": {
- "title": "Retours",
+ "title": "Retours et motifs",
"description": "Les listes dans lesquelles votre équipe choisit lors des retours, réclamations et remboursements.",
"add_cta": "Ajouter un motif",
"add_sheet_title": "Ajouter un motif",
@@ -3031,7 +3031,7 @@
"payment_methods": "Modes de paiement",
"product_types": "Types de produit",
"profile": "Profil",
- "reasons": "Retours",
+ "reasons": "Retours et motifs",
"staff": "Personnel",
"stock_locations": "Emplacements de stock",
"store": "Boutique",
diff --git a/packages/dashboard/src/locales/pl.json b/packages/dashboard/src/locales/pl.json
index ca32ebf8a6..16db822341 100644
--- a/packages/dashboard/src/locales/pl.json
+++ b/packages/dashboard/src/locales/pl.json
@@ -3000,7 +3000,7 @@
}
},
"reasons": {
- "title": "Zwroty",
+ "title": "Zwroty i powody",
"description": "Listy, z których zespół wybiera przy zwrotach, reklamacjach i zwrotach pieniędzy.",
"add_cta": "Dodaj powód",
"add_sheet_title": "Dodaj powód",
@@ -3067,7 +3067,7 @@
"payment_methods": "Metody płatności",
"product_types": "Typy produktów",
"profile": "Profil",
- "reasons": "Zwroty",
+ "reasons": "Zwroty i powody",
"staff": "Zespół",
"stock_locations": "Lokalizacje magazynowe",
"store": "Sklep",
diff --git a/packages/dashboard/src/locales/zh-CN.json b/packages/dashboard/src/locales/zh-CN.json
index 5cd4e309cc..d85a2103dd 100644
--- a/packages/dashboard/src/locales/zh-CN.json
+++ b/packages/dashboard/src/locales/zh-CN.json
@@ -2964,7 +2964,7 @@
}
},
"reasons": {
- "title": "退货",
+ "title": "退货与原因",
"description": "团队处理退货、理赔和退款时可选择的原因列表。",
"add_cta": "添加原因",
"add_sheet_title": "添加原因",
@@ -3031,7 +3031,7 @@
"payment_methods": "支付方式",
"product_types": "商品类型",
"profile": "个人资料",
- "reasons": "退货",
+ "reasons": "退货与原因",
"staff": "员工",
"stock_locations": "库存地点",
"store": "店铺",
diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/settings/reasons.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/settings/reasons.tsx
index b91f467ef1..282cb05a4f 100644
--- a/packages/dashboard/src/routes/_authenticated/$storeId/settings/reasons.tsx
+++ b/packages/dashboard/src/routes/_authenticated/$storeId/settings/reasons.tsx
@@ -41,7 +41,7 @@ import {
useConfirm,
} from '@spree/dashboard-ui'
import { createFileRoute } from '@tanstack/react-router'
-import { PlusIcon, RotateCcwIcon } from 'lucide-react'
+import { PlusIcon, RotateCcwIcon, TriangleAlertIcon } from 'lucide-react'
import { useState } from 'react'
import { Controller, type UseFormReturn, useForm } from 'react-hook-form'
import { useTranslation } from 'react-i18next'
@@ -117,7 +117,7 @@ function ReasonSection({
helpKey: string
}) {
const { t } = useTranslation()
- const { data, isLoading } = useReasons(kind)
+ const { data, isLoading, isError } = useReasons(kind)
const [creating, setCreating] = useState(false)
const [editing, setEditing] = useState<Reason | null>(null)
@@ -144,6 +144,17 @@ function ReasonSection({
<div className="p-4">
<Skeleton className="h-10 w-full" />
</div>
+ ) : isError ? (
+ // Distinct from the empty state: "no reasons yet" would tell an
+ // admin the list is empty when the request actually failed.
+ <Empty>
+ <EmptyHeader>
+ <EmptyMedia variant="icon">
+ <TriangleAlertIcon />
+ </EmptyMedia>
+ <EmptyTitle>{t('admin.errors.failed_to_load')}</EmptyTitle>
+ </EmptyHeader>
+ </Empty>
) : reasons.length === 0 ? (
<Empty>
<EmptyHeader>
diff --git a/spree/core/app/models/spree/claim_reason.rb b/spree/core/app/models/spree/claim_reason.rb
index cba7aa6297..09566de9a8 100644
--- a/spree/core/app/models/spree/claim_reason.rb
+++ b/spree/core/app/models/spree/claim_reason.rb
@@ -8,10 +8,11 @@ module Spree
include Spree::NamedType
include Spree::SingleStoreResource
+ include Spree::Metadata
# Names are unique per store, not globally — two stores can each have
# their own "Damaged" without colliding.
- validates :name, uniqueness: { case_sensitive: false, scope: :store_id }
+ validates :name, uniqueness: { case_sensitive: false, scope: [:store_id, *spree_base_uniqueness_scope] }
self.whitelisted_ransackable_attributes = %w[name active mutable]
diff --git a/spree/core/app/models/spree/refund_reason.rb b/spree/core/app/models/spree/refund_reason.rb
index a43c073178..cfc7418164 100644
--- a/spree/core/app/models/spree/refund_reason.rb
+++ b/spree/core/app/models/spree/refund_reason.rb
@@ -9,7 +9,7 @@ module Spree
# Names are unique per store, not globally — two stores can each have
# their own "Order Canceled" without colliding.
- validates :name, uniqueness: { case_sensitive: false, scope: :store_id }
+ validates :name, uniqueness: { case_sensitive: false, scope: [:store_id, *spree_base_uniqueness_scope] }
self.whitelisted_ransackable_attributes = %w[name active mutable]
@@ -17,7 +17,7 @@ module Spree
ORDER_CANCELED_REASON = 'Order Canceled'.freeze
SHIPMENT_CANCELED_REASON = 'Shipment Canceled'.freeze
- has_many :refunds, dependent: :restrict_with_error
+ has_many :refunds, class_name: 'Spree::Refund', dependent: :restrict_with_error
class << self
# The seeded reasons core attaches to refunds it issues itself.
diff --git a/spree/core/app/models/spree/return_reason.rb b/spree/core/app/models/spree/return_reason.rb
index a62106cf5f..dcb190b831 100644
--- a/spree/core/app/models/spree/return_reason.rb
+++ b/spree/core/app/models/spree/return_reason.rb
@@ -13,7 +13,7 @@ module Spree
# Names are unique per store, not globally — two stores can each have
# their own "Damaged" without colliding.
- validates :name, uniqueness: { case_sensitive: false, scope: :store_id }
+ validates :name, uniqueness: { case_sensitive: false, scope: [:store_id, *spree_base_uniqueness_scope] }
self.whitelisted_ransackable_attributes = %w[name active mutable]
diff --git a/spree/core/db/migrate/20260805100001_rename_return_authorization_reasons_to_return_reasons.rb b/spree/core/db/migrate/20260805100001_rename_return_authorization_reasons_to_return_reasons.rb
index 685fb52596..2ca63c7c7e 100644
--- a/spree/core/db/migrate/20260805100001_rename_return_authorization_reasons_to_return_reasons.rb
+++ b/spree/core/db/migrate/20260805100001_rename_return_authorization_reasons_to_return_reasons.rb
@@ -11,6 +11,11 @@ class RenameReturnAuthorizationReasonsToReturnReasons < ActiveRecord::Migration[
t.references :store, null: false
t.boolean :active, null: false, default: true
t.boolean :mutable, null: false, default: true
+ if t.respond_to?(:jsonb)
+ t.jsonb :metadata
+ else
+ t.json :metadata
+ end
t.timestamps
end
diff --git a/spree/core/lib/tasks/migrate_returns.rake b/spree/core/lib/tasks/migrate_returns.rake
index 151e7c6a93..a5b31f1a41 100644
--- a/spree/core/lib/tasks/migrate_returns.rake
+++ b/spree/core/lib/tasks/migrate_returns.rake
@@ -52,16 +52,50 @@ module Spree
ActiveRecord::Base.connection
end
- # Authorizations whose number hasn't been carried across yet.
+ # Authorizations not yet carried across.
#
# Two subqueries rather than a plucked IN-list: on a resumed run over a
- # large store the list would be every number already migrated, shipped back
- # as bind params. Both sides hit the unique index on `number`. Same shape as
- # migrate_users_to_customers' `where.not(id: customer_model.select(:id))`.
+ # large store the list would be every number already migrated, shipped
+ # back as bind params. Both sides hit the unique index on `number`. Same
+ # shape as migrate_users_to_customers' `where.not(id: model.select(:id))`.
+ #
+ # The NULL branch is load-bearing: `NULL NOT IN (...)` is UNKNOWN, not
+ # true, so a numberless legacy row would be filtered out by the two
+ # subqueries and never migrate at all. Those rows can't be matched by
+ # number, so `migrated_numberless_ids` tracks them by legacy id instead —
+ # otherwise a second run would copy them again under a fresh number.
def pending
- legacy_authorization.
- where.not(number: Spree::Return.select(:number)).
- where.not(number: Spree::Exchange.select(:number))
+ scope = legacy_authorization.
+ where.not(number: Spree::Return.select(:number)).
+ where.not(number: Spree::Exchange.select(:number))
+
+ numberless = legacy_authorization.where(number: nil).
+ where.not(id: migrated_numberless_ids)
+
+ legacy_authorization.where(id: scope.select(:id)).or(
+ legacy_authorization.where(id: numberless.select(:id))
+ )
+ end
+
+ # Numberless rows are stamped with their legacy id at copy time, which is
+ # the only durable link back to the source row.
+ #
+ # Reads the `metadata` COLUMN, not `#metadata` — the Spree::Metadata
+ # concern maps that reader to `private_metadata`, which these tables do
+ # not have, so the accessor would silently return {}.
+ def migrated_numberless_ids
+ @migrated_numberless_ids ||=
+ (Spree::Return.where.not(metadata: nil).pluck(:metadata) +
+ Spree::Exchange.where.not(metadata: nil).pluck(:metadata)).
+ filter_map { |data| parse_metadata(data)['legacy_return_authorization_id'] }
+ end
+
+ def parse_metadata(data)
+ return data if data.is_a?(Hash)
+
+ JSON.parse(data.to_s)
+ rescue JSON::ParserError
+ {}
end
def legacy_authorization
@@ -148,9 +182,17 @@ module Spree
# one would break resumption as well as lose the link to history.
#
# A legacy row with no number can't participate in either, so it falls
- # back to a generated one: copying it once is better than refusing it,
- # and the `skipped` tally below keeps a re-run from duplicating it.
- record.number = authorization.number.presence || record.generate_permalink(klass)
+ # back to a generated one and records where it came from — that stamp is
+ # what `migrated_numberless_ids` reads to keep a re-run from copying it
+ # a second time under a different generated number.
+ if authorization.number.present?
+ record.number = authorization.number
+ else
+ record.number = record.generate_permalink(klass)
+ # write_attribute, not #metadata= — see migrated_numberless_ids.
+ record.write_attribute(:metadata, { 'legacy_return_authorization_id' => authorization.id })
+ end
+
record.save!(validate: false)
record
end
diff --git a/spree/core/spec/lib/tasks/migrate_returns_spec.rb b/spree/core/spec/lib/tasks/migrate_returns_spec.rb
index 4d8e0bb31d..7d20a941c6 100644
--- a/spree/core/spec/lib/tasks/migrate_returns_spec.rb
+++ b/spree/core/spec/lib/tasks/migrate_returns_spec.rb
@@ -155,6 +155,26 @@ RSpec.describe Spree::ReturnsMigrator do
expect(result[:failed]).to be_empty
expect(result[:returns]).to eq(1)
end
+
+ # `NULL NOT IN (...)` is UNKNOWN, so a numberless row is invisible to the
+ # number-based exclusion in both directions: it would never migrate at
+ # all, or — once forced through — migrate again on every run under a
+ # fresh generated number.
+ it 'migrates it exactly once across repeated runs' do
+ migrate
+
+ expect { described_class.new.call }.not_to change(Spree::Return, :count)
+ end
+
+ it 'records the legacy id so the row can be recognised again' do
+ migrate
+
+ # The column, not #metadata — that reader maps to private_metadata,
+ # which spree_returns does not have.
+ stamped = Spree::Return.last.read_attribute(:metadata)
+ stamped = JSON.parse(stamped) unless stamped.is_a?(Hash)
+ expect(stamped['legacy_return_authorization_id']).to be_present
+ end
end
context 'when the authorization has no items' do