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.

Fixed agents being unable to add rules or actions to a promotion (V-3777) (#15079)

Damian Legawiecc2a130cd550d
diff --git a/docs/api-reference/admin.yaml b/docs/api-reference/admin.yaml
index 7cac1123b5..2bfb4751fe 100644
--- a/docs/api-reference/admin.yaml
+++ b/docs/api-reference/admin.yaml
@@ -29971,6 +29971,13 @@ paths:
required: true
schema:
type: string
+ - name: expand
+ in: query
+ required: false
+ description: 'Comma-separated associations to expand: `rules`, `actions` (each
+ under the same shape the write accepts), `custom_fields`.'
+ schema:
+ type: string
responses:
'200':
description: promotion found
@@ -69309,6 +69316,14 @@ components:
type: array
items:
type: string
+ rules:
+ type: array
+ items:
+ "$ref": "#/components/schemas/PromotionRule"
+ actions:
+ type: array
+ items:
+ "$ref": "#/components/schemas/PromotionAction"
required:
- id
- name
diff --git a/docs/developer/mcp/tools.mdx b/docs/developer/mcp/tools.mdx
index b4406509f8..055f986ab0 100644
--- a/docs/developer/mcp/tools.mdx
+++ b/docs/developer/mcp/tools.mdx
@@ -156,6 +156,10 @@ Two things worth knowing about the generic writes:
**A list replaces rather than appends.** Sending one variant leaves a product with one variant. Send every row you want to keep.
+**Rows selected by a `type` take a short name, never a class name.** A promotion's rules and actions, a price list's rules and a payment method's provider are chosen by `type`: `item_total`, `create_item_adjustments`, `check`. `describe_resource` on one resource lists the kinds under `types` and `nested_types`, each with the schema its `preferences` follow and, for an action that prices a discount, the calculators it takes. A kind the store does not offer is refused with the accepted ones named, so nothing is saved with a rule or an action missing.
+
+**Rows that live under a parent are reached through it.** Promotion rules, promotion actions and an order's payments have no search of their own: read them with `get_resource` on the parent, naming the list in `expand`. Where the parent accepts the rows as a list attribute, as a promotion does its `rules` and `actions`, that attribute is also how they are written.
+
## See also
<CardGroup cols={2}>
diff --git a/packages/admin-sdk/src/types/generated/Promotion.ts b/packages/admin-sdk/src/types/generated/Promotion.ts
index 67d8357910..340e03683f 100644
--- a/packages/admin-sdk/src/types/generated/Promotion.ts
+++ b/packages/admin-sdk/src/types/generated/Promotion.ts
@@ -1,6 +1,7 @@
-// Typelizer digest a43a43ce4221e34ed79a548b448b98c4
+// Typelizer digest fb5ed8121eb1d93bd756697d74141122
//
// DO NOT MODIFY: This file was automatically generated by Typelizer.
+import type {PromotionRule, PromotionAction} from '@/types'
interface Promotion {
id: string;
@@ -22,6 +23,8 @@ interface Promotion {
updated_at: string;
action_ids: Array<string>;
rule_ids: Array<string>;
+ rules?: Array<PromotionRule>;
+ actions?: Array<PromotionAction>;
}
export default Promotion;
diff --git a/packages/admin-sdk/src/zod/generated/Promotion.ts b/packages/admin-sdk/src/zod/generated/Promotion.ts
index b932e61947..ff90a510ff 100644
--- a/packages/admin-sdk/src/zod/generated/Promotion.ts
+++ b/packages/admin-sdk/src/zod/generated/Promotion.ts
@@ -1,5 +1,7 @@
// This file is auto-generated. Do not edit directly.
import { z } from 'zod';
+import { PromotionActionSchema } from './PromotionAction';
+import { PromotionRuleSchema } from './PromotionRule';
export const PromotionSchema = z.object({
id: z.string(),
@@ -21,6 +23,8 @@ export const PromotionSchema = z.object({
updated_at: z.string(),
action_ids: z.array(z.string()),
rule_ids: z.array(z.string()),
+ rules: z.array(PromotionRuleSchema).optional(),
+ actions: z.array(PromotionActionSchema).optional(),
});
export type Promotion = z.infer<typeof PromotionSchema>;
diff --git a/spree/api/app/controllers/concerns/spree/api/v3/admin/embed_permissions.rb b/spree/api/app/controllers/concerns/spree/api/v3/admin/embed_permissions.rb
index f294d6ee18..a9cc5e81e9 100644
--- a/spree/api/app/controllers/concerns/spree/api/v3/admin/embed_permissions.rb
+++ b/spree/api/app/controllers/concerns/spree/api/v3/admin/embed_permissions.rb
@@ -13,7 +13,9 @@ module Spree
#
# Gift card codes are bearer credentials that ride along on every
# order, so serializers show them in full only to a caller who may read
- # gift cards and masked to everyone else.
+ # gift cards and masked to everyone else. Customer records embedded in
+ # a rule (a promotion's or a price list's customer rule) are shown only
+ # to a caller who may read customers; the rule keeps its `customer_ids`.
module EmbedPermissions
extend ActiveSupport::Concern
@@ -44,7 +46,8 @@ module Spree
end
def serializer_params
- super.merge(gift_card_codes: holds_permission?('read_gift_cards'))
+ super.merge(gift_card_codes: holds_permission?('read_gift_cards'),
+ customer_records: holds_permission?('read_customers'))
end
private
diff --git a/spree/api/app/serializers/spree/api/v3/admin/price_rule_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/price_rule_serializer.rb
index 190f4455ee..092b9d500f 100644
--- a/spree/api/app/serializers/spree/api/v3/admin/price_rule_serializer.rb
+++ b/spree/api/app/serializers/spree/api/v3/admin/price_rule_serializer.rb
@@ -34,10 +34,12 @@ module Spree
resource: proc { Spree.api.admin_channel_serializer },
if: proc { |rule| rule.respond_to?(:channels) }
+ # Only for a caller who may read customers; see the promotion rule
+ # serializer.
many :users,
key: :customers,
resource: proc { Spree.api.admin_customer_serializer },
- if: proc { |rule| rule.respond_to?(:users) }
+ if: proc { |rule| rule.respond_to?(:users) && params[:customer_records] }
end
end
end
diff --git a/spree/api/app/serializers/spree/api/v3/admin/promotion_rule_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/promotion_rule_serializer.rb
index 855be7d2c9..b15e4c33b4 100644
--- a/spree/api/app/serializers/spree/api/v3/admin/promotion_rule_serializer.rb
+++ b/spree/api/app/serializers/spree/api/v3/admin/promotion_rule_serializer.rb
@@ -61,9 +61,12 @@ module Spree
resource: proc { Spree.api.admin_category_serializer },
if: proc { |rule| rule.respond_to?(:categories) }
+ # Only for a caller who may read customers: a promotion is readable
+ # under `read_promotions`, and a customer rule would otherwise carry
+ # every targeted customer's email and notes along with it.
many :customers,
resource: proc { Spree.api.admin_customer_serializer },
- if: proc { |rule| rule.respond_to?(:customers) }
+ if: proc { |rule| rule.respond_to?(:customers) && params[:customer_records] }
many :customer_groups,
resource: proc { Spree.api.admin_customer_group_serializer },
diff --git a/spree/api/app/serializers/spree/api/v3/admin/promotion_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/promotion_serializer.rb
index b63e1612b3..2b8463aef6 100644
--- a/spree/api/app/serializers/spree/api/v3/admin/promotion_serializer.rb
+++ b/spree/api/app/serializers/spree/api/v3/admin/promotion_serializer.rb
@@ -34,6 +34,19 @@ module Spree
attribute :rule_ids do |promotion|
promotion.promotion_rules.map(&:prefixed_id)
end
+
+ # The rows under the same names the write accepts, on request: a
+ # reader holding only `rule_ids` cannot tell what a promotion does
+ # without a request per rule.
+ many :promotion_rules,
+ key: :rules,
+ resource: proc { Spree.api.admin_promotion_rule_serializer },
+ if: proc { expand?('rules') }
+
+ many :promotion_actions,
+ key: :actions,
+ resource: proc { Spree.api.admin_promotion_action_serializer },
+ if: proc { expand?('actions') }
end
end
end
diff --git a/spree/api/lib/spree/api/agent_resource_map.rb b/spree/api/lib/spree/api/agent_resource_map.rb
index d47876eea2..4d98add259 100644
--- a/spree/api/lib/spree/api/agent_resource_map.rb
+++ b/spree/api/lib/spree/api/agent_resource_map.rb
@@ -142,6 +142,15 @@ module Spree
transform_values { |pairs| pairs.map(&:last).min_by { |path| [path.count(':'), path.length] } }
end
+ # The controller served at the shallowest path, which is where a tool
+ # dispatches: for a record it is the show path, else the collection.
+ def shallowest_candidate(candidates)
+ candidates.min_by do |entry|
+ path = Array(entry[:api_paths]).to_h.values_at(:show, :index).compact.first.to_s
+ [path.empty? ? Float::INFINITY : path.count(':'), path.length]
+ end
+ end
+
def api_paths_for(controller)
candidates = Spree::Core::Engine.routes.routes.filter_map do |route|
next unless route.defaults[:controller] == controller.controller_path
@@ -228,6 +237,11 @@ module Spree
# withdrawn, and only when the controllers disagree about the
# scope guarding it.
narrowest.merge(
+ # The serializer of the controller the tools actually reach:
+ # the one whose path won below. `narrowest` is chosen on
+ # permission, which left `products` described by the catalog
+ # membership serializer and `expand: ["variants"]` refused.
+ serializer_name: shallowest_candidate(candidates)[:serializer_name],
create_workflow_key: candidates.filter_map { |entry| entry[:create_workflow_key] }.first,
update_workflow_key: candidates.filter_map { |entry| entry[:update_workflow_key] }.first,
write_permission: contested ? nil : narrowest[:write_permission],
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/collections_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/collections_controller_spec.rb
index de8c5d4cd5..d54790f0ce 100644
--- a/spree/api/spec/controllers/spree/api/v3/admin/collections_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/admin/collections_controller_spec.rb
@@ -120,6 +120,17 @@ RSpec.describe Spree::Api::V3::Admin::CollectionsController, type: :controller d
)
end
+ it 'refuses a rule with an unknown type, naming the accepted ones' do
+ post :create, params: {
+ name: 'On Sale', automatic: true,
+ rules: [{ type: 'Spree::CollectionRules::Tag', value: 'summer', match_policy: 'contains' }]
+ }, as: :json
+
+ expect(response).to have_http_status(:unprocessable_content)
+ expect(json_response['error']['details']['/rules/0/type'].first).to include('is not a collection rule offered here', 'tag')
+ expect(Spree::Collection.where(name: 'On Sale')).not_to exist
+ end
+
it 'returns 422 for a blank name' do
post :create, params: { name: '' }, as: :json
expect(response).to have_http_status(:unprocessable_content)
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/price_lists_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/price_lists_controller_spec.rb
index 4cf17bab79..00ceb36582 100644
--- a/spree/api/spec/controllers/spree/api/v3/admin/price_lists_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/admin/price_lists_controller_spec.rb
@@ -463,21 +463,20 @@ RSpec.describe Spree::Api::V3::Admin::PriceListsController, type: :controller do
expect(cg_rule.preferred_customer_group_ids).to contain_exactly(customer_group.id.to_s)
end
- it 'silently drops a rule with an unknown type' do
+ it 'refuses a rule with an unknown type, naming the accepted ones, and keeps the list as it was' do
patch :update,
params: {
id: price_list.prefixed_id,
rules: [
{ type: 'volume_rule', preferences: { min_quantity: 2 } },
- { type: 'NotARealRule' }
+ { type: 'Spree::PriceRules::MarketRule' }
]
},
as: :json
- expect(response).to have_http_status(:ok)
- rules = price_list.reload.price_rules
- expect(rules.length).to eq(1)
- expect(rules.first).to be_a(Spree::PriceRules::VolumeRule)
+ expect(response).to have_http_status(:unprocessable_content)
+ expect(json_response['error']['details']['/rules/1/type'].first).to include('is not a price rule offered here', 'market_rule')
+ expect(price_list.reload.price_rules).to be_empty
end
end
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/promotions_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/promotions_controller_spec.rb
index 91de6763a0..65373f70dc 100644
--- a/spree/api/spec/controllers/spree/api/v3/admin/promotions_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/admin/promotions_controller_spec.rb
@@ -41,6 +41,50 @@ RSpec.describe Spree::Api::V3::Admin::PromotionsController, type: :controller do
expect(response).to have_http_status(:ok)
expect(json_response['id']).to eq(promotion.prefixed_id)
expect(json_response['name']).to eq(promotion.name)
+ expect(json_response).not_to have_key('rules')
+ expect(json_response).not_to have_key('actions')
+ end
+
+ # Under the names the write accepts, so a reader can tell what a
+ # promotion does without a request per `rule_ids` entry.
+ it 'embeds the rules and actions when asked to expand them' do
+ promotion.rules.create!(type: 'Spree::Promotion::Rules::FirstOrder')
+
+ get :show, params: { id: promotion.prefixed_id, expand: 'rules,actions' }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(json_response['rules'].map { |rule| rule['type'] }).to eq(['first_order'])
+ expect(json_response['actions'].map { |action| action['type'] }).to eq(['create_item_adjustments'])
+ expect(json_response['actions'].first['calculator']).to include('type')
+ end
+
+ # A promotion is readable under `read_promotions`; the customers a rule
+ # targets are another resource's records and stay behind `read_customers`.
+ context 'with a customer rule' do
+ let(:customer) { create(:user) }
+
+ before do
+ rule = promotion.rules.create!(type: 'Spree::Promotion::Rules::User')
+ rule.users = [customer]
+ end
+
+ it 'embeds the targeted customers for a caller who may read customers' do
+ get :show, params: { id: promotion.prefixed_id, expand: 'rules' }, as: :json
+
+ expect(json_response['rules'].first['customers'].map { |record| record['id'] }).to eq([customer.prefixed_id])
+ end
+
+ context 'with a promotions-only key' do
+ let(:headers) { { 'x-spree-api-key' => create(:api_key, :secret, store: store, scopes: ['read_promotions']).plaintext_token } }
+
+ it 'keeps the customer ids and leaves the records out' do
+ get :show, params: { id: promotion.prefixed_id, expand: 'rules' }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(json_response['rules'].first['customer_ids']).to eq([customer.prefixed_id])
+ expect(json_response['rules'].first).not_to have_key('customers')
+ end
+ end
end
end
@@ -154,20 +198,31 @@ RSpec.describe Spree::Api::V3::Admin::PromotionsController, type: :controller do
expect(types).to contain_exactly(Spree::Promotion::Rules::Currency, Spree::Promotion::Rules::FirstOrder)
end
- it 'silently ignores rules with an unknown type' do
+ # A row with a type nobody registered used to be dropped from a 201, so
+ # a client that sent a class name got a live promotion with no rules.
+ it 'refuses a rule with an unknown type and creates nothing' do
post :create,
params: base_params.merge(
rules: [
{ type: 'currency', preferences: { currency: 'USD' } },
- { type: 'NotARealRule' }
+ { type: 'Spree::Promotion::Rules::ItemTotal' }
]
),
as: :json
- expect(response).to have_http_status(:created)
- promotion = Spree::Promotion.find_by_prefix_id(json_response['id'])
- expect(promotion.rules.size).to eq(1)
- expect(promotion.rules.first).to be_a(Spree::Promotion::Rules::Currency)
+ expect(response).to have_http_status(:unprocessable_content)
+ expect(json_response['error']['details']).to include('/rules/1/type')
+ expect(json_response['error']['details']['/rules/1/type'].first).to include('item_total', 'currency')
+ expect(Spree::Promotion.where(name: 'Spring Sale')).not_to exist
+ end
+
+ it 'refuses an action with an unknown type' do
+ post :create,
+ params: base_params.merge(actions: [{ type: 'Spree::Promotion::Actions::CreateItemAdjustments' }]),
+ as: :json
+
+ expect(response).to have_http_status(:unprocessable_content)
+ expect(json_response['error']['details']['/actions/0/type'].first).to include('create_item_adjustments')
end
end
@@ -311,9 +366,8 @@ RSpec.describe Spree::Api::V3::Admin::PromotionsController, type: :controller do
),
as: :json
- # Unknown shorthand → rule silently dropped (same behavior as unknown class name).
- expect(response).to have_http_status(:created)
- expect(Spree::Promotion.find_by_prefix_id(json_response['id']).rules).to be_empty
+ expect(response).to have_http_status(:unprocessable_content)
+ expect(json_response['error']['message']).to include('not_a_real_rule is not a promotion rule offered here')
end
end
end
diff --git a/spree/api/spec/integration/spree/api/v3/admin/promotions_spec.rb b/spree/api/spec/integration/spree/api/v3/admin/promotions_spec.rb
index bfdd90b016..f6fd0f1017 100644
--- a/spree/api/spec/integration/spree/api/v3/admin/promotions_spec.rb
+++ b/spree/api/spec/integration/spree/api/v3/admin/promotions_spec.rb
@@ -146,6 +146,8 @@ RSpec.describe 'Admin Promotions API', type: :request, swagger_doc: 'api-referen
parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
parameter name: :Authorization, in: :header, type: :string, required: true
parameter name: :id, in: :path, type: :string, required: true
+ parameter name: :expand, in: :query, type: :string, required: false,
+ description: 'Comma-separated associations to expand: `rules`, `actions` (each under the same shape the write accepts), `custom_fields`.'
response '200', 'promotion found' do
let(:'x-spree-api-key') { secret_api_key.plaintext_token }
diff --git a/spree/api/spec/serializers/spree/api/v3/admin/price_rule_serializer_spec.rb b/spree/api/spec/serializers/spree/api/v3/admin/price_rule_serializer_spec.rb
index bd54e5cd21..08ef0dd0c8 100644
--- a/spree/api/spec/serializers/spree/api/v3/admin/price_rule_serializer_spec.rb
+++ b/spree/api/spec/serializers/spree/api/v3/admin/price_rule_serializer_spec.rb
@@ -59,9 +59,16 @@ RSpec.describe Spree::Api::V3::Admin::PriceRuleSerializer do
r
end
- it 'embeds the related customers under the `customers` key' do
- ids = payload['customers'].map { |c| c['id'] }
- expect(ids).to contain_exactly(user.prefixed_id)
+ # The records ride along only for a caller who may read customers; the
+ # controller sets the param from that permission.
+ it 'embeds the related customers under the `customers` key for a caller who may read them' do
+ payload = described_class.new(rule, params: base_params.merge(customer_records: true)).to_h
+
+ expect(payload['customers'].map { |c| c['id'] }).to contain_exactly(user.prefixed_id)
+ end
+
+ it 'leaves the customer records out for everyone else' do
+ expect(payload).not_to have_key('customers')
end
it 'does not embed unrelated associations' do
diff --git a/spree/api/spec/tools/spree/agent_tools/resource_write_spec.rb b/spree/api/spec/tools/spree/agent_tools/resource_write_spec.rb
index 7fb788abae..e11ebe94f6 100644
--- a/spree/api/spec/tools/spree/agent_tools/resource_write_spec.rb
+++ b/spree/api/spec/tools/spree/agent_tools/resource_write_spec.rb
@@ -277,5 +277,165 @@ RSpec.describe 'agent generic record writes' do
expect(described[:expandable_associations]).to include('variants')
end
+
+ # The base serializer explains `expand?` in a comment with `variants` as
+ # the example, which once put it on every resource's list.
+ it 'does not offer an association a serializer only mentions in a comment' do
+ described = tool('describe_resource').call(resource: 'promotions')[:resources].first
+
+ expect(described[:expandable_associations]).to include('rules', 'actions')
+ expect(described[:expandable_associations]).not_to include('variants')
+ end
+ end
+
+ # Rows selected by a `type` — a promotion's rules and actions, a price
+ # list's rules, a payment method's provider — take a short name from a
+ # registry. An agent that was never shown the registry guessed Ruby class
+ # names, and the write dropped every row while answering success.
+ describe 'typed rows' do
+ def described(resource)
+ tool('describe_resource').call(resource: resource)[:resources].first
+ end
+
+ it 'lists the kinds each nested row\'s type takes, with its schema and calculators' do
+ nested = described('promotions')[:nested_types]
+ rules = nested['rules'].index_by { |kind| kind[:type] }
+ actions = nested['actions'].index_by { |kind| kind[:type] }
+
+ expect(rules.keys).to include('item_total', 'product', 'first_order')
+ expect(rules['item_total'][:schema]['properties']).to include('amount_min')
+ expect(actions.keys).to include('create_item_adjustments', 'free_shipping')
+ expect(actions['create_item_adjustments'][:calculators].map { |calculator| calculator[:type] }).to include('percent_on_line_item')
+ expect(actions['free_shipping']).not_to have_key(:calculators)
+ end
+
+ it 'lists the kinds for every family written as nested rows' do
+ expect(described('price_lists')[:nested_types]['rules'].map { |kind| kind[:type] }).to include('volume_rule')
+ expect(described('delivery_methods')[:nested_types]['rules'].map { |kind| kind[:type] }).to include('weight_rule')
+ end
+
+ it 'lists the kinds a resource\'s own type takes' do
+ expect(described('payment_methods')[:types].map { |kind| kind[:type] }).to include('check')
+ end
+
+ # The whole catalogue of schemas at once is more than an index should
+ # cost a model's context; the listing names the kinds and no more.
+ it 'names the kinds without their schemas in the full listing' do
+ promotions = tool('describe_resource').call[:resources].find { |entry| entry[:resource] == 'promotions' }
+
+ expect(promotions[:nested_types]['rules']).to include('item_total')
+ expect(promotions[:nested_types]['actions']).to include('create_item_adjustments')
+ end
+
+ it 'creates a promotion with its rules and actions in one call' do
+ result = tool('create_resource').call(
+ resource: 'promotions',
+ attributes: {
+ 'name' => 'Black Friday', 'kind' => 'coupon_code', 'code' => 'BLACKFRIDAY', 'usage_limit' => 500,
+ 'rules' => [{ 'type' => 'item_total', 'preferences' => { 'amount_min' => '100' } }],
+ 'actions' => [{ 'type' => 'create_item_adjustments',
+ 'calculator' => { 'type' => 'percent_on_line_item', 'preferences' => { 'percent' => '25' } } }]
+ }
+ )
+
+ expect(result[:error]).to be_nil
+
+ promotion = Spree::Promotion.for_store(store).find_by(name: 'Black Friday')
+ expect(promotion.rules.map { |rule| rule.class.api_type }).to eq(['item_total'])
+ expect(promotion.actions.first.calculator.class.api_type).to eq('percent_on_line_item')
+ end
+
+ # "Generate 500 codes" is `multi_codes` with a count and a prefix; the
+ # batch is minted by the same write, so the merchant has codes to hand
+ # out as soon as the promotion exists.
+ it 'creates a multi-code promotion and generates its coupon batch' do
+ product = create(:product, store: store)
+
+ result = tool('create_resource').call(
+ resource: 'promotions',
+ attributes: {
+ 'name' => 'Black Friday codes', 'kind' => 'coupon_code',
+ 'multi_codes' => true, 'number_of_codes' => 5, 'code_prefix' => 'BLACKFRIDAY',
+ 'starts_at' => '2026-11-27T00:00:00Z', 'expires_at' => '2026-11-30T23:59:59Z',
+ 'rules' => [{ 'type' => 'product', 'product_ids' => [product.prefixed_id], 'preferences' => { 'match_policy' => 'any' } },
+ { 'type' => 'item_total', 'preferences' => { 'amount_min' => '100', 'operator_min' => 'gt' } }],
+ 'actions' => [{ 'type' => 'create_item_adjustments',
+ 'calculator' => { 'type' => 'percent_on_line_item', 'preferences' => { 'percent' => '25' } } }]
+ }
+ )
+
+ expect(result[:error]).to be_nil
+
+ promotion = Spree::Promotion.for_store(store).find_by(name: 'Black Friday codes')
+ expect(promotion.rules.map { |rule| rule.class.api_type }).to contain_exactly('product', 'item_total')
+ expect(promotion.rules.find { |rule| rule.respond_to?(:products) }.products).to eq([product])
+ expect(promotion.coupon_codes.count).to eq(5)
+ expect(promotion.coupon_codes.pluck(:code)).to all(start_with('blackfriday'))
+ end
+
+ it 'refuses an unknown type with the accepted ones, and creates nothing' do
+ result = tool('create_resource').call(
+ resource: 'promotions',
+ attributes: { 'name' => 'Guessed', 'kind' => 'automatic',
+ 'rules' => [{ 'type' => 'Spree::Promotion::Rules::ItemTotal' }] }
+ )
+
+ expect(result[:error]).to include('/rules/0/type', 'item_total', 'first_order')
+ expect(Spree::Promotion.for_store(store).where(name: 'Guessed')).not_to exist
+ end
+
+ it 'reads a promotion\'s rules and actions through expand' do
+ promotion = create(:promotion_with_item_adjustment, store: store)
+ promotion.rules.create!(type: 'Spree::Promotion::Rules::FirstOrder')
+
+ record = tool('get_resource').call(resource: 'promotions', id: promotion.prefixed_id, expand: %w[rules actions])[:record]
+
+ expect(record['rules'].map { |rule| rule['type'] }).to eq(['first_order'])
+ expect(record['actions'].map { |action| action['type'] }).to eq(['create_item_adjustments'])
+ end
+ end
+
+ # A resource that only exists under a parent has no path a tool can fill
+ # in. Dispatching the template as it stood answered "Promotion not found",
+ # which a model reported as a fact about the store.
+ describe 'a resource reached only under a parent' do
+ it 'is not searched on its own, and says where its rows live' do
+ result = tool('search_resources').call(resource: 'promotion_rules')
+
+ expect(result[:error]).to include('belong to a promotion', 'rules attribute of promotions', 'expand: ["rules"]')
+ expect(result[:available]).to include('promotions')
+ expect(result[:available]).not_to include('promotion_rules')
+ end
+
+ it 'is not fetched on its own' do
+ result = tool('get_resource').call(resource: 'promotion_actions', id: 'pact_x')
+
+ expect(result[:error]).to include('belong to a promotion', 'actions attribute of promotions')
+ end
+
+ it 'is not written on its own' do
+ result = tool('create_resource').call(resource: 'promotion_rules', attributes: { 'type' => 'first_order' })
+
+ expect(result[:error]).to include('cannot be created on their own', 'promotions')
+ end
+
+ it 'names the parent even when the parent carries no attribute for it' do
+ result = tool('search_resources').call(resource: 'payments')
+
+ expect(result[:error]).to include('belong to an order', 'orders')
+ end
+
+ # A hint is only offered when the caller could follow it: a read-only key
+ # is told how to read the rows, not how to write them.
+ context 'with a read-only key' do
+ let(:api_key) { create(:api_key, :secret, store: store, scopes: ['read_promotions']) }
+
+ it 'suggests only the calls the caller may make' do
+ result = tool('search_resources').call(resource: 'promotion_rules')
+
+ expect(result[:error]).to include('belong to a promotion', 'expand: ["rules"]')
+ expect(result[:error]).not_to include('Write them')
+ end
+ end
end
end
diff --git a/spree/core/app/models/concerns/spree/preference_schema.rb b/spree/core/app/models/concerns/spree/preference_schema.rb
index 7c60926ef2..b0fcd71590 100644
--- a/spree/core/app/models/concerns/spree/preference_schema.rb
+++ b/spree/core/app/models/concerns/spree/preference_schema.rb
@@ -217,6 +217,11 @@ module Spree
registered_subclasses.find { |klass| klass.api_type == shorthand.to_s }
end
+ # @return [Array<String>] the wire name of every registered subclass
+ def api_types
+ registered_subclasses.map(&:api_type)
+ end
+
# Returns a `[{ type:, label:, description:, schema: }]` array for every
# registered subclass, sorted by label for stable output. `schema` is
# the JSON Schema of the subclass's `preferences`, which never carries a
diff --git a/spree/core/app/models/concerns/spree/typed_associations.rb b/spree/core/app/models/concerns/spree/typed_associations.rb
index dc94c832ca..54a0bf1d4e 100644
--- a/spree/core/app/models/concerns/spree/typed_associations.rb
+++ b/spree/core/app/models/concerns/spree/typed_associations.rb
@@ -37,37 +37,55 @@ module Spree
reconcile_typed_association(association, pending)
end
- # Flushes a pending payload from `@pending_<assoc>` (typically from
- # an `after_save` hook) and clears the ivar.
+ # Flushes the pending payloads from `@pending_<assoc>` (typically from
+ # an `after_save` hook) and clears them.
#
+ # Every association is written before any buffer is cleared: a refused
+ # row rolls the whole save back, and a retried save must carry every
+ # payload again rather than persist the owner with the rows that
+ # happened to come first.
+ #
+ # @param associations [Array<Symbol>]
+ # @return [void]
+ def flush_pending_typed_associations(*associations)
+ pending = associations.to_h { |association| [association, instance_variable_get(:"@pending_#{association}")] }.compact
+ pending.each { |association, rows| reconcile_typed_association(association, rows) }
+ pending.each_key { |association| instance_variable_set(:"@pending_#{association}", nil) }
+ end
+
# @param association [Symbol]
# @return [void]
def flush_pending_typed_association(association)
- ivar = :"@pending_#{association}"
- pending = instance_variable_get(ivar)
- return unless pending
-
- instance_variable_set(ivar, nil)
- reconcile_typed_association(association, pending)
+ flush_pending_typed_associations(association)
end
+ # All or nothing: on a saved parent the rows are written as they are
+ # assigned, so a refusal on the second row used to leave the first one
+ # behind — a list the caller never asked for, answered with a 422.
def reconcile_typed_association(association, rows)
collection = public_send(association)
- kept_ids = rows.each_with_index.filter_map { |row, index| save_typed_association_row(collection, row, "/#{association.to_s.split('_').last}/#{index}") }
- if kept_ids.any? || rows.empty?
- collection.where.not(id: kept_ids).destroy_all
- # `where.not(...).destroy_all` deletes the dropped rows from the DB but
- # leaves them in the already-loaded association target. Reset so a
- # same-request read (e.g. the serializer rendering `rule_ids`) reflects
- # the removal instead of echoing ghosts.
+ begin
+ self.class.transaction do
+ kept_ids = rows.each_with_index.map { |row, index| save_typed_association_row(collection, row, "/#{association.to_s.split('_').last}/#{index}") }
+ collection.where.not(id: kept_ids).destroy_all
+ # `where.not(...).destroy_all` deletes the dropped rows from the DB but
+ # leaves them in the already-loaded association target. Reset so a
+ # same-request read (e.g. the serializer rendering `rule_ids`) reflects
+ # the removal instead of echoing ghosts.
+ collection.reset
+ end
+ rescue StandardError
+ # The rows built before the refusal are still in the loaded target, and
+ # the owner's next save would write them; the rollback only undid the
+ # database.
collection.reset
+ raise
end
end
# @param pointer [String] where the row sits in the request, e.g. `/rules/1`
def save_typed_association_row(collection, row, pointer)
- record = find_or_build_typed_association_row(collection, row)
- return nil unless record
+ record = find_or_build_typed_association_row(collection, row, pointer)
preferences = row[:preferences]
calculator = row[:calculator]
@@ -100,15 +118,19 @@ module Spree
raise
end
- def find_or_build_typed_association_row(collection, row)
+ def find_or_build_typed_association_row(collection, row, pointer)
if row[:id].present?
id = Spree::PrefixedId.prefixed_id?(row[:id]) ? Spree::PrefixedId.decode_prefixed_id(row[:id]) : row[:id]
existing = collection.find { |r| r.id == id } || collection.find_by(id: id)
return existing if existing
end
- klass = collection.proxy_association.klass.find_by_api_type(row[:type])
- return nil unless klass
+ family = collection.proxy_association.klass
+ klass = family.find_by_api_type(row[:type])
+ # Refused, not skipped: a dropped row answered the request with a 200
+ # and a promotion that discounted nothing. Naming the accepted types is
+ # what lets an API client or an agent correct itself.
+ raise unknown_row_type_error(family, row[:type], pointer) unless klass
# `build(type:) + becomes(klass)` would leave a stale STI-parent stub
# in the collection target alongside the becomes'd copy; autosave then
@@ -117,5 +139,16 @@ module Spree
collection.proxy_association.add_to_target(record)
record
end
+
+ def unknown_row_type_error(family, type, pointer)
+ types = family.api_types.sort.join(', ')
+ message = if type.blank?
+ I18n.t('spree.errors.messages.missing_row_type', types: types)
+ else
+ I18n.t('spree.errors.messages.unknown_row_type', type: type, family: family.model_name.human.downcase, types: types)
+ end
+
+ Spree::Preferences::InvalidPreferences.new([{ pointer: '/type', message: message }], prefix: pointer)
+ end
end
end
diff --git a/spree/core/app/models/spree/collection.rb b/spree/core/app/models/spree/collection.rb
index b18aa6db39..e5508f5e95 100644
--- a/spree/core/app/models/spree/collection.rb
+++ b/spree/core/app/models/spree/collection.rb
@@ -203,10 +203,15 @@ module Spree
existing_by_id = rules.to_a.index_by(&:id)
retained_ids = []
- rules_params.each do |rule_data|
+ rules_params.each_with_index do |rule_data, index|
data = rule_data.to_h.with_indifferent_access
rule_id = data.delete(:id)
- data[:type] = self.class.resolve_rule_type(data[:type]) if data.key?(:type)
+ if data.key?(:type) || rule_id.blank?
+ # Refused with the accepted kinds named; letting the nil through
+ # answered "type can't be blank" to a caller who had sent one.
+ data[:type] = self.class.resolve_rule_type(data[:type]) ||
+ raise(unknown_row_type_error(Spree::CollectionRule, data[:type], "/rules/#{index}"))
+ end
record = if rule_id.present?
existing_by_id[Spree::PrefixedId.decode_prefixed_id(rule_id) || rule_id] ||
diff --git a/spree/core/app/models/spree/promotion.rb b/spree/core/app/models/spree/promotion.rb
index cab7593833..dd1f78cd20 100644
--- a/spree/core/app/models/spree/promotion.rb
+++ b/spree/core/app/models/spree/promotion.rb
@@ -373,8 +373,7 @@ module Spree
end
def apply_pending_rules_and_actions
- flush_pending_typed_association(:promotion_rules)
- flush_pending_typed_association(:promotion_actions)
+ flush_pending_typed_associations(:promotion_rules, :promotion_actions)
end
# Runs before the promotion's actions are destroyed, since the carts'
diff --git a/spree/core/app/tools/spree/agent_tools/describe_resource.rb b/spree/core/app/tools/spree/agent_tools/describe_resource.rb
index 621b779386..69e41b9afd 100644
--- a/spree/core/app/tools/spree/agent_tools/describe_resource.rb
+++ b/spree/core/app/tools/spree/agent_tools/describe_resource.rb
@@ -5,9 +5,11 @@ module Spree
# producing errors the merchant has to read.
class DescribeResource < Spree::AgentTool
tool_name 'describe_resource'
- description 'List the store resources you can search, and the fields each one ' \
- 'can be filtered and sorted by. Call this before search_resources ' \
- 'if you are unsure which filter to use.'
+ description 'List the store resources you can search, the fields each one can be ' \
+ 'filtered and sorted by, and what a write accepts. Describe one resource ' \
+ 'for the full detail: what fits inside each list-valued attribute, and the ' \
+ 'kinds a `type` field takes with each kind\'s preferences schema. Call this ' \
+ 'before search_resources, create_resource or update_resource if unsure.'
# Deliberately ungated: it exposes only field names, and the resources it
# lists are already filtered to what this admin may read.
permission nil
@@ -25,11 +27,47 @@ module Spree
available: Spree::AgentTools::ResourceMap.available_for(context).map(&:key) }
end
- { resources: entries.map { |entry| describe(entry) } }
+ # One resource gets every type's schema; the listing names the types
+ # only, because every family's schema at once is more than an index
+ # should cost a model's context.
+ { resources: entries.map { |entry| describe(entry, detailed: resource.present?) } }
end
private
+ # The kinds a `type` takes, from the family's own registry — the same
+ # list its `…/types` endpoint serves. An agent that never saw this list
+ # guessed Ruby class names, and the write dropped every row.
+ def types_for(family, detailed)
+ return if family.nil?
+
+ return family.api_types.sort unless detailed
+
+ family.subclasses_with_preference_schema.map do |kind|
+ kind.slice(:type, :label, :description, :schema).merge(calculators: calculators_for(family, kind[:type])).compact
+ end
+ rescue StandardError
+ nil
+ end
+
+ # An action that prices its discount through a calculator takes one of
+ # these, each with its own preferences — the same list as
+ # `GET /promotion_actions/calculators`.
+ def calculators_for(family, type)
+ klass = family.find_by_api_type(type)
+ return unless klass.respond_to?(:calculators)
+
+ klass.calculators.map do |calculator|
+ { type: calculator.api_type, label: calculator.description, schema: calculator.preference_json_schema }
+ end.sort_by { |entry| entry[:label].to_s }.presence
+ end
+
+ def nested_types_for(entry, detailed)
+ return if writable_attributes_for(entry).blank?
+
+ entry.nested_typed_families.transform_values { |family| types_for(family, detailed) }.compact.presence
+ end
+
# Every dispatchable resource reports its attributes now: the generic
# writes reach the controller, which runs whatever workflow it
# declares, so there is no longer a class of resource they refuse.
@@ -46,7 +84,7 @@ module Spree
entry.writable_attribute_names.presence
end
- def describe(entry)
+ def describe(entry, detailed:)
{
resource: entry.key,
filterable_fields: entry.filterable_fields,
@@ -59,6 +97,12 @@ module Spree
# `variants` and has no idea a whole variant fits there, so it
# creates the product and then adds each variant separately.
nested_attributes: nested_shapes_for(entry),
+ # The kinds this resource's own `type` takes (a payment method's
+ # provider), and the kinds each nested row's `type` takes (a
+ # promotion's rules and actions). The accepted values and their
+ # preference schemas, so a model does not guess class names.
+ types: types_for(entry.typed_family, detailed),
+ nested_types: nested_types_for(entry, detailed),
# What get_resource can be asked to include. A record arrives
# without its associations, so a model that does not know these
# names cannot ask for the one it needs.
@@ -73,7 +117,8 @@ module Spree
filterable_scopes: entry.filterable_scopes,
usage: 'Attribute filters use Ransack predicates, e.g. name_cont, created_at_gteq, ' \
'status_eq. Named scopes are passed as a bare key set to true, e.g. ' \
- '{"out_of_stock": true}.'
+ '{"out_of_stock": true}. A type field takes one of the kinds under types or ' \
+ 'nested_types, and a row\'s preferences follow that kind\'s schema.'
}.compact
end
end
diff --git a/spree/core/app/tools/spree/agent_tools/get_resource.rb b/spree/core/app/tools/spree/agent_tools/get_resource.rb
index 651bd564e1..efc95c9e22 100644
--- a/spree/core/app/tools/spree/agent_tools/get_resource.rb
+++ b/spree/core/app/tools/spree/agent_tools/get_resource.rb
@@ -22,7 +22,8 @@ module Spree
context.permitted?(entry.permission)
path = entry.api_path(:show)
- return { error: "#{entry.key} cannot be fetched one at a time." } if path.blank? || path.include?('/:') && path.count(':') > 1
+ return { error: "#{entry.key} cannot be fetched one at a time." } if path.blank?
+ return nested_resource_error(entry, 'fetched', :show) if entry.nested?(:show)
requested, refusal = expansions(entry, expand)
return refusal if refusal
diff --git a/spree/core/app/tools/spree/agent_tools/resource_write.rb b/spree/core/app/tools/spree/agent_tools/resource_write.rb
index b02e1f73e0..e4ee2a04ab 100644
--- a/spree/core/app/tools/spree/agent_tools/resource_write.rb
+++ b/spree/core/app/tools/spree/agent_tools/resource_write.rb
@@ -41,6 +41,7 @@ module Spree
path = entry.api_path(action)
return [nil, { error: not_writable(entry, action) }] if path.blank?
+ return [nil, nested_resource_error(entry, verb_for(action), action)] if entry.nested?(action)
# The endpoint answers 403 for a scope the credential lacks, in its
# own words. This check only avoids offering a tool that cannot work
@@ -90,9 +91,11 @@ module Spree
end
def not_writable(entry, action)
- verb = { create: 'created', update: 'updated', destroy: 'deleted' }.fetch(action, 'changed')
+ "#{entry.key} cannot be #{verb_for(action)} this way — call describe_resource to see what can."
+ end
- "#{entry.key} cannot be #{verb} this way — call describe_resource to see what can."
+ def verb_for(action)
+ { create: 'created', update: 'updated', destroy: 'deleted' }.fetch(action, 'changed')
end
end
end
diff --git a/spree/core/app/tools/spree/agent_tools/search_resources.rb b/spree/core/app/tools/spree/agent_tools/search_resources.rb
index 55f398f329..c97b4d838f 100644
--- a/spree/core/app/tools/spree/agent_tools/search_resources.rb
+++ b/spree/core/app/tools/spree/agent_tools/search_resources.rb
@@ -145,10 +145,9 @@ module Spree
# resolves its scope per request. Named rather than guessed at, because
# a tool cannot invent the parent id such a path needs.
def not_searchable(entry)
- {
- error: "#{entry.key} cannot be searched on its own.",
- available: ResourceMap.available_for(context).select(&:dispatchable?).map(&:key).sort
- }
+ refusal = entry.nested?(:index) ? nested_resource_error(entry, 'searched', :index) : { error: "#{entry.key} cannot be searched on its own." }
+
+ refusal.merge(available: ResourceMap.available_for(context).select(&:dispatchable?).map(&:key).sort)
end
end
end
diff --git a/spree/core/config/locales/en.yml b/spree/core/config/locales/en.yml
index 573ac17521..5490deaa95 100644
--- a/spree/core/config/locales/en.yml
+++ b/spree/core/config/locales/en.yml
@@ -900,6 +900,7 @@ en:
invalid_status: Invalid status
invalid_storefront_access: is not a valid storefront access level
items_not_a_list: items must be a list of objects
+ missing_row_type: 'is required (expected one of: %{types})'
money_preference_too_many_decimals: has more than %{count} decimal places for %{currency}
must_be_greater_than_min_amount: must be greater than or equal to the minimum
no_pickup_point_provider: this delivery method has no pickup point provider configured
@@ -924,6 +925,7 @@ en:
store_is_already_set: Store is already set
unknown_calculator_type: "%{type} is not a calculator offered here"
unknown_custom_field_type: 'is not a known custom field type (expected one of: %{types})'
+ unknown_row_type: "%{type} is not a %{family} offered here (expected one of: %{types})"
unknown_scopes: 'contains unknown scopes: %{scopes}'
unregistered_actor: is not a registered actor class
variant_product_mismatch: must belong to the same product as the variant
diff --git a/spree/core/lib/spree/agent_tool.rb b/spree/core/lib/spree/agent_tool.rb
index 993874fbcd..aa37fc563d 100644
--- a/spree/core/lib/spree/agent_tool.rb
+++ b/spree/core/lib/spree/agent_tool.rb
@@ -167,6 +167,39 @@ class AgentTool
protected
+ # A resource that lives under a parent — a promotion's rules, an order's
+ # payments — has no path of its own to dispatch to, so every tool refuses
+ # it the same way: naming the parent and, where the parent carries the
+ # rows as an attribute, how to write and read them there. The old answer
+ # was the endpoint's 404 for a parent id nobody supplied.
+ #
+ # @param entry [Spree::AgentTools::ResourceMap::Entry]
+ # @param verb [String] 'searched', 'fetched', 'created'…
+ # @param action [Symbol] the operation whose path runs under the parent
+ # @return [Hash]
+ def nested_resource_error(entry, verb, action)
+ parent = entry.parent_key(action)
+ parent_entry = Spree::AgentTools::ResourceMap.find(parent)
+ attribute = parent_entry&.nested_typed_families&.key(entry.model_class)
+
+ owner = parent.singularize.tr('_', ' ')
+ sentences = ["#{entry.key} belong to #{owner.match?(/\A[aeiou]/) ? 'an' : 'a'} #{owner} and cannot be #{verb} on their own."]
+ # Each suggested call is one this caller may actually make; a hint
+ # that leads straight to a permission refusal is worse than none.
+ readable = parent_entry && context.permitted?(parent_entry.permission)
+ writable = parent_entry&.write_permission.present? && context.permitted?(parent_entry.write_permission)
+ if attribute && writable
+ sentences << "Write them in the #{attribute} attribute of #{parent} — describe_resource #{parent} shows the shape and the accepted types."
+ end
+ if attribute && readable && parent_entry.expandable_associations.include?(attribute)
+ sentences << "Read them with get_resource on #{parent} and expand: [\"#{attribute}\"]."
+ elsif readable && !attribute
+ sentences << "Start from #{parent}: get_resource with expand lists what it carries (describe_resource #{parent} names the options)."
+ end
+
+ { error: sentences.join(' '), parent: parent }
+ end
+
# Refuses unless this admin may take `action` on `record`.
#
# Holding `write_products` says an admin may edit products; it does not
diff --git a/spree/core/lib/spree/agent_tools/resource_map.rb b/spree/core/lib/spree/agent_tools/resource_map.rb
index 06839f6530..4d357997f2 100644
--- a/spree/core/lib/spree/agent_tools/resource_map.rb
+++ b/spree/core/lib/spree/agent_tools/resource_map.rb
@@ -16,6 +16,10 @@ module Spree
# than quietly leaking another store's records.
UnscopedResourceError = Class.new(StandardError)
+ # The parent segment of a nested path: `/promotions/:promotion_id/promotion_rules`
+ # names `promotions`.
+ PARENT_SEGMENT = %r{/(?<parent>[a-z_]+)/:[a-z_]+_id(?:/|\z)}
+
Entry = Struct.new(:key, :model_name, :permission, :serializer_name,
:dashboard_path, :scope_name, :write_permission,
:writable_attributes, :create_workflow_key, :update_workflow_key,
@@ -29,9 +33,38 @@ module Spree
Array(api_paths).to_h[action.to_sym]
end
- # @return [Boolean] whether a tool can dispatch to this resource
+ # Whether a tool can dispatch to this resource's collection on its own.
+ #
+ # A resource reached only under a parent is not: the tool has no
+ # parent id to put in the path, and dispatching the template as it
+ # stands answered "Promotion not found" for a search of promotion
+ # rules, which a model repeats as a fact about the store.
+ #
+ # @return [Boolean]
def dispatchable?
- api_path(:index).present?
+ api_path(:index).present? && !nested?(:index)
+ end
+
+ # Whether the path a tool would dispatch `action` to runs under a
+ # parent. Asked per action, because a resource can be listed at the
+ # top level and written under its parent (`/variants`,
+ # `/products/:product_id/variants`).
+ #
+ # @param action [Symbol]
+ # @return [Boolean]
+ def nested?(action = :index)
+ parent_key(action).present?
+ end
+
+ # The resource key of the parent `action`'s path runs under, read
+ # from the route rather than guessed from the model, so a renamed
+ # nested route (`/orders/:order_id/items`) still names `orders`. The
+ # innermost parent, for a path nested twice.
+ #
+ # @param action [Symbol]
+ # @return [String, nil]
+ def parent_key(action = :index)
+ api_path(action).to_s.scan(PARENT_SEGMENT).flatten.last
end
# Whether a search may add DISTINCT.
@@ -92,14 +125,68 @@ module Spree
end
def expand_names_in(klass)
- file = Object.const_source_location(klass.name)&.first
- return [] if file.nil? || !File.exist?(file)
+ file = serializer_file(klass)
+ return [] if file.nil?
- File.read(file).scan(/expand\?\('([a-z_]+)'\)/).flatten
+ # Comment lines are skipped: the base serializer explains `expand?`
+ # with an example, which put `variants` on every resource's list.
+ code = File.readlines(file).reject { |line| line.lstrip.start_with?('#') }.join
+ code.scan(/expand\?\('([a-z_]+)'\)/).flatten
rescue StandardError
[]
end
+ # The file the autoloader maps the class to, under whichever engine
+ # holds it. `const_source_location` is the fallback: it names the file
+ # that first touched the constant, which for a serializer another one
+ # inherits from was the subclass's file.
+ def serializer_file(klass)
+ relative = "#{klass.name.underscore}.rb"
+ found = Rails.autoloaders.main.dirs.lazy.map { |dir| File.join(dir, relative) }.find { |path| File.exist?(path) }
+ found || Object.const_source_location(klass.name)&.first.then { |path| path if path && File.exist?(path) }
+ end
+
+ # The STI family this resource is, when its rows are selected by a
+ # `type` the model's own registry resolves — payment methods, seller
+ # requirements, promotion rules. Nil for an ordinary resource.
+ #
+ # @return [Class, nil]
+ def typed_family
+ typed_family_class(model_class)
+ end
+
+ # The STI family behind each list-valued attribute whose rows carry a
+ # `type` — a promotion's `rules` and `actions`, a price list's
+ # `rules`. The attribute is the short name the write accepts; the
+ # association behind it carries the model's prefix
+ # (`promotion_rules`), which is how the two are matched.
+ #
+ # @return [Hash{String => Class}] attribute => family class
+ def nested_typed_families
+ nested_collection_shapes.each_with_object({}) do |(name, fields), families|
+ next unless fields.any? { |field| field['name'] == 'type' }
+
+ family = typed_family_class(typed_association_for(name)&.klass)
+ families[name] = family if family
+ end
+ rescue StandardError
+ {}
+ end
+
+ def typed_association_for(name)
+ reflections = model_class.reflect_on_all_associations(:has_many)
+ reflections.find { |reflection| reflection.name.to_s == name } ||
+ reflections.find { |reflection| reflection.name.to_s.end_with?("_#{name}") }
+ end
+
+ def typed_family_class(klass)
+ return unless klass.respond_to?(:subclass_registry) && klass.subclass_registry
+
+ klass
+ rescue StandardError
+ nil
+ end
+
# The shape of each attribute that carries a list of records — a
# product's `variants`, an order's `items`.
#
diff --git a/spree/core/spec/models/spree/collection_spec.rb b/spree/core/spec/models/spree/collection_spec.rb
index c205e6ad87..1de20f178f 100644
--- a/spree/core/spec/models/spree/collection_spec.rb
+++ b/spree/core/spec/models/spree/collection_spec.rb
@@ -283,6 +283,21 @@ RSpec.describe Spree::Collection, type: :model do
expect { drop.reload }.to raise_error(ActiveRecord::RecordNotFound)
end
+ it 'refuses a rule with an unknown type, naming the accepted ones' do
+ expect {
+ reloaded_collection.rules = [{ type: 'Spree::CollectionRules::Tag', value: 'sale', match_policy: 'is_equal_to' }]
+ }.to raise_error(Spree::Preferences::InvalidPreferences) { |error|
+ expect(error.failures).to contain_exactly(hash_including(pointer: '/rules/0/type'))
+ expect(error.message).to include('is not a collection rule offered here', 'tag', 'sale')
+ }
+ end
+
+ it 'refuses a new rule with no type, naming the accepted ones' do
+ expect {
+ reloaded_collection.rules = [{ value: 'sale', match_policy: 'is_equal_to' }]
+ }.to raise_error(Spree::Preferences::InvalidPreferences, %r{/rules/0/type: is required \(expected one of: .*tag})
+ end
+
it 'raises RecordNotFound for an unknown rule id' do
expect {
reloaded_collection.rules = [{ id: 'crule_nonexistent', value: 'x', match_policy: 'is_equal_to' }]
diff --git a/spree/core/spec/models/spree/promotion_spec.rb b/spree/core/spec/models/spree/promotion_spec.rb
index 3e712c4eae..4d0d61a78e 100644
--- a/spree/core/spec/models/spree/promotion_spec.rb
+++ b/spree/core/spec/models/spree/promotion_spec.rb
@@ -1030,11 +1030,56 @@ describe Spree::Promotion, type: :model do
expect(promotion.rules.first.preferred_amount_min).to eq(25)
end
- it 'ignores rows with an unknown type' do
- promotion.rules = [{ type: 'NotARealRule' }]
- promotion.reload
+ # A dropped row answered the write with success and a promotion that
+ # discounted nothing; the refusal names the kinds that would have worked.
+ it 'refuses a row with an unknown type, naming the accepted ones' do
+ expect { promotion.rules = [{ type: 'item_total' }, { type: 'NotARealRule' }] }.
+ to raise_error(Spree::Preferences::InvalidPreferences) { |error|
+ expect(error.failures).to contain_exactly(hash_including(pointer: '/rules/1/type'))
+ expect(error.message).to include('NotARealRule is not a promotion rule offered here', 'item_total', 'first_order')
+ }
+ end
- expect(promotion.rules).to be_empty
+ it 'refuses a row with no type' do
+ expect { promotion.rules = [{ preferences: { amount_min: '25' } }] }.
+ to raise_error(Spree::Preferences::InvalidPreferences, %r{/rules/0/type: is required})
+ end
+
+ # The rollback undoes the database; the rows built before the refusal
+ # must not linger in the loaded association for the next save to write.
+ it 'keeps nothing of a refused list for a later save' do
+ expect { promotion.rules = [{ type: 'item_total' }, { type: 'NotARealRule' }] }.
+ to raise_error(Spree::Preferences::InvalidPreferences)
+
+ promotion.save!
+
+ expect(promotion.reload.rules).to be_empty
+ end
+
+ it 'saves nothing of a new promotion whose rows carry an unknown type' do
+ fresh = build(:promotion, name: 'Unsaved')
+ fresh.rules = [{ type: 'Spree::Promotion::Rules::ItemTotal' }]
+
+ expect { fresh.save! }.to raise_error(Spree::Preferences::InvalidPreferences)
+ expect(Spree::Promotion.where(name: 'Unsaved')).not_to exist
+ # Still pending, so a retried save cannot persist the promotion bare.
+ expect(fresh).to be_pending_rules_or_actions
+ end
+
+ # The rules write before the actions; a refused action rolls them back,
+ # so a retry that corrects only the actions has to bring the rules too.
+ it 'keeps every pending list when a later one is refused' do
+ fresh = build(:promotion, name: 'Retried')
+ fresh.rules = [{ type: 'first_order' }]
+ fresh.actions = [{ type: 'NotARealAction' }]
+
+ expect { fresh.save! }.to raise_error(Spree::Preferences::InvalidPreferences)
+
+ fresh.actions = [{ type: 'free_shipping' }]
+ fresh.save!
+
+ expect(fresh.reload.rules.map { |rule| rule.class.api_type }).to eq(['first_order'])
+ expect(fresh.actions.map { |action| action.class.api_type }).to eq(['free_shipping'])
end
it 'falls through to AR when assigned PromotionRule instances' do