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.

feat(api): add admin Collection API

Łukasz Adamczykb4b4c41a00e5
diff --git a/packages/admin-sdk/src/types/generated/Collection.ts b/packages/admin-sdk/src/types/generated/Collection.ts
new file mode 100644
index 0000000000..2ea2c7e5b0
--- /dev/null
+++ b/packages/admin-sdk/src/types/generated/Collection.ts
@@ -0,0 +1,31 @@
+// Typelizer digest 9a2bdbea2ae8cc853148d221195b7faa
+//
+// DO NOT MODIFY: This file was automatically generated by Typelizer.
+import type {CustomField, CollectionRule} from '@/types'
+
+interface Collection {
+ id: string;
+ name: string;
+ permalink: string;
+ position: number;
+ sort_order: string;
+ hide_from_nav: boolean;
+ meta_title: string | null;
+ meta_description: string | null;
+ meta_keywords: string | null;
+ products_count: number;
+ description: string;
+ description_html: string;
+ image_url: string | null;
+ square_image_url: string | null;
+ custom_fields?: Array<CustomField>;
+ translations?: Record<string, Record<string, string | number | null>>;
+ automatic: boolean;
+ rules_match_policy: string;
+ metadata: Record<string, unknown>;
+ created_at: string;
+ updated_at: string;
+ rules: Array<CollectionRule>;
+}
+
+export default Collection;
diff --git a/packages/admin-sdk/src/types/generated/CollectionRule.ts b/packages/admin-sdk/src/types/generated/CollectionRule.ts
new file mode 100644
index 0000000000..d6d4c1141f
--- /dev/null
+++ b/packages/admin-sdk/src/types/generated/CollectionRule.ts
@@ -0,0 +1,12 @@
+// Typelizer digest 3dbad81eb1bb3e47ff8970b5e45485bf
+//
+// DO NOT MODIFY: This file was automatically generated by Typelizer.
+
+interface CollectionRule {
+ id: string;
+ type: string;
+ value: string | null;
+ match_policy: string;
+}
+
+export default CollectionRule;
diff --git a/packages/admin-sdk/src/types/generated/index.ts b/packages/admin-sdk/src/types/generated/index.ts
index 5c62f349cf..d5644ecacd 100644
--- a/packages/admin-sdk/src/types/generated/index.ts
+++ b/packages/admin-sdk/src/types/generated/index.ts
@@ -1,4 +1,4 @@
-// Typelizer digest b5f5b3915f8088d0f025fe621a24049d
+// Typelizer digest 49a51e13afaed7bb434edefd4b2fd573
//
// DO NOT MODIFY: This file was automatically generated by Typelizer.
export type { default as Address } from './Address'
@@ -8,6 +8,8 @@ export type { default as AllowedOrigin } from './AllowedOrigin'
export type { default as ApiKey } from './ApiKey'
export type { default as Category } from './Category'
export type { default as Channel } from './Channel'
+export type { default as CollectionRule } from './CollectionRule'
+export type { default as Collection } from './Collection'
export type { default as Country } from './Country'
export type { default as CouponCode } from './CouponCode'
export type { default as CreditCard } from './CreditCard'
diff --git a/packages/sdk/src/types/generated/Collection.ts b/packages/sdk/src/types/generated/Collection.ts
new file mode 100644
index 0000000000..ede6b15de4
--- /dev/null
+++ b/packages/sdk/src/types/generated/Collection.ts
@@ -0,0 +1,24 @@
+// Typelizer digest 0b52db62d44a37e8b6230314390fd2e6
+//
+// DO NOT MODIFY: This file was automatically generated by Typelizer.
+import type {CustomField} from '@/types'
+
+interface Collection {
+ id: string;
+ name: string;
+ permalink: string;
+ position: number;
+ sort_order: string;
+ hide_from_nav: boolean;
+ meta_title: string | null;
+ meta_description: string | null;
+ meta_keywords: string | null;
+ products_count: number;
+ description: string;
+ description_html: string;
+ image_url: string | null;
+ square_image_url: string | null;
+ custom_fields?: Array<CustomField>;
+}
+
+export default Collection;
diff --git a/packages/sdk/src/types/generated/index.ts b/packages/sdk/src/types/generated/index.ts
index 43bd0eda87..77662fbb57 100644
--- a/packages/sdk/src/types/generated/index.ts
+++ b/packages/sdk/src/types/generated/index.ts
@@ -1,4 +1,4 @@
-// Typelizer digest 62abadc4940a9933fc2882ec3b1eda4b
+// Typelizer digest dc2ebc4e6baf84298324f8cfa63f7f95
//
// DO NOT MODIFY: This file was automatically generated by Typelizer.
export type { default as Address } from './Address'
@@ -6,6 +6,7 @@ export type { default as Base } from './Base'
export type { default as Cart } from './Cart'
export type { default as Category } from './Category'
export type { default as Channel } from './Channel'
+export type { default as Collection } from './Collection'
export type { default as Country } from './Country'
export type { default as CreditCard } from './CreditCard'
export type { default as Currency } from './Currency'
diff --git a/packages/sdk/src/zod/generated/Collection.ts b/packages/sdk/src/zod/generated/Collection.ts
new file mode 100644
index 0000000000..354176da3e
--- /dev/null
+++ b/packages/sdk/src/zod/generated/Collection.ts
@@ -0,0 +1,23 @@
+// This file is auto-generated. Do not edit directly.
+import { z } from 'zod';
+import { CustomFieldSchema } from './CustomField';
+
+export const CollectionSchema = z.object({
+ id: z.string(),
+ name: z.string(),
+ permalink: z.string(),
+ position: z.number(),
+ sort_order: z.string(),
+ hide_from_nav: z.boolean(),
+ meta_title: z.string().nullable(),
+ meta_description: z.string().nullable(),
+ meta_keywords: z.string().nullable(),
+ products_count: z.number(),
+ description: z.string(),
+ description_html: z.string(),
+ image_url: z.string().nullable(),
+ square_image_url: z.string().nullable(),
+ custom_fields: z.array(CustomFieldSchema).optional(),
+});
+
+export type Collection = z.infer<typeof CollectionSchema>;
diff --git a/packages/sdk/src/zod/generated/index.ts b/packages/sdk/src/zod/generated/index.ts
index a6a566bd90..4024919e5b 100644
--- a/packages/sdk/src/zod/generated/index.ts
+++ b/packages/sdk/src/zod/generated/index.ts
@@ -4,6 +4,7 @@ export { BaseSchema, type Base } from './Base';
export { CartSchema, type Cart } from './Cart';
export { CategorySchema, type Category } from './Category';
export { ChannelSchema, type Channel } from './Channel';
+export { CollectionSchema, type Collection } from './Collection';
export { CountrySchema, type Country } from './Country';
export { CreditCardSchema, type CreditCard } from './CreditCard';
export { CurrencySchema, type Currency } from './Currency';
diff --git a/spree/api/app/controllers/spree/api/v3/admin/collections/products_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/collections/products_controller.rb
new file mode 100644
index 0000000000..1f72aa4c51
--- /dev/null
+++ b/spree/api/app/controllers/spree/api/v3/admin/collections/products_controller.rb
@@ -0,0 +1,96 @@
+module Spree
+ module Api
+ module V3
+ module Admin
+ module Collections
+ # Manages the products curated under a collection — the manual
+ # membership half. Listing is ordered by the ProductCollection
+ # position so the merchant's manual ordering round-trips; +reposition+
+ # persists a drag-to-reorder. Automatic (rule-based) membership is
+ # materialized by the rules, not managed here.
+ class ProductsController < ResourceController
+ scoped_resource :products
+
+ # Skip the base single-resource load — membership actions resolve
+ # the product against the collection's scope themselves (set_product).
+ skip_before_action :set_resource
+ before_action :set_product, only: [:destroy, :reposition]
+
+ # POST /api/v3/admin/collections/:collection_id/products
+ # Body: { product_id: 'prod_…' }
+ def create
+ product = product_scope.find_by_prefix_id!(params[:product_id])
+ Spree::Collections::AddProducts.call(collections: [@parent_collection], products: [product])
+ render json: serialize_resource(product), status: :created
+ end
+
+ # DELETE /api/v3/admin/collections/:collection_id/products/:id
+ def destroy
+ Spree::Collections::RemoveProducts.call(collections: [@parent_collection], products: [@product])
+ head :no_content
+ end
+
+ # PATCH /api/v3/admin/collections/:collection_id/products/:id/reposition
+ # Body: { new_position: 0 } — 0-based index among the collection's products.
+ # @product is already constrained to the collection's scope, so a
+ # ProductCollection always exists.
+ def reposition
+ position = integer_param(:new_position)
+ return render_invalid_position if position.nil?
+
+ product_collection_for(@product).insert_at(position + 1)
+ head :no_content
+ end
+
+ protected
+
+ def model_class
+ Spree::Product
+ end
+
+ def serializer_class
+ Spree.api.admin_product_serializer
+ end
+
+ # The collection's products, ordered by membership position.
+ def scope
+ product_scope.
+ joins(:product_collections).
+ where(Spree::ProductCollection.table_name => { collection_id: @parent_collection.id }).
+ order(Spree::ProductCollection.table_name => { position: :asc })
+ end
+
+ # A product is curated at most once per collection (unique
+ # [collection_id, product_id]), so the join can't duplicate rows —
+ # DISTINCT is unnecessary and breaks Postgres ordering by position.
+ def collection_distinct?
+ false
+ end
+
+ # Loads the parent collection (runs before the base set_resource).
+ def set_parent
+ @parent_collection = Spree::Collection.accessible_by(current_ability, :update).
+ for_store(current_store).
+ find_by_prefix_id!(params[:collection_id])
+ authorize_parent!(@parent_collection)
+ end
+
+ private
+
+ def set_product
+ @product = scope.find_by_prefix_id!(params[:id])
+ end
+
+ def product_scope
+ current_store.products.accessible_by(current_ability, :show)
+ end
+
+ def product_collection_for(product)
+ Spree::ProductCollection.find_by(collection_id: @parent_collection.id, product_id: product.id)
+ end
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/spree/api/app/controllers/spree/api/v3/admin/collections_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/collections_controller.rb
new file mode 100644
index 0000000000..523cba39a4
--- /dev/null
+++ b/spree/api/app/controllers/spree/api/v3/admin/collections_controller.rb
@@ -0,0 +1,49 @@
+module Spree
+ module Api
+ module V3
+ module Admin
+ # Admin CRUD for collections — the flat, merchandising half of today's
+ # dual-purpose Taxon. Both manual and automatic (rule-based) collections
+ # live here. Reordering is a plain +position+ update (acts_as_list
+ # reorders siblings on save), matching the SPA ResourceTable reorder
+ # convention, so there is no dedicated reposition action.
+ class CollectionsController < ResourceController
+ scoped_resource :collections
+
+ protected
+
+ def model_class
+ Spree::Collection
+ end
+
+ def serializer_class
+ Spree.api.admin_collection_serializer
+ end
+
+ # The serializer always renders the rule set — eager load it.
+ def scope_includes
+ [:rules]
+ end
+
+ # Flat params. +rules+ is applied by the model's sync setter
+ # (Spree::Collection#rules=): the full desired rule set, prefixed
+ # +crule_+ ids update, missing ids build, omitted rules are removed —
+ # so normalize_params is deliberately NOT called (that would rewrite
+ # +rules+ to +rules_attributes+ and route past the setter).
+ def permitted_params
+ params.permit(
+ :name, :description, :permalink, :position,
+ :meta_title, :meta_description, :meta_keywords,
+ :hide_from_nav, :image, :square_image,
+ :automatic, :rules_match_policy, :sort_order,
+ rules: [:id, :type, :value, :match_policy],
+ # Inline custom field values keyed by definition id (see
+ # CategoriesController#permitted_params for the value shapes).
+ custom_fields: [:id, :custom_field_definition_id, :value, { value: [] }, { value: {} }]
+ )
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/spree/api/app/serializers/spree/api/v3/admin/collection_rule_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/collection_rule_serializer.rb
new file mode 100644
index 0000000000..7f8349e4ee
--- /dev/null
+++ b/spree/api/app/serializers/spree/api/v3/admin/collection_rule_serializer.rb
@@ -0,0 +1,17 @@
+module Spree
+ module Api
+ module V3
+ module Admin
+ # Serializes Spree::CollectionRule (and its STI subclasses) for the
+ # admin collection editor's `rules` association. Admin-only — automatic
+ # collection rules are never exposed by the Store API. `type` is the STI
+ # class name (e.g. "Spree::CollectionRules::Tag").
+ class CollectionRuleSerializer < BaseSerializer
+ typelize type: :string, value: [:string, nullable: true], match_policy: :string
+
+ attributes :type, :value, :match_policy
+ end
+ end
+ end
+ end
+end
diff --git a/spree/api/app/serializers/spree/api/v3/admin/collection_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/collection_serializer.rb
new file mode 100644
index 0000000000..1dae2648f0
--- /dev/null
+++ b/spree/api/app/serializers/spree/api/v3/admin/collection_serializer.rb
@@ -0,0 +1,29 @@
+module Spree
+ module Api
+ module V3
+ module Admin
+ # Admin API Collection serializer — extends the customer-facing serializer
+ # with the merchandising config (automatic / rules_match_policy / rules)
+ # and back-office fields (metadata, timestamps, admin custom fields).
+ class CollectionSerializer < V3::CollectionSerializer
+ include Spree::Api::V3::Admin::Translatable
+
+ typelize automatic: :boolean, rules_match_policy: :string,
+ metadata: 'Record<string, unknown>'
+
+ attributes :automatic, :rules_match_policy, :metadata,
+ created_at: :iso8601, updated_at: :iso8601
+
+ many :rules,
+ resource: proc { Spree.api.admin_collection_rule_serializer }
+
+ # Override inherited custom_fields to use the admin serializer.
+ many :metafields,
+ key: :custom_fields,
+ resource: proc { Spree.api.admin_custom_field_serializer },
+ if: proc { expand?('custom_fields') }
+ end
+ end
+ end
+ end
+end
diff --git a/spree/api/config/routes.rb b/spree/api/config/routes.rb
index 1a4fb9f132..df8d3ac531 100644
--- a/spree/api/config/routes.rb
+++ b/spree/api/config/routes.rb
@@ -226,6 +226,18 @@ Spree::Core::Engine.add_routes do
end
end
+ # Collections (flat, merchandising). Reordering the collection itself is a
+ # plain `position` update (acts_as_list reorders on save), so there is no
+ # top-level reposition action — only the nested membership has one.
+ resources :collections, concerns: [:custom_fieldable, :translatable] do
+ # Manual product membership + ordering within the collection.
+ resources :products, controller: 'collections/products', only: [:index, :create, :destroy] do
+ member do
+ patch :reposition
+ end
+ end
+ end
+
# Option Types (with nested option_values in payload)
resources :option_types, concerns: [:custom_fieldable, :translatable]
diff --git a/spree/api/lib/spree/api/dependencies.rb b/spree/api/lib/spree/api/dependencies.rb
index 75a813b842..4000a39a66 100644
--- a/spree/api/lib/spree/api/dependencies.rb
+++ b/spree/api/lib/spree/api/dependencies.rb
@@ -172,6 +172,8 @@ module Spree
admin_custom_field_serializer: 'Spree::Api::V3::Admin::CustomFieldSerializer',
admin_custom_field_definition_serializer: 'Spree::Api::V3::Admin::CustomFieldDefinitionSerializer',
admin_category_serializer: 'Spree::Api::V3::Admin::CategorySerializer',
+ admin_collection_serializer: 'Spree::Api::V3::Admin::CollectionSerializer',
+ admin_collection_rule_serializer: 'Spree::Api::V3::Admin::CollectionRuleSerializer',
admin_line_item_serializer: 'Spree::Api::V3::Admin::LineItemSerializer',
admin_option_type_serializer: 'Spree::Api::V3::Admin::OptionTypeSerializer',
admin_option_value_serializer: 'Spree::Api::V3::Admin::OptionValueSerializer',
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/collections/products_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/collections/products_controller_spec.rb
new file mode 100644
index 0000000000..6446db2c63
--- /dev/null
+++ b/spree/api/spec/controllers/spree/api/v3/admin/collections/products_controller_spec.rb
@@ -0,0 +1,110 @@
+require 'spec_helper'
+
+RSpec.describe Spree::Api::V3::Admin::Collections::ProductsController, type: :controller do
+ render_views
+
+ include_context 'API v3 Admin authenticated'
+
+ let!(:collection) { create(:collection, store: store, name: 'Summer Sale') }
+
+ before { request.headers.merge!(headers) }
+
+ def member_ids
+ Spree::ProductCollection.where(collection_id: collection.id).order(:position).pluck(:product_id)
+ end
+
+ describe 'GET #index' do
+ let!(:product_a) { create(:product, stores: [store]) }
+ let!(:product_b) { create(:product, stores: [store]) }
+ let!(:product_c) { create(:product, stores: [store]) }
+ let!(:other_collection) { create(:collection, store: store) }
+ let!(:other_product) { create(:product, stores: [store]) }
+
+ before do
+ Spree::ProductCollection.create!(collection: collection, product: product_b, position: 1)
+ Spree::ProductCollection.create!(collection: collection, product: product_a, position: 2)
+ Spree::ProductCollection.create!(collection: collection, product: product_c, position: 3)
+ # A product in a different collection must not leak into this list.
+ Spree::ProductCollection.create!(collection: other_collection, product: other_product, position: 1)
+ end
+
+ it 'lists only the collection products, ordered by membership position' do
+ get :index, params: { collection_id: collection.prefixed_id }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ ids = json_response['data'].map { |p| p['id'] }
+ expect(ids).to eq([product_b.prefixed_id, product_a.prefixed_id, product_c.prefixed_id])
+ expect(ids).not_to include(other_product.prefixed_id)
+ end
+
+ it 'returns an empty list for a collection with no products' do
+ empty = create(:collection, store: store)
+ get :index, params: { collection_id: empty.prefixed_id }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(json_response['data']).to eq([])
+ end
+ end
+
+ describe 'POST #create' do
+ let!(:product) { create(:product, stores: [store]) }
+
+ it 'adds the product to the collection' do
+ post :create, params: { collection_id: collection.prefixed_id, product_id: product.prefixed_id }, as: :json
+
+ expect(response).to have_http_status(:created)
+ expect(member_ids).to include(product.id)
+ end
+
+ it '404s for a product outside the store' do
+ other = create(:product, stores: [create(:store)])
+ post :create, params: { collection_id: collection.prefixed_id, product_id: other.prefixed_id }, as: :json
+
+ expect(response).to have_http_status(:not_found)
+ end
+ end
+
+ describe 'DELETE #destroy' do
+ let!(:product) { create(:product, stores: [store]) }
+
+ before { Spree::ProductCollection.create!(collection: collection, product: product, position: 1) }
+
+ it 'removes the product from the collection' do
+ delete :destroy, params: { collection_id: collection.prefixed_id, id: product.prefixed_id }, as: :json
+
+ expect(response).to have_http_status(:no_content)
+ expect(member_ids).not_to include(product.id)
+ end
+
+ it '404s for a product not in the collection' do
+ stray = create(:product, stores: [store])
+ delete :destroy, params: { collection_id: collection.prefixed_id, id: stray.prefixed_id }, as: :json
+
+ expect(response).to have_http_status(:not_found)
+ end
+ end
+
+ describe 'PATCH #reposition' do
+ let!(:first) { create(:product, stores: [store]) }
+ let!(:second) { create(:product, stores: [store]) }
+ let!(:third) { create(:product, stores: [store]) }
+
+ before do
+ Spree::ProductCollection.create!(collection: collection, product: first, position: 1)
+ Spree::ProductCollection.create!(collection: collection, product: second, position: 2)
+ Spree::ProductCollection.create!(collection: collection, product: third, position: 3)
+ end
+
+ it 'moves a product to the requested index' do
+ patch :reposition, params: { collection_id: collection.prefixed_id, id: third.prefixed_id, new_position: 0 }, as: :json
+
+ expect(response).to have_http_status(:no_content)
+ expect(member_ids).to eq([third.id, first.id, second.id])
+ end
+
+ it 'returns 422 for a missing new_position' do
+ patch :reposition, params: { collection_id: collection.prefixed_id, id: third.prefixed_id }, as: :json
+ expect(response).to have_http_status(:unprocessable_content)
+ end
+ end
+end
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
new file mode 100644
index 0000000000..a0fa214468
--- /dev/null
+++ b/spree/api/spec/controllers/spree/api/v3/admin/collections_controller_spec.rb
@@ -0,0 +1,158 @@
+require 'spec_helper'
+
+RSpec.describe Spree::Api::V3::Admin::CollectionsController, type: :controller do
+ render_views
+
+ include_context 'API v3 Admin authenticated'
+
+ let!(:collection) { create(:collection, store: store, name: 'Summer Sale') }
+ let!(:other_store) { create(:store) }
+ let!(:other_collection) { create(:collection, store: other_store) }
+
+ before { request.headers.merge!(headers) }
+
+ def created_collection
+ Spree::Collection.find_by_prefix_id(json_response['id'])
+ end
+
+ describe 'GET #index' do
+ it 'lists collections for the current store only' do
+ get :index, params: {}, as: :json
+
+ expect(response).to have_http_status(:ok)
+ ids = json_response['data'].map { |c| c['id'] }
+ expect(ids).to include(collection.prefixed_id)
+ expect(ids).not_to include(other_collection.prefixed_id)
+ end
+
+ it 'exposes the merchandising config + timestamps (admin surface)' do
+ get :index, params: {}, as: :json
+
+ data = json_response['data'].find { |c| c['id'] == collection.prefixed_id }
+ expect(data).to include('automatic', 'rules_match_policy', 'rules', 'created_at', 'updated_at')
+ end
+ end
+
+ describe 'GET #show' do
+ let!(:automatic) { create(:automatic_collection, store: store, name: 'On Sale') }
+ let!(:rule) { create(:tag_collection_rule, :contains, collection: automatic, value: 'summer') }
+
+ it 'returns the collection with its rules' do
+ get :show, params: { id: automatic.prefixed_id }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(json_response['automatic']).to be(true)
+ rules = json_response['rules']
+ expect(rules.length).to eq(1)
+ expect(rules.first).to include(
+ 'type' => 'Spree::CollectionRules::Tag', 'value' => 'summer', 'match_policy' => 'contains'
+ )
+ expect(rules.first['id']).to start_with('crule_')
+ end
+
+ it "returns not found for another store's collection" do
+ get :show, params: { id: other_collection.prefixed_id }, as: :json
+ expect(response).to have_http_status(:not_found)
+ end
+ end
+
+ describe 'POST #create' do
+ it 'creates a manual collection owned by the store' do
+ post :create, params: { name: 'New Arrivals' }, as: :json
+
+ expect(response).to have_http_status(:created)
+ created = created_collection
+ expect(created.name).to eq('New Arrivals')
+ expect(created.store).to eq(store)
+ expect(created.automatic).to be(false)
+ end
+
+ it 'creates an automatic collection with typed rules from the flat rules payload' do
+ post :create, params: {
+ name: 'On Sale',
+ automatic: true,
+ rules_match_policy: 'any',
+ rules: [
+ { type: 'Spree::CollectionRules::Tag', value: 'summer', match_policy: 'contains' },
+ { type: 'Spree::CollectionRules::Sale', value: 'true', match_policy: 'is_equal_to' }
+ ]
+ }, as: :json
+
+ expect(response).to have_http_status(:created)
+ created = created_collection
+ expect(created.automatic).to be(true)
+ expect(created.rules.map(&:type)).to match_array(
+ %w[Spree::CollectionRules::Tag Spree::CollectionRules::Sale]
+ )
+ end
+
+ it 'returns 422 for a blank name' do
+ post :create, params: { name: '' }, as: :json
+ expect(response).to have_http_status(:unprocessable_content)
+ end
+ end
+
+ describe 'PATCH #update' do
+ it 'updates collection attributes' do
+ patch :update, params: { id: collection.prefixed_id, name: 'Winter Sale' }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(collection.reload.name).to eq('Winter Sale')
+ end
+
+ # The full desired rule set is sent under `rules`: present ids update,
+ # id-less entries create, omitted rules are destroyed (sync setter).
+ context 'rules sync' do
+ let!(:automatic) { create(:automatic_collection, store: store) }
+ let!(:keep) { create(:tag_collection_rule, :contains, collection: automatic, value: 'keep') }
+ let!(:drop) { create(:tag_collection_rule, :contains, collection: automatic, value: 'drop') }
+
+ it 'updates present rules, creates new ones, and destroys omitted ones' do
+ patch :update, params: {
+ id: automatic.prefixed_id,
+ rules: [
+ { id: keep.prefixed_id, value: 'kept' },
+ { type: 'Spree::CollectionRules::Sale', value: 'true', match_policy: 'is_equal_to' }
+ ]
+ }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ automatic.reload
+ expect(automatic.rules.count).to eq(2)
+ expect(automatic.rules.find_by(id: keep.id).value).to eq('kept')
+ expect(Spree::CollectionRule.find_by(id: drop.id)).to be_nil
+ expect(automatic.rules.map(&:type)).to include('Spree::CollectionRules::Sale')
+ end
+ end
+ end
+
+ describe 'DELETE #destroy' do
+ it 'deletes the collection' do
+ delete :destroy, params: { id: collection.prefixed_id }, as: :json
+
+ expect(response).to have_http_status(:no_content)
+ expect(Spree::Collection.find_by_prefix_id(collection.prefixed_id)).to be_nil
+ end
+ end
+
+ # Flat acts_as_list: the collection's own order is reordered by sending
+ # `position` on update (no dedicated reposition action) — acts_as_list shuffles
+ # siblings on save.
+ describe 'reordering via position on update' do
+ let!(:c1) { create(:collection, store: store) }
+ let!(:c2) { create(:collection, store: store) }
+ let!(:c3) { create(:collection, store: store) }
+
+ def ordered_trio
+ trio = [c1.id, c2.id, c3.id]
+ store.collections.reorder(:position).pluck(:id).select { |id| trio.include?(id) }
+ end
+
+ it 'moves a collection above its siblings when position is sent' do
+ patch :update, params: { id: c3.prefixed_id, position: c1.reload.position }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(ordered_trio).to eq([c3.id, c1.id, c2.id])
+ end
+ end
+end