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.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
Sprint 3 — Tax Categories writes, Stock Items/Transfers, Payment Methods writes
Damian Legawiece2af8044ff09
diff --git a/spree/api/app/controllers/spree/api/v3/admin/payment_methods_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/payment_methods_controller.rbindex 8e41a9ebae..a560149c4c 100644--- a/spree/api/app/controllers/spree/api/v3/admin/payment_methods_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/admin/payment_methods_controller.rb@@ -5,6 +5,21 @@ module Spreeclass PaymentMethodsController < ResourceControllerscoped_resource :settings+ def create+ klass = resolve_subclass(params[:type])+ return render_unknown_type if klass.nil?++ @resource = klass.new(permitted_params)+ authorize_resource!(@resource, :create)+ @resource.stores = [current_store] if @resource.stores.empty?++ if @resource.save+ render json: serialize_resource(@resource), status: :created+ else+ render_validation_error(@resource.errors)+ end+ end+protecteddef model_class@@ -18,6 +33,26 @@ module Spreedef scopecurrent_store.payment_methods.accessible_by(current_ability, :show)end++ def permitted_params+ params.permit(:name, :description, :active, :display_on, :auto_capture, :position, metadata: {})+ end++ private++ def resolve_subclass(type_name)+ return Spree::PaymentMethod if type_name.blank?++ Spree::PaymentMethod.providers.find { |klass| klass.to_s == type_name }+ end++ def render_unknown_type+ render_error(+ code: 'unknown_payment_method_type',+ message: Spree.t(:invalid_payment_method_type, scope: :api, default: 'Unknown payment method type'),+ status: :unprocessable_content+ )+ endendendenddiff --git a/spree/api/app/controllers/spree/api/v3/admin/stock_items_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/stock_items_controller.rbnew file mode 100644index 0000000000..5088a37b05--- /dev/null+++ b/spree/api/app/controllers/spree/api/v3/admin/stock_items_controller.rb@@ -0,0 +1,34 @@+module Spree+ module Api+ module V3+ module Admin+ # Lightweight `index`/`show`/`update`/`destroy` on `Spree::StockItem`+ # for inventory adjustments against existing variant/location+ # pairings. Stock items are auto-created when a variant lands at a+ # stock location, so there's no `create` route — use the variants+ # / stock-locations endpoints for that flow.+ class StockItemsController < ResourceController+ scoped_resource :settings++ protected++ def model_class+ Spree::StockItem+ end++ def serializer_class+ Spree.api.admin_stock_item_serializer+ end++ def collection_includes+ [:stock_location, :variant]+ end++ def permitted_params+ params.permit(:count_on_hand, :backorderable, metadata: {})+ end+ end+ end+ end+ end+enddiff --git a/spree/api/app/controllers/spree/api/v3/admin/stock_transfers_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/stock_transfers_controller.rbnew file mode 100644index 0000000000..855668870b--- /dev/null+++ b/spree/api/app/controllers/spree/api/v3/admin/stock_transfers_controller.rb@@ -0,0 +1,101 @@+module Spree+ module Api+ module V3+ module Admin+ # Inventory movement between stock locations, or external →+ # location for receives. Pass `source_location_id` for transfers,+ # omit it for receives (vendor stock arriving). Each request body+ # carries a `variants` array of `{ variant_id, quantity }` pairs;+ # the model fans them out across `stock_movements` and adjusts the+ # source/destination `count_on_hand` atomically.+ class StockTransfersController < ResourceController+ scoped_resource :settings++ def create+ authorize!(:create, model_class)++ destination = find_stock_location!(params[:destination_location_id])+ return if destination.nil?++ source = nil+ if params[:source_location_id].present?+ source = find_stock_location!(params[:source_location_id])+ return if source.nil?+ end++ variants_map = build_variants_map(params[:variants])++ if variants_map.empty?+ return render_error(+ code: 'invalid_variants',+ message: Spree.t('stock_transfer.errors.must_have_variant'),+ status: :unprocessable_content+ )+ end++ @resource = Spree::StockTransfer.new(+ source_location: source,+ destination_location: destination,+ reference: params[:reference]+ )++ if @resource.transfer(source, destination, variants_map)+ render json: serialize_resource(@resource), status: :created+ else+ render_validation_error(@resource.errors)+ end+ end++ protected++ def model_class+ Spree::StockTransfer+ end++ def serializer_class+ Spree.api.admin_stock_transfer_serializer+ end++ def collection_includes+ [:source_location, :destination_location]+ end++ private++ def find_stock_location!(prefixed_id)+ location = Spree::StockLocation.find_by_prefix_id(prefixed_id)+ return location if location++ render_error(+ code: 'stock_location_not_found',+ message: Spree.t(:resource_not_found, scope: :api),+ status: :not_found+ )+ nil+ end++ # Resolves the request's `[{ variant_id, quantity }]` payload into+ # the `{ variant => quantity }` hash `StockTransfer#transfer`+ # expects. Variants the merchant doesn't have access to (or that+ # don't exist) are simply dropped — the model layer's+ # `stock_movements_not_empty` validation surfaces a 422 if the+ # final hash ends up empty.+ def build_variants_map(input)+ entries = input.respond_to?(:each) ? input.to_a : []++ entries.each_with_object({}) do |entry, acc|+ hash = entry.respond_to?(:to_unsafe_h) ? entry.to_unsafe_h : entry+ next unless hash.is_a?(Hash)++ variant = Spree::Variant.find_by_prefix_id(hash[:variant_id] || hash['variant_id'])+ quantity = (hash[:quantity] || hash['quantity']).to_i+ next if variant.nil? || quantity.zero?++ acc[variant] = quantity+ end+ end+ end+ end+ end+ end+enddiff --git a/spree/api/app/controllers/spree/api/v3/admin/tax_categories_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/tax_categories_controller.rbindex df08636ab7..10a134dd14 100644--- a/spree/api/app/controllers/spree/api/v3/admin/tax_categories_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/admin/tax_categories_controller.rb@@ -14,6 +14,10 @@ module Spreedef serializer_classSpree.api.admin_tax_category_serializerend++ def permitted_params+ params.permit(:name, :tax_code, :description, :is_default)+ endendendenddiff --git a/spree/api/app/serializers/spree/api/v3/admin/payment_method_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/payment_method_serializer.rbindex d4b85d08bd..fc984b18e7 100644--- a/spree/api/app/serializers/spree/api/v3/admin/payment_method_serializer.rb+++ b/spree/api/app/serializers/spree/api/v3/admin/payment_method_serializer.rb@@ -3,10 +3,13 @@ module Spreemodule V3module Adminclass PaymentMethodSerializer < V3::PaymentMethodSerializer- typelize active: :boolean, auto_capture: [:boolean, nullable: true],+ typelize active: :boolean,+ auto_capture: [:boolean, nullable: true],+ display_on: :string,+ position: :number,metadata: 'Record<string, unknown>'- attributes :metadata, :active, :auto_capture,+ attributes :metadata, :active, :auto_capture, :display_on, :position,created_at: :iso8601, updated_at: :iso8601endenddiff --git a/spree/api/app/serializers/spree/api/v3/admin/stock_transfer_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/stock_transfer_serializer.rbnew file mode 100644index 0000000000..c4d43095ae--- /dev/null+++ b/spree/api/app/serializers/spree/api/v3/admin/stock_transfer_serializer.rb@@ -0,0 +1,37 @@+module Spree+ module Api+ module V3+ module Admin+ # Inventory movement between two stock locations (or external →+ # location for receives). The originating location is `nil` for+ # receives (vendor stock arriving) and present for transfers.+ class StockTransferSerializer < V3::BaseSerializer+ typelize number: :string,+ reference: [:string, nullable: true],+ source_location_id: [:string, nullable: true],+ destination_location_id: [:string, nullable: true],+ metadata: 'Record<string, unknown>'++ attributes :number, :reference, :metadata,+ created_at: :iso8601, updated_at: :iso8601++ attribute :source_location_id do |stock_transfer|+ stock_transfer.source_location&.prefixed_id+ end++ attribute :destination_location_id do |stock_transfer|+ stock_transfer.destination_location&.prefixed_id+ end++ one :source_location,+ resource: Spree.api.admin_stock_location_serializer,+ if: proc { expand?('source_location') }++ one :destination_location,+ resource: Spree.api.admin_stock_location_serializer,+ if: proc { expand?('destination_location') }+ end+ end+ end+ end+enddiff --git a/spree/api/app/serializers/spree/api/v3/admin/tax_category_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/tax_category_serializer.rbindex 1e2bf72bb9..2bb444b1d1 100644--- a/spree/api/app/serializers/spree/api/v3/admin/tax_category_serializer.rb+++ b/spree/api/app/serializers/spree/api/v3/admin/tax_category_serializer.rb@@ -3,10 +3,12 @@ module Spreemodule V3module Adminclass TaxCategorySerializer < V3::BaseSerializer- typelize name: :string, tax_code: [:string, nullable: true],+ typelize name: :string,+ tax_code: [:string, nullable: true],+ description: [:string, nullable: true],is_default: :boolean- attributes :name, :tax_code, :is_default,+ attributes :name, :tax_code, :description, :is_default,created_at: :iso8601, updated_at: :iso8601endenddiff --git a/spree/api/config/routes.rb b/spree/api/config/routes.rbindex a4ca083805..59912dd66d 100644--- a/spree/api/config/routes.rb+++ b/spree/api/config/routes.rb@@ -164,7 +164,7 @@ Spree::Core::Engine.add_routes doresources :option_types, concerns: :custom_fieldable# Tax Categories- resources :tax_categories, only: [:index, :show]+ resources :tax_categories# Store Credit Categories (read-only — for store credit dropdowns)resources :store_credit_categories, only: [:index, :show]@@ -172,8 +172,16 @@ Spree::Core::Engine.add_routes do# Stock Locationsresources :stock_locations+ # Stock Items (write surface — list/show/update/destroy; creation+ # happens implicitly when variants meet stock locations).+ resources :stock_items, only: [:index, :show, :update, :destroy]++ # Stock Transfers (move inventory between locations, or receive+ # from external vendor when source_location_id is omitted).+ resources :stock_transfers, only: [:index, :show, :create, :destroy]+# Payment Methods- resources :payment_methods, only: [:index, :show]+ resources :payment_methods# Tags (autocomplete for product/order/user tag inputs)resources :tags, only: [:index]diff --git a/spree/api/lib/spree/api/dependencies.rb b/spree/api/lib/spree/api/dependencies.rbindex 3182ec2e68..064584751a 100644--- a/spree/api/lib/spree/api/dependencies.rb+++ b/spree/api/lib/spree/api/dependencies.rb@@ -173,6 +173,7 @@ module Spreeadmin_option_value_serializer: 'Spree::Api::V3::Admin::OptionValueSerializer',admin_media_serializer: 'Spree::Api::V3::Admin::MediaSerializer',admin_stock_item_serializer: 'Spree::Api::V3::Admin::StockItemSerializer',+ admin_stock_transfer_serializer: 'Spree::Api::V3::Admin::StockTransferSerializer',admin_shipment_serializer: 'Spree::Api::V3::Admin::FulfillmentSerializer',admin_fulfillment_serializer: 'Spree::Api::V3::Admin::FulfillmentSerializer',admin_gift_card_serializer: 'Spree::Api::V3::Admin::GiftCardSerializer',diff --git a/spree/api/spec/controllers/spree/api/v3/admin/payment_methods_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/payment_methods_controller_spec.rbindex 9972658565..98574fd9ef 100644--- a/spree/api/spec/controllers/spree/api/v3/admin/payment_methods_controller_spec.rb+++ b/spree/api/spec/controllers/spree/api/v3/admin/payment_methods_controller_spec.rb@@ -38,4 +38,54 @@ RSpec.describe Spree::Api::V3::Admin::PaymentMethodsController, type: :controlleexpect(json_response['id']).to eq(payment_method.prefixed_id)endend++ describe 'POST #create' do+ let(:create_params) do+ {+ type: 'Spree::PaymentMethod::Check',+ name: 'Check on delivery',+ description: 'Pay by physical check',+ active: true,+ display_on: 'back_end'+ }+ end++ it 'creates a payment method of the given STI subclass' do+ expect { post :create, params: create_params, as: :json }.+ to change(Spree::PaymentMethod, :count).by(1)++ expect(response).to have_http_status(:created)+ expect(json_response['type']).to eq('Spree::PaymentMethod::Check')+ expect(json_response['name']).to eq('Check on delivery')++ created = Spree::PaymentMethod.find_by_prefix_id(json_response['id'])+ expect(created.stores).to include(store)+ end++ it 'rejects an unknown subclass' do+ post :create, params: create_params.merge(type: 'NotARealClass'), as: :json++ expect(response).to have_http_status(:unprocessable_content)+ expect(json_response['error']['code']).to eq('unknown_payment_method_type')+ end+ end++ describe 'PATCH #update' do+ it 'updates the payment method' do+ patch :update, params: { id: payment_method.prefixed_id, name: 'Updated', active: false }, as: :json++ expect(response).to have_http_status(:ok)+ expect(payment_method.reload.name).to eq('Updated')+ expect(payment_method.reload.active).to be false+ end+ end++ describe 'DELETE #destroy' do+ it 'soft-deletes the payment method' do+ expect { delete :destroy, params: { id: payment_method.prefixed_id }, as: :json }.+ to change { Spree::PaymentMethod.where(id: payment_method.id).count }.by(-1)++ expect(response).to have_http_status(:no_content)+ end+ endenddiff --git a/spree/api/spec/controllers/spree/api/v3/admin/stock_items_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/stock_items_controller_spec.rbnew file mode 100644index 0000000000..96d31e7cbe--- /dev/null+++ b/spree/api/spec/controllers/spree/api/v3/admin/stock_items_controller_spec.rb@@ -0,0 +1,60 @@+require 'spec_helper'++RSpec.describe Spree::Api::V3::Admin::StockItemsController, type: :controller do+ render_views++ include_context 'API v3 Admin authenticated'++ let!(:stock_location) { Spree::StockLocation.first || create(:stock_location) }+ let!(:variant) { create(:variant) }+ let!(:stock_item) { variant.stock_items.find_by(stock_location: stock_location) || create(:stock_item, variant: variant, stock_location: stock_location) }++ before { request.headers.merge!(headers) }++ describe 'GET #index' do+ it 'returns stock items' do+ get :index, as: :json++ expect(response).to have_http_status(:ok)+ expect(json_response['data'].map { |s| s['id'] }).to include(stock_item.prefixed_id)+ end++ it 'filters by stock_location_id' do+ other_location = create(:stock_location)+ _other_item = create(:stock_item, stock_location: other_location)++ get :index, params: { q: { stock_location_id_eq: stock_location.id } }, as: :json++ expect(response).to have_http_status(:ok)+ ids = json_response['data'].map { |s| s['id'] }+ expect(ids).to include(stock_item.prefixed_id)+ end+ end++ describe 'PATCH #update' do+ it 'updates count_on_hand' do+ patch :update, params: { id: stock_item.prefixed_id, count_on_hand: 42 }, as: :json++ expect(response).to have_http_status(:ok)+ expect(stock_item.reload.count_on_hand).to eq(42)+ end++ it 'toggles backorderable' do+ patch :update, params: { id: stock_item.prefixed_id, backorderable: true }, as: :json++ expect(response).to have_http_status(:ok)+ expect(stock_item.reload.backorderable).to be true+ end+ end++ describe 'DELETE #destroy' do+ it 'destroys the stock item' do+ target = create(:stock_item, stock_location: create(:stock_location))++ expect { delete :destroy, params: { id: target.prefixed_id }, as: :json }.+ to change(Spree::StockItem, :count).by(-1)++ expect(response).to have_http_status(:no_content)+ end+ end+enddiff --git a/spree/api/spec/controllers/spree/api/v3/admin/stock_transfers_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/stock_transfers_controller_spec.rbnew file mode 100644index 0000000000..6b94327e4f--- /dev/null+++ b/spree/api/spec/controllers/spree/api/v3/admin/stock_transfers_controller_spec.rb@@ -0,0 +1,69 @@+require 'spec_helper'++RSpec.describe Spree::Api::V3::Admin::StockTransfersController, type: :controller do+ render_views++ include_context 'API v3 Admin authenticated'++ let!(:source_location) { create(:stock_location_with_items, name: 'Source') }+ let!(:destination_location) { create(:stock_location, name: 'Destination') }+ let(:variant) { create(:variant) }++ before do+ request.headers.merge!(headers)+ source_location.stock_item_or_create(variant).update!(count_on_hand: 50)+ destination_location.stock_item_or_create(variant)+ end++ describe 'GET #index' do+ let!(:transfer) do+ Spree::StockTransfer.new.tap { |t| t.transfer(source_location, destination_location, variant => 5) }+ end++ it 'returns stock transfers' do+ get :index, as: :json++ expect(response).to have_http_status(:ok)+ expect(json_response['data'].map { |t| t['id'] }).to include(transfer.prefixed_id)+ end+ end++ describe 'POST #create' do+ let(:base_params) do+ {+ source_location_id: source_location.prefixed_id,+ destination_location_id: destination_location.prefixed_id,+ variants: [{ variant_id: variant.prefixed_id, quantity: 5 }]+ }+ end++ it 'transfers stock between locations' do+ expect { post :create, params: base_params, as: :json }.+ to change(Spree::StockTransfer, :count).by(1)++ expect(response).to have_http_status(:created)+ expect(source_location.stock_item(variant).reload.count_on_hand).to eq(45)+ expect(destination_location.stock_item(variant).reload.count_on_hand).to eq(5)+ end++ it 'receives from external vendor when source is omitted' do+ post :create, params: base_params.except(:source_location_id), as: :json++ expect(response).to have_http_status(:created)+ expect(destination_location.stock_item(variant).reload.count_on_hand).to eq(5)+ end++ it 'returns 422 when variants is empty' do+ post :create, params: base_params.merge(variants: []), as: :json++ expect(response).to have_http_status(:unprocessable_content)+ expect(json_response['error']['code']).to eq('invalid_variants')+ end++ it 'returns 404 when destination location is unknown' do+ post :create, params: base_params.merge(destination_location_id: 'sloc_unknown'), as: :json++ expect(response).to have_http_status(:not_found)+ end+ end+enddiff --git a/spree/api/spec/controllers/spree/api/v3/admin/tax_categories_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/tax_categories_controller_spec.rbindex 8e6145b43c..e2340e26ed 100644--- a/spree/api/spec/controllers/spree/api/v3/admin/tax_categories_controller_spec.rb+++ b/spree/api/spec/controllers/spree/api/v3/admin/tax_categories_controller_spec.rb@@ -30,4 +30,53 @@ RSpec.describe Spree::Api::V3::Admin::TaxCategoriesController, type: :controllerexpect(json_response['name']).to eq(tax_category.name)endend++ describe 'POST #create' do+ let(:create_params) { { name: 'Reduced Rate', tax_code: 'RR', description: 'Books, food, etc.' } }++ it 'creates a tax category' do+ expect { post :create, params: create_params, as: :json }.to change(Spree::TaxCategory, :count).by(1)++ expect(response).to have_http_status(:created)+ expect(json_response['name']).to eq('Reduced Rate')+ expect(json_response['tax_code']).to eq('RR')+ expect(json_response['description']).to eq('Books, food, etc.')+ end++ it 'returns 422 when name is missing' do+ post :create, params: { tax_code: 'RR' }, as: :json++ expect(response).to have_http_status(:unprocessable_content)+ end++ it 'demotes the previous default when is_default is true' do+ previous_default = create(:tax_category, is_default: true)++ post :create, params: create_params.merge(is_default: true), as: :json++ expect(response).to have_http_status(:created)+ expect(previous_default.reload.is_default).to be false+ end+ end++ describe 'PATCH #update' do+ it 'updates the tax category' do+ patch :update, params: { id: tax_category.prefixed_id, name: 'Updated' }, as: :json++ expect(response).to have_http_status(:ok)+ expect(tax_category.reload.name).to eq('Updated')+ end+ end++ describe 'DELETE #destroy' do+ it 'soft-deletes the tax category' do+ target = create(:tax_category)++ expect { delete :destroy, params: { id: target.prefixed_id }, as: :json }.+ to change { Spree::TaxCategory.where(id: target.id).count }.by(-1)++ expect(response).to have_http_status(:no_content)+ expect(Spree::TaxCategory.with_deleted.exists?(id: target.id)).to be true+ end+ endend