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.

Added market, currency and locale selection to new draft orders (#14937)

Damian Legawiec90f8f59209db
diff --git a/.changeset/draft-order-sales-context.md b/.changeset/draft-order-sales-context.md
new file mode 100644
index 0000000000..cc07208955
--- /dev/null
+++ b/.changeset/draft-order-sales-context.md
@@ -0,0 +1,6 @@
+---
+"@spree/admin-sdk": minor
+"@spree/dashboard": minor
+---
+
+New draft orders take a market, sales channel, currency and locale, chosen before any item is added. A market fixes the currency and the locales on offer. The item search on a new or existing draft order lists only what the buyer can be sold on that channel, priced as they would pay in that market; `variants.list()` accepts `order_id`, or `market_id`, `channel_id`, `customer_id`, `company_id` and `currency` for an order not yet created. `order_id` cannot be combined with the other fields, and `currency` on its own also narrows the list. Order creation refuses items the buyer cannot order on the channel, and picks a market selling the requested currency when none is named. Changing any of these after items are picked asks before removing them.
diff --git a/docs/api-reference/admin.yaml b/docs/api-reference/admin.yaml
index 29b1cac790..706a0309a0 100644
--- a/docs/api-reference/admin.yaml
+++ b/docs/api-reference/admin.yaml
@@ -17570,6 +17570,7 @@ paths:
market_id: mkt_UkLWZg9DAJ
withdrawal_period_ends_at:
within_withdrawal_period: false
+ shipping_eq_billing_address: false
cart_id:
channel_id: ch_UkLWZg9DAJ
company_id:
@@ -18438,6 +18439,7 @@ paths:
market_id: mkt_UkLWZg9DAJ
withdrawal_period_ends_at:
within_withdrawal_period: false
+ shipping_eq_billing_address: false
cart_id:
channel_id: ch_UkLWZg9DAJ
company_id:
@@ -18790,6 +18792,7 @@ paths:
market_id: mkt_UkLWZg9DAJ
withdrawal_period_ends_at:
within_withdrawal_period: false
+ shipping_eq_billing_address: false
cart_id:
channel_id: ch_UkLWZg9DAJ
company_id:
@@ -19015,6 +19018,7 @@ paths:
market_id: mkt_UkLWZg9DAJ
withdrawal_period_ends_at:
within_withdrawal_period: false
+ shipping_eq_billing_address: true
cart_id:
channel_id: ch_UkLWZg9DAJ
company_id:
@@ -19171,6 +19175,7 @@ paths:
market_id: mkt_UkLWZg9DAJ
withdrawal_period_ends_at:
within_withdrawal_period: false
+ shipping_eq_billing_address: false
cart_id:
channel_id: ch_UkLWZg9DAJ
company_id:
@@ -19317,6 +19322,7 @@ paths:
market_id: mkt_UkLWZg9DAJ
withdrawal_period_ends_at:
within_withdrawal_period: false
+ shipping_eq_billing_address: false
cart_id:
channel_id: ch_UkLWZg9DAJ
company_id:
@@ -19515,6 +19521,7 @@ paths:
market_id: mkt_UkLWZg9DAJ
withdrawal_period_ends_at:
within_withdrawal_period: true
+ shipping_eq_billing_address: false
cart_id:
channel_id: ch_UkLWZg9DAJ
company_id:
@@ -19693,6 +19700,7 @@ paths:
market_id: mkt_UkLWZg9DAJ
withdrawal_period_ends_at:
within_withdrawal_period: false
+ shipping_eq_billing_address: false
cart_id:
channel_id: ch_UkLWZg9DAJ
company_id:
@@ -19832,6 +19840,7 @@ paths:
market_id: mkt_UkLWZg9DAJ
withdrawal_period_ends_at:
within_withdrawal_period: true
+ shipping_eq_billing_address: false
cart_id:
channel_id: ch_UkLWZg9DAJ
company_id:
@@ -19965,6 +19974,7 @@ paths:
market_id: mkt_UkLWZg9DAJ
withdrawal_period_ends_at:
within_withdrawal_period: true
+ shipping_eq_billing_address: false
cart_id:
channel_id: ch_UkLWZg9DAJ
company_id:
@@ -35001,6 +35011,51 @@ paths:
description: Number of records per page
schema:
type: integer
+ - name: order_id
+ in: query
+ required: false
+ description: 'A draft order to sell to: lists only what its buyer can be sold
+ on its channel, priced in its market. Needs `read_orders`, and cannot be
+ combined with the fields below.'
+ schema:
+ type: string
+ - name: market_id
+ in: query
+ required: false
+ description: Prices in this market and lists only variants with a price in
+ its currency.
+ schema:
+ type: string
+ - name: channel_id
+ in: query
+ required: false
+ description: Lists only variants published on this channel. When a market,
+ customer, company or currency is given without it, the store default channel
+ applies; an order uses its own.
+ schema:
+ type: string
+ - name: customer_id
+ in: query
+ required: false
+ description: Narrows to the customer's catalogs and prices as they would pay.
+ Needs `read_customers`.
+ schema:
+ type: string
+ - name: company_id
+ in: query
+ required: false
+ description: Narrows to the company's catalogs and prices under its agreement.
+ Needs `read_customers`.
+ schema:
+ type: string
+ - name: currency
+ in: query
+ required: false
+ description: Lists only variants with a price in this currency. With `market_id`
+ it must be the market's currency.
+ schema:
+ allOf:
+ - "$ref": "#/components/schemas/CurrencyCode"
- name: q
in: query
required: false
@@ -64377,6 +64432,8 @@ components:
nullable: true
within_withdrawal_period:
type: boolean
+ shipping_eq_billing_address:
+ type: boolean
cart_id:
type: string
nullable: true
@@ -65057,6 +65114,7 @@ components:
- market_id
- withdrawal_period_ends_at
- within_withdrawal_period
+ - shipping_eq_billing_address
- cart_id
- channel_id
- company_id
@@ -78898,6 +78956,9 @@ components:
customer_id:
type: string
+ description: Null detaches the customer, leaving a guest order under its
+ `email`.
+ nullable: true
use_customer_default_address:
type: boolean
description: With `customer_id`, copies the customer's saved billing and
@@ -78961,6 +79022,9 @@ components:
"$ref": "#/components/schemas/AddressInputParams"
billing_address:
"$ref": "#/components/schemas/AddressInputParams"
+ use_shipping:
+ type: boolean
+ description: When true, copies the shipping address to the billing address.
items:
type: array
items:
@@ -79036,6 +79100,9 @@ components:
customer_id:
type: string
+ description: Null detaches the customer, leaving a guest order under its
+ `email`.
+ nullable: true
currency:
allOf:
- "$ref": "#/components/schemas/CurrencyCode"
@@ -79086,6 +79153,9 @@ components:
"$ref": "#/components/schemas/AddressInputParams"
billing_address:
"$ref": "#/components/schemas/AddressInputParams"
+ use_shipping:
+ type: boolean
+ description: When true, copies the shipping address to the billing address.
items:
type: array
items:
@@ -82541,6 +82611,36 @@ components:
"$ref": "#/components/schemas/StockLevelParams"
description: Stock per location. Upserted by location; omitted locations
are removed.
+ VariantSalesContextParams:
+ type: object
+ properties:
+ order_id:
+ type: string
+ description: 'A draft order to sell to: lists only what its buyer can be
+ sold on its channel, priced in its market. Needs `read_orders`, and cannot
+ be combined with the fields below.'
+ market_id:
+ type: string
+ description: Prices in this market and lists only variants with a price
+ in its currency.
+ channel_id:
+ type: string
+ description: Lists only variants published on this channel. When a market,
+ customer, company or currency is given without it, the store default channel
+ applies; an order uses its own.
+ customer_id:
+ type: string
+ description: Narrows to the customer's catalogs and prices as they would
+ pay. Needs `read_customers`.
+ company_id:
+ type: string
+ description: Narrows to the company's catalogs and prices under its agreement.
+ Needs `read_customers`.
+ currency:
+ allOf:
+ - "$ref": "#/components/schemas/CurrencyCode"
+ description: Lists only variants with a price in this currency. With `market_id`
+ it must be the market's currency.
VariantUpdateParams:
allOf:
- "$ref": "#/components/schemas/VariantParams"
diff --git a/docs/api-reference/store.yaml b/docs/api-reference/store.yaml
index 475008d880..ddf2ded4f9 100644
--- a/docs/api-reference/store.yaml
+++ b/docs/api-reference/store.yaml
@@ -3300,6 +3300,7 @@ paths:
market_id: mkt_UkLWZg9DAJ
withdrawal_period_ends_at:
within_withdrawal_period: true
+ shipping_eq_billing_address: false
cart_id: cart_UkLWZg9DAJ
channel_id: ch_UkLWZg9DAJ
company_id:
@@ -6377,6 +6378,7 @@ paths:
market_id: mkt_UkLWZg9DAJ
withdrawal_period_ends_at:
within_withdrawal_period: true
+ shipping_eq_billing_address: false
cart_id:
channel_id: ch_UkLWZg9DAJ
company_id:
@@ -7737,6 +7739,7 @@ paths:
market_id: mkt_UkLWZg9DAJ
withdrawal_period_ends_at:
within_withdrawal_period: true
+ shipping_eq_billing_address: false
cart_id:
channel_id: ch_UkLWZg9DAJ
company_id:
@@ -8063,6 +8066,7 @@ paths:
market_id: mkt_UkLWZg9DAJ
withdrawal_period_ends_at:
within_withdrawal_period: true
+ shipping_eq_billing_address: false
cart_id:
channel_id: ch_UkLWZg9DAJ
company_id:
@@ -12359,6 +12363,7 @@ paths:
market_id: mkt_UkLWZg9DAJ
withdrawal_period_ends_at:
within_withdrawal_period: true
+ shipping_eq_billing_address: false
cart_id:
channel_id: ch_UkLWZg9DAJ
company_id: comp_UkLWZg9DAJ
@@ -19318,6 +19323,8 @@ components:
nullable: true
within_withdrawal_period:
type: boolean
+ shipping_eq_billing_address:
+ type: boolean
cart_id:
type: string
nullable: true
@@ -19933,6 +19940,7 @@ components:
- market_id
- withdrawal_period_ends_at
- within_withdrawal_period
+ - shipping_eq_billing_address
- cart_id
- channel_id
- company_id
diff --git a/docs/developer/customization/email-variables.mdx b/docs/developer/customization/email-variables.mdx
index 05b54fcd88..1eac84e5bf 100644
--- a/docs/developer/customization/email-variables.mdx
+++ b/docs/developer/customization/email-variables.mdx
@@ -47,7 +47,7 @@ Each object's fields, and the fields of the objects nested in it. Format an amou
### `order`
-- `order`: `id`, `market_id`, `withdrawal_period_ends_at`, `within_withdrawal_period`, `cart_id`, `channel_id`, `company_id`, `company_name`, `po_document_filename`, `po_document_byte_size`, `number`, `email`, `customer_note`, `po_number`, `currency`, `locale`, `total_quantity`, `coupon_code`, `fulfillment_status`, `payment_status`, `completed_at`, `item_total`, `discount_total`, `tax_total`, `included_tax_total`, `additional_tax_total`, `delivery_total`, `fee_total`, `gift_card_total`, `store_credit_total`, `total`, `amount_due`, `covered_by_store_credit`, `adjustment_total`, `customer_name`, `total_minus_store_credits`
+- `order`: `id`, `market_id`, `withdrawal_period_ends_at`, `within_withdrawal_period`, `shipping_eq_billing_address`, `cart_id`, `channel_id`, `company_id`, `company_name`, `po_document_filename`, `po_document_byte_size`, `number`, `email`, `customer_note`, `po_number`, `currency`, `locale`, `total_quantity`, `coupon_code`, `fulfillment_status`, `payment_status`, `completed_at`, `item_total`, `discount_total`, `tax_total`, `included_tax_total`, `additional_tax_total`, `delivery_total`, `fee_total`, `gift_card_total`, `store_credit_total`, `total`, `amount_due`, `covered_by_store_credit`, `adjustment_total`, `customer_name`, `total_minus_store_credits`
- `order.discounts`: `id`, `promotion_id`, `name`, `description`, `code`, `amount`
- `order.fees`: `id`, `label`, `kind`, `line_item_id`, `fulfillment_id`, `amount`
- `order.items`: `id`, `variant_id`, `seller_id`, `preorder`, `preorder_ships_at`, `quantity`, `currency`, `name`, `slug`, `options_text`, `price`, `total`, `adjustment_total`, `additional_tax_total`, `included_tax_total`, `discount_total`, `pre_tax_amount`, `discounted_amount`, `compare_at_amount`, `url`, `image_url`, `sku`, `amount`
diff --git a/packages/admin-sdk/src/admin-client.ts b/packages/admin-sdk/src/admin-client.ts
index adc4678a21..a4737589f4 100644
--- a/packages/admin-sdk/src/admin-client.ts
+++ b/packages/admin-sdk/src/admin-client.ts
@@ -198,6 +198,31 @@ import type {
// Semantic reporting contract (docs/plans/6.0-analytics-semantic-layer.md)
// ============================================
+// Every sales context field, so adding one to `VariantSalesContextParams`
+// fails to compile until it is listed here too.
+const VARIANT_SALES_CONTEXT_FIELDS: Record<keyof VariantSalesContextParams, true> = {
+ order_id: true,
+ market_id: true,
+ channel_id: true,
+ customer_id: true,
+ company_id: true,
+ currency: true,
+}
+
+// The sales context scopes and prices the list, so it stays out of the Ransack filters.
+function variantListQuery(
+ params: ListParams<VariantFilters, VariantSort> & VariantSalesContextParams,
+): ReturnType<typeof transformListParams> {
+ const filters: Record<string, unknown> = { ...params }
+ const context: Record<string, string> = {}
+ for (const field of Object.keys(VARIANT_SALES_CONTEXT_FIELDS)) {
+ const value = filters[field]
+ if (typeof value === 'string' && value) context[field] = value
+ delete filters[field]
+ }
+ return { ...transformListParams(filters), ...context }
+}
+
export type ReportingGrain = 'hour' | 'day' | 'week' | 'month'
export type ReportingCompare = 'previous_period' | 'previous_year'
@@ -595,6 +620,7 @@ import type {
TaxRateUpdateParams,
TrackingCarrierOption,
VariantCreateParams,
+ VariantSalesContextParams,
VariantUpdateParams,
WebhookEndpointCreateParams,
WebhookEndpointDisableParams,
@@ -4963,12 +4989,12 @@ export class AdminClient {
readonly variants = {
list: (
- params?: ListParams<VariantFilters, VariantSort>,
+ params?: ListParams<VariantFilters, VariantSort> & VariantSalesContextParams,
options?: RequestOptions,
): Promise<PaginatedResponse<Variant>> =>
this.request<PaginatedResponse<Variant>>('GET', '/variants', {
...options,
- params: params ? transformListParams(params) : undefined,
+ params: params ? variantListQuery(params) : undefined,
}),
get: (id: string, params?: { expand?: string[] }, options?: RequestOptions): Promise<Variant> =>
diff --git a/packages/admin-sdk/src/types/generated/Order.ts b/packages/admin-sdk/src/types/generated/Order.ts
index 5ebde08d41..64eb28fd3c 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 8f2c3ae55f12f046a60a7f50a7d5d3b6
+// Typelizer digest 6c118f1474f350a48d9c3230dac29974
//
// DO NOT MODIFY: This file was automatically generated by Typelizer.
import type {FreightSummary, Payment, LineItem, Fulfillment, Address, GiftCard, Market, Seller, Actor, AppliedPromotion, PaymentSplit, Cart, Channel, StockLocation, PaymentMethod, Customer, OrderCancellationReason, Return, Exchange, Claim, CurrencyCode, LocaleCode, ActorKind} from '@/types'
@@ -8,6 +8,7 @@ interface Order {
market_id: string | null;
withdrawal_period_ends_at: string | null;
within_withdrawal_period: boolean;
+ shipping_eq_billing_address: boolean;
cart_id: string | null;
channel_id: string | null;
company_id: string | null;
diff --git a/packages/admin-sdk/src/types/generated/emails/EmailOrder.ts b/packages/admin-sdk/src/types/generated/emails/EmailOrder.ts
index ff29de0eab..658ce37491 100644
--- a/packages/admin-sdk/src/types/generated/emails/EmailOrder.ts
+++ b/packages/admin-sdk/src/types/generated/emails/EmailOrder.ts
@@ -1,4 +1,4 @@
-// Typelizer digest 3f8e42ede33b2f88b82001c7bf35303d
+// Typelizer digest 6ed7a98cfb5a64c6d07dad5581595c5f
//
// DO NOT MODIFY: This file was automatically generated by Typelizer.
import type {EmailPayment, EmailAppliedPromotion, EmailFee, EmailLineItem, EmailFulfillment, EmailAddress, EmailGiftCard, EmailMarket, EmailAmountLine, CurrencyCode, LocaleCode} from '.'
@@ -8,6 +8,7 @@ interface EmailOrder {
market_id: string | null;
withdrawal_period_ends_at: string | null;
within_withdrawal_period: boolean;
+ shipping_eq_billing_address: boolean;
cart_id: string | null;
channel_id: string | null;
company_id: string | null;
diff --git a/packages/admin-sdk/src/types/params/OrderCreateParams.ts b/packages/admin-sdk/src/types/params/OrderCreateParams.ts
index d492a1f328..8bcf918fb0 100644
--- a/packages/admin-sdk/src/types/params/OrderCreateParams.ts
+++ b/packages/admin-sdk/src/types/params/OrderCreateParams.ts
@@ -13,7 +13,8 @@ export type OrderCreateParams = {
*/
external_references?: Record<string, unknown>
email?: string
- customer_id?: string
+ /** Null detaches the customer, leaving a guest order under its `email`. */
+ customer_id?: string | null
/**
* With `customer_id`, copies the customer's saved billing and shipping addresses onto the order.
*/
@@ -57,6 +58,8 @@ export type OrderCreateParams = {
tags?: string[]
shipping_address?: AddressInputParams
billing_address?: AddressInputParams
+ /** When true, copies the shipping address to the billing address. */
+ use_shipping?: boolean
/**
* Line items to upsert, keyed by variant. An entry sets that variant's quantity, creating the
* line item when the order has none; `quantity: 0` removes it. Variants you do not send are left
diff --git a/packages/admin-sdk/src/types/params/OrderUpdateParams.ts b/packages/admin-sdk/src/types/params/OrderUpdateParams.ts
index 27316ed7ad..b9e59b73bd 100644
--- a/packages/admin-sdk/src/types/params/OrderUpdateParams.ts
+++ b/packages/admin-sdk/src/types/params/OrderUpdateParams.ts
@@ -13,7 +13,8 @@ export type OrderUpdateParams = {
*/
external_references?: Record<string, unknown>
email?: string
- customer_id?: string
+ /** Null detaches the customer, leaving a guest order under its `email`. */
+ customer_id?: string | null
currency?: CurrencyCode
market_id?: string
/** Defaults to the store primary channel when omitted. */
@@ -47,6 +48,8 @@ export type OrderUpdateParams = {
tags?: string[]
shipping_address?: AddressInputParams
billing_address?: AddressInputParams
+ /** When true, copies the shipping address to the billing address. */
+ use_shipping?: boolean
/**
* Line items to upsert, keyed by variant. An entry sets that variant's quantity, creating the
* line item when the order has none; `quantity: 0` removes it. Variants you do not send are left
diff --git a/packages/admin-sdk/src/types/params/VariantSalesContextParams.ts b/packages/admin-sdk/src/types/params/VariantSalesContextParams.ts
new file mode 100644
index 0000000000..9fc2012dc5
--- /dev/null
+++ b/packages/admin-sdk/src/types/params/VariantSalesContextParams.ts
@@ -0,0 +1,27 @@
+// This file is auto-generated from the request schemas in docs/api-reference by `pnpm generate:params`. Do not edit directly.
+
+import type { CurrencyCode } from '../generated'
+
+export type VariantSalesContextParams = {
+ /**
+ * A draft order to sell to: lists only what its buyer can be sold on its channel, priced in its
+ * market. Needs `read_orders`, and cannot be combined with the fields below.
+ */
+ order_id?: string
+ /** Prices in this market and lists only variants with a price in its currency. */
+ market_id?: string
+ /**
+ * Lists only variants published on this channel. When a market, customer, company or currency is
+ * given without it, the store default channel applies; an order uses its own.
+ */
+ channel_id?: string
+ /** Narrows to the customer's catalogs and prices as they would pay. Needs `read_customers`. */
+ customer_id?: string
+ /** Narrows to the company's catalogs and prices under its agreement. Needs `read_customers`. */
+ company_id?: string
+ /**
+ * Lists only variants with a price in this currency. With `market_id` it must be the market's
+ * currency.
+ */
+ currency?: CurrencyCode
+}
diff --git a/packages/admin-sdk/src/types/params/index.ts b/packages/admin-sdk/src/types/params/index.ts
index deb586c567..5962dd2c28 100644
--- a/packages/admin-sdk/src/types/params/index.ts
+++ b/packages/admin-sdk/src/types/params/index.ts
@@ -232,6 +232,7 @@ export type { TranslationBatchParams } from './TranslationBatchParams'
export type { VariantCreateParams } from './VariantCreateParams'
export type { VariantOptionParams } from './VariantOptionParams'
export type { VariantParams } from './VariantParams'
+export type { VariantSalesContextParams } from './VariantSalesContextParams'
export type { VariantUpdateParams } from './VariantUpdateParams'
export type { WebhookEndpointCreateParams } from './WebhookEndpointCreateParams'
export type { WebhookEndpointDisableParams } from './WebhookEndpointDisableParams'
diff --git a/packages/admin-sdk/src/zod/generated/Order.ts b/packages/admin-sdk/src/zod/generated/Order.ts
index 2c6450e033..d09d32f375 100644
--- a/packages/admin-sdk/src/zod/generated/Order.ts
+++ b/packages/admin-sdk/src/zod/generated/Order.ts
@@ -27,6 +27,7 @@ export const OrderSchema = z.object({
market_id: z.string().nullable(),
withdrawal_period_ends_at: z.string().nullable(),
within_withdrawal_period: z.boolean(),
+ shipping_eq_billing_address: z.boolean(),
cart_id: z.string().nullable(),
channel_id: z.string().nullable(),
company_id: z.string().nullable(),
@@ -117,6 +118,7 @@ export const OrderSchema = z.object({
market_id: z.ZodType<Order['market_id']>;
withdrawal_period_ends_at: z.ZodType<Order['withdrawal_period_ends_at']>;
within_withdrawal_period: z.ZodType<Order['within_withdrawal_period']>;
+ shipping_eq_billing_address: z.ZodType<Order['shipping_eq_billing_address']>;
cart_id: z.ZodType<Order['cart_id']>;
channel_id: z.ZodType<Order['channel_id']>;
company_id: z.ZodType<Order['company_id']>;
diff --git a/packages/admin-sdk/src/zod/generated/emails/EmailOrder.ts b/packages/admin-sdk/src/zod/generated/emails/EmailOrder.ts
index 97a19a9357..150823b0c0 100644
--- a/packages/admin-sdk/src/zod/generated/emails/EmailOrder.ts
+++ b/packages/admin-sdk/src/zod/generated/emails/EmailOrder.ts
@@ -15,6 +15,7 @@ export const EmailOrderSchema = z.object({
market_id: z.string().nullable(),
withdrawal_period_ends_at: z.string().nullable(),
within_withdrawal_period: z.boolean(),
+ shipping_eq_billing_address: z.boolean(),
cart_id: z.string().nullable(),
channel_id: z.string().nullable(),
company_id: z.string().nullable(),
diff --git a/packages/admin-sdk/tests/read-only-resources.test.ts b/packages/admin-sdk/tests/read-only-resources.test.ts
index 7b79ac438f..35fbd37139 100644
--- a/packages/admin-sdk/tests/read-only-resources.test.ts
+++ b/packages/admin-sdk/tests/read-only-resources.test.ts
@@ -127,6 +127,44 @@ describe('variants', () => {
expect(url!.searchParams.get('q[sku_cont]')).toBe('SKU')
})
+
+ it('sends the sales context as itself, not as filters', async () => {
+ let url: URL | null = null
+ server.use(
+ http.get(`${API_PREFIX}/variants`, ({ request }) => {
+ url = new URL(request.url)
+ return HttpResponse.json(paginated([]))
+ }),
+ )
+
+ await createTestClient().variants.list({
+ search: 'shirt',
+ market_id: 'mkt_eu',
+ channel_id: 'ch_web',
+ customer_id: undefined,
+ })
+
+ expect(url!.searchParams.get('market_id')).toBe('mkt_eu')
+ expect(url!.searchParams.get('channel_id')).toBe('ch_web')
+ expect(url!.searchParams.has('customer_id')).toBe(false)
+ expect(url!.searchParams.get('q[market_id]')).toBeNull()
+ expect(url!.searchParams.get('q[search]')).toBe('shirt')
+ })
+
+ it('sends a draft order as the sales context', async () => {
+ let url: URL | null = null
+ server.use(
+ http.get(`${API_PREFIX}/variants`, ({ request }) => {
+ url = new URL(request.url)
+ return HttpResponse.json(paginated([]))
+ }),
+ )
+
+ await createTestClient().variants.list({ order_id: 'or_abc' })
+
+ expect(url!.searchParams.get('order_id')).toBe('or_abc')
+ expect(url!.searchParams.get('q[order_id]')).toBeNull()
+ })
})
describe('get', () => {
diff --git a/packages/dashboard-ui/src/spree/address-block.tsx b/packages/dashboard-ui/src/spree/address-block.tsx
index d847f370d5..c20a773639 100644
--- a/packages/dashboard-ui/src/spree/address-block.tsx
+++ b/packages/dashboard-ui/src/spree/address-block.tsx
@@ -36,10 +36,13 @@ function localizedCountryName(
export function AddressBlock({
title,
address,
+ emptyText,
}: {
/** Omitted where the surrounding card already names the address. */
title?: string
address: AddressBlockValue | null | undefined
+ /** Shown in place of the address when there is none. Defaults to "Not provided". */
+ emptyText?: string
}) {
const { t, i18n } = useTranslation()
return (
@@ -61,7 +64,7 @@ export function AddressBlock({
</div>
) : (
<span className="text-sm text-muted-foreground">
- {t('admin.components.address_block.not_provided')}
+ {emptyText ?? t('admin.components.address_block.not_provided')}
</span>
)}
</div>
diff --git a/packages/dashboard/e2e/global-setup.ts b/packages/dashboard/e2e/global-setup.ts
index f8609bf430..ad9c8c6ec8 100644
--- a/packages/dashboard/e2e/global-setup.ts
+++ b/packages/dashboard/e2e/global-setup.ts
@@ -83,6 +83,9 @@ const BOOTSTRAP_RUBY = [
`category = s.categories.where(permalink: '${FIXTURE_PROMO_TAXON_PERMALINK}').first_or_create!(name: '${FIXTURE_PROMO_TAXON}', parent: nil)`,
`product = Spree::Product.where(name: '${FIXTURE_PROMO_PRODUCT}').first_or_create!(store: s, status: 'active')`,
`product.default_variant.set_price(s.default_currency, 19.99)`,
+ // Published on the default channel, so the new-order item search — which
+ // lists only what the order's channel sells — offers it.
+ `Spree::ProductPublication.find_or_create_by!(product: product, channel: s.default_channel)`,
`product.default_variant.update!(sku: '${FIXTURE_PROMO_SKU}') if product.default_variant.sku != '${FIXTURE_PROMO_SKU}'`,
`product.categories << category unless product.categories.include?(category)`,
// Stock the promo product on the store's default stock location so
@@ -133,6 +136,9 @@ const BOOTSTRAP_RUBY = [
// market would otherwise surface later as opaque multi-currency failures.
`germany = Spree::Country.find_by_iso!('DE')`,
`s.markets.find_or_create_by!(name: 'Europe') { |m| m.currency = 'EUR'; m.default_locale = 'de'; m.countries = [germany] } unless s.markets.exists?(currency: 'EUR')`,
+ // An order's locale has to be one its market offers, so the orders list can
+ // show a German-language order in the default US market.
+ `s.default_market.update!(supported_locales: s.default_market.supported_locales_list | ['de']) unless s.default_market.supported_locales_list.include?('de')`,
// A seller with one settled earning and one payout still owed, so the
// marketplace ledger screens have rows to read and a settlement to mark
// paid. Written directly: both are produced by fulfilment and the payout
diff --git a/packages/dashboard/e2e/orders-list.spec.ts b/packages/dashboard/e2e/orders-list.spec.ts
index c9f0842377..ae18cbf9a8 100644
--- a/packages/dashboard/e2e/orders-list.spec.ts
+++ b/packages/dashboard/e2e/orders-list.spec.ts
@@ -138,7 +138,7 @@ test.describe('orders list', () => {
test('shows and filters by market and locale', async ({ page }) => {
const session = await login(page)
- // `de` is a store language through the seeded Europe market.
+ // `de` is a locale the seeded US market offers (see global-setup).
const { lastName, small, large } = await seedOrders(page, session, 'de')
const markets = await adminRequest<{ data: { name: string; currency: string }[] }>(
page,
diff --git a/packages/dashboard/e2e/orders.spec.ts b/packages/dashboard/e2e/orders.spec.ts
index f6e60edd67..f0db51f097 100644
--- a/packages/dashboard/e2e/orders.spec.ts
+++ b/packages/dashboard/e2e/orders.spec.ts
@@ -3,9 +3,11 @@ import { fileURLToPath } from 'node:url'
import { expect, type Page, test } from '@playwright/test'
import {
adminRequest,
+ createPlacedOrder,
FIXTURE_BOGUS_GATEWAY,
FIXTURE_BOGUS_ORDER_EMAIL,
FIXTURE_BOGUS_TRANSACTION_ID,
+ FIXTURE_PROMO_CUSTOMER_EMAIL,
FIXTURE_PROMO_PRODUCT,
fillAddressForm,
login,
@@ -102,6 +104,42 @@ test.describe('new order', () => {
await expect(page.getByText('Slot probe: order.form_main')).toBeVisible()
})
+ test('picking a market switches the currency and locale to that market', async ({ page }) => {
+ const creds = await login(page)
+ await page.goto(NEW_ORDER_PATH(creds.store_id))
+ await expect(page.getByRole('heading', { name: CTA })).toBeVisible({ timeout: 15_000 })
+
+ await page.locator('#order-market').click()
+ await page.getByRole('option', { name: 'Europe' }).click()
+
+ await expect(page.locator('#order-currency')).toContainText('EUR')
+ await expect(page.locator('#order-currency')).toBeDisabled()
+ await expect(page.locator('#order-locale')).toContainText('DE')
+ })
+
+ test('asks before a market change removes the picked items', async ({ page }) => {
+ const creds = await login(page)
+ await page.goto(NEW_ORDER_PATH(creds.store_id))
+ await expect(page.getByRole('heading', { name: CTA })).toBeVisible({ timeout: 15_000 })
+
+ await fillNewOrderForm(page, `e2e-context-${Date.now()}@example.com`)
+ const itemRow = page.getByRole('cell', { name: new RegExp(FIXTURE_PROMO_PRODUCT, 'i') })
+ await expect(itemRow).toBeVisible()
+
+ await page.locator('#order-market').click()
+ await page.getByRole('option', { name: 'Europe' }).click()
+ const dialog = page.getByRole('dialog')
+ await dialog.getByRole('button', { name: /cancel/i }).click()
+ await expect(itemRow).toBeVisible()
+ await expect(page.locator('#order-currency')).not.toContainText('EUR')
+
+ await page.locator('#order-market').click()
+ await page.getByRole('option', { name: 'Europe' }).click()
+ await dialog.getByRole('button', { name: /change and remove items/i }).click()
+ await expect(itemRow).toBeHidden()
+ await expect(page.locator('#order-currency')).toContainText('EUR')
+ })
+
// The motivating case for this form: a purchase order arrives by email and
// the merchant keys the order in, reference and paperwork together.
test('carries a PO number and its document onto the created order', async ({ page }) => {
@@ -276,13 +314,7 @@ test.describe('order addresses', () => {
timeout: 15_000,
})
- // Several cards on the order page carry an Actions menu, so reach the
- // customer card's through the heading that names it.
- const customerCard = page.locator('[data-slot="card"]').filter({
- has: page.locator('[data-slot="card-title"]', { hasText: /^Customer$/ }),
- })
- await customerCard.getByRole('button', { name: /actions/i }).click()
- await page.getByRole('menuitem', { name: /edit shipping address/i }).click()
+ await page.getByRole('button', { name: /edit shipping address/i }).click()
// Named, because the country and state comboboxes inside the sheet are
// themselves dialogs.
@@ -306,6 +338,98 @@ test.describe('order addresses', () => {
await expect(dialog).toBeHidden({ timeout: 15_000 })
await expect(page.getByText(street)).toBeVisible({ timeout: 15_000 })
})
+
+ test('uses the shipping address for billing', async ({ page }) => {
+ const creds = await login(page)
+ const street = `${Date.now()} Paryska Street`
+ const order = await adminRequest<{ id: string }>(page, creds, 'post', '/orders', {
+ email: `e2e-order-same-address-${Date.now()}@example.com`,
+ shipping_address: {
+ first_name: 'Ada',
+ last_name: 'Lovelace',
+ address1: street,
+ city: 'Los Angeles',
+ country_code: 'US',
+ state_code: 'CA',
+ postal_code: '90001',
+ phone: '5555555555',
+ },
+ })
+
+ await page.goto(`${ORDERS_PATH(creds.store_id)}/${order.id}`)
+ const sameAsShipping = page.getByRole('button', { name: /same as shipping address/i })
+ await expect(sameAsShipping).toBeVisible({ timeout: 15_000 })
+ await sameAsShipping.click()
+
+ await expect(sameAsShipping).toBeHidden({ timeout: 15_000 })
+ await expect(page.getByText(/^same as shipping address$/i)).toBeVisible()
+ await expect(page.getByText(street)).toHaveCount(1)
+ })
+})
+
+test.describe('order customer', () => {
+ test("changes a guest order's email", async ({ page }) => {
+ const creds = await login(page)
+ const order = await adminRequest<{ id: string }>(page, creds, 'post', '/orders', {
+ email: `e2e-guest-${Date.now()}@example.com`,
+ })
+ const newEmail = `e2e-guest-renamed-${Date.now()}@example.com`
+
+ await page.goto(`${ORDERS_PATH(creds.store_id)}/${order.id}`)
+ await page.getByRole('button', { name: /edit customer/i }).click()
+ const dialog = page.getByRole('dialog', { name: /edit customer/i })
+ await dialog.getByLabel(/email/i).fill(newEmail)
+ await dialog.getByRole('button', { name: /^save$/i }).click()
+
+ await expect(dialog).toBeHidden({ timeout: 15_000 })
+ await expect(page.getByText(newEmail)).toBeVisible({ timeout: 15_000 })
+ })
+
+ test('detaches the customer, leaving a guest order', async ({ page }) => {
+ const creds = await login(page)
+ const customers = await adminRequest<{ data: { id: string }[] }>(
+ page,
+ creds,
+ 'get',
+ `/customers?q[email_eq]=${encodeURIComponent(FIXTURE_PROMO_CUSTOMER_EMAIL)}`,
+ )
+ const order = await adminRequest<{ id: string }>(page, creds, 'post', '/orders', {
+ customer_id: customers.data[0].id,
+ })
+
+ await page.goto(`${ORDERS_PATH(creds.store_id)}/${order.id}`)
+ const customerLink = page.getByRole('link', { name: 'Promo Customer', exact: true })
+ await expect(customerLink).toBeVisible({ timeout: 15_000 })
+
+ await page.getByRole('button', { name: /edit customer/i }).click()
+ const dialog = page.getByRole('dialog', { name: /edit customer/i })
+ await dialog.locator('[data-slot="combobox-clear"]').click()
+ await expect(dialog.getByLabel(/email/i)).toHaveValue(FIXTURE_PROMO_CUSTOMER_EMAIL)
+ await dialog.getByRole('button', { name: /^save$/i }).click()
+
+ await expect(dialog).toBeHidden({ timeout: 15_000 })
+ await expect(customerLink).toBeHidden({ timeout: 15_000 })
+ await expect(page.getByText(FIXTURE_PROMO_CUSTOMER_EMAIL)).toBeVisible()
+ })
+
+ test('asks before removing the customer from a placed order', async ({ page }) => {
+ const creds = await login(page)
+ const order = await createPlacedOrder(page, creds.accessToken, { quantity: 1, ship: false })
+
+ await page.goto(`${ORDERS_PATH(creds.store_id)}/${order.id}`)
+ const customerLink = page.getByRole('link', { name: 'Promo Customer', exact: true })
+ await expect(customerLink).toBeVisible({ timeout: 15_000 })
+
+ await page.getByRole('button', { name: /edit customer/i }).click()
+ const dialog = page.getByRole('dialog', { name: /edit customer/i })
+ await dialog.locator('[data-slot="combobox-clear"]').click()
+ await dialog.getByRole('button', { name: /^save$/i }).click()
+
+ await page.getByRole('button', { name: /^remove customer$/i }).click()
+
+ await expect(dialog).toBeHidden({ timeout: 15_000 })
+ await expect(customerLink).toBeHidden({ timeout: 15_000 })
+ })
})
test.describe('order tags', () => {
diff --git a/packages/dashboard/src/components/spree/orders/line-item-dialogs.tsx b/packages/dashboard/src/components/spree/orders/line-item-dialogs.tsx
index d2bfecc3c8..a8b53d8dd6 100644
--- a/packages/dashboard/src/components/spree/orders/line-item-dialogs.tsx
+++ b/packages/dashboard/src/components/spree/orders/line-item-dialogs.tsx
@@ -29,10 +29,13 @@ import { useTranslation } from 'react-i18next'
* pending row until the merchant saves the order.
*/
export function AddLineItemDialog({
+ orderId,
open,
onOpenChange,
onSelect,
}: {
+ /** Lists only what this order's buyer can be sold, priced as they would pay. */
+ orderId: string
open: boolean
onOpenChange: (open: boolean) => void
onSelect: (variant: Variant, quantity: number) => void
@@ -43,8 +46,8 @@ export function AddLineItemDialog({
const [quantity, setQuantity] = useState(1)
const { data: variantsData } = useQuery({
- queryKey: ['variants', 'search', search],
- queryFn: () => adminClient.variants.list({ search, limit: 10 }),
+ queryKey: ['variants', 'search', orderId, search],
+ queryFn: () => adminClient.variants.list({ search, limit: 10, order_id: orderId }),
enabled: search.length >= 3,
staleTime: 30_000,
})
diff --git a/packages/dashboard/src/components/spree/orders/order-customer-card.tsx b/packages/dashboard/src/components/spree/orders/order-customer-card.tsx
index 470219e2ee..f8763eeda4 100644
--- a/packages/dashboard/src/components/spree/orders/order-customer-card.tsx
+++ b/packages/dashboard/src/components/spree/orders/order-customer-card.tsx
@@ -1,31 +1,24 @@
import type { Order } from '@spree/admin-sdk'
-import {
- AddressFormDialog,
- type AddressParams,
- adminClient,
- getInitials,
-} from '@spree/dashboard-core'
+import { AddressFormDialog, type AddressParams, adminClient, useStore } from '@spree/dashboard-core'
import {
AddressBlock,
- Avatar,
- AvatarFallback,
Button,
Card,
CardAction,
CardContent,
CardHeader,
CardTitle,
- DropdownMenu,
- DropdownMenuContent,
- DropdownMenuItem,
- DropdownMenuTrigger,
toastManager,
} from '@spree/dashboard-ui'
-import { EllipsisVerticalIcon, PencilIcon } from '@spree/dashboard-ui/icons'
+import { CopyIcon, PencilIcon } from '@spree/dashboard-ui/icons'
+import { Link } from '@tanstack/react-router'
import { useState } from 'react'
import { useTranslation } from 'react-i18next'
import { useOrderMutation } from '../../../hooks/use-order'
import { customerDisplayName, erasedFieldValue } from '../../../lib/erased-customer'
+import { OrderCustomerDialog } from './order-customer-dialog'
+
+type AddressType = 'shipping_address' | 'billing_address'
/**
* Who the order is for and where it is going. The only place a placed order's
@@ -34,22 +27,46 @@ import { customerDisplayName, erasedFieldValue } from '../../../lib/erased-custo
*/
export function CustomerCard({ order }: { order: Order }) {
const { t } = useTranslation()
+ const { storeId } = useStore()
const orderId = order.id
const customer = order.customer
- const [editAddress, setEditAddress] = useState<'shipping_address' | 'billing_address' | null>(
- null,
- )
+ const shippingAddress = order.shipping_address
+ const billingSameAsShipping = order.shipping_eq_billing_address
+ const [editAddress, setEditAddress] = useState<AddressType | null>(null)
+ const [editCustomer, setEditCustomer] = useState(false)
+
+ const showError = (error: unknown) =>
+ toastManager.add({
+ type: 'error',
+ title:
+ error instanceof Error ? error.message : t('admin.orders.errors.failed_to_update_address'),
+ })
const addressMutation = useOrderMutation(
orderId,
- (params: { type: 'shipping_address' | 'billing_address'; address: AddressParams }) =>
+ (params: { type: AddressType; address: AddressParams }) =>
adminClient.orders.update(orderId, { [params.type]: params.address }),
)
+ const sameAsShippingMutation = useOrderMutation(orderId, () =>
+ adminClient.orders.update(orderId, { use_shipping: true }),
+ )
- const editTitle =
- editAddress === 'shipping_address'
- ? t('admin.orders.detail.address_edit.shipping_title')
- : t('admin.orders.detail.address_edit.billing_title')
+ const editButton = (type: AddressType) => (
+ <CardAction>
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ onClick={() => setEditAddress(type)}
+ aria-label={
+ type === 'shipping_address'
+ ? t('admin.orders.detail.address_edit.shipping_title')
+ : t('admin.orders.detail.address_edit.billing_title')
+ }
+ >
+ <PencilIcon className="size-4" />
+ </Button>
+ </CardAction>
+ )
return (
<>
@@ -57,69 +74,89 @@ export function CustomerCard({ order }: { order: Order }) {
<CardHeader>
<CardTitle>{t('admin.pages.orders.detail.section_customer')}</CardTitle>
<CardAction>
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- <Button variant="ghost" size="icon-xs">
- <EllipsisVerticalIcon className="size-4" />
- <span className="sr-only">{t('admin.actions.actions_menu')}</span>
- </Button>
- </DropdownMenuTrigger>
- <DropdownMenuContent align="end">
- <DropdownMenuItem onClick={() => setEditAddress('shipping_address')}>
- <PencilIcon className="size-4" />
- {t('admin.orders.detail.address_edit.shipping_title')}
- </DropdownMenuItem>
- <DropdownMenuItem onClick={() => setEditAddress('billing_address')}>
- <PencilIcon className="size-4" />
- {t('admin.orders.detail.address_edit.billing_title')}
- </DropdownMenuItem>
- </DropdownMenuContent>
- </DropdownMenu>
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ onClick={() => setEditCustomer(true)}
+ aria-label={t('admin.orders.detail.customer_edit.title')}
+ >
+ <PencilIcon className="size-4" />
+ </Button>
</CardAction>
</CardHeader>
- <CardContent className="flex flex-col gap-5">
- {/* Contact info */}
+ <CardContent className="flex flex-col gap-1 text-sm">
{customer ? (
- <div className="flex items-center gap-3 rounded-xl bg-muted p-3">
- <Avatar>
- <AvatarFallback>
- {customer.anonymized ? '—' : getInitials(customer.full_name, customer.email)}
- </AvatarFallback>
- </Avatar>
- <div className="min-w-0 flex-1">
- <div className="truncate text-sm font-medium">
- {customerDisplayName(customer, t('admin.customers.erased.name'))}
- </div>
- <div className="truncate text-xs text-muted-foreground">
- {erasedFieldValue(customer.email, customer.anonymized)}
- </div>
- </div>
- </div>
+ <>
+ <Link
+ to={'/$storeId/customers/$customerId' as string}
+ params={{ storeId, customerId: customer.id }}
+ className="font-medium text-blue-600 no-underline hover:underline"
+ >
+ {customerDisplayName(customer, t('admin.customers.erased.name'))}
+ </Link>
+ <span className="text-muted-foreground">
+ {erasedFieldValue(customer.email, customer.anonymized)}
+ </span>
+ </>
) : order.email ? (
- <div className="text-sm text-blue-600">{order.email}</div>
+ <span className="text-blue-600">{order.email}</span>
) : (
- <span className="text-sm text-muted-foreground">
- {t('admin.orders.detail.no_customer')}
- </span>
+ <span className="text-muted-foreground">{t('admin.orders.detail.no_customer')}</span>
)}
+ </CardContent>
+ </Card>
+ <Card>
+ <CardHeader>
+ <CardTitle>{t('admin.pages.orders.detail.section_shipping_address')}</CardTitle>
+ {editButton('shipping_address')}
+ </CardHeader>
+ <CardContent>
+ <AddressBlock address={shippingAddress} />
+ </CardContent>
+ </Card>
+
+ <Card>
+ <CardHeader>
+ <CardTitle>{t('admin.pages.orders.detail.section_billing_address')}</CardTitle>
+ {editButton('billing_address')}
+ </CardHeader>
+ <CardContent className="flex flex-col gap-3">
<AddressBlock
- title={t('admin.pages.orders.detail.section_shipping_address')}
- address={order.shipping_address}
- />
- <AddressBlock
- title={t('admin.pages.orders.detail.section_billing_address')}
- address={order.billing_address}
+ address={billingSameAsShipping ? null : order.billing_address}
+ emptyText={
+ billingSameAsShipping
+ ? t('admin.orders.detail.address_edit.billing_same_as_shipping')
+ : undefined
+ }
/>
+ {shippingAddress && !billingSameAsShipping && (
+ <Button
+ variant="outline"
+ size="sm"
+ className="self-start"
+ disabled={sameAsShippingMutation.isPending}
+ onClick={() => sameAsShippingMutation.mutate(undefined, { onError: showError })}
+ >
+ <CopyIcon className="size-4" />
+ {t('admin.orders.detail.address_edit.billing_same_as_shipping')}
+ </Button>
+ )}
</CardContent>
</Card>
+ {editCustomer && (
+ <OrderCustomerDialog order={order} open={editCustomer} onOpenChange={setEditCustomer} />
+ )}
+
{editAddress && (
<AddressFormDialog
- title={editTitle}
- address={
- editAddress === 'shipping_address' ? order.shipping_address : order.billing_address
+ title={
+ editAddress === 'shipping_address'
+ ? t('admin.orders.detail.address_edit.shipping_title')
+ : t('admin.orders.detail.address_edit.billing_title')
}
+ address={editAddress === 'shipping_address' ? shippingAddress : order.billing_address}
open={!!editAddress}
onOpenChange={(open) => !open && setEditAddress(null)}
onSave={(address) =>
@@ -129,14 +166,7 @@ export function CustomerCard({ order }: { order: Order }) {
onSuccess: () => setEditAddress(null),
// The dialog stays open on failure so the entered address is
// not lost and can be corrected and resubmitted.
- onError: (error) =>
- toastManager.add({
- type: 'error',
- title:
- error instanceof Error
- ? error.message
- : t('admin.orders.errors.failed_to_update_address'),
- }),
+ onError: showError,
},
)
}
diff --git a/packages/dashboard/src/components/spree/orders/order-customer-dialog.tsx b/packages/dashboard/src/components/spree/orders/order-customer-dialog.tsx
new file mode 100644
index 0000000000..db6b82f143
--- /dev/null
+++ b/packages/dashboard/src/components/spree/orders/order-customer-dialog.tsx
@@ -0,0 +1,146 @@
+import type { Customer, Order } from '@spree/admin-sdk'
+import { adminClient, mapSpreeErrorsToForm, ResourceCombobox } from '@spree/dashboard-core'
+import {
+ Button,
+ Dialog,
+ DialogBody,
+ DialogContent,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ Field,
+ FieldDescription,
+ FieldError,
+ FieldGroup,
+ FieldLabel,
+ Input,
+ useConfirm,
+} from '@spree/dashboard-ui'
+import { useState } from 'react'
+import { useForm } from 'react-hook-form'
+import { useTranslation } from 'react-i18next'
+import { customerAutocompleteProps } from '../../../hooks/use-customers'
+import { useOrderMutation } from '../../../hooks/use-order'
+
+/**
+ * Who the order belongs to: an existing customer, or a guest known only by
+ * email. Clearing the customer turns the order into a guest one.
+ */
+export function OrderCustomerDialog({
+ order,
+ open,
+ onOpenChange,
+}: {
+ order: Order
+ open: boolean
+ onOpenChange: (open: boolean) => void
+}) {
+ const { t } = useTranslation()
+ const confirm = useConfirm()
+ const [customerId, setCustomerId] = useState<string | undefined>(order.customer_id ?? undefined)
+ // The order's email is only taken from the customer when the order is
+ // created, so a newly picked customer's email is sent alongside it —
+ // otherwise notifications keep going to the previous customer.
+ const [customerEmail, setCustomerEmail] = useState<string | undefined>()
+ const form = useForm<{ email: string }>({ defaultValues: { email: order.email ?? '' } })
+
+ const mutation = useOrderMutation(
+ order.id,
+ (params: { customer_id: string | null; email?: string }) =>
+ adminClient.orders.update(order.id, params),
+ )
+
+ async function onSubmit(values: { email: string }) {
+ // A placed order leaves the customer's order history and account with
+ // its customer, so detaching one is confirmed first.
+ const detachingFromPlacedOrder = !customerId && !!order.customer_id && !!order.completed_at
+ if (
+ detachingFromPlacedOrder &&
+ !(await confirm({
+ message: t('admin.orders.detail.customer_edit.confirm_detach'),
+ variant: 'destructive',
+ confirmLabel: t('admin.orders.detail.customer_edit.detach'),
+ }))
+ ) {
+ return
+ }
+
+ try {
+ await mutation.mutateAsync(
+ customerId
+ ? { customer_id: customerId, ...(customerEmail && { email: customerEmail }) }
+ : { customer_id: null, email: values.email },
+ )
+ onOpenChange(false)
+ } catch (error) {
+ if (!mapSpreeErrorsToForm(error, form.setError)) throw error
+ }
+ }
+
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent className="sm:max-w-lg">
+ <form onSubmit={form.handleSubmit(onSubmit)}>
+ <DialogHeader>
+ <DialogTitle>{t('admin.orders.detail.customer_edit.title')}</DialogTitle>
+ </DialogHeader>
+ <DialogBody>
+ <FieldGroup>
+ {form.formState.errors.root?.message && (
+ <p className="text-sm text-destructive">{form.formState.errors.root.message}</p>
+ )}
+ <Field>
+ <FieldLabel htmlFor="order-customer-picker">
+ {t('admin.pages.orders.new.select_customer')}
+ </FieldLabel>
+ <ResourceCombobox<Customer>
+ {...customerAutocompleteProps('order-customer-picker', order.company_id)}
+ id="order-customer-picker"
+ value={customerId}
+ onChange={(id, customer) => {
+ setCustomerId(id)
+ setCustomerEmail(customer?.email ?? undefined)
+ }}
+ renderOption={(customer) => (
+ <div>
+ <div className="font-medium">{customer.email}</div>
+ {(customer.first_name || customer.last_name) && (
+ <div className="text-xs text-muted-foreground">{customer.full_name}</div>
+ )}
+ </div>
+ )}
+ />
+ <FieldDescription>
+ {t('admin.orders.detail.customer_edit.customer_help')}
+ </FieldDescription>
+ </Field>
+ {!customerId && (
+ <Field>
+ <FieldLabel htmlFor="order-customer-email">
+ {t('admin.fields.order.email.label')}
+ </FieldLabel>
+ <Input
+ id="order-customer-email"
+ type="email"
+ placeholder={t('admin.fields.order.email.placeholder')}
+ aria-invalid={!!form.formState.errors.email || undefined}
+ {...form.register('email', { required: true })}
+ />
+ <FieldError errors={[form.formState.errors.email]} />
+ </Field>
+ )}
+ </FieldGroup>
+ </DialogBody>
+ <DialogFooter>
+ <Button type="button" variant="outline" onClick={() => onOpenChange(false)}>
+ {t('admin.actions.cancel')}
+ </Button>
+ <Button type="submit" disabled={mutation.isPending}>
+ {mutation.isPending ? t('admin.actions.saving') : t('admin.actions.save')}
+ </Button>
+ </DialogFooter>
+ </form>
+ </DialogContent>
+ </Dialog>
+ )
+}
diff --git a/packages/dashboard/src/components/spree/orders/order-skeleton.tsx b/packages/dashboard/src/components/spree/orders/order-skeleton.tsx
index 0fa9526195..ad41a905e4 100644
--- a/packages/dashboard/src/components/spree/orders/order-skeleton.tsx
+++ b/packages/dashboard/src/components/spree/orders/order-skeleton.tsx
@@ -25,8 +25,11 @@ export function OrderSkeleton() {
<Skeleton className="h-48 w-full rounded-xl" />
<Skeleton className="h-48 w-full rounded-xl" />
</div>
+ {/* Customer, shipping address and billing address cards. */}
<div className="col-span-12 lg:col-span-4 flex flex-col gap-6">
- <Skeleton className="h-64 w-full rounded-xl" />
+ <Skeleton className="h-28 w-full rounded-xl" />
+ <Skeleton className="h-44 w-full rounded-xl" />
+ <Skeleton className="h-28 w-full rounded-xl" />
</div>
</div>
</div>
diff --git a/packages/dashboard/src/locales/ar.json b/packages/dashboard/src/locales/ar.json
index 7a0e37fb37..3e70edb769 100644
--- a/packages/dashboard/src/locales/ar.json
+++ b/packages/dashboard/src/locales/ar.json
@@ -1721,6 +1721,10 @@
"label": "رمز القسيمة",
"placeholder": "اختياري"
},
+ "currency": {
+ "help": "يحددها السوق.",
+ "label": "العملة"
+ },
"customer_note": {
"label": "ملاحظة العميل (مرئية للعميل)"
},
@@ -1732,10 +1736,12 @@
"label": "ملاحظة داخلية (للموظفين فقط)"
},
"locale": {
- "label": "لغة"
+ "label": "لغة",
+ "help": "تُستخدم في رسائل البريد الإلكتروني والمستندات التي يتلقاها العميل."
},
"market": {
- "label": "سوق"
+ "label": "سوق",
+ "help": "يحدد أسعار الطلب وضرائبه، والعملة واللغات المتاحة له."
},
"order_group": {
"label": "عملية الشراء",
@@ -2902,7 +2908,8 @@
},
"address_edit": {
"billing_title": "تحرير عنوان الفواتير",
- "shipping_title": "تحرير عنوان الشحن"
+ "shipping_title": "تحرير عنوان الشحن",
+ "billing_same_as_shipping": "نفس عنوان الشحن"
},
"adjustment_lines": {
"add_discount": "إضافة خصم",
@@ -3234,6 +3241,12 @@
"captures": "عمليات التحصيل",
"captures_empty": "لم يتم تحصيل أي مبلغ بعد.",
"captured_at": "تاريخ التحصيل"
+ },
+ "customer_edit": {
+ "title": "تعديل العميل",
+ "customer_help": "أزل العميل لتحويل هذا الطلب إلى طلب ضيف.",
+ "confirm_detach": "لن يظهر هذا الطلب بعد الآن في سجل طلبات العميل أو حسابه. هل تريد إزالة العميل؟",
+ "detach": "إزالة العميل"
}
},
"edit": {
@@ -3698,10 +3711,22 @@
"new": {
"add_line_item": "إضافة بند",
"company_help": "اربط هذا الطلب بشركة. ستعرض قائمة العملاء عندئذ الأشخاص المخوّلين بالشراء لها فقط.",
+ "reset_items": {
+ "confirm": "تغيير وإزالة العناصر",
+ "message_few": "قد لا تُباع العناصر المختارة ({{count}}) لهذا المشتري أو في هذا السوق أو هذه القناة، أو قد يختلف سعرها. ستتم إزالتها.",
+ "message_many": "قد لا تُباع العناصر المختارة ({{count}}) لهذا المشتري أو في هذا السوق أو هذه القناة، أو قد يختلف سعرها. ستتم إزالتها.",
+ "message_one": "قد لا تُباع العناصر المختارة ({{count}}) لهذا المشتري أو في هذا السوق أو هذه القناة، أو قد يختلف سعرها. ستتم إزالتها.",
+ "message_other": "قد لا تُباع العناصر المختارة ({{count}}) لهذا المشتري أو في هذا السوق أو هذه القناة، أو قد يختلف سعرها. ستتم إزالتها.",
+ "message_two": "قد لا تُباع العناصر المختارة ({{count}}) لهذا المشتري أو في هذا السوق أو هذه القناة، أو قد يختلف سعرها. ستتم إزالتها.",
+ "message_zero": "قد لا تُباع العناصر المختارة ({{count}}) لهذا المشتري أو في هذا السوق أو هذه القناة، أو قد يختلف سعرها. ستتم إزالتها.",
+ "title": "إزالة العناصر المختارة؟"
+ },
"search_variant": "متغير البحث…",
"section_billing": "الفواتير",
"section_customer": "العميل",
"section_items": "أغراض",
+ "section_market": "السوق والقناة",
+ "section_market_help": "ما يمكن بيعه وسعره يعتمدان على المشتري والسوق والقناة.",
"section_notes": "ملحوظات",
"section_summary": "ملخص",
"select_company": "الشركة (اختياري)",
diff --git a/packages/dashboard/src/locales/de.json b/packages/dashboard/src/locales/de.json
index cb1bd8b0f9..9d236856d9 100644
--- a/packages/dashboard/src/locales/de.json
+++ b/packages/dashboard/src/locales/de.json
@@ -1703,6 +1703,10 @@
"label": "Gutscheincode",
"placeholder": "Optional"
},
+ "currency": {
+ "help": "Wird durch den Markt festgelegt.",
+ "label": "Währung"
+ },
"customer_note": {
"label": "Kundennotiz (für Kunden sichtbar)"
},
@@ -1714,10 +1718,12 @@
"label": "Interne Notiz (nur Mitarbeiter)"
},
"locale": {
- "label": "Sprache"
+ "label": "Sprache",
+ "help": "Wird für die E-Mails und Dokumente verwendet, die der Kunde erhält."
},
"market": {
- "label": "Markt"
+ "label": "Markt",
+ "help": "Legt Preise und Steuern der Bestellung fest sowie die verfügbaren Währungen und Sprachen."
},
"order_group": {
"label": "Einkauf",
@@ -2884,7 +2890,8 @@
},
"address_edit": {
"billing_title": "Rechnungsadresse bearbeiten",
- "shipping_title": "Lieferadresse bearbeiten"
+ "shipping_title": "Lieferadresse bearbeiten",
+ "billing_same_as_shipping": "Wie Lieferadresse"
},
"adjustment_lines": {
"add_discount": "Rabatt hinzufügen",
@@ -3214,6 +3221,12 @@
"captures": "Erfassungen",
"captures_empty": "Es wurde noch nichts erfasst.",
"captured_at": "Erfasst"
+ },
+ "customer_edit": {
+ "title": "Kunde bearbeiten",
+ "customer_help": "Entfernen Sie den Kunden, um daraus eine Gastbestellung zu machen.",
+ "confirm_detach": "Diese Bestellung erscheint nicht mehr im Bestellverlauf und Konto des Kunden. Kunde entfernen?",
+ "detach": "Kunde entfernen"
}
},
"edit": {
@@ -3670,10 +3683,18 @@
"new": {
"add_line_item": "Position hinzufügen",
"company_help": "Diese Bestellung einem Unternehmen zuordnen. Die Kundenliste zeigt dann nur Personen, die dafür einkaufen dürfen.",
+ "reset_items": {
+ "confirm": "Ändern und Artikel entfernen",
+ "message_one": "Der ausgewählte Artikel ({{count}}) ist für diesen Käufer, Markt oder Kanal eventuell nicht verfügbar oder kostet etwas anderes. Er wird entfernt.",
+ "message_other": "Die {{count}} ausgewählten Artikel sind für diesen Käufer, Markt oder Kanal eventuell nicht verfügbar oder kosten etwas anderes. Sie werden entfernt.",
+ "title": "Ausgewählte Artikel entfernen?"
+ },
"search_variant": "Variante suchen…",
"section_billing": "Rechnung",
"section_customer": "Kunde",
"section_items": "Artikel",
+ "section_market": "Markt und Kanal",
+ "section_market_help": "Was verkauft werden kann und zu welchem Preis, hängt vom Käufer, vom Markt und vom Kanal ab.",
"section_notes": "Notizen",
"section_summary": "Zusammenfassung",
"select_company": "Firma (optional)",
diff --git a/packages/dashboard/src/locales/en.json b/packages/dashboard/src/locales/en.json
index bd30ee7b66..b4f6540c08 100644
--- a/packages/dashboard/src/locales/en.json
+++ b/packages/dashboard/src/locales/en.json
@@ -1703,6 +1703,10 @@
"label": "Coupon code",
"placeholder": "Optional"
},
+ "currency": {
+ "help": "Set by the market.",
+ "label": "Currency"
+ },
"customer_note": {
"label": "Customer note (visible to customer)"
},
@@ -1714,10 +1718,12 @@
"label": "Internal note (staff only)"
},
"locale": {
- "label": "Locale"
+ "label": "Locale",
+ "help": "Used for the emails and documents the customer receives."
},
"market": {
- "label": "Market"
+ "label": "Market",
+ "help": "Sets the order's pricing and taxes, and which currency and locales it can use."
},
"order_group": {
"label": "Purchase",
@@ -2884,7 +2890,8 @@
},
"address_edit": {
"billing_title": "Edit Billing Address",
- "shipping_title": "Edit Shipping Address"
+ "shipping_title": "Edit Shipping Address",
+ "billing_same_as_shipping": "Same as shipping address"
},
"adjustment_lines": {
"add_discount": "Add discount",
@@ -3214,6 +3221,12 @@
"captures": "Captures",
"captures_empty": "Nothing has been captured yet.",
"captured_at": "Captured"
+ },
+ "customer_edit": {
+ "title": "Edit customer",
+ "customer_help": "Clear the customer to make this a guest order.",
+ "confirm_detach": "This order will no longer appear in the customer's order history or account. Remove the customer?",
+ "detach": "Remove customer"
}
},
"edit": {
@@ -3670,10 +3683,18 @@
"new": {
"add_line_item": "Add line item",
"company_help": "Attach this order to a business. The customer list then shows only people who can buy for it.",
+ "reset_items": {
+ "confirm": "Change and remove items",
+ "message_one": "The {{count}} item you picked may not be sold, or may cost something else, for this buyer, market or channel. It will be removed.",
+ "message_other": "The {{count}} items you picked may not be sold, or may cost something else, for this buyer, market or channel. They will be removed.",
+ "title": "Remove the picked items?"
+ },
"search_variant": "Search variant…",
"section_billing": "Billing",
"section_customer": "Customer",
"section_items": "Items",
+ "section_market": "Market and channel",
+ "section_market_help": "What can be sold, and at what price, depends on the buyer, the market and the channel.",
"section_notes": "Notes",
"section_summary": "Summary",
"select_company": "Company (optional)",
diff --git a/packages/dashboard/src/locales/es.json b/packages/dashboard/src/locales/es.json
index 3a666877b1..ad3c4087e1 100644
--- a/packages/dashboard/src/locales/es.json
+++ b/packages/dashboard/src/locales/es.json
@@ -349,10 +349,19 @@
"new": {
"add_line_item": "Agregar línea de pedido",
"company_help": "Vinculá este pedido a una empresa. La lista de clientes mostrará solo a quienes puedan comprar para ella.",
+ "reset_items": {
+ "confirm": "Cambiar y quitar artículos",
+ "message_many": "Es posible que los {{count}} artículos elegidos no se vendan, o cuesten otra cosa, para este comprador, mercado o canal. Se quitarán.",
+ "message_one": "Es posible que el {{count}} artículo elegido no se venda, o cueste otra cosa, para este comprador, mercado o canal. Se quitará.",
+ "message_other": "Es posible que los {{count}} artículos elegidos no se vendan, o cuesten otra cosa, para este comprador, mercado o canal. Se quitarán.",
+ "title": "¿Quitar los artículos elegidos?"
+ },
"search_variant": "Buscar variante…",
"section_billing": "Facturación",
"section_customer": "Cliente",
"section_items": "Artículos",
+ "section_market": "Mercado y canal",
+ "section_market_help": "Lo que se puede vender, y a qué precio, depende del comprador, el mercado y el canal.",
"section_notes": "Notas",
"section_summary": "Resumen",
"select_company": "Empresa (opcional)",
@@ -1597,6 +1606,10 @@
"label": "Código de cupón",
"placeholder": "Opcional"
},
+ "currency": {
+ "help": "La define el mercado.",
+ "label": "Moneda"
+ },
"customer_note": {
"label": "Nota del cliente (visible para el cliente)"
},
@@ -1608,10 +1621,12 @@
"label": "Nota interna (solo staff)"
},
"locale": {
- "label": "Idioma"
+ "label": "Idioma",
+ "help": "Se usa en los correos y documentos que recibe el cliente."
},
"market": {
- "label": "Mercado"
+ "label": "Mercado",
+ "help": "Define los precios e impuestos del pedido, y qué moneda e idiomas puede usar."
},
"order_group": {
"label": "Compra",
@@ -2525,7 +2540,8 @@
},
"address_edit": {
"billing_title": "Editar dirección de facturación",
- "shipping_title": "Editar dirección de envío"
+ "shipping_title": "Editar dirección de envío",
+ "billing_same_as_shipping": "Igual que la dirección de envío"
},
"adjustment_lines": {
"add_discount": "Agregar descuento",
@@ -2855,6 +2871,12 @@
"captures": "Capturas",
"captures_empty": "Aún no se ha capturado nada.",
"captured_at": "Capturado"
+ },
+ "customer_edit": {
+ "title": "Editar cliente",
+ "customer_help": "Quita el cliente para convertir este pedido en un pedido de invitado.",
+ "confirm_detach": "Este pedido dejará de aparecer en el historial de pedidos y la cuenta del cliente. ¿Quitar el cliente?",
+ "detach": "Quitar cliente"
}
},
"edit": {
diff --git a/packages/dashboard/src/locales/fr.json b/packages/dashboard/src/locales/fr.json
index b11bc0edc2..1f522c3d5c 100644
--- a/packages/dashboard/src/locales/fr.json
+++ b/packages/dashboard/src/locales/fr.json
@@ -1703,6 +1703,10 @@
"label": "Code promo",
"placeholder": "Facultatif"
},
+ "currency": {
+ "help": "Définie par le marché.",
+ "label": "Devise"
+ },
"customer_note": {
"label": "Note du client (visible par le client)"
},
@@ -1714,10 +1718,12 @@
"label": "Note interne (personnel uniquement)"
},
"locale": {
- "label": "Langue"
+ "label": "Langue",
+ "help": "Utilisée pour les e-mails et documents envoyés au client."
},
"market": {
- "label": "Marché"
+ "label": "Marché",
+ "help": "Définit les prix et les taxes de la commande, ainsi que la devise et les langues disponibles."
},
"order_group": {
"label": "Achat",
@@ -2884,7 +2890,8 @@
},
"address_edit": {
"billing_title": "Modifier l'adresse de facturation",
- "shipping_title": "Modifier l'adresse de livraison"
+ "shipping_title": "Modifier l'adresse de livraison",
+ "billing_same_as_shipping": "Identique à l'adresse de livraison"
},
"adjustment_lines": {
"add_discount": "Ajouter une remise",
@@ -3214,6 +3221,12 @@
"captures": "Captures",
"captures_empty": "Rien n'a encore été capturé.",
"captured_at": "Capturé"
+ },
+ "customer_edit": {
+ "title": "Modifier le client",
+ "customer_help": "Retirez le client pour en faire une commande invité.",
+ "confirm_detach": "Cette commande n'apparaîtra plus dans l'historique des commandes ni dans le compte du client. Retirer le client ?",
+ "detach": "Retirer le client"
}
},
"edit": {
@@ -3670,10 +3683,19 @@
"new": {
"add_line_item": "Ajouter une ligne d'article",
"company_help": "Rattacher cette commande à une entreprise. La liste des clients n'affiche alors que les personnes autorisées à acheter pour elle.",
+ "reset_items": {
+ "confirm": "Modifier et retirer les articles",
+ "message_many": "Les {{count}} articles choisis ne sont peut-être pas vendus, ou à un autre prix, pour cet acheteur, ce marché ou ce canal. Ils seront retirés.",
+ "message_one": "L'article choisi ({{count}}) n'est peut-être pas vendu, ou à un autre prix, pour cet acheteur, ce marché ou ce canal. Il sera retiré.",
+ "message_other": "Les {{count}} articles choisis ne sont peut-être pas vendus, ou à un autre prix, pour cet acheteur, ce marché ou ce canal. Ils seront retirés.",
+ "title": "Retirer les articles choisis ?"
+ },
"search_variant": "Rechercher une variante…",
"section_billing": "Facturation",
"section_customer": "Client",
"section_items": "Articles",
+ "section_market": "Marché et canal",
+ "section_market_help": "Ce qui peut être vendu, et à quel prix, dépend de l'acheteur, du marché et du canal.",
"section_notes": "Notes",
"section_summary": "Récapitulatif",
"select_company": "Entreprise (facultatif)",
diff --git a/packages/dashboard/src/locales/pl.json b/packages/dashboard/src/locales/pl.json
index 0cda59afb0..4799d3d73d 100644
--- a/packages/dashboard/src/locales/pl.json
+++ b/packages/dashboard/src/locales/pl.json
@@ -1721,6 +1721,10 @@
"label": "Kod kuponu",
"placeholder": "Opcjonalnie"
},
+ "currency": {
+ "help": "Ustalana przez rynek.",
+ "label": "Waluta"
+ },
"customer_note": {
"label": "Notatka klienta (widoczna dla klienta)"
},
@@ -1732,10 +1736,12 @@
"label": "Notatka wewnętrzna (tylko dla personelu)"
},
"locale": {
- "label": "Język"
+ "label": "Język",
+ "help": "Używany w e-mailach i dokumentach wysyłanych do klienta."
},
"market": {
- "label": "Rynek"
+ "label": "Rynek",
+ "help": "Określa ceny i podatki zamówienia oraz dostępną walutę i języki."
},
"order_group": {
"label": "Zakup",
@@ -2908,7 +2914,8 @@
},
"address_edit": {
"billing_title": "Edytuj adres rozliczeniowy",
- "shipping_title": "Edytuj adres wysyłki"
+ "shipping_title": "Edytuj adres wysyłki",
+ "billing_same_as_shipping": "Taki sam jak adres dostawy"
},
"adjustment_lines": {
"add_discount": "Dodaj rabat",
@@ -3242,6 +3249,12 @@
"captures": "Pobrania środków",
"captures_empty": "Nie pobrano jeszcze żadnych środków.",
"captured_at": "Pobrano"
+ },
+ "customer_edit": {
+ "title": "Edytuj klienta",
+ "customer_help": "Usuń klienta, aby zamówienie stało się zamówieniem gościa.",
+ "confirm_detach": "To zamówienie zniknie z historii zamówień i konta klienta. Usunąć klienta?",
+ "detach": "Usuń klienta"
}
},
"edit": {
@@ -3708,10 +3721,20 @@
"new": {
"add_line_item": "Dodaj pozycję",
"company_help": "Przypisz to zamówienie do firmy. Lista klientów pokaże wtedy tylko osoby, które mogą dla niej kupować.",
+ "reset_items": {
+ "confirm": "Zmień i usuń pozycje",
+ "message_few": "{{count}} wybrane pozycje mogą nie być sprzedawane temu kupującemu, na tym rynku lub w tym kanale albo mieć inną cenę. Zostaną usunięte.",
+ "message_many": "{{count}} wybranych pozycji może nie być sprzedawanych temu kupującemu, na tym rynku lub w tym kanale albo mieć inną cenę. Zostaną usunięte.",
+ "message_one": "Wybrana pozycja ({{count}}) może nie być sprzedawana temu kupującemu, na tym rynku lub w tym kanale albo mieć inną cenę. Zostanie usunięta.",
+ "message_other": "{{count}} wybranej pozycji może nie być sprzedawane temu kupującemu, na tym rynku lub w tym kanale albo mieć inną cenę. Zostaną usunięte.",
+ "title": "Usunąć wybrane pozycje?"
+ },
"search_variant": "Szukaj wariantu…",
"section_billing": "Rozliczenie",
"section_customer": "Klient",
"section_items": "Pozycje",
+ "section_market": "Rynek i kanał",
+ "section_market_help": "To, co można sprzedać i po jakiej cenie, zależy od kupującego, rynku i kanału.",
"section_notes": "Notatki",
"section_summary": "Podsumowanie",
"select_company": "Firma (opcjonalnie)",
diff --git a/packages/dashboard/src/locales/zh-CN.json b/packages/dashboard/src/locales/zh-CN.json
index 6d926f9dfa..c008c3c030 100644
--- a/packages/dashboard/src/locales/zh-CN.json
+++ b/packages/dashboard/src/locales/zh-CN.json
@@ -1698,6 +1698,10 @@
"label": "优惠码",
"placeholder": "可选"
},
+ "currency": {
+ "help": "由市场决定。",
+ "label": "货币"
+ },
"customer_note": {
"label": "客户备注(客户可见)"
},
@@ -1709,10 +1713,12 @@
"label": "内部备注(仅员工可见)"
},
"locale": {
- "label": "语言区域"
+ "label": "语言区域",
+ "help": "用于发送给客户的邮件和文档。"
},
"market": {
- "label": "市场"
+ "label": "市场",
+ "help": "决定订单的价格和税费,以及可用的货币和语言区域。"
},
"order_group": {
"label": "本次购买",
@@ -2877,7 +2883,8 @@
},
"address_edit": {
"billing_title": "编辑账单地址",
- "shipping_title": "编辑收货地址"
+ "shipping_title": "编辑收货地址",
+ "billing_same_as_shipping": "与收货地址相同"
},
"adjustment_lines": {
"add_discount": "添加折扣",
@@ -3206,6 +3213,12 @@
"captures": "扣款记录",
"captures_empty": "尚未扣款。",
"captured_at": "扣款时间"
+ },
+ "customer_edit": {
+ "title": "编辑客户",
+ "customer_help": "清除客户即可将此订单改为访客订单。",
+ "confirm_detach": "此订单将不再显示在客户的订单历史和账户中。要移除客户吗?",
+ "detach": "移除客户"
}
},
"edit": {
@@ -3660,10 +3673,17 @@
"new": {
"add_line_item": "添加订单项",
"company_help": "将此订单关联到某个公司。客户列表随后只显示可为其采购的人员。",
+ "reset_items": {
+ "confirm": "更改并移除商品",
+ "message_other": "已选的 {{count}} 件商品可能不向此买家、市场或渠道销售,或价格不同。它们将被移除。",
+ "title": "移除已选商品?"
+ },
"search_variant": "搜索变体…",
"section_billing": "账单",
"section_customer": "客户",
"section_items": "商品",
+ "section_market": "市场和渠道",
+ "section_market_help": "可销售的商品及其价格取决于买家、市场和渠道。",
"section_notes": "备注",
"section_summary": "概览",
"select_company": "公司(可选)",
diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/orders/$orderId/edit.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/orders/$orderId/edit.tsx
index 2ccdec4a0d..3e05615d7e 100644
--- a/packages/dashboard/src/routes/_authenticated/$storeId/orders/$orderId/edit.tsx
+++ b/packages/dashboard/src/routes/_authenticated/$storeId/orders/$orderId/edit.tsx
@@ -372,7 +372,12 @@ function OrderEditPage() {
</form>
{addingItem && (
- <AddLineItemDialog open={addingItem} onOpenChange={setAddingItem} onSelect={stageVariant} />
+ <AddLineItemDialog
+ orderId={orderId}
+ open={addingItem}
+ onOpenChange={setAddingItem}
+ onSelect={stageVariant}
+ />
)}
</>
)
diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/orders/new.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/orders/new.tsx
index 5880568ce5..1885911579 100644
--- a/packages/dashboard/src/routes/_authenticated/$storeId/orders/new.tsx
+++ b/packages/dashboard/src/routes/_authenticated/$storeId/orders/new.tsx
@@ -2,18 +2,22 @@ import { zodResolver } from '@hookform/resolvers/zod'
import type { Company, Customer, Variant } from '@spree/admin-sdk'
import {
adminClient,
+ CurrencySelect,
EMPTY_FILE_UPLOAD_VALUE,
FileUploadField,
type FileUploadValue,
formatPrice,
+ LocaleSelect,
mapSpreeErrorsToForm,
PageHeader,
ResourceCombobox,
+ useStore,
} from '@spree/dashboard-core'
import {
Button,
Card,
CardContent,
+ CardDescription,
CardHeader,
CardTitle,
Field,
@@ -23,6 +27,11 @@ import {
FieldLabel,
Input,
ResourceLayout,
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
Switch,
Table,
TableBody,
@@ -31,6 +40,7 @@ import {
TableHeader,
TableRow,
Textarea,
+ useConfirm,
} from '@spree/dashboard-ui'
import { FileTextIcon, TrashIcon } from '@spree/dashboard-ui/icons'
import { useMutation } from '@tanstack/react-query'
@@ -43,6 +53,7 @@ import { CompanyComboboxOption } from '../../../../components/spree/company-comb
import { useChannels } from '../../../../hooks/use-channels'
import { companyAutocompleteProps } from '../../../../hooks/use-companies'
import { customerAutocompleteProps } from '../../../../hooks/use-customers'
+import { useAllMarkets } from '../../../../hooks/use-markets'
import {
NEW_ORDER_DEFAULTS,
type NewOrderFormValues,
@@ -86,9 +97,56 @@ function NewOrderPage() {
})
const { errors } = form.formState
- const { data: channelsData } = useChannels()
+ const confirm = useConfirm()
+ const { data: channelsData, isLoading: channelsLoading } = useChannels()
const channels = channelsData?.data ?? []
+ // A market fixes the order's currency and narrows its languages, so the two
+ // follow the market rather than being chosen independently of it.
+ const { markets, isLoading: marketsLoading } = useAllMarkets()
+ const { currencies, locales, defaultCurrency, defaultLocale } = useStore()
+ const marketId = form.watch('market_id')
+ const market =
+ markets.find((m) => m.id === marketId) ?? markets.find((m) => m.default) ?? markets[0]
+ const currencyOptions = market ? [market.currency] : currencies
+ const localeOptions: string[] = market
+ ? Array.from(new Set([market.default_locale, ...market.supported_locales]))
+ : locales
+ const chosenLocale = form.watch('locale')
+ const currency = market?.currency ?? (form.watch('currency') || defaultCurrency)
+ const locale = localeOptions.includes(chosenLocale)
+ ? chosenLocale
+ : (market?.default_locale ?? defaultLocale)
+ const channelId = form.watch('channel_id') || channels.find((c) => c.default)?.id
+ // Availability and prices depend on who buys, on which channel, in which
+ // market, so the item search asks in exactly that context.
+ const salesContext = {
+ market_id: market?.id,
+ channel_id: channelId,
+ customer_id: customer?.id,
+ company_id: company?.id,
+ currency,
+ }
+
+ // Searching before the defaults arrive would offer items from outside them.
+ const salesContextReady = !marketsLoading && !channelsLoading
+
+ // Items picked for another buyer, market or channel may not be sold, or
+ // priced, the same way in the new one.
+ async function changeSalesContext(apply: () => void) {
+ if (items.length > 0) {
+ const confirmed = await confirm({
+ title: t('admin.pages.orders.new.reset_items.title'),
+ message: t('admin.pages.orders.new.reset_items.message', { count: items.length }),
+ confirmLabel: t('admin.pages.orders.new.reset_items.confirm'),
+ variant: 'destructive',
+ })
+ if (!confirmed) return
+ }
+ apply()
+ setItems([])
+ }
+
const createMutation = useMutation({
mutationFn: (values: NewOrderFormValues) => {
const payload: Record<string, unknown> = {
@@ -109,6 +167,9 @@ function NewOrderPage() {
if (poDocument.signedId) payload.po_document_signed_id = poDocument.signedId
if (values.coupon_code) payload.coupon_code = values.coupon_code
if (values.channel_id) payload.channel_id = values.channel_id
+ if (market) payload.market_id = market.id
+ payload.currency = currency
+ payload.locale = locale
return adminClient.orders.create(payload)
},
onSuccess: (order) => {
@@ -201,12 +262,15 @@ function NewOrderPage() {
{...companyAutocompleteProps('order-company-picker')}
value={company?.id}
onChange={(_id, record) => {
- setCompany(record)
+ if (record?.id === company?.id) return
// A customer already chosen may have no standing for the
// new company, and silently sending that pair would
// attach the order to a business this person cannot buy
// for. Clearing is the honest reset.
- if (record?.id !== company?.id) setCustomer(null)
+ changeSalesContext(() => {
+ setCompany(record)
+ setCustomer(null)
+ })
}}
renderOption={(company) => <CompanyComboboxOption company={company} />}
/>
@@ -217,7 +281,10 @@ function NewOrderPage() {
<ResourceCombobox<Customer>
{...customerAutocompleteProps('customer-picker', company?.id)}
value={customer?.id}
- onChange={(_id, record) => setCustomer(record)}
+ onChange={(_id, record) => {
+ if (record?.id !== customer?.id)
+ changeSalesContext(() => setCustomer(record))
+ }}
renderOption={(c) => (
<div>
<div className="font-medium">{c.email}</div>
@@ -254,6 +321,101 @@ function NewOrderPage() {
</CardContent>
</Card>
+ <Card>
+ <CardHeader>
+ <CardTitle>{t('admin.pages.orders.new.section_market')}</CardTitle>
+ <CardDescription>{t('admin.pages.orders.new.section_market_help')}</CardDescription>
+ </CardHeader>
+ <CardContent>
+ <FieldGroup>
+ <div className="grid gap-4 sm:grid-cols-2">
+ {markets.length > 0 && (
+ <Field>
+ <FieldLabel htmlFor="order-market">
+ {t('admin.fields.order.market.label')}
+ </FieldLabel>
+ <Select
+ value={market?.id ?? ''}
+ disabled={markets.length < 2}
+ onValueChange={(v) =>
+ changeSalesContext(() => {
+ form.setValue('market_id', v as string, { shouldDirty: true })
+ form.setValue('locale', '', { shouldDirty: true })
+ })
+ }
+ >
+ <SelectTrigger id="order-market">
+ <SelectValue>
+ {(v) => markets.find((m) => m.id === v)?.name ?? ''}
+ </SelectValue>
+ </SelectTrigger>
+ <SelectContent>
+ {markets.map((m) => (
+ <SelectItem key={m.id} value={m.id}>
+ {m.name}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ <FieldDescription>{t('admin.fields.order.market.help')}</FieldDescription>
+ </Field>
+ )}
+ {channels.length > 0 && (
+ <Field>
+ <FieldLabel htmlFor="order-channel">
+ {t('admin.fields.order.channel.label')}
+ </FieldLabel>
+ <ChannelSelect
+ id="order-channel"
+ value={channelId ?? ''}
+ disabled={channels.length < 2}
+ onChange={(v) =>
+ changeSalesContext(() =>
+ form.setValue('channel_id', v, { shouldDirty: true }),
+ )
+ }
+ placeholder={t('admin.fields.order.channel.placeholder')}
+ />
+ <FieldDescription>{t('admin.fields.order.channel.help')}</FieldDescription>
+ </Field>
+ )}
+ <Field>
+ <FieldLabel htmlFor="order-currency">
+ {t('admin.fields.order.currency.label')}
+ </FieldLabel>
+ <CurrencySelect
+ id="order-currency"
+ value={currency}
+ options={currencyOptions}
+ disabled={currencyOptions.length < 2}
+ onChange={(v) =>
+ changeSalesContext(() =>
+ form.setValue('currency', v, { shouldDirty: true }),
+ )
+ }
+ />
+ {market && (
+ <FieldDescription>{t('admin.fields.order.currency.help')}</FieldDescription>
+ )}
+ </Field>
+ <Field>
+ <FieldLabel htmlFor="order-locale">
+ {t('admin.fields.order.locale.label')}
+ </FieldLabel>
+ <LocaleSelect
+ id="order-locale"
+ value={locale}
+ options={localeOptions}
+ disabled={localeOptions.length < 2}
+ onChange={(v) => form.setValue('locale', v, { shouldDirty: true })}
+ />
+ <FieldDescription>{t('admin.fields.order.locale.help')}</FieldDescription>
+ </Field>
+ </div>
+ </FieldGroup>
+ </CardContent>
+ </Card>
+
<Card>
<CardHeader>
<CardTitle>{t('admin.pages.orders.new.section_items')}</CardTitle>
@@ -268,14 +430,19 @@ function NewOrderPage() {
adds the row and clears the field, so no value is
held — the picker is an action, not a bound input. */}
<ResourceCombobox<Variant>
- queryKey="new-order-variant-picker"
+ queryKey={`new-order-variant-picker:${JSON.stringify(salesContext)}`}
+ disabled={!salesContextReady}
value=""
onChange={(id) => {
const variant = id ? variantById.current.get(id) : undefined
if (variant) addItem(variant)
}}
search={async (query) => {
- const res = await adminClient.variants.list({ search: query, limit: 8 })
+ const res = await adminClient.variants.list({
+ search: query,
+ limit: 8,
+ ...salesContext,
+ })
for (const v of res.data) variantById.current.set(v.id, v)
return res
}}
@@ -418,28 +585,6 @@ function NewOrderPage() {
</CardContent>
</Card>
- {channels.length > 1 && (
- <Card>
- <CardHeader>
- <CardTitle>{t('admin.fields.order.channel.label')}</CardTitle>
- </CardHeader>
- <CardContent>
- <FieldGroup>
- <Field>
- <ChannelSelect
- value={form.watch('channel_id') || ''}
- onChange={(v) => form.setValue('channel_id', v, { shouldDirty: true })}
- placeholder={t('admin.fields.order.channel.placeholder')}
- />
- <span className="text-xs text-muted-foreground">
- {t('admin.fields.order.channel.help')}
- </span>
- </Field>
- </FieldGroup>
- </CardContent>
- </Card>
- )}
-
<Card>
<CardHeader>
<CardTitle>{t('admin.fields.discount.label')}</CardTitle>
diff --git a/packages/dashboard/src/schemas/order.ts b/packages/dashboard/src/schemas/order.ts
index 8db7e82028..77980c44aa 100644
--- a/packages/dashboard/src/schemas/order.ts
+++ b/packages/dashboard/src/schemas/order.ts
@@ -27,6 +27,11 @@ export const newOrderFormSchema = z.object({
// Empty string = "use store default" (resolved server-side via
// Order#ensure_channel_presence).
channel_id: z.string(),
+ // Empty strings fall back to the store's default market, the market's
+ // currency and its default language. A market has exactly one currency.
+ market_id: z.string(),
+ currency: z.string(),
+ locale: z.string(),
})
export type NewOrderFormValues = z.infer<typeof newOrderFormSchema>
@@ -42,6 +47,9 @@ export const NEW_ORDER_DEFAULTS: NewOrderFormValues = {
po_number: '',
coupon_code: '',
channel_id: '',
+ market_id: '',
+ currency: '',
+ locale: '',
}
/**
diff --git a/packages/sdk/src/types/generated/Order.ts b/packages/sdk/src/types/generated/Order.ts
index 05ebab2800..d692e50b9e 100644
--- a/packages/sdk/src/types/generated/Order.ts
+++ b/packages/sdk/src/types/generated/Order.ts
@@ -1,4 +1,4 @@
-// Typelizer digest 3b0cd1a18e5ae733270178fb7953b117
+// Typelizer digest 70cad850e62121c3d89734f7746244a8
//
// DO NOT MODIFY: This file was automatically generated by Typelizer.
import type {Payment, AppliedPromotion, Fee, LineItem, Fulfillment, Address, GiftCard, Market, CurrencyCode, LocaleCode} from '@/types'
@@ -8,6 +8,7 @@ interface Order {
market_id: string | null;
withdrawal_period_ends_at: string | null;
within_withdrawal_period: boolean;
+ shipping_eq_billing_address: boolean;
cart_id: string | null;
channel_id: string | null;
company_id: string | null;
diff --git a/packages/sdk/src/zod/generated/Order.ts b/packages/sdk/src/zod/generated/Order.ts
index 29ccab3881..859cb1e31e 100644
--- a/packages/sdk/src/zod/generated/Order.ts
+++ b/packages/sdk/src/zod/generated/Order.ts
@@ -14,6 +14,7 @@ export const OrderSchema = z.object({
market_id: z.string().nullable(),
withdrawal_period_ends_at: z.string().nullable(),
within_withdrawal_period: z.boolean(),
+ shipping_eq_billing_address: z.boolean(),
cart_id: z.string().nullable(),
channel_id: z.string().nullable(),
company_id: z.string().nullable(),
diff --git a/spree/api/app/controllers/concerns/spree/api/v3/scoped_authorization.rb b/spree/api/app/controllers/concerns/spree/api/v3/scoped_authorization.rb
index d087974e33..fa227caa8a 100644
--- a/spree/api/app/controllers/concerns/spree/api/v3/scoped_authorization.rb
+++ b/spree/api/app/controllers/concerns/spree/api/v3/scoped_authorization.rb
@@ -159,11 +159,15 @@ module Spree
"held=#{ability.permission_keys.join(',')}"
end
+ render_missing_permission(required)
+ end
+
+ def render_missing_permission(permission)
render_error(
code: Spree::Api::V3::ErrorHandler::ERROR_CODES[:access_denied],
- message: "Missing permission: #{required}",
+ message: "Missing permission: #{permission}",
status: :forbidden,
- details: { required_permission: required }
+ details: { required_permission: permission }
)
end
diff --git a/spree/api/app/controllers/spree/api/v3/admin/customers_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/customers_controller.rb
index 3e64bdd279..8f7c3b4aa1 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/customers_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/customers_controller.rb
@@ -248,12 +248,7 @@ module Spree
missing = EXPORT_PERMISSIONS.reject { |permission| holds_permission?(permission) }
return true if missing.empty?
- render_error(
- code: Spree::Api::V3::ErrorHandler::ERROR_CODES[:access_denied],
- message: "Missing permission: #{missing.first}",
- status: :forbidden,
- details: { required_permission: missing.first }
- )
+ render_missing_permission(missing.first)
false
end
diff --git a/spree/api/app/controllers/spree/api/v3/admin/gift_cards_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/gift_cards_controller.rb
index 883edf629f..7c54c2c46c 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/gift_cards_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/gift_cards_controller.rb
@@ -59,14 +59,7 @@ module Spree
return unless params.key?(:customer_id)
return @customer = nil if params[:customer_id].blank?
- unless holds_permission?('read_customers')
- return render_error(
- code: Spree::Api::V3::ErrorHandler::ERROR_CODES[:access_denied],
- message: 'Missing permission: read_customers',
- status: :forbidden,
- details: { required_permission: 'read_customers' }
- )
- end
+ return render_missing_permission('read_customers') unless holds_permission?('read_customers')
@customer = Spree.customer_class.
accessible_by(current_ability, :show).
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 70af0850df..53e986d28d 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
@@ -17,7 +17,9 @@ module Spree
request_params :order do |body|
body.external_references
body.attribute :email, :string, example: '[email protected]'
- body.attribute :customer_id, :id
+ body.attribute :customer_id, :id,
+ nullable: true,
+ description: 'Null detaches the customer, leaving a guest order under its `email`.'
body.attribute :use_customer_default_address, :boolean,
only: :create,
description: "With `customer_id`, copies the customer's saved billing and shipping addresses onto the order."
@@ -51,6 +53,8 @@ module Spree
body.attribute :tags, :array, of: :string
body.attribute :shipping_address, :object, shape: ADDRESS
body.attribute :billing_address, :object, shape: ADDRESS
+ body.attribute :use_shipping, :boolean,
+ description: 'When true, copies the shipping address to the billing address.'
body.attribute :items, :array,
description: 'Line items to upsert, keyed by variant. An entry sets that variant\'s quantity, creating the line item when the order has none; `quantity: 0` removes it. Variants you do not send are left alone.' do |item|
item.attribute :variant_id, :id, required: true
@@ -343,7 +347,9 @@ module Spree
# Named rather than read from the action, since an upsert reaches
# update from the create action.
def order_update_params
- resolve_company_param(normalize_params(params.permit(*request_params_schema.permit_list(:update))))
+ permitted = resolve_company_param(normalize_params(params.permit(*request_params_schema.permit_list(:update))))
+ permitted[:customer_id] = resolve_customer&.id if permitted.key?(:customer_id)
+ permitted
end
# An incidental lookup like any other: resolved through the store so
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 5d74f741ab..f169dfce38 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
@@ -5,6 +5,30 @@ module Spree
class VariantsController < ResourceController
scoped_resource :products
+ SALES_CONTEXT = Spree::Api::V3::RequestSchema.shape('VariantSalesContextParams') do |query|
+ query.attribute :order_id, :id,
+ description: 'A draft order to sell to: lists only what its buyer can be sold on its channel, ' \
+ 'priced in its market. Needs `read_orders`, and cannot be combined with the fields below.'
+ query.attribute :market_id, :id,
+ description: 'Prices in this market and lists only variants with a price in its currency.'
+ query.attribute :channel_id, :id,
+ description: 'Lists only variants published on this channel. When a market, customer, company or ' \
+ "currency is given without it, the store default channel applies; an order uses its own."
+ query.attribute :customer_id, :id,
+ description: "Narrows to the customer's catalogs and prices as they would pay. Needs `read_customers`."
+ query.attribute :company_id, :id,
+ description: "Narrows to the company's catalogs and prices under its agreement. Needs `read_customers`."
+ query.attribute :currency, :currency,
+ description: 'Lists only variants with a price in this currency. ' \
+ "With `market_id` it must be the market's currency."
+ end
+ SALES_CONTEXT_PARAMS = (SALES_CONTEXT.fields.keys - [:order_id]).freeze
+
+ # A draft order's item picker asks with the order's market, channel and
+ # buyer, so it lists only what that buyer can be sold there, priced as
+ # they would pay.
+ before_action :load_sales_context, only: :index
+
protected
def model_class
@@ -19,7 +43,21 @@ module Spree
# relation from scratch dropped `scope_includes`, so every listed
# variant fell back to per-row price and stock queries.
def scope
- super.eligible.accessible_by(current_ability, ability_action_for_request)
+ variants = super.eligible.accessible_by(current_ability, ability_action_for_request)
+ @sales_context ? variants.where(id: @sales_context.sellable_variants.select(:id)) : variants
+ end
+
+ def serializer_params
+ return super unless @sales_context
+
+ super.merge(
+ currency: @sales_context.currency,
+ user: @sales_context.customer,
+ company: @sales_context.company,
+ market: @sales_context.market,
+ channel: @sales_context.channel,
+ country: @sales_context.country
+ )
end
# `active_stock_reservations` rides along with the stock levels:
@@ -33,6 +71,63 @@ module Spree
{ primary_media: [{ attachment_attachment: :blob }, { poster_attachment: :blob }] }
]
end
+
+ private
+
+ def load_sales_context
+ requested = SALES_CONTEXT_PARAMS.select { |key| params[key].present? }
+ return if requested.empty? && params[:order_id].blank?
+
+ permission = required_sales_context_permission
+ return render_missing_permission(permission) if permission && !holds_permission?(permission)
+
+ if params[:order_id].present?
+ return refuse_order_with_context(requested) if requested.any?
+
+ @sales_context = Spree::SalesContext.from_order(context_order)
+ else
+ @sales_context = requested_sales_context
+ render_errors(@sales_context.errors) unless @sales_context.valid?
+ end
+ end
+
+ # An order already fixes its market, channel, buyer and currency, so
+ # naming them too could only disagree with it.
+ def refuse_order_with_context(requested)
+ render_error(
+ code: Spree::Api::V3::ErrorHandler::ERROR_CODES[:parameter_invalid],
+ message: I18n.t('spree.api.errors.order_sales_context_exclusive', params: requested.join(', ')),
+ status: :unprocessable_content,
+ details: { order_id: requested.map(&:to_s) }
+ )
+ end
+
+ def required_sales_context_permission
+ return 'read_orders' if params[:order_id].present?
+
+ 'read_customers' if params[:customer_id].present? || params[:company_id].present?
+ end
+
+ def requested_sales_context
+ Spree::SalesContext.new(
+ store: current_store,
+ market: find_requested(current_store.markets, :market_id),
+ channel: find_requested(current_store.channels, :channel_id),
+ customer: find_requested(
+ Spree.customer_class.for_store(current_store).accessible_by(current_ability, :show), :customer_id
+ ),
+ company: find_requested(current_store.companies, :company_id),
+ currency: params[:currency]
+ )
+ end
+
+ def find_requested(relation, key)
+ relation.find_by_prefix_id!(params[key]) if params[key].present?
+ end
+
+ def context_order
+ current_store.orders.accessible_by(current_ability, :show).find_by_prefix_id!(params[:order_id])
+ end
end
end
end
diff --git a/spree/api/app/serializers/spree/api/v3/base_serializer.rb b/spree/api/app/serializers/spree/api/v3/base_serializer.rb
index 0351c63660..be8bcd1975 100644
--- a/spree/api/app/serializers/spree/api/v3/base_serializer.rb
+++ b/spree/api/app/serializers/spree/api/v3/base_serializer.rb
@@ -277,6 +277,10 @@ module Spree
currency: current_currency,
store: current_store,
user: current_user,
+ company: params[:company],
+ market: params[:market],
+ channel: params[:channel],
+ country: params[:country],
quantity: quantity
)
end
@@ -295,8 +299,9 @@ module Spree
return Spree::QuantityRule.new if current_store.nil?
Spree::Current.quantity_rules_resolver_for(
- company: Spree::Current.standing_company_for(current_user),
- user: current_user
+ company: params.key?(:company) ? params[:company] : Spree::Current.standing_company_for(current_user),
+ user: current_user,
+ channel: params[:channel]
).call(variant)
end
diff --git a/spree/api/app/serializers/spree/api/v3/order_serializer.rb b/spree/api/app/serializers/spree/api/v3/order_serializer.rb
index 97fcc9e152..fa1d5acdcf 100644
--- a/spree/api/app/serializers/spree/api/v3/order_serializer.rb
+++ b/spree/api/app/serializers/spree/api/v3/order_serializer.rb
@@ -15,6 +15,7 @@ module Spree
payment_status: [:string, nullable: true, enum: Spree::Order::PAYMENT_STATUSES],
completed_at: [:string, nullable: true],
withdrawal_period_ends_at: [:string, nullable: true], within_withdrawal_period: :boolean,
+ shipping_eq_billing_address: :boolean,
billing_address: { nullable: true }, shipping_address: { nullable: true },
gift_card: { nullable: true }, market: { nullable: true }
@@ -28,6 +29,7 @@ module Spree
end
attribute :within_withdrawal_period, &:within_withdrawal_period?
+ attribute :shipping_eq_billing_address, &:shipping_eq_billing_address?
# The checkout handle this order was born from (nil for admin drafts).
# Lets abandonment tooling match cart.* events to the conversion.
diff --git a/spree/api/config/locales/en.yml b/spree/api/config/locales/en.yml
index 03797ce28c..6c58a98724 100644
--- a/spree/api/config/locales/en.yml
+++ b/spree/api/config/locales/en.yml
@@ -14,6 +14,7 @@ en:
media_in_use: This file is still in use (%{places}). Pass detach=true to remove it everywhere and delete it, or clear those places first.
media_not_deleted: The file could not be deleted. Nothing was changed.
media_url_import_requires_product: Importing media from a URL needs a product to import it into. Upload the file instead, or post it to a product's media.
+ order_sales_context_exclusive: An order already fixes its sales context, so order_id cannot be combined with %{params}.
store_mismatch: The requested store does not match the store this API key belongs to.
storefront_login_required: Authentication required to access this store.
unsupported_export_type: 'Unsupported export type. Supported types: %{types}'
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/orders_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/orders_controller_spec.rb
index cc62f5f306..af71fb18ee 100644
--- a/spree/api/spec/controllers/spree/api/v3/admin/orders_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/admin/orders_controller_spec.rb
@@ -727,6 +727,18 @@ RSpec.describe Spree::Api::V3::Admin::OrdersController, type: :controller do
end
end
+ context 'with use_shipping' do
+ let(:order) { create(:order, store: store, ship_address: create(:address), bill_address: nil) }
+
+ it 'copies the shipping address to the billing address' do
+ patch :update, params: { id: order.prefixed_id, use_shipping: true }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(json_response['shipping_eq_billing_address']).to be(true)
+ expect(order.reload.bill_address).to eq(order.ship_address)
+ end
+ end
+
# Staff assigning the business an order is for. A buyer with several
# memberships names the node on their own cart; this is the back-office
# equivalent.
@@ -786,6 +798,21 @@ RSpec.describe Spree::Api::V3::Admin::OrdersController, type: :controller do
expect(response).to have_http_status(:ok)
expect(order.reload.customer).to eq(new_customer)
end
+
+ it 'detaches the customer, keeping the order email' do
+ patch :update, params: { id: order.prefixed_id, customer_id: nil }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(order.reload.customer).to be_nil
+ expect(order.email).to be_present
+ end
+
+ it 'refuses a customer that does not exist' do
+ patch :update, params: { id: order.prefixed_id, customer_id: 'cus_missing' }, as: :json
+
+ expect(response).to have_http_status(:not_found)
+ expect(order.reload.customer).to eq(original_customer)
+ end
end
context 'with tags' do
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/variants_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/variants_controller_spec.rb
index 3b18cd15bd..34321b86c8 100644
--- a/spree/api/spec/controllers/spree/api/v3/admin/variants_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/admin/variants_controller_spec.rb
@@ -101,6 +101,102 @@ RSpec.describe Spree::Api::V3::Admin::VariantsController, type: :controller do
end
end
+ context "with a draft order's sales context" do
+ let(:wholesale_channel) { create(:channel, store: store) }
+ let!(:wholesale_product) do
+ create(:product, store: store).tap { |p| create(:product_publication, product: p, channel: wholesale_channel) }
+ end
+
+ it 'lists only products published on the channel' do
+ get :index, params: { channel_id: wholesale_channel.prefixed_id }, as: :json
+
+ product_ids = json_response['data'].map { |v| v['product_id'] }
+ expect(product_ids).to include(wholesale_product.prefixed_id)
+ expect(product_ids).not_to include(product.prefixed_id)
+ end
+
+ context 'and a market' do
+ let(:market) { create(:market, :eu, store: store) }
+ let!(:dollar_only_product) do
+ create(:product, store: store).tap do |dollar_product|
+ create(:product_publication, product: dollar_product, channel: wholesale_channel)
+ end
+ end
+
+ before { wholesale_product.default_variant.set_price('EUR', 20) }
+
+ it "prices in the market's currency and skips products without a price in it" do
+ get :index, params: { channel_id: wholesale_channel.prefixed_id, market_id: market.prefixed_id }, as: :json
+
+ rows = json_response['data']
+ expect(rows.map { |v| v['product_id'] }).to eq([wholesale_product.prefixed_id])
+ expect(rows.first['price']['currency']).to eq('EUR')
+ end
+
+ it 'offers a product priced in the currency only by a price list' do
+ price_list = create(:price_list, :active, store: store)
+ create(:price, variant: dollar_only_product.default_variant, currency: 'EUR', amount: 15,
+ price_list: price_list)
+
+ get :index, params: { channel_id: wholesale_channel.prefixed_id, market_id: market.prefixed_id }, as: :json
+
+ expect(json_response['data'].map { |v| v['product_id'] }).to include(dollar_only_product.prefixed_id)
+ end
+
+ it 'narrows to variants priced in a currency given on its own' do
+ market
+ get :index, params: { currency: 'EUR' }, as: :json
+
+ product_ids = json_response['data'].map { |v| v['product_id'] }
+ expect(product_ids).not_to include(product.prefixed_id)
+ end
+
+ it 'refuses an order combined with other sales context fields' do
+ order = create(:order, store: store, market: market, currency: 'EUR', status: 'draft')
+ get :index, params: { order_id: order.prefixed_id, currency: 'USD' }, as: :json
+
+ expect(response).to have_http_status(:unprocessable_content)
+ end
+
+ it "refuses a currency other than the market's" do
+ get :index, params: { market_id: market.prefixed_id, currency: 'USD' }, as: :json
+
+ expect(response).to have_http_status(:unprocessable_content)
+ end
+
+ it 'reads the context from a draft order' do
+ order = create(:order, store: store, market: market, currency: 'EUR', channel: wholesale_channel,
+ status: 'draft')
+
+ get :index, params: { order_id: order.prefixed_id }, as: :json
+
+ rows = json_response['data']
+ expect(rows.map { |v| v['product_id'] }).to eq([wholesale_product.prefixed_id])
+ expect(rows.first['price']['currency']).to eq('EUR')
+ end
+ end
+
+ context 'with a key that holds products but not customers' do
+ let(:products_key) { create(:api_key, :secret, store: store, scopes: ['read_products']) }
+ let(:headers) { { 'x-spree-api-key' => products_key.plaintext_token } }
+
+ it 'refuses to price for a customer' do
+ customer = create(:user)
+ get :index, params: { channel_id: wholesale_channel.prefixed_id, customer_id: customer.prefixed_id },
+ as: :json
+
+ expect(response).to have_http_status(:forbidden)
+ end
+ end
+
+ it 'refuses a channel from another store' do
+ foreign_channel = create(:channel, store: create(:store))
+ get :index, params: { channel_id: foreign_channel.prefixed_id }, as: :json
+
+ expect(response).to have_http_status(:not_found)
+ end
+ end
+
context 'without authentication' do
let(:headers) { {} }
diff --git a/spree/api/spec/integration/spree/api/v3/admin/variants_spec.rb b/spree/api/spec/integration/spree/api/v3/admin/variants_spec.rb
index ab41597b11..0d2b0cbcbd 100644
--- a/spree/api/spec/integration/spree/api/v3/admin/variants_spec.rb
+++ b/spree/api/spec/integration/spree/api/v3/admin/variants_spec.rb
@@ -198,6 +198,7 @@ RSpec.describe 'Admin Variants API', type: :request, swagger_doc: 'api-reference
description: 'Bearer token for admin authentication'
parameter name: :page, in: :query, type: :integer, required: false, description: 'Page number'
parameter name: :limit, in: :query, type: :integer, required: false, description: 'Number of records per page'
+ query_parameters_for Spree::Api::V3::Admin::VariantsController::SALES_CONTEXT
filter_parameters_for
response '200', 'variants found' do
diff --git a/spree/api/spec/support/request_body_helper.rb b/spree/api/spec/support/request_body_helper.rb
index 37362d0b0f..f4d7ee5cdd 100644
--- a/spree/api/spec/support/request_body_helper.rb
+++ b/spree/api/spec/support/request_body_helper.rb
@@ -29,6 +29,20 @@ module RequestBodyHelper
parameter name: :body, in: :body, required: required, schema: { '$ref': "#/components/schemas/#{name}" }
end
+ # Documents a shape a read endpoint takes as query parameters, and publishes
+ # it as a component so the SDKs generate one type for it.
+ #
+ # @param shape [Spree::Api::V3::RequestSchema] a named shape
+ def query_parameters_for(shape)
+ register_request_schema(shape.name, shape.json_schema)
+ shape.code_lists.each { |list_name, definition| register_request_schema(list_name, definition) }
+
+ shape.json_schema[:properties].each do |name, property|
+ parameter name: name, in: :query, required: false, description: property[:description],
+ schema: property.except(:description)
+ end
+ end
+
private
def request_body_route
diff --git a/spree/core/app/models/concerns/spree/purchase/addresses.rb b/spree/core/app/models/concerns/spree/purchase/addresses.rb
index 1a79bcb13c..078c2f85e9 100644
--- a/spree/core/app/models/concerns/spree/purchase/addresses.rb
+++ b/spree/core/app/models/concerns/spree/purchase/addresses.rb
@@ -40,9 +40,12 @@ module Spree
before_validation :clone_shipping_address, if: :use_shipping?
end
+ # Whether both addresses are present and match. With neither present
+ # there is nothing to call the same.
+ #
# @return [Boolean]
def shipping_eq_billing_address?
- bill_address == ship_address
+ ship_address.present? && bill_address == ship_address
end
# Whether checkout must collect a customer shipping address. Selected
diff --git a/spree/core/app/models/spree/cart.rb b/spree/core/app/models/spree/cart.rb
index f26c0a49ea..2ca557ec31 100644
--- a/spree/core/app/models/spree/cart.rb
+++ b/spree/core/app/models/spree/cart.rb
@@ -284,12 +284,9 @@ module Spree
#
# @return [ActiveRecord::Relation<Spree::Variant>]
def orderable_variants
- products = Spree.products_for_context_service.call(
- store: store, channel: channel, customer: customer, company: resolved_company,
- base: store.products.not_discontinued_on(channel)
- ).value
-
- Spree::Variant.for_products(products)
+ Spree::SalesContext.new(
+ store: store, channel: channel, customer: customer, company: resolved_company, resolve_company: false
+ ).orderable_variants
end
# Removes out-of-stock/discontinued items and populates warnings
diff --git a/spree/core/app/models/spree/sales_context.rb b/spree/core/app/models/spree/sales_context.rb
new file mode 100644
index 0000000000..f3846fdf3f
--- /dev/null
+++ b/spree/core/app/models/spree/sales_context.rb
@@ -0,0 +1,162 @@
+module Spree
+ # Who buys, on which channel, in which market: what a buyer can be sold, and
+ # at what price, depends on all of these together. A market fixes the
+ # currency and the languages a sale may use.
+ class SalesContext
+ include ActiveModel::Model
+ include ActiveModel::Attributes
+
+ attribute :store
+ attribute :market
+ attribute :channel
+ attribute :customer
+ attribute :company
+ attribute :country
+ attribute :currency, :string
+ attribute :locale, :string
+ # A placed sale keeps the company it was stamped with, even none, so only
+ # a sale still being put together looks up the customer's company.
+ attribute :resolve_company, :boolean, default: true
+
+ validate :currency_sold_in_a_market
+ validate :currency_matches_market
+ validate :locale_supported_by_market
+
+ # @param order [Spree::Order]
+ # @return [Spree::SalesContext]
+ def self.from_order(order)
+ new(
+ store: order.store, market: order.market, channel: order.channel, customer: order.customer,
+ company: order.resolved_company, resolve_company: false, country: order.tax_country,
+ currency: order.currency, locale: order.locale
+ )
+ end
+
+ # The market chosen for the sale, else one selling the requested currency,
+ # else the store's default.
+ #
+ # @return [Spree::Market, nil]
+ def market
+ chosen = super
+ return chosen if chosen
+ return @resolved_market if defined?(@resolved_market)
+
+ @resolved_market = resolve_market
+ end
+
+ def channel
+ super || store&.default_channel
+ end
+
+ # @return [String] the requested currency, else the market's, else the store's
+ def currency
+ requested_currency || market&.currency || store&.default_currency
+ end
+
+ # @return [String, nil] the requested language, else the market's default
+ def locale
+ super.presence || market&.default_locale
+ end
+
+ # The company chosen for the sale, else the one the customer stands in
+ # alone — the same answer pricing and catalog visibility reach.
+ #
+ # @return [Spree::Company, nil]
+ def company
+ chosen = super
+ return chosen if chosen || !resolve_company
+ return @standing_company if defined?(@standing_company)
+
+ @standing_company =
+ if customer.is_a?(Spree.customer_class) && store
+ Spree::Company.sole_standing_for(store: store, customer: customer)
+ end
+ end
+
+ # Variants the buyer may order on the channel: published there and inside
+ # their catalogs.
+ #
+ # @return [ActiveRecord::Relation<Spree::Variant>]
+ def orderable_variants
+ @orderable_variants ||= Spree::Variant.for_products(
+ Spree.products_for_context_service.call(
+ store: store, channel: channel, customer: customer, company: company,
+ base: store.products.not_discontinued_on(channel)
+ ).value
+ )
+ end
+
+ # Orderable variants the buyer can be quoted in the sale's currency: a base
+ # price, or a price from a list that applies to them, so a product sold to
+ # a buyer only under their agreement is offered to that buyer alone.
+ #
+ # @return [ActiveRecord::Relation<Spree::Variant>]
+ def sellable_variants
+ prices = Spree::Price.where(variant_id: orderable_variants.select(:id), currency: currency)
+ .where.not(amount: nil)
+ .where(price_list_id: [nil, *applicable_price_list_ids])
+
+ orderable_variants.where(id: prices.select(:variant_id))
+ end
+
+ # @return [Spree::Pricing::Context] the context prices are resolved in
+ def pricing_context
+ @pricing_context ||= Spree::Pricing::Context.new(
+ currency: currency, store: store, country: country, market: market,
+ channel: channel, user: customer, company: company
+ )
+ end
+
+ private
+
+ def requested_currency
+ attributes['currency'].presence&.upcase
+ end
+
+ def resolve_market
+ return unless store
+
+ candidates = [(Spree::Current.market if Spree::Current.store == store), store.default_market].compact
+ return candidates.first unless requested_currency
+
+ candidates.find { |candidate| candidate.currency == requested_currency } ||
+ store.markets.find_by(currency: requested_currency)
+ end
+
+ # Catalog price lists the buyer's catalogs carry, and standalone lists
+ # whose rules match the sale, judged the way the internal pricing provider
+ # judges them.
+ def applicable_price_list_ids
+ @applicable_price_list_ids ||= begin
+ catalogs = Spree::Catalog.groups_for_buyer(store: store, customer: customer, company: company, channel: channel)
+ catalog_lists = catalogs.flatten.filter_map(&:price_list).select do |list|
+ list.currently_active? && list.contextual_rules_applicable?(pricing_context)
+ end
+ standalone_lists = Spree::PriceList.for_context(pricing_context).select { |list| list.applicable?(pricing_context) }
+
+ (catalog_lists + standalone_lists).map(&:id).uniq
+ end
+ end
+
+ def currency_sold_in_a_market
+ return if requested_currency.nil? || market || store.nil? || !store.markets.exists?
+
+ errors.add(:currency, :currency_not_supported_by_store, message: I18n.t('spree.currency_not_supported_by_store'))
+ end
+
+ def currency_matches_market
+ return if market.nil? || currency == market.currency
+
+ errors.add(
+ :currency, :currency_does_not_match_market,
+ message: I18n.t('spree.currency_does_not_match_market', currency: market.currency)
+ )
+ end
+
+ def locale_supported_by_market
+ return if market.nil? || locale.blank? || market.supported_locales_list.include?(locale)
+
+ errors.add(:locale, :locale_not_supported_by_market, message: I18n.t('spree.locale_not_supported_by_market'))
+ end
+ end
+end
diff --git a/spree/core/app/workflows/spree/orders/create.rb b/spree/core/app/workflows/spree/orders/create.rb
index 36997de837..46558b3b85 100644
--- a/spree/core/app/workflows/spree/orders/create.rb
+++ b/spree/core/app/workflows/spree/orders/create.rb
@@ -28,6 +28,14 @@ module Spree
return failure(:store_is_required) if store.nil?
+ @sales_context = Spree::SalesContext.new(
+ store: store,
+ market: (resolve_market if @params[:market_id].present?),
+ currency: @params[:currency],
+ locale: @params[:locale]
+ )
+ return refuse_sales_context unless @sales_context.valid?
+
order = nil
ApplicationRecord.transaction do
order = build_order
@@ -60,8 +68,9 @@ module Spree
customer: @customer,
created_by: @created_by,
email: @params[:email] || @customer&.email,
- currency: @params[:currency].presence&.upcase || @store.default_currency,
- locale: @params[:locale] || Spree::Current.locale,
+ market: @sales_context.market,
+ currency: @sales_context.currency,
+ locale: @sales_context.locale || Spree::Current.locale,
customer_note: @params[:customer_note],
po_number: @params[:po_number],
internal_note: @params[:internal_note],
@@ -74,7 +83,6 @@ module Spree
# signed id, so it assigns like any other attribute.
attrs[:po_document_signed_id] = @params[:po_document_signed_id] if @params[:po_document_signed_id].present?
- attrs[:market] = resolve_market if @params[:market_id].present?
attrs[:channel] = resolve_channel if @params[:channel_id].present?
attrs[:company] = resolve_company if @params[:company_id].present?
attrs[:preferred_stock_location] = resolve_preferred_stock_location if @params[:preferred_stock_location_id].present?
@@ -83,6 +91,12 @@ module Spree
@store.orders.new(attrs)
end
+ def refuse_sales_context
+ order = @store.orders.new
+ order.errors.merge!(@sales_context.errors)
+ failure(order, order.errors.full_messages.to_sentence)
+ end
+
def resolve_market
@store.markets.find_by_param!(@params[:market_id])
end
@@ -109,6 +123,7 @@ module Spree
assign_address(order, :ship_address, @params[:shipping_address_id], @params[:shipping_address])
assign_address(order, :bill_address, @params[:billing_address_id], @params[:billing_address])
+ order.use_shipping = @params[:use_shipping]
end
def assign_address(order, association, address_id, address_attrs)
@@ -127,7 +142,10 @@ module Spree
end
def add_items(order)
- result = Spree::Orders::UpsertItems.call(order: order, items: @params[:items])
+ result = Spree::Orders::UpsertItems.call(
+ order: order, items: @params[:items],
+ orderable_variants: Spree::SalesContext.from_order(order).orderable_variants
+ )
return if result.success?
propagate_step_failure!(order, result, fallback: 'Failed to add items to order')
diff --git a/spree/core/config/locales/en.yml b/spree/core/config/locales/en.yml
index 0aaf55c210..95638f4ef0 100644
--- a/spree/core/config/locales/en.yml
+++ b/spree/core/config/locales/en.yml
@@ -765,6 +765,7 @@ en:
created_at: Created at
credit_card: Credit Card
currency: Currency
+ currency_does_not_match_market: must be %{currency}, the currency of the chosen market
currency_not_supported_by_store: is not supported by this store
custom_field_definitions: Custom Field Definitions
custom_fields: Custom Fields
@@ -1016,6 +1017,7 @@ en:
line_items: Line items
link: Link
locale: Locale
+ locale_not_supported_by_market: is not offered by the chosen market
locale_not_supported_by_store: is not supported by this store
locales_not_listed: 'includes locales Spree does not support: %{codes}'
manual: Manual
diff --git a/spree/core/spec/models/spree/order_spec.rb b/spree/core/spec/models/spree/order_spec.rb
index 1f12239e82..73e9dfeeb8 100644
--- a/spree/core/spec/models/spree/order_spec.rb
+++ b/spree/core/spec/models/spree/order_spec.rb
@@ -1247,7 +1247,7 @@ describe Spree::Order, type: :model do
order.ship_address = nil
end
- it { expect(order.shipping_eq_billing_address?).to eq(true) }
+ it { expect(order.shipping_eq_billing_address?).to eq(false) }
end
end
diff --git a/spree/core/spec/models/spree/sales_context_spec.rb b/spree/core/spec/models/spree/sales_context_spec.rb
new file mode 100644
index 0000000000..111a18861a
--- /dev/null
+++ b/spree/core/spec/models/spree/sales_context_spec.rb
@@ -0,0 +1,100 @@
+require 'spec_helper'
+
+RSpec.describe Spree::SalesContext do
+ let(:store) { @default_store }
+ let(:market) { create(:market, :eu, store: store) }
+
+ describe 'validation' do
+ it "takes the market's currency and default language when none is given" do
+ context = described_class.new(store: store, market: market)
+
+ expect(context).to be_valid
+ expect(context.currency).to eq('EUR')
+ expect(context.locale).to eq('de')
+ end
+
+ it "refuses a currency other than the market's" do
+ context = described_class.new(store: store, market: market, currency: 'usd')
+
+ expect(context).not_to be_valid
+ expect(context.errors[:currency]).to be_present
+ end
+
+ it 'picks a market selling the requested currency when none is chosen' do
+ market
+ context = described_class.new(store: store, currency: 'eur')
+
+ expect(context.market).to eq(market)
+ expect(context).to be_valid
+ end
+
+ it 'refuses a currency no market sells' do
+ market
+ context = described_class.new(store: store, currency: 'JPY')
+
+ expect(context).not_to be_valid
+ expect(context.errors[:currency]).to be_present
+ end
+
+ it 'refuses a language the market does not offer' do
+ context = described_class.new(store: store, market: market, locale: 'ja')
+
+ expect(context).not_to be_valid
+ expect(context.errors[:locale]).to be_present
+ end
+ end
+
+ describe '#company' do
+ let(:customer) { create(:user) }
+
+ it "keeps a placed sale's company, even none" do
+ expect(Spree::Company).not_to receive(:sole_standing_for)
+
+ expect(described_class.new(store: store, customer: customer, resolve_company: false).company).to be_nil
+ end
+
+ it 'looks up the company the customer stands in for a new sale' do
+ company = build(:company, store: store)
+ allow(Spree::Company).to receive(:sole_standing_for).with(store: store, customer: customer).and_return(company)
+
+ expect(described_class.new(store: store, customer: customer).company).to eq(company)
+ end
+ end
+
+ describe '#sellable_variants' do
+ let(:product) { create(:product_in_stock, store: store) }
+ let(:context) { described_class.new(store: store, market: market) }
+
+ before do
+ next if product.publication_for(store.default_channel)
+
+ create(:product_publication, product: product, channel: store.default_channel)
+ end
+
+ it 'skips variants without a price in the currency' do
+ expect(context.sellable_variants).not_to include(product.default_variant)
+ end
+
+ context 'when only a price list prices it in the currency' do
+ let(:price_list) { create(:price_list, :active, store: store) }
+
+ before { create(:price, variant: product.default_variant, currency: 'EUR', amount: 10, price_list: price_list) }
+
+ it 'offers it when the list applies to the buyer' do
+ expect(context.sellable_variants).to include(product.default_variant)
+ end
+
+ it 'skips it when the list is not active' do
+ price_list.update!(status: 'draft')
+
+ expect(context.sellable_variants).not_to include(product.default_variant)
+ end
+
+ it 'skips it when the list belongs to another buyer' do
+ create(:user_price_rule, price_list: price_list, user_ids: [create(:user).id])
+
+ expect(context.sellable_variants).not_to include(product.default_variant)
+ end
+ end
+ end
+end
diff --git a/spree/core/spec/services/spree/orders/create_spec.rb b/spree/core/spec/services/spree/orders/create_spec.rb
index b52f93879b..6f8c10639c 100644
--- a/spree/core/spec/services/spree/orders/create_spec.rb
+++ b/spree/core/spec/services/spree/orders/create_spec.rb
@@ -65,6 +65,67 @@ module Spree
end
end
+ context 'with a market' do
+ let(:market) { create(:market, :eu, store: store) }
+ let(:params) { { email: '[email protected]', market_id: market.prefixed_id } }
+
+ it "takes the market's currency and default locale" do
+ order = subject.value
+ expect(order.market).to eq(market)
+ expect(order.currency).to eq('EUR')
+ expect(order.locale).to eq('de')
+ end
+
+ context 'and one of its languages' do
+ before { market.update!(supported_locales: %w[de fr]) }
+
+ let(:params) { { email: '[email protected]', market_id: market.prefixed_id, locale: 'fr' } }
+
+ it 'keeps the given language' do
+ expect(subject.value.locale).to eq('fr')
+ end
+ end
+
+ context 'and no market, only its currency' do
+ let(:params) { { email: '[email protected]', currency: 'EUR' } }
+
+ before { market }
+
+ it 'places the order in a market that sells the currency' do
+ expect(subject.value.market).to eq(market)
+ end
+ end
+
+ context 'and a currency the market does not use' do
+ let(:params) { { email: '[email protected]', market_id: market.prefixed_id, currency: 'USD' } }
+
+ it 'refuses the order' do
+ expect { subject }.not_to change(Spree::Order, :count)
+ expect(subject).to be_failure
+ expect(subject.value.errors[:currency]).to be_present
+ end
+ end
+
+ context 'and a language the market does not offer' do
+ let(:params) { { email: '[email protected]', market_id: market.prefixed_id, locale: 'ja' } }
+
+ it 'refuses the order' do
+ expect(subject).to be_failure
+ expect(subject.value.errors[:locale]).to be_present
+ end
+ end
+ end
+
+ context 'with use_shipping' do
+ let(:params) { { email: '[email protected]', shipping_address: address_attrs, use_shipping: true } }
+
+ it 'copies the shipping address to the billing address' do
+ order = subject.value
+ expect(order.bill_address).to be_present
+ expect(order.bill_address).to eq(order.ship_address)
+ end
+ end
+
context 'with items but no shipping address' do
let(:params) do
{
@@ -234,6 +295,23 @@ module Spree
end
end
+ context 'with an item not published on the channel' do
+ let(:unpublished_product) do
+ create(:product_in_stock).tap { |p| p.product_publications.destroy_all }
+ end
+ let(:params) do
+ {
+ email: '[email protected]',
+ items: [{ variant_id: unpublished_product.default_variant.prefixed_id, quantity: 1 }]
+ }
+ end
+
+ it 'does not create the order' do
+ expect { subject }.to raise_error(ActiveRecord::RecordNotFound)
+ expect(Spree::Order.where(email: '[email protected]')).to be_empty
+ end
+ end
+
context 'when add_items fails because the variant is out of stock' do
# Product factory propagates stock items as +backorderable: true+ by
# default. Strip both so the LineItem +quantity_available+ validation