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.

Let a connector read and write records by its own key

Damian Legawiec471f7a0ef3d1
diff --git a/packages/admin-sdk/examples/companies/create.ts b/packages/admin-sdk/examples/companies/create.ts
index 9baaadf39e..aac2d830f9 100644
--- a/packages/admin-sdk/examples/companies/create.ts
+++ b/packages/admin-sdk/examples/companies/create.ts
@@ -8,7 +8,7 @@ const client = createAdminClient({
// region:example
const company = await client.companies.create({
name: 'Globex Corporation',
- external_id: 'GLBX-42',
+ external_references: { erp: 'GLBX-42' },
})
// endregion:example
diff --git a/packages/admin-sdk/src/admin-client.ts b/packages/admin-sdk/src/admin-client.ts
index 96570f6f90..ffe3f1a761 100644
--- a/packages/admin-sdk/src/admin-client.ts
+++ b/packages/admin-sdk/src/admin-client.ts
@@ -224,11 +224,13 @@ import type {
SetupCountries,
SetupParams,
SetupStatus,
+ StockLevelBulkUpsertRow,
StockLevelUpdateParams,
StockLocationCreateParams,
StockLocationUpdateParams,
StockTransferCreateParams,
StoreCreditApplyParams,
+ StoreDataSources,
StoreUpdateParams,
TaxCategoryCreateParams,
TaxCategoryUpdateParams,
@@ -681,6 +683,16 @@ export class AdminClient {
update: (params: StoreUpdateParams, options?: RequestOptions): Promise<Store> =>
this.request<Store>('PATCH', '/store', { ...options, body: params }),
+
+ /**
+ * The pricing and inventory engines this store can choose between, and
+ * whether each is usable — a provider whose integration is not connected
+ * is listed but not selectable.
+ */
+ dataSources: (options?: RequestOptions): Promise<StoreDataSources> =>
+ this.request<{ data: StoreDataSources }>('GET', '/store/data_sources', options).then(
+ (r) => r.data,
+ ),
}
/** The locales a merchant can translate content into for the current store. */
@@ -4123,8 +4135,25 @@ export class AdminClient {
delete: (id: string, options?: RequestOptions): Promise<void> =>
this.request<void>('DELETE', `/stock_levels/${id}`, options),
+
+ /**
+ * Sets stock levels for many (variant, location) pairs at once — what a
+ * warehouse feed posts on a schedule. Rows name their variant and location
+ * either by Spree id or by an external reference, so a feed can use the
+ * keys it already holds.
+ *
+ * Each change is recorded as a stock movement, so the history stays
+ * intact. Response is `{ stock_level_count }`.
+ */
+ bulkUpsert: (
+ params: { stock_levels: StockLevelBulkUpsertRow[] },
+ options?: RequestOptions,
+ ): Promise<{ stock_level_count: number }> =>
+ this.request('POST', '/stock_levels/bulk_upsert', { ...options, body: params }),
}
+ // }
+
// ============================================
// Stock Movements
// ============================================
diff --git a/packages/admin-sdk/src/params.ts b/packages/admin-sdk/src/params.ts
index d2df657235..969057cd40 100644
--- a/packages/admin-sdk/src/params.ts
+++ b/packages/admin-sdk/src/params.ts
@@ -3,6 +3,24 @@
import type { SellerRequirementStatus } from './types'
+/** One pricing or inventory engine a store can choose between. */
+export interface StoreDataSourceProvider {
+ /** What the store preference stores, and what a priced line records as its source. */
+ key: string
+ name: string
+ integration_class: string | null
+ /** The integration's wire shorthand, for deep-linking to its settings page. */
+ integration_type: string | null
+ /** False while the provider's integration is not connected for this store. */
+ available: boolean
+}
+
+export interface StoreDataSources {
+ pricing_providers: StoreDataSourceProvider[]
+ inventory_providers: StoreDataSourceProvider[]
+ failure_policies: string[]
+}
+
export interface StoreUpdateParams {
name?: string
preferred_admin_locale?: string
@@ -64,6 +82,14 @@ export interface StoreUpdateParams {
preferred_send_consumer_transactional_emails?: boolean
/** Active Storage signed_id from a direct upload — the logo embedded in transactional emails. */
mailer_logo?: string | null
+ /** Where prices come from: a registered provider key, or `internal`. */
+ preferred_pricing_provider?: string
+ /** Where stock levels come from: a registered provider key, or `internal`. */
+ preferred_inventory_provider?: string
+ /** `strict` refuses to price when the provider cannot answer; `fallback` uses the catalog. */
+ preferred_pricing_provider_failure_policy?: 'strict' | 'fallback'
+ /** `fallback` sells on the local snapshot when the provider cannot answer; `strict` refuses. */
+ preferred_inventory_provider_failure_policy?: 'strict' | 'fallback'
}
export interface OptionValueParams {
@@ -397,6 +423,7 @@ export interface OrderCreateParams {
}
export interface OrderUpdateParams {
+ external_references?: ExternalReferencesParams
email?: string
customer_id?: string
customer_note?: string
@@ -647,6 +674,7 @@ export interface ProductPublicationInput {
}
export interface ProductCreateParams {
+ external_references?: ExternalReferencesParams
name: string
/** Rich text HTML. Reads come back as this (plain text) plus `description_html`. */
description?: string
@@ -677,6 +705,7 @@ export interface ProductCreateParams {
}
export interface ProductUpdateParams {
+ external_references?: ExternalReferencesParams
name?: string
/** Rich text HTML. Reads come back as this (plain text) plus `description_html`. */
description?: string
@@ -739,6 +768,7 @@ export interface ProductVariantInput {
}
export interface CategoryCreateParams {
+ external_references?: ExternalReferencesParams
name: string
/** Prefixed ID of the parent category. Omit or null for a top-level category. */
parent_id?: string | null
@@ -755,6 +785,7 @@ export interface CategoryCreateParams {
}
export interface CategoryUpdateParams {
+ external_references?: ExternalReferencesParams
name?: string
/** Prefixed ID of the parent category, or null to move it to the top level. */
parent_id?: string | null
@@ -912,6 +943,7 @@ export interface VariantStockLevel {
}
export interface VariantCreateParams {
+ external_references?: ExternalReferencesParams
sku?: string
/** Decimal amount; see `VariantPrice.amount` for the string rationale. */
cost_price?: string | number
@@ -942,6 +974,7 @@ export interface VariantCreateParams {
}
export interface VariantUpdateParams {
+ external_references?: ExternalReferencesParams
sku?: string
/** Decimal amount; see `VariantPrice.amount` for the string rationale. */
cost_price?: string | number
@@ -1144,6 +1177,7 @@ export interface MeUpdateParams {
}
export interface StockLocationCreateParams {
+ external_references?: ExternalReferencesParams
name: string
admin_name?: string | null
active?: boolean
@@ -1172,6 +1206,7 @@ export interface StockLocationCreateParams {
}
export interface StockLocationUpdateParams {
+ external_references?: ExternalReferencesParams
name?: string
admin_name?: string | null
active?: boolean
@@ -1196,6 +1231,7 @@ export interface StockLocationUpdateParams {
/** Corrects one stock level. */
export interface StockLevelUpdateParams {
+ external_references?: ExternalReferencesParams
/**
* The count the shelf should end at. The API records the difference as an
* `adjusted` movement rather than writing the column, so the correction
@@ -1210,6 +1246,37 @@ export interface StockLevelUpdateParams {
metadata?: Record<string, unknown>
}
+/**
+ * Identities a record has in external systems, keyed by system — the same
+ * `{ system: external_id }` map the Admin API renders, so what you read can be
+ * sent straight back. Systems you do not name keep the reference they have.
+ * A list of `{ system, external_id }` entries is accepted too.
+ */
+export type ExternalReferencesParams =
+ | Record<string, string>
+ | Array<{ system: string; external_id: string }>
+
+/** How a feed names the record it is reporting on, when it does not hold Spree's id. */
+export interface ExternalReferenceLookup {
+ /** `{ system: external_id }`, e.g. `{ erp: 'MAT-100' }`. */
+ external_id: Record<string, string>
+}
+
+export interface StockLevelBulkUpsertRow {
+ /** Spree's own id. Use this or `variant`. */
+ variant_id?: string
+ /** Address the variant by the key the feeding system holds. */
+ variant?: ExternalReferenceLookup
+ /** Spree's own id. Use this or `stock_location`. */
+ stock_location_id?: string
+ stock_location?: ExternalReferenceLookup
+ /** The absolute level the external system reports. */
+ count_on_hand?: number
+ /** A relative change, for feeds that report movements rather than levels. */
+ adjustment?: number
+ backorderable?: boolean
+}
+
export interface StockTransferCreateParams {
/** Omit for a seller receive (external stock arriving at the destination). */
source_location_id?: string
@@ -2345,8 +2412,7 @@ export interface DeliveryZoneParams {
export interface CompanyParams {
name?: string
- /** Your own reference for this business, unique within the store. */
- external_id?: string | null
+ external_references?: ExternalReferencesParams
metadata?: Record<string, unknown>
}
@@ -2369,7 +2435,7 @@ export interface CompanyLocationAddressParams {
export interface CompanyLocationParams {
name?: string
- external_id?: string | null
+ external_references?: ExternalReferencesParams
billing_address?: CompanyLocationAddressParams
shipping_address?: CompanyLocationAddressParams
metadata?: Record<string, unknown>
diff --git a/packages/admin-sdk/src/types/generated/Category.ts b/packages/admin-sdk/src/types/generated/Category.ts
index f44d8e70bb..660b82dcd3 100644
--- a/packages/admin-sdk/src/types/generated/Category.ts
+++ b/packages/admin-sdk/src/types/generated/Category.ts
@@ -1,4 +1,4 @@
-// Typelizer digest a664c2965050201bf085ede78defb625
+// Typelizer digest 25b0674ad41b04fe33cfb5e371a7a44a
//
// DO NOT MODIFY: This file was automatically generated by Typelizer.
import type {CustomField} from '@/types'
@@ -25,6 +25,7 @@ interface Category {
children?: Array<Category>;
ancestors?: Array<Category>;
custom_fields?: Array<CustomField>;
+ external_references: Record<string, string>;
translations?: Record<string, Record<string, string | number | null>>;
metadata: Record<string, unknown>;
pretty_name: string;
diff --git a/packages/admin-sdk/src/types/generated/Company.ts b/packages/admin-sdk/src/types/generated/Company.ts
index 5727206c60..19304c2ea0 100644
--- a/packages/admin-sdk/src/types/generated/Company.ts
+++ b/packages/admin-sdk/src/types/generated/Company.ts
@@ -1,4 +1,4 @@
-// Typelizer digest 3126522f6a67e0ca1b34d6662b3d0344
+// Typelizer digest 3187af0bbdf327a082c7fbf6fbd8dfc6
//
// DO NOT MODIFY: This file was automatically generated by Typelizer.
import type {CompanyLocation} from '@/types'
@@ -6,7 +6,7 @@ import type {CompanyLocation} from '@/types'
interface Company {
id: string;
name: string;
- external_id: string | null;
+ external_references: Record<string, string>;
metadata: Record<string, unknown> | null;
created_at: string;
updated_at: string;
diff --git a/packages/admin-sdk/src/types/generated/CompanyLocation.ts b/packages/admin-sdk/src/types/generated/CompanyLocation.ts
index 6f5c5feec8..df01c75ff2 100644
--- a/packages/admin-sdk/src/types/generated/CompanyLocation.ts
+++ b/packages/admin-sdk/src/types/generated/CompanyLocation.ts
@@ -1,12 +1,12 @@
-// Typelizer digest 360e7f05e35ee3a3de470756f97e5d12
+// Typelizer digest c131d6947f6a57f75ea1e17c1f193c41
//
// DO NOT MODIFY: This file was automatically generated by Typelizer.
import type {Address, CompanyContact} from '@/types'
interface CompanyLocation {
id: string;
+ external_references: Record<string, string>;
name: string;
- external_id: string | null;
metadata: Record<string, unknown> | null;
created_at: string;
updated_at: string;
diff --git a/packages/admin-sdk/src/types/generated/Order.ts b/packages/admin-sdk/src/types/generated/Order.ts
index 9a3f83e676..0f0c0b84f8 100644
--- a/packages/admin-sdk/src/types/generated/Order.ts
+++ b/packages/admin-sdk/src/types/generated/Order.ts
@@ -1,4 +1,4 @@
-// Typelizer digest 1e527c82d4587146ab589172e40c5271
+// Typelizer digest a717b917eec36f223eaf5c3ed8b7374a
//
// DO NOT MODIFY: This file was automatically generated by Typelizer.
import type {LineItem, Fulfillment, Payment, Address, GiftCard, Market, Seller, AppliedPromotion, Cart, Channel, StockLocation, PaymentMethod, Customer, Return, Exchange, Claim} from '@/types'
@@ -50,6 +50,7 @@ interface Order {
shipping_address?: Address | null;
gift_card: GiftCard | null;
market: Market | null;
+ external_references: Record<string, string>;
status: string;
last_ip_address: string | null;
considered_risky: boolean;
diff --git a/packages/admin-sdk/src/types/generated/Product.ts b/packages/admin-sdk/src/types/generated/Product.ts
index 4b99cb6514..cb32c81987 100644
--- a/packages/admin-sdk/src/types/generated/Product.ts
+++ b/packages/admin-sdk/src/types/generated/Product.ts
@@ -1,4 +1,4 @@
-// Typelizer digest 8ad4c9d78357b98f72f85ec68d898265
+// Typelizer digest daf6367acf0b228a99c809eb8b0dd159
//
// DO NOT MODIFY: This file was automatically generated by Typelizer.
import type {Price, PriceHistory, Seller, Media, Variant, OptionType, OptionValue, Category, CustomField, Collection, ProductPublication, Channel, ProductType} from '@/types'
@@ -37,6 +37,7 @@ interface Product {
categories?: Array<Category>;
custom_fields?: Array<CustomField>;
prior_price?: PriceHistory | null;
+ external_references: Record<string, string>;
translations?: Record<string, Record<string, string | number | null>>;
status: string;
metadata: Record<string, unknown>;
diff --git a/packages/admin-sdk/src/types/generated/StockLevel.ts b/packages/admin-sdk/src/types/generated/StockLevel.ts
index 70bb4cb312..af0658fc72 100644
--- a/packages/admin-sdk/src/types/generated/StockLevel.ts
+++ b/packages/admin-sdk/src/types/generated/StockLevel.ts
@@ -1,4 +1,4 @@
-// Typelizer digest ed9c8e602f9172a2a75fb4611d9cb4e4
+// Typelizer digest 81da75ce4af0428cf29c095cbf9944a2
//
// DO NOT MODIFY: This file was automatically generated by Typelizer.
import type {StockLocation, Variant} from '@/types'
@@ -9,6 +9,7 @@ interface StockLevel {
backorderable: boolean;
stock_location_id: string | null;
variant_id: string | null;
+ external_references: Record<string, string>;
metadata: Record<string, unknown>;
created_at: string;
updated_at: string;
diff --git a/packages/admin-sdk/src/types/generated/StockLocation.ts b/packages/admin-sdk/src/types/generated/StockLocation.ts
index 225b4e313b..c1922c5371 100644
--- a/packages/admin-sdk/src/types/generated/StockLocation.ts
+++ b/packages/admin-sdk/src/types/generated/StockLocation.ts
@@ -1,4 +1,4 @@
-// Typelizer digest 100d4da3c36db4aa2ea5aefc208d5f25
+// Typelizer digest 11972f44e75f3a95c88825fe54e2c038
//
// DO NOT MODIFY: This file was automatically generated by Typelizer.
@@ -14,6 +14,7 @@ interface StockLocation {
state_text: string | null;
pickup_ready_in_minutes: number | null;
pickup_instructions: string | null;
+ external_references: Record<string, string>;
admin_name: string | null;
address2: string | null;
state_name: string | null;
diff --git a/packages/admin-sdk/src/types/generated/Variant.ts b/packages/admin-sdk/src/types/generated/Variant.ts
index 5e6fdba158..a2929a3a0b 100644
--- a/packages/admin-sdk/src/types/generated/Variant.ts
+++ b/packages/admin-sdk/src/types/generated/Variant.ts
@@ -1,4 +1,4 @@
-// Typelizer digest 3981c27f433be71217f0b96be7fd2b90
+// Typelizer digest 861b6e6d2415a0063b1116344e39c9cb
//
// DO NOT MODIFY: This file was automatically generated by Typelizer.
import type {Price, PriceHistory, Seller, Media, OptionValue, CustomField, StockLevel} from '@/types'
@@ -29,6 +29,7 @@ interface Variant {
option_values: Array<OptionValue>;
custom_fields?: Array<CustomField>;
prior_price?: PriceHistory | null;
+ external_references: Record<string, string>;
metadata: Record<string, unknown>;
position: number;
cost_price: string | null;
diff --git a/packages/admin-sdk/tests/companies.test.ts b/packages/admin-sdk/tests/companies.test.ts
index 2e9507b46a..ab9b00f9d4 100644
--- a/packages/admin-sdk/tests/companies.test.ts
+++ b/packages/admin-sdk/tests/companies.test.ts
@@ -6,7 +6,7 @@ import { server } from './mocks/server'
const sampleCompany = {
id: 'comp_abc123',
name: 'Acme Industrial',
- external_id: 'ACME-1',
+ external_references: { erp: 'ACME-1' },
locations_count: 2,
metadata: {},
created_at: '2026-08-01T00:00:00Z',
@@ -17,7 +17,7 @@ const sampleLocation = {
id: 'cloc_abc123',
company_id: 'comp_abc123',
name: 'Berlin',
- external_id: null,
+ external_references: {},
contacts_count: 1,
billing_address: null,
shipping_address: null,
@@ -81,11 +81,17 @@ describe('companies', () => {
)
const client = createTestClient()
- await client.companies.create({ name: 'Globex Corporation', external_id: 'GLBX' })
+ await client.companies.create({
+ name: 'Globex Corporation',
+ external_references: { erp: 'GLBX' },
+ })
await client.companies.update('comp_abc123', { name: 'Acme Global' })
await client.companies.delete('comp_abc123')
- expect(created).toEqual({ name: 'Globex Corporation', external_id: 'GLBX' })
+ expect(created).toEqual({
+ name: 'Globex Corporation',
+ external_references: { erp: 'GLBX' },
+ })
expect(patched).toEqual({ name: 'Acme Global' })
expect(deleted).toBe(true)
})
diff --git a/packages/dashboard/src/components/spree/company-location-sheet.tsx b/packages/dashboard/src/components/spree/company-location-sheet.tsx
index 4c773a553c..31d8934627 100644
--- a/packages/dashboard/src/components/spree/company-location-sheet.tsx
+++ b/packages/dashboard/src/components/spree/company-location-sheet.tsx
@@ -5,7 +5,6 @@ import {
Button,
Checkbox,
Field,
- FieldDescription,
FieldError,
FieldGroup,
FieldLabel,
@@ -67,7 +66,6 @@ export function CompanyLocationSheet({
const shipping = addressToForm(location.shipping_address)
form.reset({
name: location.name,
- external_id: location.external_id ?? '',
billing_address: billing,
shipping_address: shipping,
// A branch saved with matching addresses reopens with the box ticked, so
@@ -132,16 +130,6 @@ export function CompanyLocationSheet({
<FieldError errors={[errors.name]} />
</Field>
- <Field>
- <FieldLabel htmlFor="location-external-id">
- {t('admin.fields.external_id.label')}
- </FieldLabel>
- <Input id="location-external-id" {...form.register('external_id')} />
- <FieldDescription>
- {t('admin.fields.company_location.external_id.help')}
- </FieldDescription>
- </Field>
-
<AddressFieldset
form={form}
prefix="billing_address"
diff --git a/packages/dashboard/src/locales/ar.json b/packages/dashboard/src/locales/ar.json
index d2703cb404..5c21bbea17 100644
--- a/packages/dashboard/src/locales/ar.json
+++ b/packages/dashboard/src/locales/ar.json
@@ -1592,6 +1592,34 @@
"track_price_history": {
"help": "الاحتفاظ بالأسعار السابقة ليتمكن المتجر من عرض أقل سعر خلال آخر 30 يومًا، وفقًا لقواعد الاتحاد الأوروبي.",
"label": "تسجيل سجل الأسعار"
+ },
+ "data_sources": {
+ "internal": "Spree (مدمج)",
+ "not_connected": "اربط هذا التكامل لاستخدامه",
+ "pricing_provider": {
+ "label": "مصدر الأسعار",
+ "help": "يسعّر Spree من الكتالوج وقوائم الأسعار ما لم يجب نظام خارجي."
+ },
+ "inventory_provider": {
+ "label": "مصدر المخزون",
+ "help": "يُسأل المصدر الخارجي عند الإضافة إلى السلة وعند الدفع. تعرض القوائم دائمًا سجلات مخزونك."
+ },
+ "pricing_failure_policy": {
+ "label": "إذا تعذر تأكيد الأسعار",
+ "help": "يصعب التراجع عن سعر خاطئ، لذا الرفض هو الإعداد الافتراضي الأكثر أمانًا."
+ },
+ "inventory_failure_policy": {
+ "label": "إذا تعذر تأكيد المخزون",
+ "help": "بيع صنف غير متوفر يمكن تداركه، لذا يبقيك الرجوع قادرًا على البيع."
+ },
+ "policies": {
+ "strict": {
+ "label": "ارفض واطلب من العميل المحاولة مرة أخرى"
+ },
+ "fallback": {
+ "label": "استخدم أرقام Spree"
+ }
+ }
}
},
"store_credit": {
@@ -1731,18 +1759,11 @@
"company": {
"name": {
"placeholder": "Acme Industries"
- },
- "external_id": {
- "help": "مرجعك الخاص لهذه الشركة، فريد داخل المتجر.",
- "placeholder": "ACME-001"
}
},
"company_location": {
"name": {
"placeholder": "المقر الرئيسي"
- },
- "external_id": {
- "help": "مرجعك الخاص لهذا الفرع."
}
},
"company_contact": {
@@ -1890,6 +1911,9 @@
"help": "لا تحتسب أقل من الأول ولا أكثر من الثاني. ينطبق كل منهما على المبيعات بعملته فقط؛ والعملة المتروكة فارغة تُحتسب دون حدود.",
"label": "حد أدنى وأقصى (اختياري)"
}
+ },
+ "external_references": {
+ "label": "المراجع الخارجية"
}
},
"gift_cards": {
@@ -3129,7 +3153,8 @@
"tab_payments": "المدفوعات",
"tab_standards": "المعايير والأشكال",
"tab_storefront_access": "الوصول إلى المتجر",
- "title": "إعدادات المتجر"
+ "title": "إعدادات المتجر",
+ "tab_data_sources": "مصادر الأسعار والمخزون"
},
"tax_categories": {
"add_sheet_title": "إضافة فئة الضريبة",
diff --git a/packages/dashboard/src/locales/de.json b/packages/dashboard/src/locales/de.json
index 1ae1188b79..cfe61a6478 100644
--- a/packages/dashboard/src/locales/de.json
+++ b/packages/dashboard/src/locales/de.json
@@ -1577,6 +1577,34 @@
"track_price_history": {
"help": "Frühere Preise speichern, damit der Shop den niedrigsten Preis der letzten 30 Tage anzeigen kann, wie es EU-Regeln verlangen.",
"label": "Preisverlauf aufzeichnen"
+ },
+ "data_sources": {
+ "internal": "Spree (integriert)",
+ "not_connected": "Verbinden Sie diese Integration, um sie zu nutzen",
+ "pricing_provider": {
+ "label": "Preise stammen aus",
+ "help": "Spree berechnet Preise aus Ihrem Katalog und Ihren Preislisten, sofern kein externes System antwortet."
+ },
+ "inventory_provider": {
+ "label": "Bestände stammen aus",
+ "help": "Eine externe Quelle wird beim Hinzufügen zum Warenkorb und an der Kasse gefragt. Listen zeigen immer Ihre eigenen Bestände."
+ },
+ "pricing_failure_policy": {
+ "label": "Wenn Preise nicht bestätigt werden können",
+ "help": "Ein falscher Preis lässt sich schwer rückgängig machen, daher ist Ablehnen die sicherere Voreinstellung."
+ },
+ "inventory_failure_policy": {
+ "label": "Wenn Bestände nicht bestätigt werden können",
+ "help": "Ein Verkauf ohne Ware ist korrigierbar, daher hält der Rückfall Ihren Verkauf am Laufen."
+ },
+ "policies": {
+ "strict": {
+ "label": "Ablehnen und Kunden um erneuten Versuch bitten"
+ },
+ "fallback": {
+ "label": "Sprees eigene Zahlen verwenden"
+ }
+ }
}
},
"store_credit": {
@@ -1716,18 +1744,11 @@
"company": {
"name": {
"placeholder": "Acme Industries"
- },
- "external_id": {
- "help": "Ihre eigene Referenz für diese Firma, eindeutig innerhalb des Shops.",
- "placeholder": "ACME-001"
}
},
"company_location": {
"name": {
"placeholder": "Hauptsitz"
- },
- "external_id": {
- "help": "Ihre eigene Referenz für diese Niederlassung."
}
},
"company_contact": {
@@ -1875,6 +1896,9 @@
"help": "Nie weniger als der erste und nie mehr als der zweite Betrag. Jeder gilt nur für Verkäufe in seiner eigenen Währung; eine leer gelassene Währung wird unbegrenzt berechnet.",
"label": "Unter- und Obergrenze (optional)"
}
+ },
+ "external_references": {
+ "label": "Externe Referenzen"
}
},
"gift_cards": {
@@ -3115,7 +3139,8 @@
"tab_payments": "Zahlungen",
"tab_standards": "Standards und Formate",
"tab_storefront_access": "Storefront-Zugriff",
- "title": "Shop-Einstellungen"
+ "title": "Shop-Einstellungen",
+ "tab_data_sources": "Preis- und Bestandsquellen"
},
"tax_categories": {
"add_sheet_title": "Steuerkategorie hinzufügen",
diff --git a/packages/dashboard/src/locales/en.json b/packages/dashboard/src/locales/en.json
index e1d895d678..d3786702fb 100644
--- a/packages/dashboard/src/locales/en.json
+++ b/packages/dashboard/src/locales/en.json
@@ -1577,6 +1577,34 @@
"track_price_history": {
"help": "Keep past prices so the storefront can show the lowest price of the last 30 days, as EU rules require.",
"label": "Record price history"
+ },
+ "data_sources": {
+ "internal": "Spree (built in)",
+ "not_connected": "Connect this integration to use it",
+ "pricing_provider": {
+ "label": "Prices come from",
+ "help": "Spree prices from your catalog and price lists unless an external system answers instead."
+ },
+ "inventory_provider": {
+ "label": "Stock levels come from",
+ "help": "An external source is asked when an item is added to a cart and at checkout. Listings always show your own stock records."
+ },
+ "pricing_failure_policy": {
+ "label": "If prices cannot be confirmed",
+ "help": "Charging the wrong price is hard to undo, so refusing is the safer default."
+ },
+ "inventory_failure_policy": {
+ "label": "If stock cannot be confirmed",
+ "help": "Selling an item that turns out to be unavailable is recoverable, so falling back keeps you trading."
+ },
+ "policies": {
+ "strict": {
+ "label": "Refuse and ask the customer to retry"
+ },
+ "fallback": {
+ "label": "Use Spree's own figures"
+ }
+ }
}
},
"store_credit": {
@@ -1716,18 +1744,11 @@
"company": {
"name": {
"placeholder": "Acme Industries"
- },
- "external_id": {
- "help": "Your own reference for this business, unique within the store.",
- "placeholder": "ACME-001"
}
},
"company_location": {
"name": {
"placeholder": "Head office"
- },
- "external_id": {
- "help": "Your own reference for this branch."
}
},
"company_contact": {
@@ -1875,6 +1896,9 @@
"help": "Never charge less than the first, or more than the second. Each applies only to sales in its own currency; leave a currency empty to charge it unbounded.",
"label": "Floor and cap (optional)"
}
+ },
+ "external_references": {
+ "label": "External references"
}
},
"gift_cards": {
@@ -3115,7 +3139,8 @@
"tab_payments": "Payments",
"tab_standards": "Standards and formats",
"tab_storefront_access": "Storefront access",
- "title": "Store settings"
+ "title": "Store settings",
+ "tab_data_sources": "Pricing and inventory sources"
},
"tax_categories": {
"add_sheet_title": "Add tax category",
diff --git a/packages/dashboard/src/locales/fr.json b/packages/dashboard/src/locales/fr.json
index 9526cc00a6..7211f1d174 100644
--- a/packages/dashboard/src/locales/fr.json
+++ b/packages/dashboard/src/locales/fr.json
@@ -1577,6 +1577,34 @@
"track_price_history": {
"help": "Conserver les anciens prix afin d’afficher le prix le plus bas des 30 derniers jours, comme l’exige la réglementation européenne.",
"label": "Enregistrer l’historique des prix"
+ },
+ "data_sources": {
+ "internal": "Spree (intégré)",
+ "not_connected": "Connectez cette intégration pour l’utiliser",
+ "pricing_provider": {
+ "label": "Les prix proviennent de",
+ "help": "Spree calcule les prix depuis votre catalogue et vos listes de prix, sauf si un système externe répond."
+ },
+ "inventory_provider": {
+ "label": "Les stocks proviennent de",
+ "help": "Une source externe est interrogée à l’ajout au panier et au paiement. Les listes affichent toujours vos propres stocks."
+ },
+ "pricing_failure_policy": {
+ "label": "Si les prix ne peuvent être confirmés",
+ "help": "Facturer un mauvais prix se corrige difficilement : refuser est la valeur par défaut la plus sûre."
+ },
+ "inventory_failure_policy": {
+ "label": "Si les stocks ne peuvent être confirmés",
+ "help": "Vendre un article finalement indisponible se rattrape : le repli vous permet de continuer à vendre."
+ },
+ "policies": {
+ "strict": {
+ "label": "Refuser et demander au client de réessayer"
+ },
+ "fallback": {
+ "label": "Utiliser les chiffres de Spree"
+ }
+ }
}
},
"store_credit": {
@@ -1716,18 +1744,11 @@
"company": {
"name": {
"placeholder": "Acme Industries"
- },
- "external_id": {
- "help": "Votre propre référence pour cette entreprise, unique dans la boutique.",
- "placeholder": "ACME-001"
}
},
"company_location": {
"name": {
"placeholder": "Siège social"
- },
- "external_id": {
- "help": "Votre propre référence pour cet établissement."
}
},
"company_contact": {
@@ -1875,6 +1896,9 @@
"help": "Ne jamais facturer moins que le premier, ni plus que le second. Chacun ne s'applique qu'aux ventes dans sa propre devise ; une devise laissée vide est facturée sans limite.",
"label": "Plancher et plafond (facultatif)"
}
+ },
+ "external_references": {
+ "label": "Références externes"
}
},
"gift_cards": {
@@ -3115,7 +3139,8 @@
"tab_payments": "Paiements",
"tab_standards": "Normes et formats",
"tab_storefront_access": "Accès à la vitrine",
- "title": "Paramètres de la boutique"
+ "title": "Paramètres de la boutique",
+ "tab_data_sources": "Sources de prix et de stock"
},
"tax_categories": {
"add_sheet_title": "Ajouter une catégorie de taxe",
diff --git a/packages/dashboard/src/locales/pl.json b/packages/dashboard/src/locales/pl.json
index 6af814ee5a..c5d6974dcf 100644
--- a/packages/dashboard/src/locales/pl.json
+++ b/packages/dashboard/src/locales/pl.json
@@ -1593,6 +1593,34 @@
"track_price_history": {
"help": "Przechowuj poprzednie ceny, aby sklep mógł pokazać najniższą cenę z ostatnich 30 dni, zgodnie z przepisami UE.",
"label": "Zapisuj historię cen"
+ },
+ "data_sources": {
+ "internal": "Spree (wbudowane)",
+ "not_connected": "Połącz tę integrację, aby jej użyć",
+ "pricing_provider": {
+ "label": "Źródło cen",
+ "help": "Spree wylicza ceny z katalogu i cenników, chyba że odpowiada system zewnętrzny."
+ },
+ "inventory_provider": {
+ "label": "Źródło stanów magazynowych",
+ "help": "Źródło zewnętrzne jest pytane przy dodaniu do koszyka i przy zamówieniu. Listy zawsze pokazują Twoje własne stany."
+ },
+ "pricing_failure_policy": {
+ "label": "Gdy nie można potwierdzić cen",
+ "help": "Naliczenie złej ceny trudno cofnąć, dlatego bezpieczniej jest odmówić."
+ },
+ "inventory_failure_policy": {
+ "label": "Gdy nie można potwierdzić stanów",
+ "help": "Sprzedaż niedostępnego towaru da się naprawić, więc wycofanie pozwala dalej sprzedawać."
+ },
+ "policies": {
+ "strict": {
+ "label": "Odmów i poproś klienta o ponowną próbę"
+ },
+ "fallback": {
+ "label": "Użyj danych Spree"
+ }
+ }
}
},
"store_credit": {
@@ -1732,18 +1760,11 @@
"company": {
"name": {
"placeholder": "Acme Industries"
- },
- "external_id": {
- "help": "Twój własny identyfikator tej firmy, unikalny w sklepie.",
- "placeholder": "ACME-001"
}
},
"company_location": {
"name": {
"placeholder": "Siedziba główna"
- },
- "external_id": {
- "help": "Twój własny identyfikator tego oddziału."
}
},
"company_contact": {
@@ -1891,6 +1912,9 @@
"help": "Nigdy nie naliczaj mniej niż pierwsza kwota ani więcej niż druga. Każda dotyczy tylko sprzedaży w swojej walucie; waluta pozostawiona pusta jest naliczana bez ograniczeń.",
"label": "Dolna i górna granica (opcjonalnie)"
}
+ },
+ "external_references": {
+ "label": "Odniesienia zewnętrzne"
}
},
"gift_cards": {
@@ -3159,7 +3183,8 @@
"tab_payments": "Płatności",
"tab_standards": "Standardy i formaty",
"tab_storefront_access": "Dostęp do sklepu",
- "title": "Ustawienia sklepu"
+ "title": "Ustawienia sklepu",
+ "tab_data_sources": "Źródła cen i stanów magazynowych"
},
"tax_categories": {
"add_sheet_title": "Dodaj kategorię podatkową",
diff --git a/packages/dashboard/src/locales/zh-CN.json b/packages/dashboard/src/locales/zh-CN.json
index 15b4157553..7024b59466 100644
--- a/packages/dashboard/src/locales/zh-CN.json
+++ b/packages/dashboard/src/locales/zh-CN.json
@@ -1574,6 +1574,34 @@
"track_price_history": {
"help": "保留历史价格,以便店铺按欧盟规定显示最近 30 天的最低价。",
"label": "记录价格历史"
+ },
+ "data_sources": {
+ "internal": "Spree(内置)",
+ "not_connected": "连接此集成后方可使用",
+ "pricing_provider": {
+ "label": "价格来源",
+ "help": "除非有外部系统作答,否则 Spree 按您的目录和价格表定价。"
+ },
+ "inventory_provider": {
+ "label": "库存来源",
+ "help": "加入购物车和结账时会询问外部来源。列表始终显示您自己的库存记录。"
+ },
+ "pricing_failure_policy": {
+ "label": "无法确认价格时",
+ "help": "收错价格难以撤销,因此拒绝是更安全的默认设置。"
+ },
+ "inventory_failure_policy": {
+ "label": "无法确认库存时",
+ "help": "售出后发现缺货尚可补救,因此回退可让您继续交易。"
+ },
+ "policies": {
+ "strict": {
+ "label": "拒绝并请顾客重试"
+ },
+ "fallback": {
+ "label": "使用 Spree 自己的数据"
+ }
+ }
}
},
"store_credit": {
@@ -1713,18 +1741,11 @@
"company": {
"name": {
"placeholder": "Acme Industries"
- },
- "external_id": {
- "help": "您为该企业设定的编号,在本店内唯一。",
- "placeholder": "ACME-001"
}
},
"company_location": {
"name": {
"placeholder": "总部"
- },
- "external_id": {
- "help": "您为该分支机构设定的编号。"
}
},
"company_contact": {
@@ -1872,6 +1893,9 @@
"help": "收费不低于前者,也不高于后者。每项仅适用于其对应货币的销售;留空的货币将不受限制地收费。",
"label": "下限与上限(可选)"
}
+ },
+ "external_references": {
+ "label": "外部引用"
}
},
"gift_cards": {
@@ -3109,7 +3133,8 @@
"tab_payments": "支付",
"tab_standards": "标准与格式",
"tab_storefront_access": "店铺访问权限",
- "title": "店铺设置"
+ "title": "店铺设置",
+ "tab_data_sources": "价格与库存来源"
},
"tax_categories": {
"add_sheet_title": "添加税收类别",
diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/companies/$companyId.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/companies/$companyId.tsx
index 2e201bbb34..e560477a5d 100644
--- a/packages/dashboard/src/routes/_authenticated/$storeId/companies/$companyId.tsx
+++ b/packages/dashboard/src/routes/_authenticated/$storeId/companies/$companyId.tsx
@@ -18,7 +18,6 @@ import {
CardTitle,
ErrorState,
Field,
- FieldDescription,
FieldError,
FieldGroup,
FieldLabel,
@@ -96,7 +95,6 @@ function CompanyBody({ company }: { company: Company }) {
header={
<PageHeader
title={company.name}
- subtitle={company.external_id ?? undefined}
backTo="companies"
resource={{ id: company.id }}
jsonPreview={{
@@ -140,7 +138,7 @@ function CompanyProfileCard({ company, canEdit }: { company: Company; canEdit: b
})
useEffect(() => {
- form.reset({ name: company.name, external_id: company.external_id ?? '' })
+ form.reset({ name: company.name })
}, [company, form])
async function onSubmit(values: CompanyFormValues) {
@@ -176,19 +174,6 @@ function CompanyProfileCard({ company, canEdit }: { company: Company; canEdit: b
/>
<FieldError errors={[errors.name]} />
</Field>
- <Field>
- <FieldLabel htmlFor="company-external-id">
- {t('admin.fields.external_id.label')}
- </FieldLabel>
- <Input
- id="company-external-id"
- disabled={!canEdit}
- aria-invalid={!!errors.external_id || undefined}
- {...form.register('external_id')}
- />
- <FieldDescription>{t('admin.fields.company.external_id.help')}</FieldDescription>
- <FieldError errors={[errors.external_id]} />
- </Field>
{canEdit && (
<div className="flex justify-end">
{/* This card sits inside a page that is not itself a form, but
diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/companies/index.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/companies/index.tsx
index 207e910894..dcd32cdd2e 100644
--- a/packages/dashboard/src/routes/_authenticated/$storeId/companies/index.tsx
+++ b/packages/dashboard/src/routes/_authenticated/$storeId/companies/index.tsx
@@ -12,7 +12,6 @@ import {
import {
Button,
Field,
- FieldDescription,
FieldError,
FieldGroup,
FieldLabel,
@@ -192,18 +191,6 @@ function CreateCompanySheet({
/>
<FieldError errors={[errors.name]} />
</Field>
-
- <Field>
- <FieldLabel htmlFor="external_id">{t('admin.fields.external_id.label')}</FieldLabel>
- <Input
- id="external_id"
- placeholder={t('admin.fields.company.external_id.placeholder')}
- aria-invalid={!!errors.external_id || undefined}
- {...form.register('external_id')}
- />
- <FieldDescription>{t('admin.fields.company.external_id.help')}</FieldDescription>
- <FieldError errors={[errors.external_id]} />
- </Field>
</FieldGroup>
</div>
<SheetFooter>
diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/companies/locations.$locationId.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/companies/locations.$locationId.tsx
index 9ed77e2e9e..d8d27689de 100644
--- a/packages/dashboard/src/routes/_authenticated/$storeId/companies/locations.$locationId.tsx
+++ b/packages/dashboard/src/routes/_authenticated/$storeId/companies/locations.$locationId.tsx
@@ -104,7 +104,6 @@ function CompanyLocationBody({ location }: { location: CompanyLocation }) {
header={
<PageHeader
title={location.name}
- subtitle={location.external_id ?? undefined}
backTo={`companies/${location.company_id}`}
resource={{ id: location.id }}
jsonPreview={{
diff --git a/packages/dashboard/src/schemas/company.ts b/packages/dashboard/src/schemas/company.ts
index 9e7a0ba1d0..36a36893a6 100644
--- a/packages/dashboard/src/schemas/company.ts
+++ b/packages/dashboard/src/schemas/company.ts
@@ -10,17 +10,15 @@ import { z } from 'zod/v4'
export const companyFormSchema = z.object({
name: z.string().min(1, { error: requiredMessage('name') }),
- external_id: z.string().optional(),
})
export type CompanyFormValues = z.infer<typeof companyFormSchema>
-export const COMPANY_DEFAULTS: CompanyFormValues = { name: '', external_id: '' }
+export const COMPANY_DEFAULTS: CompanyFormValues = { name: '' }
export function companyValuesToParams(values: CompanyFormValues): CompanyParams {
return {
name: values.name,
- external_id: blankToNull(values.external_id),
}
}
@@ -39,7 +37,6 @@ const addressSchema = z.object({
export const companyLocationFormSchema = z.object({
name: z.string().min(1, { error: requiredMessage('name') }),
- external_id: z.string().optional(),
billing_address: addressSchema,
// Kept separate from billing rather than merged on submit, so a branch that
// ships somewhere other than it is invoiced stays expressible.
@@ -66,7 +63,6 @@ const EMPTY_ADDRESS = {
export const COMPANY_LOCATION_DEFAULTS: CompanyLocationFormValues = {
name: '',
- external_id: '',
billing_address: { ...EMPTY_ADDRESS },
shipping_address: { ...EMPTY_ADDRESS },
shipping_same_as_billing: true,
@@ -80,7 +76,6 @@ export function companyLocationValuesToParams(
return {
name: values.name,
- external_id: blankToNull(values.external_id),
// A branch may have no address at all, but an address that exists must be
// complete — so an untouched fieldset is omitted rather than sent empty,
// which would fail the address record's own validations.
diff --git a/packages/dashboard/src/tables/companies.tsx b/packages/dashboard/src/tables/companies.tsx
index 76e2c483a6..da27313614 100644
--- a/packages/dashboard/src/tables/companies.tsx
+++ b/packages/dashboard/src/tables/companies.tsx
@@ -36,12 +36,13 @@ defineTable<Company>('companies', {
render: (company) => company.locations_count,
},
{
- key: 'external_id',
- label: i18n.t('admin.fields.external_id.label'),
- sortable: true,
+ // Off by default: only a merchant reconciling against an ERP or PIM
+ // wants a column of foreign keys, and they can switch it on.
+ key: 'external_references',
+ label: i18n.t('admin.fields.external_references.label'),
filterable: true,
- default: true,
- render: (company) => company.external_id ?? '—',
+ default: false,
+ render: (company) => Object.values(company.external_references ?? {}).join(', ') || '—',
},
{
key: 'created_at',
diff --git a/spree/api/app/controllers/concerns/spree/api/v3/admin/product_listing.rb b/spree/api/app/controllers/concerns/spree/api/v3/admin/product_listing.rb
index 3f75c82830..5cce7bc965 100644
--- a/spree/api/app/controllers/concerns/spree/api/v3/admin/product_listing.rb
+++ b/spree/api/app/controllers/concerns/spree/api/v3/admin/product_listing.rb
@@ -32,6 +32,7 @@ module Spree
[
:tax_category,
:product_type,
+ :external_references,
{ product_publications: :channel },
{ primary_media: [attachment_attachment: :blob, poster_attachment: :blob] },
{ default_variant: [:prices, { stock_levels: [:stock_location, :active_stock_reservations] }] },
diff --git a/spree/api/app/controllers/spree/api/v3/admin/categories_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/categories_controller.rb
index 5736b6d2b4..8764ee5d68 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/categories_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/categories_controller.rb
@@ -9,6 +9,7 @@ module Spree
# collection-bound attributes (automatic, sort_order, rules) are
# readable or writable here.
class CategoriesController < ResourceController
+ include Spree::Api::V3::Admin::Concerns::ExternalReferences
scoped_resource :categories
# PATCH /api/v3/admin/categories/:id/reposition
diff --git a/spree/api/app/controllers/spree/api/v3/admin/companies/locations_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/companies/locations_controller.rb
index 75f22e0034..79e0742764 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/companies/locations_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/companies/locations_controller.rb
@@ -7,6 +7,7 @@ module Spree
# deleting a branch are addressed directly, since a caller holding a
# branch id shouldn't have to know its company.
class LocationsController < BaseController
+ include Spree::Api::V3::Admin::Concerns::ExternalReferences
include Spree::Api::V3::Admin::Concerns::CompanyLocationParams
before_action :authorize_parent_access!
diff --git a/spree/api/app/controllers/spree/api/v3/admin/companies_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/companies_controller.rb
index 33d3e05882..4d81f308e0 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/companies_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/companies_controller.rb
@@ -5,6 +5,7 @@ module Spree
# Business customers. A company is a customer record, so it answers to
# the customer scopes rather than earning one of its own.
class CompaniesController < ResourceController
+ include Spree::Api::V3::Admin::Concerns::ExternalReferences
scoped_resource :customers
protected
@@ -22,11 +23,11 @@ module Spree
end
def collection_includes
- [:company_locations]
+ [:company_locations, :external_references]
end
def permitted_params
- params.permit(*model_additional_permitted_attributes, :name, :external_id, metadata: {})
+ params.permit(*model_additional_permitted_attributes, :name, metadata: {})
end
end
end
diff --git a/spree/api/app/controllers/spree/api/v3/admin/company_locations_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/company_locations_controller.rb
index 239d42d769..6bac71d2d1 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/company_locations_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/company_locations_controller.rb
@@ -5,6 +5,7 @@ module Spree
# A branch addressed directly. Reached through the store's companies so a
# branch of another tenant's company is a 404.
class CompanyLocationsController < ResourceController
+ include Spree::Api::V3::Admin::Concerns::ExternalReferences
include Spree::Api::V3::Admin::Concerns::CompanyLocationParams
scoped_resource :customers
diff --git a/spree/api/app/controllers/spree/api/v3/admin/concerns/company_location_params.rb b/spree/api/app/controllers/spree/api/v3/admin/concerns/company_location_params.rb
index 66ce4057ce..f09eafad56 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/concerns/company_location_params.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/concerns/company_location_params.rb
@@ -19,7 +19,7 @@ module Spree
def permitted_params
params.permit(
- :name, :external_id,
+ :name,
metadata: {},
billing_address: ADDRESS_KEYS,
shipping_address: ADDRESS_KEYS
diff --git a/spree/api/app/controllers/spree/api/v3/admin/concerns/external_references.rb b/spree/api/app/controllers/spree/api/v3/admin/concerns/external_references.rb
new file mode 100644
index 0000000000..90edd06d3f
--- /dev/null
+++ b/spree/api/app/controllers/spree/api/v3/admin/concerns/external_references.rb
@@ -0,0 +1,161 @@
+module Spree
+ module Api
+ module V3
+ module Admin
+ module Concerns
+ # Lets a connector address records by the identity its own system
+ # knows, rather than by Spree's prefixed id.
+ #
+ # Two halves:
+ #
+ # * **write** — `external_references` in the payload records the
+ # caller's key for the record it just wrote. Systems the payload
+ # does not mention keep their references, so a PIM sync never
+ # erases the ERP's key.
+ # * **read** — a member path may carry `external:<system>:<id>` in
+ # place of the prefixed id, so a connector that only ever learned
+ # the ERP's key can read, update and delete without first asking
+ # Spree for its id.
+ #
+ # A create carrying an `external_references` entry that already
+ # matches a record **updates that record** instead of failing on the
+ # unique index — the upsert a nightly feed needs, since a feed cannot
+ # know whether Spree has seen a row before.
+ #
+ # The write hangs off +serialize_resource+ rather than overriding
+ # +create+/+update+: several admin controllers implement those
+ # themselves (products and orders route through workflows), and every
+ # one of them reaches serialization with the saved record. Rendering
+ # is the one place they all agree on.
+ module ExternalReferences
+ extend ActiveSupport::Concern
+
+ included do
+ before_action :update_instead_when_external_id_known, only: :create
+ end
+
+ protected
+
+ # A create whose payload names an external id Spree already knows
+ # becomes an update of that record. Without this a re-run of the
+ # same feed 422s on the unique index — after persisting a duplicate
+ # on controllers whose +create+ builds through a workflow rather
+ # than +build_resource+ — which reads to a connector author as "the
+ # sync is broken" rather than "already imported".
+ #
+ # A before_action rather than a +build_resource+ override because
+ # products and orders create through workflows and never call
+ # +build_resource+; rendering from here halts the action, so every
+ # controller's +create+ gets the same upsert.
+ #
+ # Dispatches into the controller's own +update+, which is the only
+ # action that knows how to write that resource (orders update
+ # through a service, products through a workflow).
+ #
+ # A controller whose two actions permit different keys would
+ # silently drop a payload key the update action does not name.
+ # +normalize_upsert_params!+ is where such a controller reconciles
+ # them, and where one prepares state its update path expects; the
+ # default is a no-op.
+ def update_instead_when_external_id_known
+ existing = find_by_external_reference_params
+ return if existing.blank?
+
+ @resource = existing
+ authorize_resource!(@resource, :update)
+ normalize_upsert_params!
+ update
+ end
+
+ # Rewrites create-shaped keys into the ones this controller's
+ # +update+ accepts. A no-op unless the two actions disagree.
+ def normalize_upsert_params!; end
+
+ # `external_references` lives in its own table, so it must not
+ # reach the model's attribute writer.
+ def permitted_params
+ super.except(:external_references)
+ end
+
+ # Accepts both the `{ system => external_id }` map the serializer
+ # renders — so a client can send back exactly what it read — and
+ # the `[{ system:, external_id: }]` list a feed finds natural.
+ def external_reference_params
+ return @external_reference_params if defined?(@external_reference_params)
+
+ raw = params[:external_references]
+ return @external_reference_params = [] if raw.blank?
+
+ raw = raw.to_unsafe_h if raw.respond_to?(:to_unsafe_h)
+ entries =
+ if raw.is_a?(Hash) && !raw.key?(:system) && !raw.key?('system')
+ raw.map { |system, external_id| { system: system, external_id: external_id } }
+ else
+ Array(raw).map { |entry| entry.respond_to?(:to_unsafe_h) ? entry.to_unsafe_h : entry.to_h }
+ end
+
+ @external_reference_params = entries.filter_map do |entry|
+ entry = entry.to_h.symbolize_keys.slice(:system, :external_id)
+ next if entry[:system].blank?
+
+ entry
+ end
+ end
+
+ # A member path may address the record by an external identity
+ # instead of its prefixed id, written `external:<system>:<id>` —
+ # e.g. `/admin/products/external:erp:MAT-100`. A connector that
+ # only ever learned the ERP's key can then read, update and delete
+ # without first querying Spree for its id.
+ #
+ # It resolves through the controller's own +scope+, so store
+ # scoping and authorization are exactly as they are for a prefixed
+ # id, and a key belonging to another store is a 404.
+ EXTERNAL_ID_PREFIX = 'external:'.freeze
+
+ def find_resource
+ return super unless external_id_lookup?
+
+ _prefix, system, external_id = params[:id].split(':', 3)
+ scope.find_by_external_id!(system, external_id)
+ end
+
+ def external_id_lookup?
+ params[:id].to_s.start_with?(EXTERNAL_ID_PREFIX) &&
+ model_class.respond_to?(:find_by_external_id) &&
+ params[:id].to_s.split(':', 3).length == 3
+ end
+
+ def find_by_external_reference_params
+ return if external_reference_params.blank?
+ return unless model_class.respond_to?(:find_by_external_id)
+
+ external_reference_params.each do |entry|
+ match = scope.find_by_external_id(entry[:system], entry[:external_id])
+ return match if match.present?
+ end
+
+ nil
+ end
+
+ def serialize_resource(resource, **options)
+ write_external_references(resource)
+ super
+ end
+
+ def write_external_references(resource)
+ # Cheapest guard first: a GET must not even parse the params.
+ return unless request.post? || request.patch? || request.put?
+ return if external_reference_params.blank?
+ return unless resource.respond_to?(:assign_external_references)
+ return unless resource.persisted?
+
+ resource.assign_external_references(external_reference_params)
+ resource.external_references.reload
+ end
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/spree/api/app/controllers/spree/api/v3/admin/orders_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/orders_controller.rb
index 72b3fc0699..a77da59cdb 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/orders_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/orders_controller.rb
@@ -3,6 +3,7 @@ module Spree
module V3
module Admin
class OrdersController < ResourceController
+ include Spree::Api::V3::Admin::Concerns::ExternalReferences
include Spree::Api::V3::OrderLock
scoped_resource :orders
@@ -120,8 +121,12 @@ module Spree
base.where(cart_id: nil).or(base.where.not(status: 'draft'))
end
+ # Through find_resource, not find_by_prefix_id! directly, so the
+ # external:<system>:<id> addressing the concern provides reaches
+ # orders — an ERP that pushed its order number wants to read the
+ # order back by it.
def set_resource
- @resource = scope.find_by_prefix_id!(params[:id])
+ @resource = find_resource
@order = @resource # needed for OrderLock
authorize_resource!(@resource)
end
@@ -141,7 +146,7 @@ module Spree
# expanded list renders the whole profile; order_group is not, since
# only its id is reported and that comes off the order's own column.
def collection_includes
- [:line_items, :customer, :channel, :seller]
+ [:line_items, :customer, :channel, :seller, :external_references]
end
private
@@ -155,6 +160,15 @@ module Spree
find_by_prefix_id!(customer_param)
end
+ # An upsert arrives on the create action, so addresses come in under
+ # the create names. Translate them to the ones update accepts, or a
+ # replayed feed row would silently lose the address it sent.
+ def normalize_upsert_params!
+ # update runs under with_order_lock, which reads @order — normally
+ # set by set_resource, which the create path never runs.
+ @order = @resource
+ end
+
def order_create_params
normalize_params(
params.permit(
diff --git a/spree/api/app/controllers/spree/api/v3/admin/products_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/products_controller.rb
index 5cefff99e6..d4f4dcb9ff 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/products_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/products_controller.rb
@@ -3,6 +3,7 @@ module Spree
module V3
module Admin
class ProductsController < ResourceController
+ include Spree::Api::V3::Admin::Concerns::ExternalReferences
include Spree::Api::V3::BulkOperations
include Spree::Api::V3::Admin::ProductListing
diff --git a/spree/api/app/controllers/spree/api/v3/admin/stock_locations_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/stock_locations_controller.rb
index 72d902ddb6..8f8d73a0f7 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/stock_locations_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/stock_locations_controller.rb
@@ -3,6 +3,7 @@ module Spree
module V3
module Admin
class StockLocationsController < ResourceController
+ include Spree::Api::V3::Admin::Concerns::ExternalReferences
scoped_resource :stock
protected
diff --git a/spree/api/app/controllers/spree/api/v3/admin/variants_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/variants_controller.rb
index e1fb8a2269..9e5495468c 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/variants_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/variants_controller.rb
@@ -3,6 +3,7 @@ module Spree
module V3
module Admin
class VariantsController < ResourceController
+ include Spree::Api::V3::Admin::Concerns::ExternalReferences
scoped_resource :products
protected
diff --git a/spree/api/app/serializers/spree/api/v3/admin/category_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/category_serializer.rb
index 3da5d1d1ec..53ab756406 100644
--- a/spree/api/app/serializers/spree/api/v3/admin/category_serializer.rb
+++ b/spree/api/app/serializers/spree/api/v3/admin/category_serializer.rb
@@ -5,6 +5,8 @@ module Spree
# Admin API Category Serializer
# Full category data including admin-only fields
class CategorySerializer < V3::CategorySerializer
+ include Concerns::ExternalReferencesAttribute
+
include Spree::Api::V3::Admin::Translatable
typelize pretty_name: :string, lft: :number, rgt: :number, products_count: :number,
diff --git a/spree/api/app/serializers/spree/api/v3/admin/company_location_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/company_location_serializer.rb
index 8961593826..6c423c458d 100644
--- a/spree/api/app/serializers/spree/api/v3/admin/company_location_serializer.rb
+++ b/spree/api/app/serializers/spree/api/v3/admin/company_location_serializer.rb
@@ -8,11 +8,13 @@ module Spree
# emits one TS type per serializer, and an abstract one would reach the
# admin SDK without any endpoint returning it.
class CompanyLocationSerializer < V3::BaseSerializer
- typelize name: :string, external_id: [:string, nullable: true],
+ include Concerns::ExternalReferencesAttribute
+
+ typelize name: :string,
company_id: :string, contacts_count: :number,
metadata: 'Record<string, unknown> | null'
- attributes :name, :external_id, :metadata,
+ attributes :name, :metadata,
created_at: :iso8601, updated_at: :iso8601
# A branch always belongs to a company, so this is never null.
diff --git a/spree/api/app/serializers/spree/api/v3/admin/company_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/company_serializer.rb
index 6a444e75b6..cab8a6a9e5 100644
--- a/spree/api/app/serializers/spree/api/v3/admin/company_serializer.rb
+++ b/spree/api/app/serializers/spree/api/v3/admin/company_serializer.rb
@@ -3,6 +3,8 @@ module Spree
module V3
module Admin
class CompanySerializer < V3::CompanySerializer
+ include Concerns::ExternalReferencesAttribute
+
typelize locations_count: :number, metadata: 'Record<string, unknown> | null'
attributes :metadata, created_at: :iso8601, updated_at: :iso8601
diff --git a/spree/api/app/serializers/spree/api/v3/admin/concerns/external_references_attribute.rb b/spree/api/app/serializers/spree/api/v3/admin/concerns/external_references_attribute.rb
new file mode 100644
index 0000000000..ebb8d4924c
--- /dev/null
+++ b/spree/api/app/serializers/spree/api/v3/admin/concerns/external_references_attribute.rb
@@ -0,0 +1,33 @@
+module Spree
+ module Api
+ module V3
+ module Admin
+ module Concerns
+ # Renders a record's identities in external systems as a flat
+ # `{ system => external_id }` map — the shape a connector reads, and
+ # the same shape the controllers accept on write.
+ #
+ # Admin-only: which ERP a merchant runs, and under what key a product
+ # lives there, is back-office information.
+ #
+ # Named for the attribute rather than the feature because the
+ # controller concern of the obvious name already sits in the sibling
+ # controller namespace, and Alba resolves the shorter constant to it.
+ module ExternalReferencesAttribute
+ def self.included(base)
+ base.class_eval do
+ typelize external_references: 'Record<string, string>'
+
+ attribute :external_references do |resource|
+ resource.external_references.each_with_object({}) do |reference, result|
+ result[reference.system] = reference.external_id
+ end
+ end
+ end
+ end
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/spree/api/app/serializers/spree/api/v3/admin/order_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/order_serializer.rb
index 47089bd1bc..128d815aea 100644
--- a/spree/api/app/serializers/spree/api/v3/admin/order_serializer.rb
+++ b/spree/api/app/serializers/spree/api/v3/admin/order_serializer.rb
@@ -5,6 +5,8 @@ module Spree
# Admin API Order Serializer
# Full order data including admin-only fields
class OrderSerializer < V3::OrderSerializer
+ include Concerns::ExternalReferencesAttribute
+
typelize company_location_id: [:string, nullable: true],
company_id: [:string, nullable: true],
diff --git a/spree/api/app/serializers/spree/api/v3/admin/product_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/product_serializer.rb
index c84d5d2dc1..8491d84ed5 100644
--- a/spree/api/app/serializers/spree/api/v3/admin/product_serializer.rb
+++ b/spree/api/app/serializers/spree/api/v3/admin/product_serializer.rb
@@ -6,6 +6,8 @@ module Spree
# Full product data including admin-only fields
# Extends the store serializer with additional attributes
class ProductSerializer < V3::ProductSerializer
+ include Concerns::ExternalReferencesAttribute
+
include Spree::Api::V3::Admin::Translatable
typelize status: :string,
diff --git a/spree/api/app/serializers/spree/api/v3/admin/stock_level_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/stock_level_serializer.rb
index 0fc6b0f5f7..e54a2b477d 100644
--- a/spree/api/app/serializers/spree/api/v3/admin/stock_level_serializer.rb
+++ b/spree/api/app/serializers/spree/api/v3/admin/stock_level_serializer.rb
@@ -3,6 +3,8 @@ module Spree
module V3
module Admin
class StockLevelSerializer < V3::StockLevelSerializer
+ include Concerns::ExternalReferencesAttribute
+
typelize metadata: 'Record<string, unknown>',
allocated_count: :number, available_count: :number
diff --git a/spree/api/app/serializers/spree/api/v3/admin/stock_location_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/stock_location_serializer.rb
index fd395b3b14..9e5a943ffc 100644
--- a/spree/api/app/serializers/spree/api/v3/admin/stock_location_serializer.rb
+++ b/spree/api/app/serializers/spree/api/v3/admin/stock_location_serializer.rb
@@ -3,6 +3,8 @@ module Spree
module V3
module Admin
class StockLocationSerializer < V3::StockLocationSerializer
+ include Concerns::ExternalReferencesAttribute
+
typelize active: :boolean, default: :boolean, backorderable_default: :boolean,
propagate_all_variants: :boolean, pickup_enabled: :boolean,
admin_name: [:string, nullable: true],
diff --git a/spree/api/app/serializers/spree/api/v3/admin/variant_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/variant_serializer.rb
index 3951379c7f..1176c6d30e 100644
--- a/spree/api/app/serializers/spree/api/v3/admin/variant_serializer.rb
+++ b/spree/api/app/serializers/spree/api/v3/admin/variant_serializer.rb
@@ -5,6 +5,8 @@ module Spree
# Admin API Variant Serializer
# Full variant data including admin-only fields
class VariantSerializer < V3::VariantSerializer
+ include Concerns::ExternalReferencesAttribute
+
typelize product_name: :string,
position: :number, tax_category_id: [:string, nullable: true],
diff --git a/spree/api/app/serializers/spree/api/v3/company_serializer.rb b/spree/api/app/serializers/spree/api/v3/company_serializer.rb
index 187b585f49..d6a508081e 100644
--- a/spree/api/app/serializers/spree/api/v3/company_serializer.rb
+++ b/spree/api/app/serializers/spree/api/v3/company_serializer.rb
@@ -6,9 +6,9 @@ module Spree
# ExportSerializer sit in this namespace. The admin serializer extends it
# so back-office fields stay in one place.
class CompanySerializer < BaseSerializer
- typelize name: :string, external_id: [:string, nullable: true]
+ typelize name: :string
- attributes :name, :external_id
+ attributes :name
end
end
end
diff --git a/spree/api/config/routes.rb b/spree/api/config/routes.rb
index 67f9875c49..0003cfc31c 100644
--- a/spree/api/config/routes.rb
+++ b/spree/api/config/routes.rb
@@ -202,7 +202,9 @@ Spree::Core::Engine.add_routes do
patch 'me', to: 'me#update'
# Store Settings
- resource :store, only: [:show, :update], controller: 'store'
+ resource :store, only: [:show, :update], controller: 'store' do
+ get :data_sources
+ end
# Staff & access (invitations, admin users, roles, API keys)
resources :admin_users, only: [:index, :show, :update, :destroy]
@@ -351,7 +353,11 @@ Spree::Core::Engine.add_routes do
# Inventory
resources :stock_locations
resources :stock_reservations, only: [:index, :show]
- resources :stock_levels, only: [:index, :show, :update, :destroy]
+ resources :stock_levels, only: [:index, :show, :update, :destroy] do
+ collection do
+ post :bulk_upsert
+ end
+ end
resources :stock_movements, only: [:index, :show]
resources :stock_transfers, only: [:index, :show, :create, :destroy]
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/companies_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/companies_controller_spec.rb
index 7508c47f87..489fe7fa36 100644
--- a/spree/api/spec/controllers/spree/api/v3/admin/companies_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/admin/companies_controller_spec.rb
@@ -5,7 +5,9 @@ RSpec.describe Spree::Api::V3::Admin::CompaniesController, type: :controller do
include_context 'API v3 Admin authenticated'
- let!(:company) { create(:company, store: store, name: 'Acme Industrial', external_id: 'ACME-1') }
+ let!(:company) do
+ create(:company, store: store, name: 'Acme Industrial').tap { |record| record.set_external_id('erp', 'ACME-1') }
+ end
before { request.headers.merge!(headers) }
@@ -17,7 +19,7 @@ RSpec.describe Spree::Api::V3::Admin::CompaniesController, type: :controller do
row = json_response['data'].first
expect(row['id']).to start_with('comp_')
expect(row['name']).to eq('Acme Industrial')
- expect(row['external_id']).to eq('ACME-1')
+ expect(row['external_references']).to eq('erp' => 'ACME-1')
end
it 'hides companies belonging to another store' do
@@ -57,21 +59,32 @@ RSpec.describe Spree::Api::V3::Admin::CompaniesController, type: :controller do
describe 'POST #create' do
it 'creates a company bound to the current store' do
- post :create, params: { name: 'Globex', external_id: 'GLBX' }, as: :json
+ post :create, params: { name: 'Globex' }, as: :json
expect(response).to have_http_status(:created)
expect(json_response['name']).to eq('Globex')
expect(Spree::Company.find_by(name: 'Globex').store).to eq(store)
end
- it 'rejects a duplicate reference with a validation error, not a crash' do
- post :create, params: { name: 'Acme Again', external_id: 'ACME-1' }, as: :json
+ it 'records the external identity the connector sent' do
+ post :create, params: { name: 'Globex', external_references: [{ system: 'erp', external_id: 'GLBX' }] }, as: :json
- expect(response).to have_http_status(:unprocessable_content)
+ expect(response).to have_http_status(:created)
+ expect(json_response['external_references']).to eq('erp' => 'GLBX')
+ expect(Spree::Company.find_by(name: 'Globex').external_id_for('erp')).to eq('GLBX')
+ end
+
+ it 'updates the existing record when the external id is already known' do
+ expect do
+ post :create, params: { name: 'Acme Renamed', external_references: [{ system: 'erp', external_id: 'ACME-1' }] },
+ as: :json
+ end.not_to change(Spree::Company, :count)
+
+ expect(company.reload.name).to eq('Acme Renamed')
end
it 'rejects a company with no name' do
- post :create, params: { external_id: 'X' }, as: :json
+ post :create, params: {}, as: :json
expect(response).to have_http_status(:unprocessable_content)
end
@@ -84,6 +97,33 @@ RSpec.describe Spree::Api::V3::Admin::CompaniesController, type: :controller do
expect(response).to have_http_status(:ok)
expect(company.reload.name).to eq('Acme Global')
end
+
+ it 'addresses the company by the identity the external system knows' do
+ patch :update, params: { id: 'external:erp:ACME-1', name: 'Acme Via ERP' }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(company.reload.name).to eq('Acme Via ERP')
+ end
+
+ it 'leaves other systems alone when one connector writes its key' do
+ company.set_external_id('crm', 'CUST-9')
+
+ patch :update, params: { id: company.prefixed_id,
+ external_references: [{ system: 'erp', external_id: 'ACME-2' }] }, as: :json
+
+ expect(company.reload.external_id_for('erp')).to eq('ACME-2')
+ expect(company.external_id_for('crm')).to eq('CUST-9')
+ end
+
+ it 'does not reach a company in another store through its external id' do
+ other = create(:company, store: create(:store))
+ other.set_external_id('erp', 'OTHER-1')
+
+ patch :update, params: { id: 'external:erp:OTHER-1', name: 'Hijacked' }, as: :json
+
+ expect(response).to have_http_status(:not_found)
+ expect(other.reload.name).not_to eq('Hijacked')
+ end
end
describe 'DELETE #destroy' do
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/external_references_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/external_references_spec.rb
new file mode 100644
index 0000000000..b67c19b4ac
--- /dev/null
+++ b/spree/api/spec/controllers/spree/api/v3/admin/external_references_spec.rb
@@ -0,0 +1,189 @@
+require 'spec_helper'
+
+# The external-reference behaviour is one concern shared by every connector-facing
+# admin controller, so it is proved once here against two controllers that reach
+# persistence very differently: products write through a workflow, stock locations
+# through the plain resource controller. A regression in either shape shows up here.
+RSpec.describe 'Admin API external references', type: :controller do
+ render_views
+
+ include_context 'API v3 Admin authenticated'
+
+ before { request.headers.merge!(headers) }
+
+ describe Spree::Api::V3::Admin::ProductsController do
+ let!(:product) { create(:product, store: store, name: 'Widget') }
+
+ it 'records the identity a connector sends when creating' do
+ post :create, params: { name: 'Synced Widget',
+ external_references: [{ system: 'pim', external_id: 'SKU-1' }] }, as: :json
+
+ expect(response).to have_http_status(:created)
+ expect(json_response['external_references']).to eq('pim' => 'SKU-1')
+ end
+
+ # Products create through a workflow, not build_resource — the path where
+ # a re-sent feed row used to persist a duplicate and then 422 writing the
+ # reference.
+ it 'updates the existing product when the feed re-sends a known key' do
+ product.set_external_id('pim', 'SKU-1')
+
+ expect do
+ post :create, params: { name: 'Widget Renamed',
+ external_references: [{ system: 'pim', external_id: 'SKU-1' }] }, as: :json
+ end.not_to change(Spree::Product, :count)
+
+ expect(response).to have_http_status(:ok)
+ expect(product.reload.name).to eq('Widget Renamed')
+ end
+
+ it 'keeps one product identifiable in two systems at once' do
+ product.set_external_id('pim', 'SKU-1')
+
+ patch :update, params: { id: product.prefixed_id,
+ external_references: [{ system: 'erp', external_id: 'MAT-100' }] }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(json_response['external_references']).to eq('pim' => 'SKU-1', 'erp' => 'MAT-100')
+ end
+
+ # Read and write shapes match: a client can PATCH back exactly what it read.
+ it 'accepts the same map shape it renders' do
+ patch :update, params: { id: product.prefixed_id,
+ external_references: { erp: 'MAT-100', pim: 'SKU-1' } }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(json_response['external_references']).to eq('erp' => 'MAT-100', 'pim' => 'SKU-1')
+ end
+
+ it 'addresses a product by its external identity' do
+ product.set_external_id('erp', 'MAT-100')
+
+ patch :update, params: { id: 'external:erp:MAT-100', name: 'Renamed By ERP' }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(product.reload.name).to eq('Renamed By ERP')
+ end
+
+ it 'does not reach a product in another store through its external id' do
+ elsewhere = create(:product, store: create(:store))
+ elsewhere.set_external_id('erp', 'MAT-999')
+
+ patch :update, params: { id: 'external:erp:MAT-999', name: 'Hijacked' }, as: :json
+
+ expect(response).to have_http_status(:not_found)
+ expect(elsewhere.reload.name).not_to eq('Hijacked')
+ end
+
+ it 'still resolves a prefixed id when no external identity is used' do
+ patch :update, params: { id: product.prefixed_id, name: 'Renamed Normally' }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(product.reload.name).to eq('Renamed Normally')
+ end
+ end
+
+ describe Spree::Api::V3::Admin::StockLocationsController do
+ let!(:stock_location) { create(:stock_location, store: store, name: 'Main') }
+
+ it 'upserts rather than duplicating when the feed re-sends a known id' do
+ stock_location.set_external_id('erp', 'WH-1')
+
+ expect do
+ post :create, params: { name: 'Main Renamed',
+ external_references: [{ system: 'erp', external_id: 'WH-1' }] }, as: :json
+ end.not_to change(Spree::StockLocation, :count)
+
+ expect(stock_location.reload.name).to eq('Main Renamed')
+ end
+
+ it 'creates a new record when the external id is unknown' do
+ expect do
+ post :create, params: { name: 'Second Warehouse',
+ external_references: [{ system: 'erp', external_id: 'WH-2' }] }, as: :json
+ end.to change(Spree::StockLocation, :count).by(1)
+
+ expect(Spree::StockLocation.find_by_external_id('erp', 'WH-2')).to be_present
+ end
+
+ it 'does not treat another store external id as a match, so the feed creates its own row' do
+ other_store = create(:store)
+ create(:stock_location, store: other_store).set_external_id('erp', 'WH-9')
+
+ expect do
+ post :create, params: { name: 'Ours', external_references: [{ system: 'erp', external_id: 'WH-9' }] }, as: :json
+ end.to change { store.stock_locations.count }.by(1)
+
+ expect(store.stock_locations.find_by_external_id('erp', 'WH-9').name).to eq('Ours')
+ end
+ end
+end
+
+RSpec.describe Spree::Api::V3::Admin::OrdersController, type: :controller do
+ render_views
+
+ include_context 'API v3 Admin authenticated'
+
+ before { request.headers.merge!(headers) }
+
+ # An ERP that pushed its own order number wants to read the order back by
+ # it; OrdersController resolves its resource itself, so this proves the
+ # external addressing survives that override.
+ it 'reaches an order by the number an external system pushed onto it' do
+ order = create(:completed_order_with_totals, store: store)
+ order.set_external_id('erp', 'SO-8812')
+
+ get :show, params: { id: 'external:erp:SO-8812' }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(json_response['id']).to eq(order.prefixed_id)
+ end
+end
+
+RSpec.describe Spree::Api::V3::Admin::OrdersController, 'upsert by external id', type: :controller do
+ render_views
+
+ include_context 'API v3 Admin authenticated'
+
+ before { request.headers.merge!(headers) }
+
+ # A replayed feed row must keep the address it sent rather than having it
+ # dropped on the way through the update action. Create and update now name
+ # addresses identically, so this guards against them diverging again.
+ it 'keeps an address the create payload names when the feed replays a known key' do
+ order = create(:order, store: store)
+ order.set_external_id('erp', 'SO-1')
+
+ expect do
+ post :create, params: {
+ email: '[email protected]',
+ shipping_address: { firstname: 'Ada', lastname: 'Lovelace', address1: '1 Main St',
+ city: 'New York', zipcode: '10001', phone: '555-0100',
+ country_code: 'US', state_code: 'NY' },
+ external_references: [{ system: 'erp', external_id: 'SO-1' }]
+ }, as: :json
+ end.not_to change(Spree::Order, :count)
+
+ expect(response).to have_http_status(:ok)
+ expect(order.reload.email).to eq('[email protected]')
+ expect(order.ship_address&.address1).to eq('1 Main St')
+ end
+end
+
+RSpec.describe Spree::Api::V3::Admin::CompanyLocationsController, type: :controller do
+ render_views
+
+ include_context 'API v3 Admin authenticated'
+
+ before { request.headers.merge!(headers) }
+
+ it 'records the identity a connector sends for a branch' do
+ location = create(:company_location, company: create(:company, store: store))
+
+ patch :update, params: { id: location.prefixed_id,
+ external_references: { crm: 'LOC-1' } }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(location.reload.external_id_for('crm')).to eq('LOC-1')
+ end
+end
diff --git a/spree/api/spec/integration/spree/api/v3/admin/companies_spec.rb b/spree/api/spec/integration/spree/api/v3/admin/companies_spec.rb
index 553924c22c..e16c531208 100644
--- a/spree/api/spec/integration/spree/api/v3/admin/companies_spec.rb
+++ b/spree/api/spec/integration/spree/api/v3/admin/companies_spec.rb
@@ -7,7 +7,9 @@ RSpec.describe 'Admin Companies API', type: :request, swagger_doc: 'api-referenc
let(:Authorization) { "Bearer #{admin_jwt_token}" }
- let!(:company) { create(:company, store: store, name: 'Acme Industrial', external_id: 'ACME-1') }
+ let!(:company) do
+ create(:company, store: store, name: 'Acme Industrial').tap { |record| record.set_external_id('erp', 'ACME-1') }
+ end
path '/api/v3/admin/companies' do
get 'List companies' do
@@ -48,9 +50,20 @@ RSpec.describe 'Admin Companies API', type: :request, swagger_doc: 'api-referenc
type: :object,
properties: {
name: { type: :string, example: 'Globex Corporation' },
- external_id: { type: :string, nullable: true,
- description: 'Your own reference for this business, unique within the store.',
- example: 'GLBX-42' }
+ external_references: {
+ type: :array,
+ description: 'Identities this business has in your own systems. A system you do ' \
+ 'not name keeps the reference it already has, and creating with a ' \
+ 'reference that already exists updates that business instead.',
+ items: {
+ type: :object,
+ properties: {
+ system: { type: :string, example: 'erp' },
+ external_id: { type: :string, example: 'GLBX-42' }
+ },
+ required: %w[system external_id]
+ }
+ }
},
required: ['name']
}
@@ -58,7 +71,9 @@ RSpec.describe 'Admin Companies API', type: :request, swagger_doc: 'api-referenc
let(:'x-spree-api-key') { secret_api_key.plaintext_token }
response '201', 'company created' do
- let(:body) { { name: 'Globex Corporation', external_id: 'GLBX-42' } }
+ let(:body) do
+ { name: 'Globex Corporation', external_references: [{ system: 'erp', external_id: 'GLBX-42' }] }
+ end
run_test! do |response|
expect(JSON.parse(response.body)['name']).to eq('Globex Corporation')
@@ -66,7 +81,7 @@ RSpec.describe 'Admin Companies API', type: :request, swagger_doc: 'api-referenc
end
response '422', 'invalid request' do
- let(:body) { { external_id: 'NO-NAME' } }
+ let(:body) { { external_references: [{ system: 'erp', external_id: 'NO-NAME' }] } }
run_test!
end