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.

Ask a store owner where they ship from (#14579)

Damian Legawiecc66033a4e27d
diff --git a/packages/admin-sdk/src/params.ts b/packages/admin-sdk/src/params.ts
index 697e1f4c31..c31b97d05e 100644
--- a/packages/admin-sdk/src/params.ts
+++ b/packages/admin-sdk/src/params.ts
@@ -1760,11 +1760,14 @@ export interface SellerCreateParams {
* its own, so an id would reference a row belonging to someone else.
*/
billing_address?: SellerAddressParams
- returns_address?: SellerAddressParams
metadata?: Record<string, unknown>
}
-/** The seller's own billing / returns address. */
+/**
+ * The seller's own billing address. Their returns address is not written here
+ * — it lives on the stock location returns route to, so it is written through
+ * the stock locations endpoint.
+ */
export interface SellerAddressParams {
first_name?: string
last_name?: string
diff --git a/packages/dashboard-core/src/lib/form-mappers.ts b/packages/dashboard-core/src/lib/form-mappers.ts
index 40651cce76..5d1ddcc53e 100644
--- a/packages/dashboard-core/src/lib/form-mappers.ts
+++ b/packages/dashboard-core/src/lib/form-mappers.ts
@@ -28,3 +28,79 @@ export function emptyToUndefined(value: unknown): unknown {
if (value === '' || value === null) return undefined
return value
}
+
+/**
+ * The address columns a stock location carries, in either panel's SDK shape.
+ * Structural rather than either `StockLocation` type so both the admin and
+ * seller panels can map their own rows through the helpers below.
+ */
+export interface StockLocationAddressFields {
+ company?: string | null
+ address1?: string | null
+ address2?: string | null
+ city?: string | null
+ zipcode?: string | null
+ state_code?: string | null
+ state_text?: string | null
+ country_code?: string | null
+ country_name?: string | null
+ phone?: string | null
+}
+
+/**
+ * The three shapes a stock location's address sits between. A location stores
+ * `zipcode` where an address says `postal_code`, and carries no personal name
+ * — mapping the fields explicitly keeps that difference in one place instead
+ * of leaking a cast into every call.
+ */
+export function stockLocationToAddressBlock(location: StockLocationAddressFields) {
+ return {
+ company: location.company,
+ address1: location.address1,
+ address2: location.address2,
+ city: location.city,
+ state_text: location.state_text,
+ postal_code: location.zipcode,
+ country_code: location.country_code,
+ country_name: location.country_name,
+ phone: location.phone,
+ }
+}
+
+export function stockLocationToEditableAddress(
+ location: StockLocationAddressFields & { id: string },
+) {
+ return {
+ id: location.id,
+ company: location.company,
+ address1: location.address1,
+ address2: location.address2,
+ city: location.city,
+ postal_code: location.zipcode,
+ country_code: location.country_code,
+ state_code: location.state_code,
+ phone: location.phone,
+ }
+}
+
+export function editableAddressToStockLocationParams(values: {
+ company?: string | null
+ address1?: string | null
+ address2?: string | null
+ city?: string | null
+ postal_code?: string | null
+ country_code?: string | null
+ state_code?: string | null
+ phone?: string | null
+}) {
+ return {
+ company: values.company,
+ address1: values.address1,
+ address2: values.address2,
+ city: values.city,
+ zipcode: values.postal_code,
+ country_code: values.country_code,
+ state_code: values.state_code,
+ phone: values.phone,
+ }
+}
diff --git a/packages/dashboard/src/components/spree/setup-tasks/register.ts b/packages/dashboard/src/components/spree/setup-tasks/register.ts
index ff73ddaf23..33fc196bf1 100644
--- a/packages/dashboard/src/components/spree/setup-tasks/register.ts
+++ b/packages/dashboard/src/components/spree/setup-tasks/register.ts
@@ -1,5 +1,6 @@
import { registerSlot } from '@spree/dashboard-core'
import { AddProductsTask } from './add-products-task'
+import { StoreAddressTask } from './store-address-task'
import { StorefrontConnectTask } from './storefront-connect-task'
import { type SetupTaskSlotContext, setupTaskSlot } from './types'
@@ -20,3 +21,8 @@ registerSlot<SetupTaskSlotContext>(setupTaskSlot('add_products'), {
id: 'builtin',
component: AddProductsTask,
})
+
+registerSlot<SetupTaskSlotContext>(setupTaskSlot('setup_address'), {
+ id: 'builtin',
+ component: StoreAddressTask,
+})
diff --git a/packages/dashboard/src/components/spree/setup-tasks/store-address-task.tsx b/packages/dashboard/src/components/spree/setup-tasks/store-address-task.tsx
new file mode 100644
index 0000000000..e188c24201
--- /dev/null
+++ b/packages/dashboard/src/components/spree/setup-tasks/store-address-task.tsx
@@ -0,0 +1,125 @@
+import {
+ AddressFormDialog,
+ adminClient,
+ editableAddressToStockLocationParams,
+ STORE_QUERY_RESOURCE,
+ stockLocationToAddressBlock,
+ stockLocationToEditableAddress,
+ useResourceKey,
+ useUpdateStockLocationById,
+} from '@spree/dashboard-core'
+import { AddressBlock, Button, Skeleton } from '@spree/dashboard-ui'
+import { PencilIcon, PlusIcon } from '@spree/dashboard-ui/icons'
+import { useQuery, useQueryClient } from '@tanstack/react-query'
+import { useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import type { SetupTaskSlotContext } from './types'
+
+/**
+ * Card body for the setup_address task: the merchant's own shipping and
+ * returns address.
+ *
+ * The address is written to the store's default stock location, not to the
+ * store — `Spree::Store#address` is a free-text blob for the email footer,
+ * while carriers rating a parcel need the structured columns a location
+ * carries. That is the same record returns route to, so asking once covers
+ * both.
+ *
+ * The same dialog the seller panel edits its returns address with, against
+ * the operator's own location — so the two panels cannot drift on what a
+ * complete address is.
+ */
+export function StoreAddressTask({ task }: SetupTaskSlotContext) {
+ const { t } = useTranslation()
+ const queryClient = useQueryClient()
+ const [editing, setEditing] = useState(false)
+ const update = useUpdateStockLocationById()
+
+ // Two filtered requests rather than one page filtered in the browser, to
+ // match `Store#primary_location` exactly: a location that accepts returns
+ // wins outright, and only then default and name decide. The list also holds
+ // every seller's warehouse on a marketplace, so the operator's own
+ // returns-enabled row can sit well past any page we could fetch — and
+ // editing the wrong one means an address their parcels never come back to.
+ //
+ // The list endpoint cannot express the preference in one call: it orders by
+ // default then name, and its `sort` param collapses to a single key.
+ const firstParty = { seller_id_null: true, active_true: true, limit: 1 }
+ const {
+ data: takesReturns,
+ isFetching: fetchingReturns,
+ isError: returnsFailed,
+ } = useQuery({
+ queryKey: useResourceKey('stock-locations', { firstParty: true, returns: true }),
+ queryFn: () => adminClient.stockLocations.list({ ...firstParty, returns_enabled_true: true }),
+ })
+ const hasReturnsLocation = (takesReturns?.data.length ?? 0) > 0
+ const {
+ data: anyActive,
+ isFetching: fetchingAny,
+ isError: anyFailed,
+ } = useQuery({
+ queryKey: useResourceKey('stock-locations', { firstParty: true }),
+ queryFn: () => adminClient.stockLocations.list(firstParty),
+ enabled: !!takesReturns && !hasReturnsLocation,
+ })
+
+ // `isFetching`, not `isLoading`: a disabled query stays pending forever, so
+ // the fallback request would hold the skeleton open once the first one hit.
+ const isLoading = fetchingReturns || fetchingAny
+ const location = takesReturns?.data[0] ?? anyActive?.data[0]
+ // A failed lookup must not read as "you have no warehouse" — that would
+ // send the merchant off to create a second one they do not need.
+ const failed = returnsFailed || anyFailed
+
+ const hasAddress = Boolean(location?.address1)
+
+ return (
+ <>
+ <p className="text-muted-foreground text-sm">
+ {t('admin.pages.getting_started.tasks.setup_address.description')}
+ </p>
+
+ {isLoading ? (
+ <Skeleton className="h-9 w-64" />
+ ) : location ? (
+ <>
+ {hasAddress && <AddressBlock address={stockLocationToAddressBlock(location)} />}
+ <Button variant={task.done ? 'outline' : 'default'} onClick={() => setEditing(true)}>
+ {hasAddress ? <PencilIcon className="size-4" /> : <PlusIcon className="size-4" />}
+ {t('admin.pages.getting_started.tasks.setup_address.cta')}
+ </Button>
+ </>
+ ) : (
+ <p className={failed ? 'text-destructive text-sm' : 'text-muted-foreground text-sm'}>
+ {t(
+ failed
+ ? 'admin.errors.failed_to_load'
+ : 'admin.pages.getting_started.tasks.setup_address.no_location',
+ )}
+ </p>
+ )}
+
+ {editing && location && (
+ <AddressFormDialog
+ title={t('admin.pages.getting_started.tasks.setup_address.title')}
+ address={stockLocationToEditableAddress(location)}
+ open
+ business
+ onOpenChange={setEditing}
+ onSave={async (values) => {
+ await update.mutateAsync({
+ id: location.id,
+ params: editableAddressToStockLocationParams(values),
+ })
+ // The checklist reads this address off the store payload, so the
+ // tick and the nav badge only move once the store is re-read.
+ await queryClient.invalidateQueries({ queryKey: [STORE_QUERY_RESOURCE] })
+ setEditing(false)
+ }}
+ isPending={update.isPending}
+ />
+ )}
+ </>
+ )
+}
diff --git a/packages/dashboard/src/locales/ar.json b/packages/dashboard/src/locales/ar.json
index a0bba409bb..472e5097e8 100644
--- a/packages/dashboard/src/locales/ar.json
+++ b/packages/dashboard/src/locales/ar.json
@@ -3094,6 +3094,12 @@
"description": "يظهر في متجرك كنقطة اتصال لأسئلة العملاء والدعم.",
"title": "تعيين البريد الإلكتروني لدعم العملاء"
},
+ "setup_address": {
+ "cta": "حفظ العنوان",
+ "description": "عنوان الشحن والإرجاع الخاص بك. تستخدمه شركات الشحن لحساب أسعار التوصيل، وإليه تُرسل مرتجعات العملاء.",
+ "no_location": "ليس لديك موقع مخزون خاص بك بعد — أنشئ واحدًا في الإعدادات لإضافة عنوان.",
+ "title": "أضف عنوان الشحن"
+ },
"setup_payment_method": {
"cta": "إعداد المدفوعات",
"description": "لاستلام المدفوعات، قم بإعداد مزود دفع إلكتروني واحد على الأقل.",
diff --git a/packages/dashboard/src/locales/de.json b/packages/dashboard/src/locales/de.json
index c762e079ab..93b58f9f5d 100644
--- a/packages/dashboard/src/locales/de.json
+++ b/packages/dashboard/src/locales/de.json
@@ -3077,6 +3077,12 @@
"description": "Wird in Ihrem Storefront als Kontaktpunkt für Kundenfragen und Support angezeigt.",
"title": "Kundensupport-E-Mail festlegen"
},
+ "setup_address": {
+ "cta": "Adresse speichern",
+ "description": "Ihre Versand- und Rücksendeadresse. Zusteller berechnen damit die Versandkosten, und Kundenrücksendungen gehen an diese Adresse.",
+ "no_location": "Sie haben noch kein eigenes Lager — legen Sie in den Einstellungen eines an, um eine Adresse zu hinterlegen.",
+ "title": "Versandadresse hinzufügen"
+ },
"setup_payment_method": {
"cta": "Zahlungsmethoden einrichten",
"description": "Um Zahlungen zu empfangen, richten Sie mindestens einen Online-Zahlungsanbieter ein.",
diff --git a/packages/dashboard/src/locales/en.json b/packages/dashboard/src/locales/en.json
index e15e314a06..60ea10a492 100644
--- a/packages/dashboard/src/locales/en.json
+++ b/packages/dashboard/src/locales/en.json
@@ -3077,6 +3077,12 @@
"description": "Shown on your storefront as the contact point for customer questions and support.",
"title": "Set customer support email"
},
+ "setup_address": {
+ "cta": "Save address",
+ "description": "Your shipping and returns address. Carriers use it to calculate delivery rates, and it is where customer returns are sent.",
+ "no_location": "You have no stock location of your own yet — create one in Settings to add an address.",
+ "title": "Add your shipping address"
+ },
"setup_payment_method": {
"cta": "Set up payment methods",
"description": "To collect payments, set up at least one online payment provider.",
diff --git a/packages/dashboard/src/locales/fr.json b/packages/dashboard/src/locales/fr.json
index 74c6702173..e71e79dee0 100644
--- a/packages/dashboard/src/locales/fr.json
+++ b/packages/dashboard/src/locales/fr.json
@@ -3077,6 +3077,12 @@
"description": "Affiché sur votre boutique comme point de contact pour les questions et le support client.",
"title": "Définir l'e-mail du support client"
},
+ "setup_address": {
+ "cta": "Enregistrer l'adresse",
+ "description": "Votre adresse d'expédition et de retour. Les transporteurs l'utilisent pour calculer les frais de livraison, et c'est là que les retours clients sont envoyés.",
+ "no_location": "Vous n'avez pas encore de lieu de stock — créez-en un dans les paramètres pour ajouter une adresse.",
+ "title": "Ajouter votre adresse d'expédition"
+ },
"setup_payment_method": {
"cta": "Configurer les paiements",
"description": "Pour encaisser des paiements, configurez au moins un prestataire de paiement en ligne.",
diff --git a/packages/dashboard/src/locales/pl.json b/packages/dashboard/src/locales/pl.json
index 9b76bcead6..dc94ffd6f9 100644
--- a/packages/dashboard/src/locales/pl.json
+++ b/packages/dashboard/src/locales/pl.json
@@ -3105,6 +3105,12 @@
"description": "Wyświetlany w Twoim sklepie jako punkt kontaktowy dla pytań i wsparcia klientów.",
"title": "Ustaw e-mail obsługi klienta"
},
+ "setup_address": {
+ "cta": "Zapisz adres",
+ "description": "Twój adres wysyłki i zwrotów. Przewoźnicy używają go do obliczania kosztów dostawy, a klienci wysyłają tam zwroty.",
+ "no_location": "Nie masz jeszcze własnej lokalizacji magazynowej — utwórz ją w ustawieniach, aby dodać adres.",
+ "title": "Dodaj adres wysyłki"
+ },
"setup_payment_method": {
"cta": "Skonfiguruj płatności",
"description": "Aby przyjmować płatności, skonfiguruj co najmniej jednego dostawcę płatności online.",
diff --git a/packages/dashboard/src/locales/zh-CN.json b/packages/dashboard/src/locales/zh-CN.json
index e9ed75a2cf..cd1a4b6970 100644
--- a/packages/dashboard/src/locales/zh-CN.json
+++ b/packages/dashboard/src/locales/zh-CN.json
@@ -3069,6 +3069,12 @@
"description": "显示在店铺前台,作为客户咨询和支持的联系方式。",
"title": "设置客服邮箱"
},
+ "setup_address": {
+ "cta": "保存地址",
+ "description": "您的发货和退货地址。承运商使用它计算配送费率,客户退货也将寄送至此。",
+ "no_location": "您还没有自己的库存地点 — 请在设置中创建一个以添加地址。",
+ "title": "添加您的发货地址"
+ },
"setup_payment_method": {
"cta": "设置支付方式",
"description": "要收款,请至少设置一个在线支付服务商。",
diff --git a/packages/seller-dashboard/src/components/seller-returns-location-card.tsx b/packages/seller-dashboard/src/components/seller-returns-location-card.tsx
index df595a197d..e21353ae63 100644
--- a/packages/seller-dashboard/src/components/seller-returns-location-card.tsx
+++ b/packages/seller-dashboard/src/components/seller-returns-location-card.tsx
@@ -1,4 +1,9 @@
-import { AddressFormDialog, type EditableAddress } from '@spree/dashboard-core'
+import {
+ AddressFormDialog,
+ editableAddressToStockLocationParams,
+ stockLocationToAddressBlock,
+ stockLocationToEditableAddress,
+} from '@spree/dashboard-core'
import {
AddressBlock,
Badge,
@@ -12,7 +17,7 @@ import {
toastManager,
} from '@spree/dashboard-ui'
import { PencilIcon, PlusIcon } from '@spree/dashboard-ui/icons'
-import type { StockLocation, StockLocationParams } from '@spree/seller-sdk'
+import type { StockLocationParams } from '@spree/seller-sdk'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { useParams } from '@tanstack/react-router'
import { useState } from 'react'
@@ -35,18 +40,29 @@ export function SellerReturnsLocationCard({ headless = false }: { headless?: boo
const queryClient = useQueryClient()
const [editing, setEditing] = useState(false)
- const { data: locations } = useQuery({
+ // Two filtered requests rather than one page filtered in the browser, to
+ // match `Seller#returns_location` exactly: a location that accepts returns
+ // wins outright, and only then does default and name decide. A seller with
+ // more locations than one page holds would otherwise see one address while
+ // the server sent their returns to another, with nothing on screen saying
+ // so — and they would edit the wrong one.
+ const activeParams = { active_true: true, limit: 1 }
+ const { data: takesReturns, isError: returnsFailed } = useQuery({
+ queryKey: ['seller', sellerId, 'stock-locations', 'returns'],
+ queryFn: () =>
+ sellerClient().stockLocations.list({ ...activeParams, returns_enabled_true: true }),
+ })
+ const hasReturnsLocation = (takesReturns?.data.length ?? 0) > 0
+ const { data: anyActive, isError: anyFailed } = useQuery({
queryKey: ['seller', sellerId, 'stock-locations'],
- queryFn: () => sellerClient().stockLocations.list({ per_page: 100 }),
+ queryFn: () => sellerClient().stockLocations.list(activeParams),
+ enabled: !!takesReturns && !hasReturnsLocation,
})
- // Must match `Seller#returns_location` exactly — active only, default
- // first, then by name. Ignoring `active` here would present a deactivated
- // location as the returns address while the server had already moved
- // returns somewhere else, with nothing on screen saying so.
- const location = (locations?.data ?? [])
- .filter((candidate) => candidate.active)
- .sort((a, b) => Number(b.default) - Number(a.default) || a.name.localeCompare(b.name))[0]
+ const location = takesReturns?.data[0] ?? anyActive?.data[0]
+ // A failed lookup must not read as "no address yet" — that invites the
+ // seller to re-enter one they already have.
+ const failed = returnsFailed || anyFailed
const hasAddress = Boolean(location?.address1)
const title = t('profile.returns_address')
@@ -72,9 +88,11 @@ export function SellerReturnsLocationCard({ headless = false }: { headless?: boo
const body =
hasAddress && location ? (
- <AddressBlock address={toAddressBlock(location)} />
+ <AddressBlock address={stockLocationToAddressBlock(location)} />
) : (
- <p className="text-muted-foreground text-sm">{t('profile.address_not_provided')}</p>
+ <p className={failed ? 'text-destructive text-sm' : 'text-muted-foreground text-sm'}>
+ {t(failed ? 'common.error' : 'profile.address_not_provided')}
+ </p>
)
const editButton = (
@@ -92,11 +110,11 @@ export function SellerReturnsLocationCard({ headless = false }: { headless?: boo
const dialog = editing && location && (
<AddressFormDialog
title={title}
- address={toEditableAddress(location)}
+ address={stockLocationToEditableAddress(location)}
open
business
onOpenChange={setEditing}
- onSave={(values) => save.mutate(toStockLocationParams(values))}
+ onSave={(values) => save.mutate(editableAddressToStockLocationParams(values))}
isPending={save.isPending}
/>
)
@@ -131,50 +149,3 @@ export function SellerReturnsLocationCard({ headless = false }: { headless?: boo
</>
)
}
-
-/**
- * The three shapes this card sits between. A stock location stores `zipcode`
- * where an address says `postal_code`, and carries no personal name — mapping
- * the fields explicitly is what keeps that difference in one place instead of
- * leaking a cast into every call.
- */
-function toAddressBlock(location: StockLocation) {
- return {
- company: location.company,
- address1: location.address1,
- address2: location.address2,
- city: location.city,
- state_text: location.state_text,
- postal_code: location.zipcode,
- country_code: location.country_code,
- country_name: location.country_name,
- phone: location.phone,
- }
-}
-
-function toEditableAddress(location: StockLocation) {
- return {
- id: location.id,
- company: location.company,
- address1: location.address1,
- address2: location.address2,
- city: location.city,
- postal_code: location.zipcode,
- country_code: location.country_code,
- state_code: location.state_code,
- phone: location.phone,
- }
-}
-
-function toStockLocationParams(values: EditableAddress): StockLocationParams {
- return {
- company: values.company,
- address1: values.address1,
- address2: values.address2,
- city: values.city,
- zipcode: values.postal_code,
- country_code: values.country_code,
- state_code: values.state_code,
- phone: values.phone,
- }
-}
diff --git a/packages/seller-dashboard/src/pages/onboarding.tsx b/packages/seller-dashboard/src/pages/onboarding.tsx
index c6e9bf8a3e..6dec7eb16b 100644
--- a/packages/seller-dashboard/src/pages/onboarding.tsx
+++ b/packages/seller-dashboard/src/pages/onboarding.tsx
@@ -197,12 +197,14 @@ function RequirementAction({ requirement }: { requirement: RequirementStatus })
const [file, setFile] = useState<FileUploadValue>(EMPTY_FILE_UPLOAD_VALUE)
const [fields, setFields] = useState<Record<string, string>>({})
- // Only the address kinds need it, and it is already loaded by the profile
- // page and the sidebar switcher — this reads the same cache entry.
+ // Only the billing address needs it, and it is already loaded by the
+ // profile page and the sidebar switcher — this reads the same cache entry.
+ // The returns address does not: it lives on a stock location, which its own
+ // card fetches.
const { data: profile } = useQuery({
queryKey: ['seller', sellerId, 'profile'],
queryFn: () => sellerClient().profile.get(),
- enabled: isAddressKind(requirement.kind),
+ enabled: requirement.kind === 'billing_address',
})
const invalidate = () =>
@@ -478,11 +480,6 @@ function RequirementAction({ requirement }: { requirement: RequirementStatus })
)
}
-/** Kinds the seller satisfies by filling an address, rendered inline. */
-function isAddressKind(kind: string): boolean {
- return kind === 'billing_address' || kind === 'returns_address'
-}
-
/**
* Where in this panel a seller goes to satisfy a kind.
*
diff --git a/packages/seller-sdk/src/seller-client.ts b/packages/seller-sdk/src/seller-client.ts
index 3bf33262f9..368f529ea8 100644
--- a/packages/seller-sdk/src/seller-client.ts
+++ b/packages/seller-sdk/src/seller-client.ts
@@ -1559,7 +1559,6 @@ export interface ProfileUpdateParams {
* validation verdict, since that answer was about the old one.
*/
billing_address?: SellerAddressParams
- returns_address?: SellerAddressParams
/**
* Answers to the custom fields this marketplace's onboarding asks for.
* Narrowed server-side to those definitions — a field nothing asked for is
diff --git a/spree/api/spec/integration/spree/api/v3/admin/store_spec.rb b/spree/api/spec/integration/spree/api/v3/admin/store_spec.rb
index a33f1885dd..75adf99770 100644
--- a/spree/api/spec/integration/spree/api/v3/admin/store_spec.rb
+++ b/spree/api/spec/integration/spree/api/v3/admin/store_spec.rb
@@ -41,7 +41,8 @@ RSpec.describe 'Admin Store API', type: :request, swagger_doc: 'api-reference/ad
expect(data['url']).to eq(store.storefront_url)
expect(data['default_country_code']).to eq(store.default_country_code)
expect(data['setup_tasks'].map { |t| t['name'] }).to eq(
- %w[setup_payment_method add_products set_customer_support_email setup_taxes_collection setup_storefront]
+ %w[setup_address setup_payment_method add_products set_customer_support_email setup_taxes_collection
+ setup_storefront]
)
expect(data['setup_tasks']).to all(match('name' => be_a(String), 'done' => be_in([true, false])))
end
diff --git a/spree/core/app/models/concerns/spree/stores/setup.rb b/spree/core/app/models/concerns/spree/stores/setup.rb
index 6dc2dd03f2..fa0e0ec69f 100644
--- a/spree/core/app/models/concerns/spree/stores/setup.rb
+++ b/spree/core/app/models/concerns/spree/stores/setup.rb
@@ -66,6 +66,16 @@ module Spree
def storefront_setup?
preferred_storefront_url.present?
end
+
+ # Whether the store has a postable address to ship from and receive
+ # returns at. Read off the location returns route to rather than the
+ # store: the store's own `address` is a free-text blob for the email
+ # footer, while carriers need the structured columns a location carries.
+ #
+ # @return [Boolean]
+ def address_setup?
+ primary_location&.postable?
+ end
end
end
end
diff --git a/spree/core/app/models/spree/seller.rb b/spree/core/app/models/spree/seller.rb
index 9313a650d7..c5d9ee1cfc 100644
--- a/spree/core/app/models/spree/seller.rb
+++ b/spree/core/app/models/spree/seller.rb
@@ -345,14 +345,14 @@ module Spree
# The postal address a shopper is given for returns.
#
- # Nil until the location has an address on it: the location builds one from
- # its own columns on demand, so an empty one would otherwise answer with a
+ # Nil until the location is postable: it builds an address from its own
+ # columns on demand, so an incomplete one would otherwise answer with a
# blank address that reads as configured.
#
# @return [Spree::Address, nil]
def returns_address
location = returns_location
- return if location.nil? || location.address1.blank?
+ return unless location&.postable?
location.address
end
diff --git a/spree/core/app/models/spree/seller_requirements/returns_address.rb b/spree/core/app/models/spree/seller_requirements/returns_address.rb
index 2745207c0f..28fb9465bf 100644
--- a/spree/core/app/models/spree/seller_requirements/returns_address.rb
+++ b/spree/core/app/models/spree/seller_requirements/returns_address.rb
@@ -10,10 +10,9 @@ module Spree
# its own would leave the goods arriving nowhere (Decision 12).
class ReturnsAddress < Spree::SellerRequirement
def met_by_seller?(seller)
- location = seller.returns_location
- return false if location.nil?
-
- location.address1.present? && location.city.present? && location.country_code.present?
+ # Boolean rather than the bare `&.`: `satisfied?` is public API and
+ # sibling kinds all answer true or false.
+ seller.returns_location&.postable? == true
end
end
end
diff --git a/spree/core/app/models/spree/stock_location.rb b/spree/core/app/models/spree/stock_location.rb
index ebb8a71add..411545c953 100644
--- a/spree/core/app/models/spree/stock_location.rb
+++ b/spree/core/app/models/spree/stock_location.rb
@@ -236,6 +236,16 @@ module Spree
end
end
+ # Enough of an address to post a parcel to and for a carrier to rate
+ # against. `#address` below builds an unsaved record from these columns
+ # whatever their state, so a blank location answers with a blank address
+ # that reads as configured — every caller needs this guard first.
+ #
+ # @return [Boolean]
+ def postable?
+ address1.present? && city.present? && country_code.present?
+ end
+
def address
Spree::Address.new(
address1: address1,
diff --git a/spree/core/app/models/spree/store.rb b/spree/core/app/models/spree/store.rb
index 24654d4c9a..f57d0ee4a3 100644
--- a/spree/core/app/models/spree/store.rb
+++ b/spree/core/app/models/spree/store.rb
@@ -541,6 +541,39 @@ module Spree
country_codes.filter_map { |code| Spree::Country.by_iso(code) }.sort_by(&:name)
end
+ # The operator's own location that accepts returns, or nil when none does.
+ #
+ # First-party only: `stock_locations` includes every seller's warehouse on a
+ # marketplace, and the operator's goods must never be routed into one.
+ #
+ # Nil rather than a fallback, because the caller's fallback is not ours to
+ # guess: {Spree::Returns::Create} answers nil by sending goods back where
+ # they shipped from, which is a better destination than a location the
+ # merchant told us not to send returns to.
+ #
+ # @return [Spree::StockLocation, nil]
+ def returns_location
+ stock_locations.active.first_party.returns_enabled.order_default.first
+ end
+
+ # The location the address checklist asks the merchant to fill in: the one
+ # that takes returns, falling back to any active location of their own,
+ # since the address is also what carriers rate against.
+ #
+ # Ordered rather than two queries with a fallback — both columns are
+ # NOT NULL, so sorting on the flag puts a returns-enabled location first
+ # and answers the fallback in the same round trip.
+ #
+ # Deliberately not `default_stock_location`, which creates the row when it
+ # is missing: this is read on every dashboard render (the Getting Started
+ # checklist), and a read that writes would provision a location for every
+ # store that loaded the page.
+ #
+ # @return [Spree::StockLocation, nil]
+ def primary_location
+ stock_locations.active.first_party.order(returns_enabled: :desc, default: :desc, name: :asc).first
+ end
+
# The store's own default stock location, created if it does not exist yet.
#
# Scoped to this store's first-party locations on both counts: unscoped it
diff --git a/spree/core/app/workflows/spree/returns/create.rb b/spree/core/app/workflows/spree/returns/create.rb
index 57a8ccc8bd..4ce5f9f935 100644
--- a/spree/core/app/workflows/spree/returns/create.rb
+++ b/spree/core/app/workflows/spree/returns/create.rb
@@ -126,11 +126,9 @@ module Spree
first&.returns_location
end
- # First-party only: `store.stock_locations` includes every seller's own
- # warehouses, and an operator's goods must never be routed into one.
# A seller's return is answered by seller_returns_location above.
def store_returns_location
- order.store.stock_locations.active.first_party.returns_enabled.order_default.first
+ order.store.returns_location
end
end
end
diff --git a/spree/core/config/initializers/spree_store_setup_tasks.rb b/spree/core/config/initializers/spree_store_setup_tasks.rb
index dbee553d45..b945061116 100644
--- a/spree/core/config/initializers/spree_store_setup_tasks.rb
+++ b/spree/core/config/initializers/spree_store_setup_tasks.rb
@@ -1,6 +1,10 @@
# Default Getting Started tasks shown on the admin dashboard.
# See Spree::SetupTasks for how to add or remove tasks.
Rails.application.config.after_initialize do
+ Spree.store_setup_tasks.add :setup_address,
+ position: 5,
+ done: ->(store) { store.address_setup? }
+
Spree.store_setup_tasks.add :setup_payment_method,
position: 10,
done: ->(store) { store.payment_method_setup? }
diff --git a/spree/core/spec/models/spree/setup_tasks_spec.rb b/spree/core/spec/models/spree/setup_tasks_spec.rb
index 4634bfda75..06a0b691e1 100644
--- a/spree/core/spec/models/spree/setup_tasks_spec.rb
+++ b/spree/core/spec/models/spree/setup_tasks_spec.rb
@@ -62,9 +62,10 @@ describe Spree::SetupTasks do
end
describe 'default registration' do
- it 'registers the five default tasks in order on the global registry' do
+ it 'registers the six default tasks in order on the global registry' do
expect(Spree.store_setup_tasks.tasks.map(&:key)).to eq(
- %i[setup_payment_method add_products set_customer_support_email setup_taxes_collection setup_storefront]
+ %i[setup_address setup_payment_method add_products set_customer_support_email setup_taxes_collection
+ setup_storefront]
)
end
end
diff --git a/spree/core/spec/models/spree/store_spec.rb b/spree/core/spec/models/spree/store_spec.rb
index b537160cc0..f1aa3e9e10 100644
--- a/spree/core/spec/models/spree/store_spec.rb
+++ b/spree/core/spec/models/spree/store_spec.rb
@@ -1167,6 +1167,92 @@ describe Spree::Store, type: :model, without_global_store: true do
end
end
+ describe 'address setup task' do
+ let(:store) { create(:store) }
+
+ describe '#address_setup?' do
+ subject { store.address_setup? }
+
+ context 'with no stock location' do
+ it { is_expected.to be_falsey }
+ end
+
+ context 'with a stock location carrying no address' do
+ before { create(:stock_location, store: store, address1: nil, city: nil) }
+
+ it 'stays pending' do
+ expect(subject).to be_falsey
+ expect(store.setup_task_done?(:setup_address)).to be false
+ end
+ end
+
+ context 'with a postable address on the default location' do
+ before do
+ create(:stock_location, store: store, default: true, state: nil,
+ address1: '1 Warehouse Way', city: 'London', country_code: 'GB')
+ end
+
+ it 'marks the setup task as done' do
+ expect(subject).to be true
+ expect(store.setup_task_done?(:setup_address)).to be true
+ end
+ end
+
+ # The checklist must ask about the location returns actually route to,
+ # or a merchant fills in one address and their parcels go to another.
+ context 'when a returns-enabled location has no address' do
+ before do
+ create(:stock_location, store: store, default: true, state: nil, returns_enabled: false,
+ address1: '1 Warehouse Way', city: 'London', country_code: 'GB')
+ create(:stock_location, store: store, state: nil, returns_enabled: true,
+ address1: nil, city: nil)
+ end
+
+ it 'reads the location that accepts returns' do
+ expect(subject).to be_falsey
+ end
+ end
+
+ # Every flag off still leaves an address to collect: it is what carriers
+ # rate against, not only where returns land.
+ context 'when no location accepts returns' do
+ before do
+ create(:stock_location, store: store, default: true, state: nil, returns_enabled: false,
+ address1: '1 Warehouse Way', city: 'London', country_code: 'GB')
+ end
+
+ it { is_expected.to be true }
+ end
+
+ context 'when the addressed location is inactive' do
+ before do
+ create(:stock_location, store: store, default: true, state: nil, active: false,
+ address1: '1 Warehouse Way', city: 'London', country_code: 'GB')
+ end
+
+ it { is_expected.to be_falsey }
+ end
+
+ # The operator's checklist asks for the operator's address. A seller's
+ # warehouse is on the same table and would otherwise answer for it.
+ context 'when only a seller owns an addressed location' do
+ before do
+ seller = create(:seller, store: store)
+ create(:stock_location, store: store, seller: seller, default: true, state: nil,
+ address1: '1 Seller Way', city: 'London', country_code: 'GB')
+ end
+
+ it { is_expected.to be_falsey }
+ end
+ end
+
+ # `default_stock_location` creates the row when it is missing, and this
+ # checklist is evaluated on every dashboard render.
+ it 'does not provision a stock location just by being asked' do
+ expect { store.address_setup? }.not_to change(Spree::StockLocation, :count)
+ end
+ end
+
describe '#payment_method_setup?' do
let(:store) { create(:store) }