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
Companies and tax exemptions, Phases 7-8: manage all of it over the admin API
Łukasz Adamczyk4baa6fbe1ddf
diff --git a/spree/api/app/controllers/spree/api/v3/admin/companies/base_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/companies/base_controller.rbnew file mode 100644index 0000000000..f1a1595333--- /dev/null+++ b/spree/api/app/controllers/spree/api/v3/admin/companies/base_controller.rb@@ -0,0 +1,29 @@+module Spree+ module Api+ module V3+ module Admin+ module Companies+ # Anything nested under a company. The parent is resolved through the+ # store, so a company belonging to another tenant is a 404 rather than+ # a readable record.+ class BaseController < ResourceController+ scoped_resource :customers++ protected++ def set_parent+ @parent = current_store.companies.+ accessible_by(current_ability, parent_ability_action).+ find_by_prefix_id!(params[:company_id])+ @company = @parent+ end++ def authorize_parent_access!+ authorize_parent!(@parent)+ end+ end+ end+ end+ end+ end+enddiff --git a/spree/api/app/controllers/spree/api/v3/admin/companies/locations_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/companies/locations_controller.rbnew file mode 100644index 0000000000..75f22e0034--- /dev/null+++ b/spree/api/app/controllers/spree/api/v3/admin/companies/locations_controller.rb@@ -0,0 +1,40 @@+module Spree+ module Api+ module V3+ module Admin+ module Companies+ # Branches of one company. Listing and creating live here; editing and+ # deleting a branch are addressed directly, since a caller holding a+ # branch id shouldn't have to know its company.+ class LocationsController < BaseController+ include Spree::Api::V3::Admin::Concerns::CompanyLocationParams++ before_action :authorize_parent_access!++ protected++ def model_class+ Spree::CompanyLocation+ end++ def serializer_class+ Spree.api.admin_company_location_serializer+ end++ def scope+ @parent.company_locations+ end++ def parent_association+ :company_locations+ end++ def collection_includes+ [:billing_address, :shipping_address, :company_contacts]+ end+ end+ end+ end+ end+ end+enddiff --git a/spree/api/app/controllers/spree/api/v3/admin/companies/tax_exemption_certificates_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/companies/tax_exemption_certificates_controller.rbnew file mode 100644index 0000000000..71ab7e9f7a--- /dev/null+++ b/spree/api/app/controllers/spree/api/v3/admin/companies/tax_exemption_certificates_controller.rb@@ -0,0 +1,116 @@+module Spree+ module Api+ module V3+ module Admin+ module Companies+ # A company's exemption evidence. Accepting one is a decision, so it+ # runs through the verify workflow rather than a status write, and a+ # verified certificate is revoked rather than deleted.+ class TaxExemptionCertificatesController < BaseController+ include ActiveStorage::SetCurrent++ before_action :authorize_parent_access!+ # Re-declaring the filter replaces the inherited options, so the+ # standard actions have to be listed alongside the custom ones.+ before_action :set_resource, only: [:show, :update, :destroy, :verify, :revoke, :download]++ # A tampered signed id would otherwise surface as a 500.+ rescue_from ActiveSupport::MessageVerifier::InvalidSignature, with: :render_invalid_signature++ # PATCH /api/v3/admin/companies/:company_id/tax_exemption_certificates/:id/verify+ def verify+ authorize_resource!(@resource, :update)++ result = Spree.tax_exemption_certificate_verify_workflow.call(+ certificate: @resource,+ verified_by: try_spree_current_user+ )++ if result.success?+ render json: serialize_resource(result.value)+ else+ render_result_error(result)+ end+ end++ # PATCH .../:id/revoke — withdrawing evidence that was accepted.+ def revoke+ authorize_resource!(@resource, :update)++ if @resource.update(status: 'revoked')+ render json: serialize_resource(@resource.reload)+ else+ render_validation_error(@resource.errors)+ end+ end++ # GET .../:id/download — streamed rather than redirected, so the+ # document is never reachable without admin credentials.+ def download+ authorize_resource!(@resource, :show)++ unless @resource.document.attached?+ return render_error(+ code: Spree::Api::V3::ErrorHandler::ERROR_CODES[:validation_error],+ message: 'Certificate has no attached document',+ status: :unprocessable_content+ )+ end++ send_data(+ @resource.document.download,+ filename: @resource.document.filename.to_s,+ type: @resource.document.content_type || 'application/octet-stream',+ disposition: 'attachment'+ )+ end++ protected++ def model_class+ Spree::TaxExemptionCertificate+ end++ def serializer_class+ Spree.api.admin_tax_exemption_certificate_serializer+ end++ def scope+ @parent.tax_exemption_certificates+ end++ def parent_association+ :tax_exemption_certificates+ end++ def collection_includes+ [:country, :state, { document_attachment: :blob }]+ end++ # `document` is an ActiveStorage signed blob id from+ # POST /api/v3/admin/direct_uploads.+ def permitted_params+ params.permit(:certificate_number, :reason_code, :issuing_authority,+ :issued_at, :expires_at, :country_iso, :state_code, :document,+ metadata: {})+ end++ def build_resource+ super.tap { |certificate| certificate.status ||= 'pending' }+ end++ private++ def render_invalid_signature+ render_error(+ code: Spree::Api::V3::ErrorHandler::ERROR_CODES[:validation_error],+ message: 'Invalid document signed id',+ status: :unprocessable_content+ )+ end+ end+ end+ end+ end+ end+enddiff --git a/spree/api/app/controllers/spree/api/v3/admin/companies_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/companies_controller.rbnew file mode 100644index 0000000000..dc5266d14b--- /dev/null+++ b/spree/api/app/controllers/spree/api/v3/admin/companies_controller.rb@@ -0,0 +1,35 @@+module Spree+ module Api+ module V3+ module Admin+ # Business customers. A company is a customer record, so it answers to+ # the customer scopes rather than earning one of its own.+ class CompaniesController < ResourceController+ scoped_resource :customers++ protected++ def model_class+ Spree::Company+ end++ def serializer_class+ Spree.api.admin_company_serializer+ end++ def scope+ super.for_store(current_store)+ end++ def collection_includes+ [:company_locations]+ end++ def permitted_params+ params.permit(:name, :external_id, metadata: {})+ end+ end+ end+ end+ end+enddiff --git a/spree/api/app/controllers/spree/api/v3/admin/company_contacts_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/company_contacts_controller.rbnew file mode 100644index 0000000000..7ec9006589--- /dev/null+++ b/spree/api/app/controllers/spree/api/v3/admin/company_contacts_controller.rb@@ -0,0 +1,29 @@+module Spree+ module Api+ module V3+ module Admin+ # Removing a buyer's authority to purchase for a branch, addressed+ # directly by contact id.+ class CompanyContactsController < ResourceController+ scoped_resource :customers++ protected++ def model_class+ Spree::CompanyContact+ end++ def serializer_class+ Spree.api.admin_company_contact_serializer+ end++ def scope+ Spree::CompanyContact.where(+ company_location_id: Spree::CompanyLocation.where(company_id: current_store.companies.select(:id)).select(:id)+ )+ end+ end+ end+ end+ end+enddiff --git a/spree/api/app/controllers/spree/api/v3/admin/company_locations/contacts_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/company_locations/contacts_controller.rbnew file mode 100644index 0000000000..40a7469f23--- /dev/null+++ b/spree/api/app/controllers/spree/api/v3/admin/company_locations/contacts_controller.rb@@ -0,0 +1,46 @@+module Spree+ module Api+ module V3+ module Admin+ module CompanyLocations+ # The buyers who purchase for one branch.+ class ContactsController < ResourceController+ scoped_resource :customers++ protected++ def model_class+ Spree::CompanyContact+ end++ def serializer_class+ Spree.api.admin_company_contact_serializer+ end++ def set_parent+ @parent = Spree::CompanyLocation.+ where(company_id: current_store.companies.select(:id)).+ find_by_prefix_id!(params[:company_location_id])+ end++ def scope+ @parent.company_contacts+ end++ def parent_association+ :company_contacts+ end++ def collection_includes+ [:customer]+ end++ def permitted_params+ params.permit(:customer_id, :role)+ end+ end+ end+ end+ end+ end+enddiff --git a/spree/api/app/controllers/spree/api/v3/admin/company_locations_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/company_locations_controller.rbnew file mode 100644index 0000000000..0433840314--- /dev/null+++ b/spree/api/app/controllers/spree/api/v3/admin/company_locations_controller.rb@@ -0,0 +1,33 @@+module Spree+ module Api+ module V3+ module Admin+ # A branch addressed directly. Reached through the store's companies so a+ # branch of another tenant's company is a 404.+ class CompanyLocationsController < ResourceController+ include Spree::Api::V3::Admin::Concerns::CompanyLocationParams++ scoped_resource :customers++ protected++ def model_class+ Spree::CompanyLocation+ end++ def serializer_class+ Spree.api.admin_company_location_serializer+ end++ def scope+ Spree::CompanyLocation.where(company_id: current_store.companies.select(:id))+ end++ def collection_includes+ [:billing_address, :shipping_address, :company_contacts]+ end+ end+ end+ end+ end+enddiff --git a/spree/api/app/controllers/spree/api/v3/admin/concerns/company_location_params.rb b/spree/api/app/controllers/spree/api/v3/admin/concerns/company_location_params.rbnew file mode 100644index 0000000000..4d32f641e0--- /dev/null+++ b/spree/api/app/controllers/spree/api/v3/admin/concerns/company_location_params.rb@@ -0,0 +1,33 @@+module Spree+ module Api+ module V3+ module Admin+ module Concerns+ # Shared by the two places a branch is written: nested creation under a+ # company, and direct edits by branch id.+ module CompanyLocationParams+ extend ActiveSupport::Concern++ # Enumerated rather than borrowing the legacy global list, which+ # permits :id, :user_id and :deleted_at.+ ADDRESS_KEYS = [+ :first_name, :last_name, :company, :address1, :address2, :city,+ :postal_code, :zipcode, :phone, :country_iso, :state_abbr, :state_name, :label+ ].freeze++ protected++ def permitted_params+ params.permit(+ :name, :external_id,+ metadata: {},+ billing_address: ADDRESS_KEYS,+ shipping_address: ADDRESS_KEYS+ )+ end+ end+ end+ end+ end+ end+enddiff --git a/spree/api/app/serializers/spree/api/v3/admin/company_contact_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/company_contact_serializer.rbnew file mode 100644index 0000000000..b4037b52b7--- /dev/null+++ b/spree/api/app/serializers/spree/api/v3/admin/company_contact_serializer.rb@@ -0,0 +1,28 @@+module Spree+ module Api+ module V3+ module Admin+ class CompanyContactSerializer < V3::BaseSerializer+ typelize role: :string, company_location_id: :string, customer_id: :string,+ email: [:string, nullable: true]++ attributes :role, created_at: :iso8601, updated_at: :iso8601++ attribute :company_location_id do |contact|+ contact.company_location&.prefixed_id+ end++ attribute :customer_id do |contact|+ contact.customer&.prefixed_id+ end++ # The dashboard lists contacts by who they are, and would otherwise+ # need a customer request per row.+ attribute :email do |contact|+ contact.customer&.email+ end+ end+ end+ end+ end+enddiff --git a/spree/api/app/serializers/spree/api/v3/admin/company_location_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/company_location_serializer.rbnew file mode 100644index 0000000000..cb51f26b62--- /dev/null+++ b/spree/api/app/serializers/spree/api/v3/admin/company_location_serializer.rb@@ -0,0 +1,36 @@+module Spree+ module Api+ module V3+ module Admin+ # Admin-only: branches are back-office records with no storefront+ # surface, so there is no store serializer to extend. Deliberately not+ # sharing a parent with the company and contact serializers — Typelizer+ # emits one TS type per serializer, and an abstract one would reach the+ # admin SDK without any endpoint returning it.+ class CompanyLocationSerializer < V3::BaseSerializer+ typelize name: :string, external_id: [:string, nullable: true],+ company_id: :string, contacts_count: :number,+ metadata: 'Record<string, unknown> | null'++ attributes :name, :external_id, :metadata,+ created_at: :iso8601, updated_at: :iso8601++ attribute :company_id do |location|+ location.company&.prefixed_id+ end++ attribute :contacts_count do |location|+ location.company_contacts.size+ end++ one :billing_address, resource: proc { Spree.api.address_serializer }+ one :shipping_address, resource: proc { Spree.api.address_serializer }++ many :company_contacts,+ resource: proc { Spree.api.admin_company_contact_serializer },+ if: proc { expand?('company_contacts') }+ end+ end+ end+ end+enddiff --git a/spree/api/app/serializers/spree/api/v3/admin/company_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/company_serializer.rbnew file mode 100644index 0000000000..6a444e75b6--- /dev/null+++ b/spree/api/app/serializers/spree/api/v3/admin/company_serializer.rb@@ -0,0 +1,22 @@+module Spree+ module Api+ module V3+ module Admin+ class CompanySerializer < V3::CompanySerializer+ typelize locations_count: :number, metadata: 'Record<string, unknown> | null'++ attributes :metadata, created_at: :iso8601, updated_at: :iso8601++ # Saves the dashboard a request per row just to say "3 branches".+ attribute :locations_count do |company|+ company.company_locations.size+ end++ many :company_locations,+ resource: proc { Spree.api.admin_company_location_serializer },+ if: proc { expand?('company_locations') }+ end+ end+ end+ end+enddiff --git a/spree/api/app/serializers/spree/api/v3/admin/tax_exemption_certificate_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/tax_exemption_certificate_serializer.rbnew file mode 100644index 0000000000..002a5e8951--- /dev/null+++ b/spree/api/app/serializers/spree/api/v3/admin/tax_exemption_certificate_serializer.rb@@ -0,0 +1,73 @@+module Spree+ module Api+ module V3+ module Admin+ # Admin-only: certificates are back-office evidence with no storefront+ # surface, so there is no store serializer to extend.+ class TaxExemptionCertificateSerializer < V3::BaseSerializer+ typelize certificate_number: :string, reason_code: :string, status: :string,+ issuing_authority: [:string, nullable: true],+ company_id: :string,+ country_iso: [:string, nullable: true], state_code: [:string, nullable: true],+ active: :boolean, lapsed: :boolean, can_be_deleted: :boolean,+ document_filename: [:string, nullable: true],+ document_byte_size: ['number | null'],+ document_url: [:string, nullable: true],+ metadata: 'Record<string, unknown> | null'++ attributes :certificate_number, :reason_code, :status, :issuing_authority, :metadata,+ issued_at: :iso8601, expires_at: :iso8601, verified_at: :iso8601,+ created_at: :iso8601, updated_at: :iso8601++ attribute :company_id do |certificate|+ certificate.company&.prefixed_id+ end++ # The jurisdiction the certificate holds in, in the same vocabulary the+ # tax lines use.+ attribute :country_iso do |certificate|+ certificate.country&.iso+ end++ attribute :state_code do |certificate|+ certificate.state&.abbr+ end++ # Whether it counts right now — the status alone can't say, since a+ # verified certificate stops counting once its date passes.+ attribute :active do |certificate|+ certificate.verified? && !certificate.lapsed?+ end++ attribute :lapsed do |certificate|+ certificate.lapsed?+ end++ # Lets the dashboard hide a delete the model will refuse.+ attribute :can_be_deleted do |certificate|+ certificate.can_be_deleted?+ end++ attribute :document_filename do |certificate|+ certificate.document.blob&.filename&.to_s if certificate.document.attached?+ end++ attribute :document_byte_size do |certificate|+ certificate.document.blob&.byte_size if certificate.document.attached?+ end++ # Our own endpoint rather than a pre-signed URL: the controller streams+ # the bytes, so admin auth runs on every download of a confidential+ # document.+ attribute :document_url do |certificate|+ next nil unless certificate.document.attached?++ Spree::Core::Engine.routes.url_helpers.download_api_v3_admin_company_tax_exemption_certificate_path(+ company_id: certificate.company.prefixed_id, id: certificate.prefixed_id+ )+ end+ end+ end+ end+ end+enddiff --git a/spree/api/app/serializers/spree/api/v3/company_serializer.rb b/spree/api/app/serializers/spree/api/v3/company_serializer.rbnew file mode 100644index 0000000000..187b585f49--- /dev/null+++ b/spree/api/app/serializers/spree/api/v3/company_serializer.rb@@ -0,0 +1,15 @@+module Spree+ module Api+ module V3+ # Companies have no Store API — this exists as the payload for the+ # company lifecycle events, the same reason ImportSerializer and+ # ExportSerializer sit in this namespace. The admin serializer extends it+ # so back-office fields stay in one place.+ class CompanySerializer < BaseSerializer+ typelize name: :string, external_id: [:string, nullable: true]++ attributes :name, :external_id+ end+ end+ end+enddiff --git a/spree/api/config/routes.rb b/spree/api/config/routes.rbindex bcd8b13f60..a3fabb6c76 100644--- a/spree/api/config/routes.rb+++ b/spree/api/config/routes.rb@@ -396,6 +396,30 @@ Spree::Core::Engine.add_routes do# Customer groups (segmentation; used by promotion rules + bulk customer ops)resources :customer_groups+ # Business customers. Branches and their buyers are created under their+ # parent and then addressed directly, so a caller holding a branch id+ # does not have to know which company it belongs to.+ resources :companies do+ resources :locations, controller: 'companies/locations', only: [:index, :show, :create]++ # Exemption evidence. Accepting or withdrawing one is its own action —+ # never mass assignment — and a verified certificate is revoked+ # rather than deleted.+ resources :tax_exemption_certificates, controller: 'companies/tax_exemption_certificates' do+ member do+ patch :verify+ patch :revoke+ get :download+ end+ end+ end++ resources :company_locations, only: [:show, :update, :destroy] do+ resources :contacts, controller: 'company_locations/contacts', only: [:index, :show, :create]+ end++ resources :company_contacts, only: [:show, :destroy]+# Price listsresources :price_lists docollection dodiff --git a/spree/api/lib/spree/api/dependencies.rb b/spree/api/lib/spree/api/dependencies.rbindex be1521c4b4..b08205108f 100644--- a/spree/api/lib/spree/api/dependencies.rb+++ b/spree/api/lib/spree/api/dependencies.rb@@ -140,6 +140,12 @@ module Spreeadmin_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',++ company_serializer: 'Spree::Api::V3::CompanySerializer',+ admin_company_serializer: 'Spree::Api::V3::Admin::CompanySerializer',+ admin_company_location_serializer: 'Spree::Api::V3::Admin::CompanyLocationSerializer',+ admin_company_contact_serializer: 'Spree::Api::V3::Admin::CompanyContactSerializer',+ admin_tax_exemption_certificate_serializer: 'Spree::Api::V3::Admin::TaxExemptionCertificateSerializer',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/companies/locations_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/companies/locations_controller_spec.rbnew file mode 100644index 0000000000..688059ed4e--- /dev/null+++ b/spree/api/spec/controllers/spree/api/v3/admin/companies/locations_controller_spec.rb@@ -0,0 +1,66 @@+require 'spec_helper'++RSpec.describe Spree::Api::V3::Admin::Companies::LocationsController, type: :controller do+ render_views++ include_context 'API v3 Admin authenticated'++ let!(:company) { create(:company, store: store) }++ before { request.headers.merge!(headers) }++ describe 'GET #index' do+ it 'lists the branches of the company' do+ create(:company_location, company: company, name: 'Berlin')++ get :index, params: { company_id: company.prefixed_id }, as: :json++ expect(response).to have_http_status(:ok)+ row = json_response['data'].first+ expect(row['id']).to start_with('cloc_')+ expect(row['name']).to eq('Berlin')+ expect(row['company_id']).to eq(company.prefixed_id)+ end++ it '404s under another store company' do+ get :index, params: { company_id: create(:company, store: create(:store)).prefixed_id }, as: :json++ expect(response).to have_http_status(:not_found)+ end+ end++ describe 'POST #create' do+ let(:germany) { create(:country, iso: 'DE', name: 'Germany') }++ it 'creates a branch' do+ post :create, params: { company_id: company.prefixed_id, name: 'Hamburg' }, as: :json++ expect(response).to have_http_status(:created)+ expect(json_response['name']).to eq('Hamburg')+ expect(company.company_locations.count).to eq(1)+ end++ # The branch owns its address rather than pointing at a shared row.+ it 'creates the addresses inline' do+ post :create, params: {+ company_id: company.prefixed_id,+ name: 'Munich',+ billing_address: {+ first_name: 'Anna', last_name: 'Muller', address1: 'Leopoldstr 1',+ city: 'Munich', postal_code: '80802', country_iso: germany.iso+ }+ }, as: :json++ expect(response).to have_http_status(:created)+ location = company.company_locations.sole+ expect(location.billing_address.city).to eq('Munich')+ expect(json_response['billing_address']['city']).to eq('Munich')+ end++ it 'rejects a branch with no name' do+ post :create, params: { company_id: company.prefixed_id }, as: :json++ expect(response).to have_http_status(:unprocessable_content)+ end+ end+enddiff --git a/spree/api/spec/controllers/spree/api/v3/admin/companies/tax_exemption_certificates_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/companies/tax_exemption_certificates_controller_spec.rbnew file mode 100644index 0000000000..b2c5c64b0b--- /dev/null+++ b/spree/api/spec/controllers/spree/api/v3/admin/companies/tax_exemption_certificates_controller_spec.rb@@ -0,0 +1,184 @@+require 'spec_helper'++RSpec.describe Spree::Api::V3::Admin::Companies::TaxExemptionCertificatesController, type: :controller do+ render_views++ include_context 'API v3 Admin authenticated'++ let!(:company) { create(:company, store: store) }+ let(:germany) { create(:country, iso: 'DE', name: 'Germany') }++ before { request.headers.merge!(headers) }++ def pdf_blob+ ActiveStorage::Blob.create_and_upload!(+ io: StringIO.new('%PDF-1.4 certificate'),+ filename: 'resale.pdf',+ content_type: 'application/pdf'+ )+ end++ describe 'GET #index' do+ it 'lists the company certificates with whether each counts' do+ create(:tax_exemption_certificate, :verified, company: company,+ certificate_number: 'DE-1', reason_code: 'resale',+ country: germany)++ get :index, params: { company_id: company.prefixed_id }, as: :json++ expect(response).to have_http_status(:ok)+ row = json_response['data'].first+ expect(row['id']).to start_with('cert_')+ expect(row['certificate_number']).to eq('DE-1')+ expect(row['status']).to eq('verified')+ expect(row['country_iso']).to eq('DE')+ expect(row['active']).to be(true)+ expect(row['can_be_deleted']).to be(false)+ end++ # The status alone cannot answer this — a verified certificate stops+ # counting once its date passes.+ it 'reports a lapsed certificate as inactive' do+ create(:tax_exemption_certificate, :expired, company: company)++ get :index, params: { company_id: company.prefixed_id }, as: :json++ row = json_response['data'].first+ expect(row['status']).to eq('verified')+ expect(row['lapsed']).to be(true)+ expect(row['active']).to be(false)+ end++ it '404s under another store company' do+ get :index, params: { company_id: create(:company, store: create(:store)).prefixed_id }, as: :json++ expect(response).to have_http_status(:not_found)+ end+ end++ describe 'POST #create' do+ it 'records a certificate awaiting verification' do+ post :create, params: {+ company_id: company.prefixed_id,+ certificate_number: 'DE-RESALE-7',+ reason_code: 'resale',+ country_iso: germany.iso+ }, as: :json++ expect(response).to have_http_status(:created)+ expect(json_response['status']).to eq('pending')+ expect(json_response['country_iso']).to eq('DE')+ expect(company.tax_exemption_certificates.sole.country).to eq(germany)+ end++ it 'attaches a document from a direct upload' do+ post :create, params: {+ company_id: company.prefixed_id,+ certificate_number: 'DE-1', reason_code: 'resale',+ document: pdf_blob.signed_id+ }, as: :json++ expect(response).to have_http_status(:created)+ expect(json_response['document_filename']).to eq('resale.pdf')+ expect(company.tax_exemption_certificates.sole.document).to be_attached+ end++ # Without the rescue this is a 500.+ it 'rejects a tampered signed id with a validation error' do+ post :create, params: {+ company_id: company.prefixed_id,+ certificate_number: 'DE-1', reason_code: 'resale',+ document: 'not-a-real-signed-id'+ }, as: :json++ expect(response).to have_http_status(:unprocessable_content)+ end++ it 'requires a certificate number and a reason' do+ post :create, params: { company_id: company.prefixed_id }, as: :json++ expect(response).to have_http_status(:unprocessable_content)+ end+ end++ describe 'PATCH #verify' do+ let!(:certificate) { create(:tax_exemption_certificate, company: company) }++ it 'accepts the certificate and records who did' do+ patch :verify, params: { company_id: company.prefixed_id, id: certificate.prefixed_id }, as: :json++ expect(response).to have_http_status(:ok)+ expect(json_response['status']).to eq('verified')+ expect(certificate.reload.verified_at).to be_present+ end++ it 'refuses one that is not awaiting a decision' do+ certificate.update!(status: 'revoked')++ patch :verify, params: { company_id: company.prefixed_id, id: certificate.prefixed_id }, as: :json++ expect(response).to have_http_status(:unprocessable_content)+ expect(certificate.reload).to be_revoked+ end++ it 'reports a handler veto as a validation failure' do+ Spree.hooks.register('tax_exemption_certificates.verify.validate') { |flow| flow.reject!('registry down') }++ patch :verify, params: { company_id: company.prefixed_id, id: certificate.prefixed_id }, as: :json++ expect(response).to have_http_status(:unprocessable_content)+ expect(certificate.reload).to be_pending+ Spree.hooks.clear!+ end+ end++ describe 'PATCH #revoke' do+ it 'withdraws a verified certificate' do+ certificate = create(:tax_exemption_certificate, :verified, company: company)++ patch :revoke, params: { company_id: company.prefixed_id, id: certificate.prefixed_id }, as: :json++ expect(response).to have_http_status(:ok)+ expect(certificate.reload).to be_revoked+ end+ end++ describe 'DELETE #destroy' do+ it 'removes one still awaiting a decision' do+ certificate = create(:tax_exemption_certificate, company: company)++ delete :destroy, params: { company_id: company.prefixed_id, id: certificate.prefixed_id }, as: :json++ expect(response).to have_http_status(:no_content)+ end++ it 'refuses a verified one — revoke instead' do+ certificate = create(:tax_exemption_certificate, :verified, company: company)++ delete :destroy, params: { company_id: company.prefixed_id, id: certificate.prefixed_id }, as: :json++ expect(response).to have_http_status(:unprocessable_content)+ expect(certificate.reload).to be_verified+ end+ end++ describe 'GET #download' do+ it 'streams the document rather than redirecting to storage' do+ certificate = create(:tax_exemption_certificate, company: company)+ certificate.document.attach(pdf_blob.signed_id)++ get :download, params: { company_id: company.prefixed_id, id: certificate.prefixed_id }++ expect(response).to have_http_status(:ok)+ expect(response.body).to include('certificate')+ end++ it 'reports a certificate with nothing attached' do+ certificate = create(:tax_exemption_certificate, company: company)++ get :download, params: { company_id: company.prefixed_id, id: certificate.prefixed_id }++ expect(response).to have_http_status(:unprocessable_content)+ end+ end+enddiff --git a/spree/api/spec/controllers/spree/api/v3/admin/companies_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/companies_controller_spec.rbnew file mode 100644index 0000000000..7508c47f87--- /dev/null+++ b/spree/api/spec/controllers/spree/api/v3/admin/companies_controller_spec.rb@@ -0,0 +1,100 @@+require 'spec_helper'++RSpec.describe Spree::Api::V3::Admin::CompaniesController, type: :controller do+ render_views++ include_context 'API v3 Admin authenticated'++ let!(:company) { create(:company, store: store, name: 'Acme Industrial', external_id: 'ACME-1') }++ before { request.headers.merge!(headers) }++ describe 'GET #index' do+ it 'lists the store companies' do+ get :index, as: :json++ expect(response).to have_http_status(:ok)+ row = json_response['data'].first+ expect(row['id']).to start_with('comp_')+ expect(row['name']).to eq('Acme Industrial')+ expect(row['external_id']).to eq('ACME-1')+ end++ it 'hides companies belonging to another store' do+ other = create(:company, store: create(:store))++ get :index, as: :json++ expect(json_response['data'].map { |row| row['id'] }).not_to include(other.prefixed_id)+ end++ it 'counts branches without a request per row' do+ create(:company_location, company: company)++ get :index, as: :json++ expect(json_response['data'].first['locations_count']).to eq(1)+ end+ end++ describe 'GET #show' do+ it 'expands branches on request' do+ location = create(:company_location, company: company, name: 'Berlin')++ get :show, params: { id: company.prefixed_id, expand: 'company_locations' }, as: :json++ expect(response).to have_http_status(:ok)+ expect(json_response['company_locations'].first['name']).to eq('Berlin')+ expect(json_response['company_locations'].first['id']).to eq(location.prefixed_id)+ end++ it '404s for another store company' do+ get :show, params: { id: create(:company, store: create(:store)).prefixed_id }, as: :json++ expect(response).to have_http_status(:not_found)+ end+ end++ describe 'POST #create' do+ it 'creates a company bound to the current store' do+ post :create, params: { name: 'Globex', external_id: 'GLBX' }, as: :json++ expect(response).to have_http_status(:created)+ expect(json_response['name']).to eq('Globex')+ expect(Spree::Company.find_by(name: 'Globex').store).to eq(store)+ end++ it 'rejects a duplicate reference with a validation error, not a crash' do+ post :create, params: { name: 'Acme Again', external_id: 'ACME-1' }, as: :json++ expect(response).to have_http_status(:unprocessable_content)+ end++ it 'rejects a company with no name' do+ post :create, params: { external_id: 'X' }, as: :json++ expect(response).to have_http_status(:unprocessable_content)+ end+ end++ describe 'PATCH #update' do+ it 'renames a company' do+ patch :update, params: { id: company.prefixed_id, name: 'Acme Global' }, as: :json++ expect(response).to have_http_status(:ok)+ expect(company.reload.name).to eq('Acme Global')+ end+ end++ describe 'DELETE #destroy' do+ it 'removes the company and its branches' do+ create(:company_location, company: company)++ delete :destroy, params: { id: company.prefixed_id }, as: :json++ expect(response).to have_http_status(:no_content)+ expect(Spree::Company.where(id: company.id)).to be_empty+ expect(Spree::CompanyLocation.count).to eq(0)+ end+ end+enddiff --git a/spree/api/spec/controllers/spree/api/v3/admin/company_locations/contacts_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/company_locations/contacts_controller_spec.rbnew file mode 100644index 0000000000..37e5ff2d97--- /dev/null+++ b/spree/api/spec/controllers/spree/api/v3/admin/company_locations/contacts_controller_spec.rb@@ -0,0 +1,58 @@+require 'spec_helper'++RSpec.describe Spree::Api::V3::Admin::CompanyLocations::ContactsController, type: :controller do+ render_views++ include_context 'API v3 Admin authenticated'++ let!(:company) { create(:company, store: store) }+ let!(:location) { create(:company_location, company: company) }+ let!(:customer) { create(:customer, email: '[email protected]') }++ before { request.headers.merge!(headers) }++ describe 'GET #index' do+ it 'lists who buys for the branch' do+ create(:company_contact, company_location: location, customer: customer)++ get :index, params: { company_location_id: location.prefixed_id }, as: :json++ expect(response).to have_http_status(:ok)+ row = json_response['data'].first+ expect(row['id']).to start_with('cc_')+ expect(row['email']).to eq('[email protected]')+ expect(row['role']).to eq('buyer')+ expect(row['customer_id']).to eq(customer.prefixed_id)+ end++ it '404s under a branch of another store company' do+ elsewhere = create(:company_location, company: create(:company, store: create(:store)))++ get :index, params: { company_location_id: elsewhere.prefixed_id }, as: :json++ expect(response).to have_http_status(:not_found)+ end+ end++ describe 'POST #create' do+ it 'authorises a customer to buy for the branch' do+ post :create, params: {+ company_location_id: location.prefixed_id,+ customer_id: customer.prefixed_id,+ role: 'admin'+ }, as: :json++ expect(response).to have_http_status(:created)+ expect(json_response['role']).to eq('admin')+ expect(location.customers).to eq([customer])+ end++ it 'refuses the same customer twice on one branch' do+ create(:company_contact, company_location: location, customer: customer)++ post :create, params: { company_location_id: location.prefixed_id, customer_id: customer.prefixed_id }, as: :json++ expect(response).to have_http_status(:unprocessable_content)+ end+ end+enddiff --git a/spree/api/spec/controllers/spree/api/v3/admin/company_locations_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/company_locations_controller_spec.rbnew file mode 100644index 0000000000..8040ae5e6b--- /dev/null+++ b/spree/api/spec/controllers/spree/api/v3/admin/company_locations_controller_spec.rb@@ -0,0 +1,64 @@+require 'spec_helper'++RSpec.describe Spree::Api::V3::Admin::CompanyLocationsController, type: :controller do+ render_views++ include_context 'API v3 Admin authenticated'++ let!(:company) { create(:company, store: store) }+ let!(:location) { create(:company_location, company: company, name: 'Berlin') }++ before { request.headers.merge!(headers) }++ describe 'GET #show' do+ it 'returns the branch' do+ get :show, params: { id: location.prefixed_id }, as: :json++ expect(response).to have_http_status(:ok)+ expect(json_response['name']).to eq('Berlin')+ end++ it '404s for a branch of another store company' do+ elsewhere = create(:company_location, company: create(:company, store: create(:store)))++ get :show, params: { id: elsewhere.prefixed_id }, as: :json++ expect(response).to have_http_status(:not_found)+ end+ end++ describe 'PATCH #update' do+ it 'renames the branch' do+ patch :update, params: { id: location.prefixed_id, name: 'Berlin Mitte' }, as: :json++ expect(response).to have_http_status(:ok)+ expect(location.reload.name).to eq('Berlin Mitte')+ end++ it 'replaces the billing address inline' do+ germany = create(:country, iso: 'DE', name: 'Germany')++ patch :update, params: {+ id: location.prefixed_id,+ billing_address: {+ first_name: 'Anna', last_name: 'Muller', address1: 'Neue Str 5',+ city: 'Berlin', postal_code: '10115', country_iso: germany.iso+ }+ }, as: :json++ expect(response).to have_http_status(:ok)+ expect(location.reload.billing_address.address1).to eq('Neue Str 5')+ end+ end++ describe 'DELETE #destroy' do+ it 'removes the branch and the address it owned' do+ location.update!(billing_address: create(:address))++ expect { delete :destroy, params: { id: location.prefixed_id }, as: :json }.+ to change(Spree::Address, :count).by(-1)++ expect(response).to have_http_status(:no_content)+ end+ end+enddiff --git a/spree/core/app/models/spree/company_location.rb b/spree/core/app/models/spree/company_location.rbindex 15d1b78087..5d977498a4 100644--- a/spree/core/app/models/spree/company_location.rb+++ b/spree/core/app/models/spree/company_location.rb@@ -19,6 +19,14 @@ module Spreeaccepts_nested_attributes_for :billing_addressaccepts_nested_attributes_for :shipping_address+ # The API reads and writes these under the same name, so the writer takes+ # either a record or the nested hash a client sends.+ %i[billing_address shipping_address].each do |name|+ define_method(:"#{name}=") do |value|+ value.is_a?(Hash) || value.is_a?(ActionController::Parameters) ? send(:"#{name}_attributes=", value) : super(value)+ end+ end+has_many :company_contacts, class_name: 'Spree::CompanyContact', dependent: :destroy,inverse_of: :company_locationhas_many :customers, through: :company_contacts, source: :customerdiff --git a/spree/core/app/models/spree/permission_sets/user_display.rb b/spree/core/app/models/spree/permission_sets/user_display.rbindex dc376642b5..82c407c82f 100644--- a/spree/core/app/models/spree/permission_sets/user_display.rb+++ b/spree/core/app/models/spree/permission_sets/user_display.rb@@ -13,6 +13,10 @@ module Spreecan [:read, :admin, :index], Spree.customer_classcan [:read, :admin], Spree::Addresscan [:read, :admin], Spree::CreditCard+ can [:read, :admin], Spree::Company+ can [:read, :admin], Spree::CompanyLocation+ can [:read, :admin], Spree::CompanyContact+ can [:read, :admin], Spree::TaxExemptionCertificateendendenddiff --git a/spree/core/app/models/spree/permission_sets/user_management.rb b/spree/core/app/models/spree/permission_sets/user_management.rbindex b96f600417..de1817f41c 100644--- a/spree/core/app/models/spree/permission_sets/user_management.rb+++ b/spree/core/app/models/spree/permission_sets/user_management.rb@@ -13,6 +13,10 @@ module Spreecan :manage, Spree.customer_classcan :manage, Spree::Addresscan :manage, Spree::CreditCard+ can :manage, Spree::Company+ can :manage, Spree::CompanyLocation+ can :manage, Spree::CompanyContact+ can :manage, Spree::TaxExemptionCertificatecan [:read, :admin], Spree::Metafieldendenddiff --git a/spree/core/app/models/spree/tax_exemption_certificate.rb b/spree/core/app/models/spree/tax_exemption_certificate.rbindex bcddf1f999..c318d5aca0 100644--- a/spree/core/app/models/spree/tax_exemption_certificate.rb+++ b/spree/core/app/models/spree/tax_exemption_certificate.rb@@ -31,6 +31,9 @@ module Spreevalidates :certificate_number, :reason_code, presence: true+ before_validation :resolve_state_code+ validate :state_belongs_to_country+# Expiry is decided here rather than persisted: the date is the fact, and a# sweeper writing 'expired' would only restate it. Matches how gift cards# and stock reservations treat their own deadlines.@@ -43,6 +46,18 @@ module Spreedelegate :store, :store_id, to: :company+ # The jurisdiction is written in the same vocabulary it is read in, mirroring+ # Spree::TaxRate. State abbreviations repeat across countries, so the state+ # is resolved in a callback once the country is known — a JSON body may name+ # the state first.+ def country_iso=(value)+ self.country = value.present? ? Spree::Country.by_iso(value) : nil+ end++ def state_code=(value)+ @state_code_input = value+ end+# Accepting a certificate is a decision on record; withdrawing it is# revocation, not deletion.def can_be_deleted?@@ -53,5 +68,22 @@ module Spreedef lapsed?expires_at.present? && expires_at <= Time.currentend++ private++ def resolve_state_code+ return unless defined?(@state_code_input)++ self.state = @state_code_input.blank? ? nil : Spree::State.where(country_id: country_id).find_by(abbr: @state_code_input)+ remove_instance_variable(:@state_code_input)+ end++ # A certificate whose state sits in another country would never match an+ # address — the two columns have to agree.+ def state_belongs_to_country+ return if state.nil? || country.nil? || state.country_id == country_id++ errors.add(:state, :invalid)+ endendend