Skip to content

armgit / spree

Public Imported from GitHub
0

Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.

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.ts
deleted file mode 100644
index 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.ts
index 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.ts
deleted file mode 100644
index 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.ts
index 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.rb
index 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/verify
def 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 Spree
protected
+ # 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_class
Spree::TaxExemptionCertificate
end
@@ -99,6 +108,18 @@ module Spree
super.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
+
private
def render_invalid_signature
diff --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.rb
index 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 Spree
def scope
Spree::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)
end
end
end
diff --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.rb
index 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 Spree
class ContactsController < ResourceController
scoped_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!
+
protected
def model_class
@@ -17,12 +22,20 @@ module Spree
Spree.api.admin_company_contact_serializer
end
+ # 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_contacts
end
diff --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.rb
index 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 Spree
end
def 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)
end
def collection_includes
diff --git a/spree/api/config/initializers/typelizer.rb b/spree/api/config/initializers/typelizer.rb
index 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 do
StockItem StockMovement StockTransfer ShippingCategory
Report Export Import ImportRow
TaxCategory Exchange ExchangeLineItem
+ Company
].to_set
# Store SDK — no prefix, package provides namespace
diff --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.rb
index 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::TaxExemptionCertificatesControl
let(:germany) { create(:country, iso: 'DE', name: 'Germany') }
before { request.headers.merge!(headers) }
+ after { Spree.hooks.clear! }
def pdf_blob
ActiveStorage::Blob.create_and_upload!(
@@ -128,7 +129,6 @@ RSpec.describe Spree::Api::V3::Admin::Companies::TaxExemptionCertificatesControl
expect(response).to have_http_status(:unprocessable_content)
expect(certificate.reload).to be_pending
- Spree.hooks.clear!
end
end
diff --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.rb
index 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, type
end
end
+ # 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' do
it 'authorises a customer to buy for the branch' do
post :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.rb
index 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: :control
expect(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' do
germany = 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.rb
index 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 Spree
private
+ # 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_location
return nil if customer.nil?
diff --git a/spree/core/app/models/spree/company_contact.rb b/spree/core/app/models/spree/company_contact.rb
index 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 Spree
has_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_location
diff --git a/spree/core/app/models/spree/company_location.rb b/spree/core/app/models/spree/company_location.rb
index 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 Spree
belongs_to :billing_address, class_name: 'Spree::Address', optional: true, dependent: :destroy
belongs_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.rb
index 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 Spree
expires_at.present? && expires_at <= Time.current
end
+ # 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
+
private
def resolve_state_code
diff --git a/spree/core/app/workflows/spree/tax_exemption_certificates/verify.rb b/spree/core/app/workflows/spree/tax_exemption_certificates/verify.rb
index 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 Spree
certificate.update!(
status: 'verified',
verified_at: Time.current,
- verified_by: certificate.verified_by || verified_by
+ verified_by: verified_by || certificate.verified_by
)
end
end
diff --git a/spree/core/spec/models/concerns/spree/purchase/company_spec.rb b/spree/core/spec/models/concerns/spree/purchase/company_spec.rb
index 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 @@ end
RSpec.describe Spree::Purchase::Company do
let(: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' do
let(:record) { create(:cart, store: @default_store, customer: customer) }