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
Fix defects found reviewing the company and certificate work
Łukasz Adamczyk2981c11ee2c4
diff --git a/packages/sdk/src/types/generated/Company.ts b/packages/sdk/src/types/generated/Company.tsdeleted file mode 100644index 4d672d5da5..0000000000--- a/packages/sdk/src/types/generated/Company.ts+++ /dev/null@@ -1,11 +0,0 @@-// Typelizer digest 988862bf42811a399a2e37bb7f1a82da-//-// DO NOT MODIFY: This file was automatically generated by Typelizer.--interface Company {- id: string;- name: string;- external_id: string | null;-}--export default Company;diff --git a/packages/sdk/src/types/generated/index.ts b/packages/sdk/src/types/generated/index.tsindex 8fa0c9517c..59e8582fb7 100644--- a/packages/sdk/src/types/generated/index.ts+++ b/packages/sdk/src/types/generated/index.ts@@ -1,4 +1,4 @@-// Typelizer digest 246bdc538eebd383fd43515435f9040b+// Typelizer digest 633530336b8aac863cf9cdd6fd46b204//// DO NOT MODIFY: This file was automatically generated by Typelizer.export type { default as Address } from './Address'@@ -10,7 +10,6 @@ export type { default as Channel } from './Channel'export type { default as ClaimLineItem } from './ClaimLineItem'export type { default as Claim } from './Claim'export type { default as Collection } from './Collection'-export type { default as Company } from './Company'export type { default as Country } from './Country'export type { default as CreditCard } from './CreditCard'export type { default as Currency } from './Currency'diff --git a/packages/sdk/src/zod/generated/Company.ts b/packages/sdk/src/zod/generated/Company.tsdeleted file mode 100644index b0a4aae171..0000000000--- a/packages/sdk/src/zod/generated/Company.ts+++ /dev/null@@ -1,10 +0,0 @@-// This file is auto-generated. Do not edit directly.-import { z } from 'zod';--export const CompanySchema = z.object({- id: z.string(),- name: z.string(),- external_id: z.string().nullable(),-});--export type Company = z.infer<typeof CompanySchema>;diff --git a/packages/sdk/src/zod/generated/index.ts b/packages/sdk/src/zod/generated/index.tsindex 94f67ddbf8..b0df2177c6 100644--- a/packages/sdk/src/zod/generated/index.ts+++ b/packages/sdk/src/zod/generated/index.ts@@ -8,7 +8,6 @@ export { ChannelSchema, type Channel } from './Channel';export { ClaimSchema, type Claim } from './Claim';export { ClaimLineItemSchema, type ClaimLineItem } from './ClaimLineItem';export { CollectionSchema, type Collection } from './Collection';-export { CompanySchema, type Company } from './Company';export { CountrySchema, type Country } from './Country';export { CreditCardSchema, type CreditCard } from './CreditCard';export { CurrencySchema, type Currency } from './Currency';diff --git a/spree/api/app/controllers/spree/api/v3/admin/companies/tax_exemption_certificates_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/companies/tax_exemption_certificates_controller.rbindex 71ab7e9f7a..7ad0366d64 100644--- 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.rb@@ -19,8 +19,6 @@ module Spree# PATCH /api/v3/admin/companies/:company_id/tax_exemption_certificates/:id/verifydef verify- authorize_resource!(@resource, :update)-result = Spree.tax_exemption_certificate_verify_workflow.call(certificate: @resource,verified_by: try_spree_current_user@@ -35,8 +33,6 @@ module Spree# 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@@ -47,7 +43,6 @@ module Spree# 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(@@ -67,6 +62,20 @@ module Spreeprotected+ # Fetching the document is a read of the certificate, so it takes the+ # read scope and the :show ability rather than being classed as a+ # write because it isn't index or show. Without this a key holding+ # read_customers is refused its own certificate.+ READ_ACTIONS = %w[index show download].freeze++ def read_actions+ READ_ACTIONS+ end++ def action_kind+ READ_ACTIONS.include?(action_name) ? 'read' : 'write'+ end+def model_classSpree::TaxExemptionCertificateend@@ -99,6 +108,18 @@ module Spreesuper.tap { |certificate| certificate.status ||= 'pending' }end+ # The custom actions are not permissions of their own: accepting or+ # withdrawing is updating, fetching the document is reading.+ def authorize_resource!(resource = @resource, action = action_name.to_sym)+ mapped = case action+ when :verify, :revoke then :update+ when :download then :show+ else action+ end++ authorize!(mapped, resource)+ end+privatedef render_invalid_signaturediff --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.rbindex 7ec9006589..2a1f0baae8 100644--- 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.rb@@ -20,7 +20,7 @@ module Spreedef scopeSpree::CompanyContact.where(company_location_id: Spree::CompanyLocation.where(company_id: current_store.companies.select(:id)).select(:id)- )+ ).accessible_by(current_ability, ability_action_for_request)endendenddiff --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.rbindex 40a7469f23..960a4e8f50 100644--- 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.rb@@ -7,6 +7,11 @@ module Spreeclass ContactsController < ResourceControllerscoped_resource :customers+ # Overriding `scope` bypasses the base class's `accessible_by`, so+ # without this a role with no customer permission could still list+ # who buys for a branch — and contacts carry customer emails.+ before_action :authorize_parent_access!+protecteddef model_class@@ -17,12 +22,20 @@ module SpreeSpree.api.admin_company_contact_serializerend+ # Filtered by ability as well as by store: a branch the caller may+ # not act on is not found rather than refused, so its existence+ # doesn't leak.def set_parent@parent = Spree::CompanyLocation.where(company_id: current_store.companies.select(:id)).+ accessible_by(current_ability, parent_ability_action).find_by_prefix_id!(params[:company_location_id])end+ def authorize_parent_access!+ authorize_parent!(@parent)+ end+def scope@parent.company_contactsenddiff --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.rbindex 0433840314..239d42d769 100644--- 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.rb@@ -20,7 +20,8 @@ module Spreeenddef scope- Spree::CompanyLocation.where(company_id: current_store.companies.select(:id))+ Spree::CompanyLocation.where(company_id: current_store.companies.select(:id)).+ accessible_by(current_ability, ability_action_for_request)enddef collection_includesdiff --git a/spree/api/config/initializers/typelizer.rb b/spree/api/config/initializers/typelizer.rbindex 1c66bff04f..09741591df 100644--- a/spree/api/config/initializers/typelizer.rb+++ b/spree/api/config/initializers/typelizer.rb@@ -26,6 +26,7 @@ Rails.application.config.after_initialize doStockItem StockMovement StockTransfer ShippingCategoryReport Export Import ImportRowTaxCategory Exchange ExchangeLineItem+ Company].to_set# Store SDK — no prefix, package provides namespacediff --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.rbindex b2c5c64b0b..3da14f26db 100644--- 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.rb@@ -9,6 +9,7 @@ RSpec.describe Spree::Api::V3::Admin::Companies::TaxExemptionCertificatesControllet(:germany) { create(:country, iso: 'DE', name: 'Germany') }before { request.headers.merge!(headers) }+ after { Spree.hooks.clear! }def pdf_blobActiveStorage::Blob.create_and_upload!(@@ -128,7 +129,6 @@ RSpec.describe Spree::Api::V3::Admin::Companies::TaxExemptionCertificatesControlexpect(response).to have_http_status(:unprocessable_content)expect(certificate.reload).to be_pending- Spree.hooks.clear!endenddiff --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.rbindex 37e5ff2d97..cc914dfaf7 100644--- 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.rb@@ -34,6 +34,30 @@ RSpec.describe Spree::Api::V3::Admin::CompanyLocations::ContactsController, typeendend+ # Overriding `scope` bypasses the base class's ability filter, so this has to+ # be asserted rather than assumed: contacts carry customer emails.+ describe 'a role without customer permission' do+ include_context 'API v3 Admin with custom permissions'++ let(:custom_permission_set) do+ Class.new(Spree::PermissionSets::Base) do+ def activate!+ can :manage, Spree::Product+ end+ end+ end++ it 'cannot list who buys for a branch' do+ create(:company_contact, company_location: location, customer: customer)++ get :index, params: { company_location_id: location.prefixed_id }, as: :json++ # Not found rather than forbidden, so the branch's existence doesn't leak.+ expect(response).to have_http_status(:not_found)+ expect(response.body).not_to include('[email protected]')+ end+ end+describe 'POST #create' doit 'authorises a customer to buy for the branch' dopost :create, params: {diff --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.rbindex 8040ae5e6b..c633805f9e 100644--- 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.rb@@ -35,7 +35,29 @@ RSpec.describe Spree::Api::V3::Admin::CompanyLocationsController, type: :controlexpect(location.reload.name).to eq('Berlin Mitte')end- it 'replaces the billing address inline' do+ context 'with an address already on file' do+ let!(:existing) { create(:address, address1: 'Alte Str 1', city: 'Berlin') }++ before { location.update!(billing_address: existing) }++ # Rebuilding would leave the old row behind and make one-field edits+ # impossible, since the replacement starts blank.+ it 'edits the address in place rather than replacing it' do+ expect {+ patch :update, params: {+ id: location.prefixed_id,+ billing_address: { address1: 'Neue Str 5' }+ }, as: :json+ }.not_to change(Spree::Address, :count)++ expect(response).to have_http_status(:ok)+ expect(location.reload.billing_address_id).to eq(existing.id)+ expect(existing.reload.address1).to eq('Neue Str 5')+ expect(existing.city).to eq('Berlin')+ end+ end++ it 'sets an address on a branch that had none' dogermany = create(:country, iso: 'DE', name: 'Germany')patch :update, params: {diff --git a/spree/core/app/models/concerns/spree/purchase/company.rb b/spree/core/app/models/concerns/spree/purchase/company.rbindex 9ff0d706b2..690bf9311a 100644--- a/spree/core/app/models/concerns/spree/purchase/company.rb+++ b/spree/core/app/models/concerns/spree/purchase/company.rb@@ -36,6 +36,10 @@ module Spree## @return [Spree::CompanyLocation, nil]def resolved_company_location+ # A placed order answers from what it was stamped with, never by+ # resolving again — otherwise adding a buyer to a company months later+ # would reach back and exempt an order that legitimately charged tax.+ return company_location if is_a?(Spree::Order) && completed?return company_location if company_location_id.present?sole_customer_location@@ -43,6 +47,11 @@ module Spreeprivate+ # Deliberately not memoized. An instance variable survives #reload, so a+ # value cached before a contact was added stays stale for the life of the+ # object — which silently dropped the branch at completion. Caching this+ # safely needs the reset-on-reload machinery; the repeated query is the+ # cheaper problem.def sole_customer_locationreturn nil if customer.nil?diff --git a/spree/core/app/models/spree/company_contact.rb b/spree/core/app/models/spree/company_contact.rbindex 144aeec9f5..e7f902b2c8 100644--- a/spree/core/app/models/spree/company_contact.rb+++ b/spree/core/app/models/spree/company_contact.rb@@ -12,7 +12,7 @@ module Spreehas_one :company, through: :company_location- validates :customer_id, uniqueness: { scope: :company_location_id }+ validates :customer_id, uniqueness: { scope: [:company_location_id, *spree_base_uniqueness_scope] }delegate :store, :store_id, to: :company_locationdiff --git a/spree/core/app/models/spree/company_location.rb b/spree/core/app/models/spree/company_location.rbindex 5d977498a4..4d492e0bfc 100644--- a/spree/core/app/models/spree/company_location.rb+++ b/spree/core/app/models/spree/company_location.rb@@ -16,8 +16,10 @@ module Spreebelongs_to :billing_address, class_name: 'Spree::Address', optional: true, dependent: :destroybelongs_to :shipping_address, class_name: 'Spree::Address', optional: true, dependent: :destroy- accepts_nested_attributes_for :billing_address- accepts_nested_attributes_for :shipping_address+ # update_only, so editing one field of an existing address changes that+ # row instead of building a replacement and orphaning the old one.+ accepts_nested_attributes_for :billing_address, update_only: true+ accepts_nested_attributes_for :shipping_address, update_only: true# The API reads and writes these under the same name, so the writer takes# either a record or the nested hash a client sends.diff --git a/spree/core/app/models/spree/tax_exemption_certificate.rb b/spree/core/app/models/spree/tax_exemption_certificate.rbindex c318d5aca0..516a6bb737 100644--- a/spree/core/app/models/spree/tax_exemption_certificate.rb+++ b/spree/core/app/models/spree/tax_exemption_certificate.rb@@ -38,8 +38,14 @@ module Spree# sweeper writing 'expired' would only restate it. Matches how gift cards# and stock reservations treat their own deadlines.scope :active, -> { verified.where('expires_at IS NULL OR expires_at > ?', Time.current) }+ scope :expired, -> { where(status: 'expired').or(where('expires_at <= ?', Time.current)) }+ # No address means no jurisdiction to match, which is not the same as+ # "matches the certificates valid everywhere" — a swapped-in resolver+ # calling this without a destination must not be handed a claim.scope :for_address, lambda { |address|- where(country: [address&.country, nil].uniq).where(state: [address&.state, nil].uniq)+ next none if address.nil?++ where(country: [address.country, nil].uniq).where(state: [address.state, nil].uniq)}self.whitelisted_ransackable_attributes = %w[certificate_number reason_code status expires_at]@@ -69,6 +75,14 @@ module Spreeexpires_at.present? && expires_at <= Time.currentend+ # Nothing writes the 'expired' status — the date is the fact — so the+ # predicate and scope HasStatus generated would answer false and empty+ # forever. Both derive instead, the way Spree::GiftCard does, so a caller+ # reaching for the obvious name gets the truth.+ def expired?+ status == 'expired' || lapsed?+ end+privatedef resolve_state_codediff --git a/spree/core/app/workflows/spree/tax_exemption_certificates/verify.rb b/spree/core/app/workflows/spree/tax_exemption_certificates/verify.rbindex fbafd50cb3..456adec956 100644--- a/spree/core/app/workflows/spree/tax_exemption_certificates/verify.rb+++ b/spree/core/app/workflows/spree/tax_exemption_certificates/verify.rb@@ -40,7 +40,7 @@ module Spreecertificate.update!(status: 'verified',verified_at: Time.current,- verified_by: certificate.verified_by || verified_by+ verified_by: verified_by || certificate.verified_by)endenddiff --git a/spree/core/spec/models/concerns/spree/purchase/company_spec.rb b/spree/core/spec/models/concerns/spree/purchase/company_spec.rbindex 8114a25acb..cc45e8c01c 100644--- a/spree/core/spec/models/concerns/spree/purchase/company_spec.rb+++ b/spree/core/spec/models/concerns/spree/purchase/company_spec.rb@@ -64,6 +64,41 @@ endRSpec.describe Spree::Purchase::Company dolet(:customer) { create(:customer) }+ # A placed order's tax has to stay explainable, so it answers from what it was+ # stamped with — otherwise adding this buyer to a company later would reach+ # back and exempt a sale that legitimately charged tax.+ describe 'a completed order' do+ let(:store) { @default_store }+ let(:order) { create(:completed_order_with_totals, store: store, customer: customer) }++ it 'does not acquire a company it was never placed for' do+ expect(order.b2b?).to be(false)++ location = create(:company_location, company: create(:company, store: store))+ create(:company_contact, company_location: location, customer: customer)++ expect(Spree::Order.find(order.id).b2b?).to be(false)+ expect(Spree::Order.find(order.id).company).to be_nil+ end++ it 'keeps the branch it was stamped with' do+ location = create(:company_location, company: create(:company, store: store))+ order.update_columns(company_location_id: location.id)++ expect(Spree::Order.find(order.id).resolved_company_location).to eq(location)+ end++ it 'does not lose it when the buyer later joins a second branch' do+ company = create(:company, store: store)+ location = create(:company_location, company: company)+ order.update_columns(company_location_id: location.id)+ create(:company_contact, company_location: location, customer: customer)+ create(:company_contact, company_location: create(:company_location, company: company), customer: customer)++ expect(Spree::Order.find(order.id).company).to eq(company)+ end+ end+context 'included in Spree::Cart' dolet(:record) { create(:cart, store: @default_store, customer: customer) }