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
Phase 8: expose tax configuration and identity through the API
Łukasz Adamczykba5d84d04c82
diff --git a/spree/api/app/controllers/spree/api/v3/admin/customers/tax_identifiers_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/customers/tax_identifiers_controller.rbnew file mode 100644index 0000000000..9da4635bf1--- /dev/null+++ b/spree/api/app/controllers/spree/api/v3/admin/customers/tax_identifiers_controller.rb@@ -0,0 +1,58 @@+module Spree+ module Api+ module V3+ module Admin+ module Customers+ class TaxIdentifiersController < BaseController+ scoped_resource :customers++ # Re-declaring the filter replaces the inherited options, so the+ # standard actions have to be listed alongside the custom one.+ before_action :set_resource, only: [:show, :update, :destroy, :validate]++ # POST /api/v3/admin/customers/:customer_id/tax_identifiers/:id/validate+ #+ # Re-asks the registry. Manual because a registry answers only "valid+ # now": a number verified last year may have been deregistered since,+ # and staff need a way to check without editing the row.+ def validate+ authorize_resource!(@resource, :update)++ unless @resource.validatable?+ render_error(+ code: 'tax_id_not_validatable',+ message: "No validator is registered for tax identifier kind '#{@resource.kind}'",+ status: :unprocessable_content+ )+ return+ end++ Spree::TaxIdentifiers::ValidateJob.perform_later(@resource.id)+ @resource.update_columns(validation_status: 'pending', validated_at: nil, updated_at: Time.current)++ render json: serialize_resource(@resource.reload), status: :accepted+ end++ protected++ def model_class+ Spree::TaxIdentifier+ end++ def serializer_class+ Spree.api.admin_tax_identifier_serializer+ end++ def scope+ @parent.tax_identifiers+ end++ def permitted_params+ params.permit(:kind, :value)+ end+ end+ end+ end+ end+ end+enddiff --git a/spree/api/app/controllers/spree/api/v3/admin/tax_rates_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/tax_rates_controller.rbnew file mode 100644index 0000000000..9afac76889--- /dev/null+++ b/spree/api/app/controllers/spree/api/v3/admin/tax_rates_controller.rb@@ -0,0 +1,32 @@+module Spree+ module Api+ module V3+ module Admin+ # Tax rates are the whole configuration of the internal tax provider, so+ # these endpoints are how the default engine is set up and inspected.+ class TaxRatesController < ResourceController+ scoped_resource :settings++ protected++ def model_class+ Spree::TaxRate+ end++ def serializer_class+ Spree.api.admin_tax_rate_serializer+ end++ def collection_includes+ [:tax_category, :zone]+ end++ def permitted_params+ params.permit(:name, :amount, :amount_percentage, :included_in_price,+ :show_rate_in_label, :tax_category_id, :zone_id, metadata: {})+ end+ end+ end+ end+ end+enddiff --git a/spree/api/app/controllers/spree/api/v3/store/carts/tax_identifiers_controller.rb b/spree/api/app/controllers/spree/api/v3/store/carts/tax_identifiers_controller.rbnew file mode 100644index 0000000000..d4afd89a5a--- /dev/null+++ b/spree/api/app/controllers/spree/api/v3/store/carts/tax_identifiers_controller.rb@@ -0,0 +1,58 @@+module Spree+ module Api+ module V3+ module Store+ module Carts+ # A registration entered during checkout, overriding whatever the+ # customer's profile holds — the buyer paying through a different+ # company than the one on their account.+ class TaxIdentifiersController < Store::BaseController+ include Spree::Api::V3::CartResolvable++ before_action :find_cart!++ # GET /api/v3/store/carts/:cart_id/tax_identifier+ def show+ return head :not_found if @cart.tax_identifier.nil?++ render json: serialize_resource(@cart.tax_identifier)+ end++ # PUT /api/v3/store/carts/:cart_id/tax_identifier+ def update+ resource = @cart.tax_identifier || @cart.build_tax_identifier+ resource.assign_attributes(permitted_params)++ if resource.save+ # Tax depends on the registration, so the cart has to be re-costed.+ Spree.cart_recalculate_totals_workflow.call(cart: @cart)+ render json: serialize_resource(resource), status: resource.previously_new_record? ? :created : :ok+ else+ render_validation_error(resource.errors)+ end+ end++ # DELETE /api/v3/store/carts/:cart_id/tax_identifier+ def destroy+ return head :not_found if @cart.tax_identifier.nil?++ @cart.tax_identifier.destroy!+ Spree.cart_recalculate_totals_workflow.call(cart: @cart.reload)+ head :no_content+ end++ protected++ def serializer_class+ Spree.api.tax_identifier_serializer+ end++ def permitted_params+ params.permit(:kind, :value)+ end+ end+ end+ end+ end+ end+enddiff --git a/spree/api/app/controllers/spree/api/v3/store/customer/tax_identifiers_controller.rb b/spree/api/app/controllers/spree/api/v3/store/customer/tax_identifiers_controller.rbnew file mode 100644index 0000000000..80eb40d48c--- /dev/null+++ b/spree/api/app/controllers/spree/api/v3/store/customer/tax_identifiers_controller.rb@@ -0,0 +1,66 @@+module Spree+ module Api+ module V3+ module Store+ module Customer+ # The signed-in customer's own tax registration. Singular: one+ # registration per kind, and the storefront deals in one at a time.+ class TaxIdentifiersController < Store::BaseController+ prepend_before_action :require_authentication!++ # GET /api/v3/store/customers/me/tax_identifier+ def show+ return head :not_found if tax_identifier.nil?++ render json: serialize_resource(tax_identifier)+ end++ # PUT /api/v3/store/customers/me/tax_identifier+ #+ # Upsert rather than create/update: a buyer has one registration of a+ # kind, and asking the storefront to know whether it exists yet would+ # be bookkeeping we can do ourselves.+ def update+ resource = current_user.tax_identifiers.find_or_initialize_by(kind: permitted_params[:kind])+ resource.value = permitted_params[:value]++ if resource.save+ render json: serialize_resource(resource), status: resource.previously_new_record? ? :created : :ok+ else+ render_validation_error(resource.errors)+ end+ end++ # DELETE /api/v3/store/customers/me/tax_identifier+ def destroy+ return head :not_found if tax_identifier.nil?++ tax_identifier.destroy!+ head :no_content+ end++ protected++ def serializer_class+ Spree.api.tax_identifier_serializer+ end++ def permitted_params+ params.permit(:kind, :value)+ end++ private++ def tax_identifier+ @tax_identifier ||= if params[:kind].present?+ current_user.tax_identifiers.for_kind(params[:kind]).first+ else+ current_user.tax_identifiers.first+ end+ end+ end+ end+ end+ end+ end+enddiff --git a/spree/api/app/controllers/spree/api/v3/store/orders/tax_identifiers_controller.rb b/spree/api/app/controllers/spree/api/v3/store/orders/tax_identifiers_controller.rbnew file mode 100644index 0000000000..ae3a4ff819--- /dev/null+++ b/spree/api/app/controllers/spree/api/v3/store/orders/tax_identifiers_controller.rb@@ -0,0 +1,55 @@+module Spree+ module Api+ module V3+ module Store+ module Orders+ # Read-only: an order's registration is the snapshot taken when it was+ # placed, and an invoice has to keep saying what it said.+ class TaxIdentifiersController < Store::BaseController+ # GET /api/v3/store/orders/:order_id/tax_identifier+ def show+ return head :not_found if order.tax_identifier.nil?++ render json: serialize_resource(order.tax_identifier)+ end++ protected++ def serializer_class+ Spree.api.tax_identifier_serializer+ end++ private++ # The order is the customer's own — by JWT or by guest token,+ # mirroring Store::Orders::ReturnsController.+ def order+ @order ||= begin+ cart_pk = Spree::Cart.decode_own_prefixed_id(params[:order_id])+ found = if cart_pk+ order_scope.find_by!(cart_id: cart_pk)+ else+ order_scope.find_by_prefix_id!(params[:order_id])+ end+ authorize!(:show, found, order_token)+ found+ end+ end++ def order_scope+ base = current_store.orders.complete++ if current_user.present?+ base.where(customer: current_user)+ elsif order_token.present?+ base.where(token: order_token)+ else+ base.none+ end+ end+ end+ end+ end+ end+ end+enddiff --git a/spree/api/app/serializers/spree/api/v3/admin/tax_identifier_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/tax_identifier_serializer.rbnew file mode 100644index 0000000000..14cbe23211--- /dev/null+++ b/spree/api/app/serializers/spree/api/v3/admin/tax_identifier_serializer.rb@@ -0,0 +1,40 @@+module Spree+ module Api+ module V3+ module Admin+ class TaxIdentifierSerializer < V3::TaxIdentifierSerializer+ typelize validation_status: [:string, nullable: true],+ validated_at: [:string, nullable: true],+ validation_evidence: ['Record<string, unknown>', nullable: true],+ source: [:string, nullable: true],+ validatable: :boolean,+ customer_id: [:string, nullable: true],+ cart_id: [:string, nullable: true],+ order_id: [:string, nullable: true]++ attributes :validation_status, :validation_evidence, :source,+ validated_at: :iso8601, created_at: :iso8601, updated_at: :iso8601++ # Whether this installation can check a number of this kind at all —+ # what tells a nil verdict "not checked yet" apart from "nothing here+ # knows how to ask".+ attribute :validatable do |tax_identifier|+ tax_identifier.validatable?+ end++ attribute :customer_id do |tax_identifier|+ tax_identifier.customer&.prefixed_id+ end++ attribute :cart_id do |tax_identifier|+ tax_identifier.cart&.prefixed_id+ end++ attribute :order_id do |tax_identifier|+ tax_identifier.order&.prefixed_id+ end+ end+ end+ end+ end+enddiff --git a/spree/api/app/serializers/spree/api/v3/admin/tax_line_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/tax_line_serializer.rbindex 2b6f0e433d..451f13a807 100644--- a/spree/api/app/serializers/spree/api/v3/admin/tax_line_serializer.rb+++ b/spree/api/app/serializers/spree/api/v3/admin/tax_line_serializer.rb@@ -4,9 +4,23 @@ module Spreemodule Adminclass TaxLineSerializer < V3::TaxLineSerializertypelize amount: [:string, nullable: false], display_amount: [:string, nullable: false],- provider_id: [:string, nullable: true], metadata: ['Record<string, unknown>', nullable: true]+ provider_id: [:string, nullable: true], metadata: ['Record<string, unknown>', nullable: true],+ taxability_reason: [:string, nullable: true], country_iso: [:string, nullable: true],+ state_code: [:string, nullable: true], category_code: [:string, nullable: true],+ data: ['Record<string, unknown>', nullable: true]- attributes :provider_id, :metadata, created_at: :iso8601, updated_at: :iso8601+ # The treatment and its jurisdiction stay admin-only: no surveyed+ # platform shows a buyer a machine-readable tax reason, and `label`+ # already covers what they need. `data` carries the provider's own+ # breakdown, which is what an e-invoicing integration reads.+ attributes :provider_id, :metadata, :taxability_reason, :country_iso, :state_code, :data,+ created_at: :iso8601, updated_at: :iso8601++ # Derived from the reason at read time, never stored — the code lists+ # are revised on someone else's schedule.+ attribute :category_code do |tax_line|+ tax_line.category_code+ endendendenddiff --git a/spree/api/app/serializers/spree/api/v3/admin/tax_rate_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/tax_rate_serializer.rbnew file mode 100644index 0000000000..a7f60978c8--- /dev/null+++ b/spree/api/app/serializers/spree/api/v3/admin/tax_rate_serializer.rb@@ -0,0 +1,47 @@+module Spree+ module Api+ module V3+ module Admin+ # Admin-only: tax rates are the internal provider's configuration, never+ # customer-facing. What the customer sees is the label on a tax line.+ class TaxRateSerializer < V3::BaseSerializer+ typelize name: :string,+ amount: :string,+ amount_percentage: [:number, nullable: true],+ included_in_price: :boolean,+ show_rate_in_label: :boolean,+ tax_category_id: [:string, nullable: true],+ store_id: [:string, nullable: true],+ zone_id: [:string, nullable: true],+ metadata: ['Record<string, unknown>', nullable: true],+ deleted_at: [:string, nullable: true]++ attributes :name, :included_in_price, :show_rate_in_label, :metadata,+ created_at: :iso8601, updated_at: :iso8601, deleted_at: :iso8601++ attribute :amount do |tax_rate|+ tax_rate.amount&.to_s+ end++ # A real number, unlike the money-style `amount` string — this is a+ # percentage for display, not an amount to round-trip exactly.+ attribute :amount_percentage do |tax_rate|+ tax_rate.amount_percentage&.to_f+ end++ attribute :tax_category_id do |tax_rate|+ tax_rate.tax_category&.prefixed_id+ end++ attribute :store_id do |tax_rate|+ tax_rate.store&.prefixed_id+ end++ attribute :zone_id do |tax_rate|+ tax_rate.zone&.prefixed_id+ end+ end+ end+ end+ end+enddiff --git a/spree/api/app/serializers/spree/api/v3/fulfillment_serializer.rb b/spree/api/app/serializers/spree/api/v3/fulfillment_serializer.rbindex d08a1a9c39..c9e0f9bf69 100644--- a/spree/api/app/serializers/spree/api/v3/fulfillment_serializer.rb+++ b/spree/api/app/serializers/spree/api/v3/fulfillment_serializer.rb@@ -55,6 +55,7 @@ module Spreeone :delivery_method, resource: proc { Spree.api.delivery_method_serializer }one :stock_location, resource: proc { Spree.api.stock_location_serializer }many :delivery_rates, resource: proc { Spree.api.delivery_rate_serializer }+ many :tax_lines, resource: proc { Spree.api.tax_line_serializer }, if: proc { expand?('tax_lines') }endendenddiff --git a/spree/api/app/serializers/spree/api/v3/line_item_serializer.rb b/spree/api/app/serializers/spree/api/v3/line_item_serializer.rbindex a4f9abbb39..3c34533e7c 100644--- a/spree/api/app/serializers/spree/api/v3/line_item_serializer.rb+++ b/spree/api/app/serializers/spree/api/v3/line_item_serializer.rb@@ -59,6 +59,10 @@ module Spreemany :option_values, resource: proc { Spree.api.option_value_serializer }many :digital_links, resource: proc { Spree.api.digital_link_serializer }+ # Tax hangs off its adjustable, never off the cart or order: the+ # exactly-one-adjustable rule makes the nested view complete, and the+ # owner already carries the tax totals.+ many :tax_lines, resource: proc { Spree.api.tax_line_serializer }, if: proc { expand?('tax_lines') }endendenddiff --git a/spree/api/app/serializers/spree/api/v3/tax_identifier_serializer.rb b/spree/api/app/serializers/spree/api/v3/tax_identifier_serializer.rbnew file mode 100644index 0000000000..8e3ebc1ecd--- /dev/null+++ b/spree/api/app/serializers/spree/api/v3/tax_identifier_serializer.rb@@ -0,0 +1,15 @@+module Spree+ module Api+ module V3+ # The buyer's own tax registration. Deliberately just the kind and the+ # number: the validation verdict is the platform's bookkeeping, and showing+ # a customer that their number came back unverified invites support+ # tickets about a check they cannot influence.+ class TaxIdentifierSerializer < BaseSerializer+ typelize kind: :string, value: :string++ attributes :kind, :value+ end+ end+ end+enddiff --git a/spree/api/config/routes.rb b/spree/api/config/routes.rbindex 2413af0e7a..28736f9329 100644--- a/spree/api/config/routes.rb+++ b/spree/api/config/routes.rb@@ -51,6 +51,7 @@ Spree::Core::Engine.add_routes doendendresource :store_credits, only: [:create, :destroy], controller: 'carts/store_credits'+ resource :tax_identifier, only: [:show, :update, :destroy], controller: 'carts/tax_identifiers'end# Delivery methods (pickup discovery)@@ -67,6 +68,8 @@ Spree::Core::Engine.add_routes do# merchant approves, receives and refunds through the Admin API.resources :returns, only: [:index, :show, :create], controller: 'orders/returns'resources :claims, only: [:index, :show, :create], controller: 'orders/claims'+ # Read-only — the registration frozen onto the order at completion.+ resource :tax_identifier, only: [:show], controller: 'orders/tax_identifiers'end# Policies (return policy, privacy policy, terms of service, etc.)@@ -100,6 +103,7 @@ Spree::Core::Engine.add_routes doresources :credit_cards, only: [:index, :show, :destroy]resources :gift_cards, only: [:index, :show]resources :store_credits, only: [:index, :show]+ resource :tax_identifier, only: [:show, :update, :destroy], controller: 'tax_identifiers'resources :payment_setup_sessions, only: [:create, :show] domember dopatch :complete@@ -302,6 +306,9 @@ Spree::Core::Engine.add_routes do# Tax Categoriesresources :tax_categories+ # Tax Rates — the internal tax provider's configuration+ resources :tax_rates+# Return / claim / refund reasons (dropdowns + settings management)resources :return_reasonsresources :claim_reasons@@ -369,6 +376,11 @@ Spree::Core::Engine.add_routes doresources :addresses, controller: 'customers/addresses'resources :credit_cards, controller: 'customers/credit_cards', only: [:index, :show, :destroy]resources :store_credits, controller: 'customers/store_credits'+ resources :tax_identifiers, controller: 'customers/tax_identifiers' do+ member do+ post :validate+ end+ endcollection dopost :bulk_add_to_groupsdiff --git a/spree/api/lib/spree/api/dependencies.rb b/spree/api/lib/spree/api/dependencies.rbindex 76df1c5153..be1521c4b4 100644--- a/spree/api/lib/spree/api/dependencies.rb+++ b/spree/api/lib/spree/api/dependencies.rb@@ -56,6 +56,7 @@ module Spreepolicy_serializer: 'Spree::Api::V3::PolicySerializer',custom_field_serializer: 'Spree::Api::V3::CustomFieldSerializer',tax_category_serializer: 'Spree::Api::V3::TaxCategorySerializer',+ tax_identifier_serializer: 'Spree::Api::V3::TaxIdentifierSerializer',product_filters_serializer: 'Spree::Api::V3::ProductFiltersSerializer',product_filter_price_range_serializer: 'Spree::Api::V3::ProductFilterPriceRangeSerializer',product_filter_availability_serializer: 'Spree::Api::V3::ProductFilterAvailabilitySerializer',@@ -137,6 +138,8 @@ module Spreeadmin_claim_serializer: 'Spree::Api::V3::Admin::ClaimSerializer',admin_claim_line_item_serializer: 'Spree::Api::V3::Admin::ClaimLineItemSerializer',admin_tax_category_serializer: 'Spree::Api::V3::Admin::TaxCategorySerializer',+ admin_tax_rate_serializer: 'Spree::Api::V3::Admin::TaxRateSerializer',+ admin_tax_identifier_serializer: 'Spree::Api::V3::Admin::TaxIdentifierSerializer',admin_admin_user_serializer: 'Spree::Api::V3::Admin::AdminUserSerializer',admin_address_serializer: 'Spree::Api::V3::Admin::AddressSerializer',admin_channel_serializer: 'Spree::Api::V3::Admin::ChannelSerializer',diff --git a/spree/api/spec/controllers/spree/api/v3/admin/customers/tax_identifiers_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/customers/tax_identifiers_controller_spec.rbnew file mode 100644index 0000000000..84ec430299--- /dev/null+++ b/spree/api/spec/controllers/spree/api/v3/admin/customers/tax_identifiers_controller_spec.rb@@ -0,0 +1,98 @@+require 'spec_helper'++RSpec.describe Spree::Api::V3::Admin::Customers::TaxIdentifiersController, type: :controller do+ render_views++ include_context 'API v3 Admin authenticated'++ let!(:customer) { create(:user) }+ let!(:tax_identifier) { create(:tax_identifier, :verified, customer: customer, kind: 'eu_vat', value: 'DE123456789') }++ before { request.headers.merge!(headers) }++ describe 'GET #index' do+ it 'lists the customer registrations with their verdict' do+ get :index, params: { customer_id: customer.prefixed_id }, as: :json++ expect(response).to have_http_status(:ok)+ row = json_response['data'].first+ expect(row['kind']).to eq('eu_vat')+ expect(row['value']).to eq('DE123456789')+ expect(row['validation_status']).to eq('verified')+ expect(row['validation_evidence']['registry']).to eq('vies')+ expect(row['customer_id']).to eq(customer.prefixed_id)+ end++ it 'reports whether this installation can check the kind at all' do+ get :index, params: { customer_id: customer.prefixed_id }, as: :json++ expect(json_response['data'].first['validatable']).to be(false)+ end+ end++ describe 'POST #create' do+ it 'adds a registration to the customer' do+ expect do+ post :create, params: { customer_id: customer.prefixed_id, kind: 'gb_vat', value: 'GB123456789' }, as: :json+ end.to change { customer.tax_identifiers.count }.by(1)++ expect(response).to have_http_status(:created)+ expect(json_response['id']).to start_with('txi_')+ expect(json_response['value']).to eq('GB123456789')+ end++ it 'normalizes what was typed' do+ post :create, params: { customer_id: customer.prefixed_id, kind: 'gb_vat', value: ' gb 123 456 789 ' }, as: :json++ expect(json_response['value']).to eq('GB123456789')+ end+ end++ describe 'PATCH #update' do+ it 'updates the number' do+ patch :update, params: { customer_id: customer.prefixed_id, id: tax_identifier.prefixed_id, value: 'DE987654321' },+ as: :json++ expect(response).to have_http_status(:ok)+ expect(tax_identifier.reload.value).to eq('DE987654321')+ end+ end++ describe 'DELETE #destroy' do+ it 'removes the registration' do+ delete :destroy, params: { customer_id: customer.prefixed_id, id: tax_identifier.prefixed_id }, as: :json++ expect(response).to have_http_status(:no_content)+ expect(Spree::TaxIdentifier.find_by(id: tax_identifier.id)).to be_nil+ end+ end++ describe 'POST #validate' do+ context 'when a validator is registered for the kind' do+ around do |example|+ Spree.tax_id_validators['eu_vat'] = 'Spree::TaxIdValidator::Base'+ example.run+ ensure+ Spree.tax_id_validators.delete('eu_vat')+ end++ it 'queues a fresh registry check' do+ expect do+ post :validate, params: { customer_id: customer.prefixed_id, id: tax_identifier.prefixed_id }, as: :json+ end.to have_enqueued_job(Spree::TaxIdentifiers::ValidateJob)++ expect(response).to have_http_status(:accepted)+ expect(json_response['validation_status']).to eq('pending')+ end+ end++ context 'when nothing here can check the kind' do+ it 'says so rather than queueing a job with nothing to do' do+ post :validate, params: { customer_id: customer.prefixed_id, id: tax_identifier.prefixed_id }, as: :json++ expect(response).to have_http_status(:unprocessable_content)+ expect(json_response['error']['code']).to eq('tax_id_not_validatable')+ end+ end+ end+enddiff --git a/spree/api/spec/controllers/spree/api/v3/admin/orders/tax_lines_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/orders/tax_lines_controller_spec.rbindex 6b867f53a5..4732e37484 100644--- a/spree/api/spec/controllers/spree/api/v3/admin/orders/tax_lines_controller_spec.rb+++ b/spree/api/spec/controllers/spree/api/v3/admin/orders/tax_lines_controller_spec.rb@@ -23,6 +23,40 @@ RSpec.describe Spree::Api::V3::Admin::Orders::TaxLinesController, type: :controlexpect(json_response['data'].first['rate']).to eq('0.15')expect(json_response['data'].first['line_item_id']).to eq(line_item.prefixed_id)end++ it 'exposes the treatment, the jurisdiction and the provider payload' do+ tax_line.update!(taxability_reason: 'standard_rated', country_iso: 'DE',+ data: { 'jurisdictions' => [{ 'name' => 'DE', 'amount' => '1.5' }] })++ get :index, params: { order_id: order.prefixed_id }, as: :json++ row = json_response['data'].first+ expect(row['taxability_reason']).to eq('standard_rated')+ expect(row['category_code']).to eq('S')+ expect(row['country_iso']).to eq('DE')+ expect(row['state_code']).to be_nil+ expect(row['data']['jurisdictions'].first['name']).to eq('DE')+ expect(row['provider_id']).to eq('internal')+ end++ it 'filters by taxability reason, which is what tax reporting needs' do+ exempt_line = create(:tax_line, order: order, line_item: line_item, amount: 0, rate: 0,+ taxability_reason: 'customer_exempt')++ get :index, params: { order_id: order.prefixed_id, q: { taxability_reason_eq: 'customer_exempt' } }, as: :json++ expect(response).to have_http_status(:ok)+ expect(json_response['data'].map { |row| row['id'] }).to eq([exempt_line.prefixed_id])+ end++ it 'filters by taxing country' do+ tax_line.update!(country_iso: 'DE')+ create(:tax_line, order: order, line_item: line_item, country_iso: 'FR')++ get :index, params: { order_id: order.prefixed_id, q: { country_iso_eq: 'DE' } }, as: :json++ expect(json_response['data'].map { |row| row['id'] }).to eq([tax_line.prefixed_id])+ endenddescribe 'GET #show' dodiff --git a/spree/api/spec/controllers/spree/api/v3/admin/tax_rates_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/tax_rates_controller_spec.rbnew file mode 100644index 0000000000..66850fb04a--- /dev/null+++ b/spree/api/spec/controllers/spree/api/v3/admin/tax_rates_controller_spec.rb@@ -0,0 +1,96 @@+require 'spec_helper'++RSpec.describe Spree::Api::V3::Admin::TaxRatesController, type: :controller do+ render_views++ include_context 'API v3 Admin authenticated'++ let!(:tax_category) { create(:tax_category) }+ let!(:zone) { create(:zone, kind: 'country') }+ let!(:tax_rate) { create(:tax_rate, tax_category: tax_category, zone: zone, amount: 0.19, included_in_price: true) }++ before { request.headers.merge!(headers) }++ describe 'GET #index' do+ it 'returns the rates of the current store only' do+ other_store_rate = create(:tax_rate, store: create(:store))++ get :index, as: :json++ expect(response).to have_http_status(:ok)+ ids = json_response['data'].map { |rate| rate['id'] }+ expect(ids).to include(tax_rate.prefixed_id)+ expect(ids).not_to include(other_store_rate.prefixed_id)+ end+ end++ describe 'GET #show' do+ it 'returns the rate with its percentage and associations' do+ get :show, params: { id: tax_rate.prefixed_id }, as: :json++ expect(response).to have_http_status(:ok)+ expect(json_response['id']).to eq(tax_rate.prefixed_id)+ expect(json_response['amount']).to eq('0.19')+ expect(json_response['amount_percentage']).to eq(19.0)+ expect(json_response['included_in_price']).to be(true)+ expect(json_response['tax_category_id']).to eq(tax_category.prefixed_id)+ expect(json_response['zone_id']).to eq(zone.prefixed_id)+ expect(json_response['store_id']).to eq(@default_store.prefixed_id)+ end+ end++ describe 'POST #create' do+ let(:create_params) do+ { name: 'German VAT', amount: 0.19, included_in_price: true,+ tax_category_id: tax_category.prefixed_id, zone_id: zone.prefixed_id }+ end++ it 'creates a rate bound to the current store' do+ expect { post :create, params: create_params, as: :json }.to change(Spree::TaxRate, :count).by(1)++ expect(response).to have_http_status(:created)+ expect(json_response['id']).to start_with('tax_')+ expect(Spree::TaxRate.last.store).to eq(@default_store)+ end++ it 'accepts a percentage instead of a decimal' do+ post :create, params: create_params.merge(amount: nil, amount_percentage: 7), as: :json++ expect(response).to have_http_status(:created)+ expect(Spree::TaxRate.last.amount).to eq(0.07)+ end++ it 'rejects a rate with no category' do+ post :create, params: create_params.except(:tax_category_id), as: :json++ expect(response).to have_http_status(:unprocessable_content)+ end+ end++ describe 'PATCH #update' do+ it 'updates the rate' do+ patch :update, params: { id: tax_rate.prefixed_id, amount: 0 }, as: :json++ expect(response).to have_http_status(:ok)+ expect(tax_rate.reload.amount).to eq(0)+ end++ it 'cannot move a rate to another store' do+ other_store = create(:store)++ patch :update, params: { id: tax_rate.prefixed_id, store_id: other_store.prefixed_id }, as: :json++ expect(response).to have_http_status(:ok)+ expect(tax_rate.reload.store).to eq(@default_store)+ end+ end++ describe 'DELETE #destroy' do+ it 'soft-deletes the rate' do+ delete :destroy, params: { id: tax_rate.prefixed_id }, as: :json++ expect(response).to have_http_status(:no_content)+ expect(tax_rate.reload.deleted_at).to be_present+ end+ end+enddiff --git a/spree/api/spec/integration/spree/api/v3/admin/tax_rates_spec.rb b/spree/api/spec/integration/spree/api/v3/admin/tax_rates_spec.rbnew file mode 100644index 0000000000..52142ba519--- /dev/null+++ b/spree/api/spec/integration/spree/api/v3/admin/tax_rates_spec.rb@@ -0,0 +1,197 @@+# frozen_string_literal: true++require 'swagger_helper'++RSpec.describe 'Admin Tax Rates API', type: :request, swagger_doc: 'api-reference/admin.yaml' do+ include_context 'API v3 Admin'++ let!(:tax_category) { create(:tax_category) }+ let!(:zone) { create(:zone, kind: 'country') }+ let!(:tax_rate) { create(:tax_rate, tax_category: tax_category, zone: zone, amount: 0.19, included_in_price: true) }+ let(:Authorization) { "Bearer #{admin_jwt_token}" }++ path '/api/v3/admin/tax_rates' do+ get 'List tax rates' do+ tags 'Settings'+ produces 'application/json'+ security [api_key: [], bearer_auth: []]+ description <<~DESC+ Returns the store's tax rates. Rates are the entire configuration of+ the built-in tax provider: each pairs a tax category with a zone and a+ percentage, and decides whether the tax is already included in the+ product price (VAT-style) or added on top (US-style).++ Markets using an external tax provider ignore these rows — that+ provider carries its own jurisdiction data.+ DESC+ admin_scope :read, :settings++ parameter name: 'x-spree-api-key', in: :header, type: :string, required: true+ parameter name: :Authorization, in: :header, type: :string, required: true,+ description: 'Bearer token for admin authentication'+ parameter name: :page, in: :query, type: :integer, required: false, description: 'Page number'+ parameter name: :limit, in: :query, type: :integer, required: false, description: 'Number of records per page'+ parameter name: :'q[name_cont]', in: :query, type: :string, required: false,+ description: 'Filter by name (contains)'+ parameter name: :'q[included_in_price_true]', in: :query, type: :boolean, required: false,+ description: 'Only rates included in the product price'+ parameter name: :sort, in: :query, type: :string, required: false,+ description: 'Sort by field. Prefix with `-` for descending (e.g., `-created_at`).'++ response '200', 'tax rates found' do+ let(:'x-spree-api-key') { secret_api_key.plaintext_token }++ schema SwaggerSchemaHelpers.paginated('TaxRate')++ run_test! do |response|+ data = JSON.parse(response.body)+ expect(data['data'].map { |rate| rate['id'] }).to include(tax_rate.prefixed_id)+ end+ end++ response '401', 'unauthorized' do+ let(:'x-spree-api-key') { 'invalid' }+ let(:Authorization) { 'Bearer invalid' }++ schema '$ref' => '#/components/schemas/ErrorResponse'++ run_test!+ end+ end++ post 'Create a tax rate' do+ tags 'Settings'+ consumes 'application/json'+ produces 'application/json'+ security [api_key: [], bearer_auth: []]+ description <<~DESC+ Creates a tax rate for the current store. Give either `amount` as a+ decimal (`0.19`) or `amount_percentage` as a percentage (`19`).++ Set `included_in_price` for VAT-style pricing, where the rate is backed+ out of the displayed price rather than added to it.+ DESC+ admin_scope :write, :settings++ parameter name: 'x-spree-api-key', in: :header, type: :string, required: true+ parameter name: :Authorization, in: :header, type: :string, required: true,+ description: 'Bearer token for admin authentication'+ parameter name: :body, in: :body, required: true, schema: {+ type: :object,+ properties: {+ name: { type: :string, description: 'Customer-facing rate name, e.g. "VAT"' },+ amount: { type: :string, description: 'Rate as a decimal, e.g. "0.19"' },+ amount_percentage: { type: :number, description: 'Rate as a percentage, e.g. 19' },+ included_in_price: { type: :boolean },+ show_rate_in_label: { type: :boolean },+ tax_category_id: { type: :string },+ zone_id: { type: :string }+ },+ required: %w[name tax_category_id]+ }++ response '201', 'tax rate created' do+ let(:'x-spree-api-key') { secret_api_key.plaintext_token }+ let(:body) do+ { name: 'VAT', amount_percentage: 19, included_in_price: true,+ tax_category_id: tax_category.prefixed_id, zone_id: zone.prefixed_id }+ end++ schema '$ref' => '#/components/schemas/TaxRate'++ run_test! do |response|+ data = JSON.parse(response.body)+ expect(data['amount']).to eq('0.19')+ expect(data['amount_percentage']).to eq(19.0)+ end+ end++ response '422', 'validation failed' do+ let(:'x-spree-api-key') { secret_api_key.plaintext_token }+ let(:body) { { amount_percentage: 19 } }++ schema '$ref' => '#/components/schemas/ErrorResponse'++ run_test!+ end+ end+ end++ path '/api/v3/admin/tax_rates/{id}' do+ parameter name: :id, in: :path, type: :string, description: 'Tax rate ID'++ let(:id) { tax_rate.prefixed_id }++ get 'Get a tax rate' do+ tags 'Settings'+ produces 'application/json'+ security [api_key: [], bearer_auth: []]+ admin_scope :read, :settings++ parameter name: 'x-spree-api-key', in: :header, type: :string, required: true+ parameter name: :Authorization, in: :header, type: :string, required: true,+ description: 'Bearer token for admin authentication'++ response '200', 'tax rate found' do+ let(:'x-spree-api-key') { secret_api_key.plaintext_token }++ schema '$ref' => '#/components/schemas/TaxRate'++ run_test!+ end+ end++ patch 'Update a tax rate' do+ tags 'Settings'+ consumes 'application/json'+ produces 'application/json'+ security [api_key: [], bearer_auth: []]+ admin_scope :write, :settings++ parameter name: 'x-spree-api-key', in: :header, type: :string, required: true+ parameter name: :Authorization, in: :header, type: :string, required: true,+ description: 'Bearer token for admin authentication'+ parameter name: :body, in: :body, required: true, schema: {+ type: :object,+ properties: {+ name: { type: :string },+ amount: { type: :string },+ amount_percentage: { type: :number },+ included_in_price: { type: :boolean },+ show_rate_in_label: { type: :boolean },+ tax_category_id: { type: :string },+ zone_id: { type: :string }+ }+ }++ response '200', 'tax rate updated' do+ let(:'x-spree-api-key') { secret_api_key.plaintext_token }+ let(:body) { { amount_percentage: 7 } }++ schema '$ref' => '#/components/schemas/TaxRate'++ run_test! do |response|+ expect(JSON.parse(response.body)['amount']).to eq('0.07')+ end+ end+ end++ delete 'Delete a tax rate' do+ tags 'Settings'+ produces 'application/json'+ security [api_key: [], bearer_auth: []]+ description 'Soft-deletes the rate. Tax lines it already produced keep their own rate snapshot.'+ admin_scope :write, :settings++ parameter name: 'x-spree-api-key', in: :header, type: :string, required: true+ parameter name: :Authorization, in: :header, type: :string, required: true,+ description: 'Bearer token for admin authentication'++ response '204', 'tax rate deleted' do+ let(:'x-spree-api-key') { secret_api_key.plaintext_token }++ run_test!+ end+ end+ end+enddiff --git a/spree/api/spec/requests/spree/api/v3/admin/tax_configuration_spec.rb b/spree/api/spec/requests/spree/api/v3/admin/tax_configuration_spec.rbnew file mode 100644index 0000000000..edfab96c38--- /dev/null+++ b/spree/api/spec/requests/spree/api/v3/admin/tax_configuration_spec.rb@@ -0,0 +1,83 @@+require 'spec_helper'++# The reason /admin/tax_rates exists: rate rows are the whole configuration of+# the internal provider, so this walks the merchant's path — configure a rate+# through the API, then observe the tax it produces on a real cart.+RSpec.describe 'Admin tax configuration', type: :request do+ include_context 'API v3 Admin authenticated'++ let(:country) { Spree::Country.find_by(iso: 'DE') || create(:country, iso: 'DE', name: 'Germany') }+ let(:address) { create(:address, country: country, state: nil, state_name: 'Berlin') }+ let(:zone) do+ create(:zone, kind: 'country', default_tax: true).tap do |zone|+ zone.members.create!(zoneable: country)+ end+ end+ let(:tax_category) { create(:tax_category) }++ let(:cart) do+ create(:cart_with_line_items, line_items_count: 1, store: store,+ ship_address: address, bill_address: address).tap do |cart|+ cart.line_items.first.update!(tax_category: tax_category)+ end+ end++ # The publishable key the storefront reads with.+ let(:store_headers) { { 'x-spree-api-key' => create(:api_key, :publishable, store: store).token } }++ it 'configures a rate and produces the tax it describes' do+ post '/api/v3/admin/tax_rates',+ params: { name: 'German VAT', amount_percentage: 19, included_in_price: true,+ tax_category_id: tax_category.prefixed_id, zone_id: zone.prefixed_id },+ headers: headers, as: :json++ expect(response).to have_http_status(:created)+ rate_id = JSON.parse(response.body)['id']+ expect(rate_id).to start_with('tax_')++ Spree::Carts::RecalculateTotals.call(cart: cart)++ expect(cart.tax_lines.reload.pluck(:amount, :taxability_reason, :country_iso, :provider_id)).to eq(+ [[BigDecimal('1.6'), 'standard_rated', 'DE', 'internal']]+ )+ end++ it 'still records a treatment when the rate is zero' do+ post '/api/v3/admin/tax_rates',+ params: { name: 'German VAT', amount_percentage: 19, included_in_price: true,+ tax_category_id: tax_category.prefixed_id, zone_id: zone.prefixed_id },+ headers: headers, as: :json+ rate_id = JSON.parse(response.body)['id']++ Spree::Carts::RecalculateTotals.call(cart: cart)++ patch "/api/v3/admin/tax_rates/#{rate_id}", params: { amount: 0 }, headers: headers, as: :json+ expect(response).to have_http_status(:ok)++ Spree::Carts::RecalculateTotals.call(cart: cart.reload)++ tax_line = cart.tax_lines.reload.sole+ expect(tax_line.amount).to eq(0)+ expect(tax_line.taxability_reason).to eq('zero_rated')+ end++ it 'shows the storefront the tax on a line, without the admin treatment fields' do+ post '/api/v3/admin/tax_rates',+ params: { name: 'German VAT', amount_percentage: 19, included_in_price: true,+ tax_category_id: tax_category.prefixed_id, zone_id: zone.prefixed_id },+ headers: headers, as: :json++ Spree::Carts::RecalculateTotals.call(cart: cart)++ get "/api/v3/store/carts/#{cart.prefixed_id}?expand=items.tax_lines",+ headers: store_headers.merge('x-spree-token' => cart.token), as: :json++ expect(response).to have_http_status(:ok)+ tax_lines = JSON.parse(response.body)['items'].first['tax_lines']+ expect(tax_lines.length).to eq(1)+ expect(tax_lines.first).to include('label', 'rate', 'amount', 'included')+ expect(tax_lines.first['included']).to be(true)+ expect(tax_lines.first).not_to have_key('taxability_reason')+ expect(tax_lines.first).not_to have_key('country_iso')+ end+enddiff --git a/spree/api/spec/requests/spree/api/v3/store/tax_identifiers_spec.rb b/spree/api/spec/requests/spree/api/v3/store/tax_identifiers_spec.rbnew file mode 100644index 0000000000..3ef11dd3fd--- /dev/null+++ b/spree/api/spec/requests/spree/api/v3/store/tax_identifiers_spec.rb@@ -0,0 +1,84 @@+require 'spec_helper'++RSpec.describe 'Store tax identifiers', type: :request do+ include_context 'API v3 Store authenticated'++ describe 'the customer own registration' do+ it 'is upserted, read back and removed' do+ put '/api/v3/store/customers/me/tax_identifier',+ params: { kind: 'eu_vat', value: ' de 123 456 789 ' }, headers: headers, as: :json++ expect(response).to have_http_status(:created)+ body = JSON.parse(response.body)+ expect(body['value']).to eq('DE123456789')+ # The verdict is the platform's bookkeeping, not the buyer's business.+ expect(body).not_to have_key('validation_status')++ put '/api/v3/store/customers/me/tax_identifier',+ params: { kind: 'eu_vat', value: 'DE987654321' }, headers: headers, as: :json+ expect(response).to have_http_status(:ok)+ expect(user.tax_identifiers.count).to eq(1)++ get '/api/v3/store/customers/me/tax_identifier', headers: headers, as: :json+ expect(JSON.parse(response.body)['value']).to eq('DE987654321')++ delete '/api/v3/store/customers/me/tax_identifier', headers: headers, as: :json+ expect(response).to have_http_status(:no_content)++ get '/api/v3/store/customers/me/tax_identifier', headers: headers, as: :json+ expect(response).to have_http_status(:not_found)+ end+ end++ describe 'a checkout override on the cart' do+ let(:cart) { create(:cart_with_line_items, line_items_count: 1, store: store, customer: user) }++ it 'is stored against the cart and read back' do+ put "/api/v3/store/carts/#{cart.prefixed_id}/tax_identifier",+ params: { kind: 'eu_vat', value: 'DE555555555' },+ headers: headers.merge('x-spree-token' => cart.token), as: :json++ expect(response).to have_http_status(:created)+ expect(cart.reload.tax_identifier.value).to eq('DE555555555')++ get "/api/v3/store/carts/#{cart.prefixed_id}/tax_identifier",+ headers: headers.merge('x-spree-token' => cart.token), as: :json+ expect(JSON.parse(response.body)['kind']).to eq('eu_vat')+ end++ it 'rejects a malformed number when this installation can check the kind' do+ stub_const('SpecStoreValidator', Class.new(Spree::TaxIdValidator::Base) do+ def self.valid_format?(value)+ value.start_with?('DE')+ end+ end)+ Spree.tax_id_validators['eu_vat'] = 'SpecStoreValidator'++ put "/api/v3/store/carts/#{cart.prefixed_id}/tax_identifier",+ params: { kind: 'eu_vat', value: '123' },+ headers: headers.merge('x-spree-token' => cart.token), as: :json++ expect(response).to have_http_status(:unprocessable_content)+ ensure+ Spree.tax_id_validators.delete('eu_vat')+ end+ end++ describe 'the snapshot on a placed order' do+ let(:order) { create(:completed_order_with_totals, store: store, customer: user) }++ it 'is readable and cannot be written' do+ create(:tax_identifier, :on_order, order: order, value: 'DE111111111')++ get "/api/v3/store/orders/#{order.prefixed_id}/tax_identifier", headers: headers, as: :json++ expect(response).to have_http_status(:ok)+ expect(JSON.parse(response.body)['value']).to eq('DE111111111')++ put "/api/v3/store/orders/#{order.prefixed_id}/tax_identifier",+ params: { kind: 'eu_vat', value: 'DE222222222' }, headers: headers, as: :json+ expect(response).to have_http_status(:not_found)+ expect(order.tax_identifier.reload.value).to eq('DE111111111')+ end+ end+enddiff --git a/spree/core/app/models/spree/tax_line.rb b/spree/core/app/models/spree/tax_line.rbindex d869fc4cbc..119432e4fb 100644--- a/spree/core/app/models/spree/tax_line.rb+++ b/spree/core/app/models/spree/tax_line.rb@@ -68,6 +68,10 @@ module Spreeallow_nil: truevalidate :exactly_one_adjustable+ # Tax reporting is the reason the treatment columns exist — "which country's+ # tax was this, and which sales were reverse-charged" has to be answerable.+ self.whitelisted_ransackable_attributes = %w[taxability_reason country_iso state_code included provider_id]+scope :included_in_price, -> { where(included: true) }scope :additional, -> { where(included: false) }scope :for_line_items, -> { where.not(line_item_id: nil) }