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
Replace the flat company prototype with a multi-level organization tree
Damian Legawiecf0debe31b7ad
diff --git a/spree/core/app/models/concerns/spree/customer_methods.rb b/spree/core/app/models/concerns/spree/customer_methods.rbindex 5733365625..3289c798c6 100644--- a/spree/core/app/models/concerns/spree/customer_methods.rb+++ b/spree/core/app/models/concerns/spree/customer_methods.rb@@ -71,9 +71,9 @@ module Spree# One per registration kind — a business can hold both an EU and a UK VAT number.has_many :tax_identifiers, class_name: 'Spree::TaxIdentifier', as: :owner,dependent: :destroy, inverse_of: :owner- has_many :company_contacts, class_name: 'Spree::CompanyContact', foreign_key: :customer_id,- dependent: :destroy, inverse_of: :customer- has_many :company_locations, through: :company_contacts+ has_many :company_memberships, class_name: 'Spree::CompanyMembership', foreign_key: :customer_id,+ dependent: :destroy, inverse_of: :customer+ has_many :companies, through: :company_memberships, class_name: 'Spree::Company'belongs_to :ship_address, class_name: 'Spree::Address', optional: truebelongs_to :bill_address, class_name: 'Spree::Address', optional: true@@ -100,6 +100,29 @@ module Spree#attr_accessor :confirm_email, :terms_of_service+ # The company nodes this customer may act for within a store — their+ # memberships on that store's trees, expanded by subtree. Customers are+ # global while companies are store-scoped, so standing is always+ # evaluated per store.+ #+ # @param store [Spree::Store]+ # @return [ActiveRecord::Relation<Spree::Company>]+ def company_standing(store:)+ Spree::Company.subtree_of(companies.where(store_id: store.id))+ end++ # Whether this customer may act for the given node: a membership on the+ # node or any of its ancestors. Always a subtree check, never an+ # equality check on one node.+ #+ # @param company [Spree::Company]+ # @return [Boolean]+ def standing_for?(company)+ return false if company.nil?++ company_memberships.where(company_id: company.self_and_ancestors.map(&:id)).exists?+ end+def self.find_by_password_reset_token(token)find_by_token_for(:password_reset, token)enddiff --git a/spree/core/app/models/concerns/spree/purchase/company.rb b/spree/core/app/models/concerns/spree/purchase/company.rbindex 2d368fce4e..943afafd59 100644--- a/spree/core/app/models/concerns/spree/purchase/company.rb+++ b/spree/core/app/models/concerns/spree/purchase/company.rb@@ -1,91 +1,100 @@module Spreemodule Purchase- # Which business customer a sale is for, shared by Spree::Cart and- # Spree::Order. The branch is what the sale references; the company is- # derived from it, so a per-branch address or registration has somewhere to- # live later without moving this column.+ # Which company node a sale is for, shared by Spree::Cart and+ # Spree::Order. The purchase points at any node in the tree — buying *for*+ # a division is pointing at it — and tax reads through the node's legal+ # entity, never the node itself+ # (docs/plans/6.0-b2b-companies-and-catalogs.md).module Companyextend ActiveSupport::Concernincluded do- belongs_to :company_location, class_name: 'Spree::CompanyLocation', optional: true+ belongs_to :company, class_name: 'Spree::Company', optional: true# Guarded on the model rather than in the controller so every path is- # covered — the admin write, a future storefront one, and the console.- # Companies are store-scoped, so a branch from another store would tax+ # covered — the admin write, the storefront one, and the console.+ # Companies are store-scoped, so a node from another store would tax# this sale against a business the merchant does not trade as.- validate :company_location_belongs_to_store- end-- # @return [Spree::Company, nil]- def company- resolved_company_location&.company+ validate :company_belongs_to_store, if: :company_id_changing?+ # The storefront's write path is the cart; an order's company arrives+ # from completion (already validated on the cart) or from staff, whose+ # authority is the admin credential rather than a membership.+ validate :customer_has_standing_over_company,+ if: -> { is_a?(Spree::Cart) && company_id_changing? && customer_id.present? }end# @return [Boolean] whether this sale is for a business customerdef b2b?- resolved_company_location.present?+ resolved_company.present?end- # The branch this sale is for. An explicit choice wins; otherwise a buyer- # who acts for exactly one branch is unambiguous and resolves to it.+ # The node this sale is for. An explicit choice wins; otherwise a buyer+ # whose standing in this store resolves to exactly one membership is+ # unambiguous and resolves to that membership's node.#- # A buyer who acts for several resolves to nothing, so no company applies- # and no exemption is claimed — refusing to guess, because guessing would+ # A buyer with several memberships resolves to nothing until the cart+ # says which node it is for — refusing to guess, because guessing would# invoice one business for another's purchase.#- # **Provisional — revisit when channels and catalogs are implemented.**- # That work (docs/plans/6.1-channels-catalogs-b2b.md — filed as 6.1 today,- # expected to land in 6.0) has the identical question and no answer either:- # its `Products::ForContext` calls `user_company_location(user, store)`,- # singular, which the plan never defines. Catalog, negotiated pricing and- # tax all need the same answer, so it must be settled once and read from- # one place — otherwise a buyer could browse one company's catalog at its- # prices while being taxed as another.- #- # Until then, staff can set the branch explicitly through the admin order- # API. A buyer acting for several businesses who checks out unaided gets no- # company and no exemption, which is why this must not stay as it is.- #- # @return [Spree::CompanyLocation, nil]- def resolved_company_location+ # @return [Spree::Company, nil]+ def resolved_company# 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?+ return company if is_a?(Spree::Order) && completed?+ return company if company_id.present?- sole_customer_location+ sole_standing_company+ end++ # The tax anchor for this sale: the resolved node's nearest+ # self-or-ancestor legal entity. Registrations and exemption+ # certificates are always read through it — a division holds none, and+ # reading the node's own would silently lose the exemption.+ #+ # @return [Spree::Company, nil]+ def company_legal_entity+ resolved_company&.legal_entityendprivate- def company_location_belongs_to_store- return if company_location.nil? || store_id.nil?- return if company_location.store_id == store_id+ def company_id_changing?+ new_record? ? company_id.present? : will_save_change_to_company_id?+ end++ def company_belongs_to_store+ return if company.nil? || store_id.nil?+ return if company.store_id == store_id++ errors.add(:company, :invalid)+ end++ def customer_has_standing_over_company+ return if company.nil?+ return if customer.standing_for?(company)- errors.add(:company_location, :invalid)+ errors.add(:company, :invalid)end# 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+ # value cached before a membership was added stays stale for the life of+ # the object — which silently dropped the company at completion. Caching+ # this safely needs the reset-on-reload machinery; the repeated query is+ # the cheaper problem.+ def sole_standing_companyreturn nil if customer.nil? || store_id.nil?# Scoped to this sale's store. Customers are global, so without this a- # buyer who is a contact at a company in another store would resolve to+ # buyer who is a member at a company in another store would resolve to# that business here — and its registration and exemption certificates- # would then decide this sale's tax. The explicit-assignment path is- # guarded by the validation above; this is the implicit one.- locations = customer.company_locations.- joins(:company).- merge(Spree::Company.where(store_id: store_id)).- to_a.uniq+ # would then decide this sale's tax.+ memberships = customer.company_memberships.+ joins(:company).+ merge(Spree::Company.where(store_id: store_id)).+ to_a.uniq- locations.one? ? locations.first : nil+ memberships.one? ? memberships.first.company : nilendendenddiff --git a/spree/core/app/models/concerns/spree/purchase/taxation.rb b/spree/core/app/models/concerns/spree/purchase/taxation.rbindex 7228473b74..686b72284e 100644--- a/spree/core/app/models/concerns/spree/purchase/taxation.rb+++ b/spree/core/app/models/concerns/spree/purchase/taxation.rb@@ -127,8 +127,10 @@ module Spreeendend+ # Read through the legal entity, never the node — a division holds no+ # registrations of its own.def company_tax_identifier- best_of(company&.tax_identifiers)+ best_of(company_legal_entity&.tax_identifiers)enddef customer_tax_identifierdiff --git a/spree/core/app/models/spree/company.rb b/spree/core/app/models/spree/company.rbindex 30001b6fa2..38f9dc2bed 100644--- a/spree/core/app/models/spree/company.rb+++ b/spree/core/app/models/spree/company.rb@@ -1,12 +1,18 @@module Spree- # A business customer — the entity an invoice is addressed to, as distinct- # from the person who placed the order. Carries the tax registration and the- # exemption certificates that decide how its purchases are taxed.+ # A node in a business customer's organization tree — the entity an invoice+ # is addressed to, or one of its organizational units.#- # Deliberately minimal: this is the part of the B2B model that tax needs- # (docs/plans/6.0-tax-provider.md Phase 7). Assortment, negotiated pricing- # and buyer roles belong to docs/plans/6.1-channels-catalogs-b2b.md, which- # extends these models rather than redefining them.+ # The tree is self-referential and shallow (depth capped at MAX_DEPTH).+ # Nodes are typed: a +company+ is a legal entity that may hold tax+ # registrations and exemption certificates; a +division+ is an+ # organizational unit that borrows its tax identity from the nearest+ # self-or-ancestor +company+ node (see {#legal_entity}). Roots must be legal+ # entities — a division with no legal-entity ancestor would have no tax+ # identity.+ #+ # Governance (roles, spend limits, approvals) deliberately lives elsewhere:+ # OSS ships the directory and injection points only+ # (docs/plans/6.0-b2b-companies-and-catalogs.md).class Company < Spree.base_classhas_prefix_id :comp@@ -17,23 +23,212 @@ module Spreepublishes_lifecycle_events+ KINDS = %w[company division].freeze+ MAX_DEPTH = 5++ attribute :kind, :string, default: 'company'+belongs_to :store, class_name: 'Spree::Store', inverse_of: :companies+ belongs_to :parent, class_name: 'Spree::Company', optional: true, inverse_of: :children+ has_many :children, class_name: 'Spree::Company', foreign_key: :parent_id,+ inverse_of: :parent, dependent: :destroy- has_many :company_locations, class_name: 'Spree::CompanyLocation', dependent: :destroy,+ has_many :company_addresses, class_name: 'Spree::CompanyAddress', dependent: :destroy,inverse_of: :company- has_many :company_contacts, through: :company_locations+ has_many :addresses, through: :company_addresses, class_name: 'Spree::Address'+ has_many :memberships, class_name: 'Spree::CompanyMembership', dependent: :destroy,+ inverse_of: :company+ has_many :customers, through: :memberships, class_name: Spree.customer_class.to_s+ has_many :invitations, class_name: 'Spree::CompanyInvitation', dependent: :destroy,+ inverse_of: :company++ has_many :catalog_assignments, as: :assignable, class_name: 'Spree::CatalogAssignment',+ dependent: :destroy+ has_many :catalogs, through: :catalog_assignments, class_name: 'Spree::Catalog'+has_many :tax_identifiers, class_name: 'Spree::TaxIdentifier', as: :owner,dependent: :destroy, inverse_of: :ownerhas_many :tax_exemption_certificates, class_name: 'Spree::TaxExemptionCertificate',dependent: :destroy, inverse_of: :companyvalidates :name, presence: true+ validates :kind, inclusion: { in: KINDS }+ validate :parent_in_same_store+ validate :root_must_be_legal_entity+ validate :no_ancestry_cycle+ validate :depth_within_cap+ validate :kind_change_keeps_tax_anchor++ scope :roots, -> { where(parent_id: nil) }++ # The subtree rooted at the given node(s) — the node itself plus every+ # descendant. A recursive CTE, bounded in practice by MAX_DEPTH, that works+ # on PostgreSQL, MySQL 8 and SQLite.+ #+ # @param nodes [Spree::Company, Integer, Array, ActiveRecord::Relation]+ # @return [ActiveRecord::Relation]+ scope :subtree_of, lambda { |nodes|+ ids = case nodes+ when ActiveRecord::Relation then nodes.ids+ else Array(nodes).map { |node| node.respond_to?(:id) ? node.id : node }+ end+ next none if ids.empty?++ subtree_sql = sanitize_sql_array([<<~SQL.squish, ids])+ WITH RECURSIVE subtree(id) AS (+ SELECT id FROM #{table_name} WHERE id IN (?)+ UNION+ SELECT child.id FROM #{table_name} child+ INNER JOIN subtree ON child.parent_id = subtree.id+ )+ SELECT id FROM subtree+ SQL++ where("#{table_name}.id IN (#{subtree_sql})")+ }++ self.whitelisted_ransackable_attributes = %w[name kind parent_id]+ self.whitelisted_ransackable_associations = %w[parent children memberships external_references]++ # @return [Array<Spree::Company>] parent chain, nearest first (leaf → root)+ def ancestors+ chain = []+ node = parent+ # The walk is bounded so a cycle written behind the validation's back+ # (raw SQL, a race) degrades to a truncated chain rather than a hang.+ while node && chain.length < MAX_DEPTH+ chain << node+ node = node.parent+ end+ chain+ end++ # @return [Array<Spree::Company>] self first, then the parent chain+ def self_and_ancestors+ [self, *ancestors]+ end++ # @return [Spree::Company] the top of this node's tree+ def root+ self_and_ancestors.last+ end++ # @return [ActiveRecord::Relation] this node and everything below it+ def self_and_descendants+ self.class.subtree_of(self)+ end++ # @return [ActiveRecord::Relation] everything below this node+ def descendants+ self_and_descendants.where.not(id: id)+ end++ # The single tax anchor: the nearest self-or-ancestor +company+ node. Tax+ # identifiers and exemption certificates are always read through it, and+ # the walk stops at the first legal entity whether or not it holds+ # anything — a subsidiary with no VAT id has no VAT id, it does not borrow+ # its parent's.+ #+ # @return [Spree::Company, nil]+ def legal_entity+ self_and_ancestors.find { |node| node.kind == 'company' }+ end++ # @return [Boolean] whether this node is a legal entity+ def legal_entity?+ kind == 'company'+ end++ # @return [Boolean] whether this node is an organizational unit+ def division?+ kind == 'division'+ end++ # @return [Integer] 1 for a root, growing downward, capped by MAX_DEPTH+ def depth+ ancestors.length + 1+ end++ # The default billing/shipping rows for checkout prefill, falling back to+ # the nearest ancestor's when this node has none. Nothing is resolved+ # implicitly at order time — the order's own address columns are the truth.+ #+ # @return [Spree::Address, nil]+ def default_billing_address+ default_address(:default_billing)+ end++ # @return [Spree::Address, nil]+ def default_shipping_address+ default_address(:default_shipping)+ end++ private++ def default_address(flag)+ self_and_ancestors.each do |node|+ row = node.company_addresses.where(flag => true).first+ return row.address if row+ end+ nil+ end++ def parent_in_same_store+ return if parent.nil? || store_id.nil?+ return if parent.store_id == store_id++ errors.add(:parent, :invalid)+ end++ def root_must_be_legal_entity+ return if parent_id.present? || kind == 'company'++ errors.add(:kind, :root_must_be_legal_entity)+ end++ def no_ancestry_cycle+ return if parent_id.blank?++ if parent_id == id || (persisted? && parent.self_and_ancestors.any? { |node| node.id == id })+ errors.add(:parent, :cycle)+ end+ end++ # Depth is validated for the whole subtree, not just this node —+ # re-parenting a branch must not push its leaves past the cap.+ def depth_within_cap+ return if parent.nil?+ return if errors[:parent].any? # a cycle makes depth meaningless++ new_depth = parent.depth + 1+ if new_depth + subtree_height > MAX_DEPTH+ errors.add(:parent, :too_deep)+ end+ end++ # Levels below this node (0 for a leaf), walked breadth-first. Bounded by+ # MAX_DEPTH, so the walk stays cheap.+ def subtree_height+ return 0 if new_record?++ height = 0+ level = [self]+ while height < MAX_DEPTH+ level = Spree::Company.where(parent_id: level.map(&:id)).to_a+ break if level.empty?++ height += 1+ end+ height+ end- self.whitelisted_ransackable_attributes = %w[name]- self.whitelisted_ransackable_associations = %w[company_locations external_references]+ # A legal entity that holds registrations or certificates cannot become a+ # division — its purchases would silently lose their tax identity.+ def kind_change_keeps_tax_anchor+ return unless persisted? && will_save_change_to_kind? && kind == 'division'+ return unless tax_identifiers.exists? || tax_exemption_certificates.exists?- def event_serializer_class- 'Spree::Api::V3::CompanySerializer'.safe_constantize+ errors.add(:kind, :holds_tax_registrations)endendenddiff --git a/spree/core/app/models/spree/company_address.rb b/spree/core/app/models/spree/company_address.rbnew file mode 100644index 0000000000..1567eda8ae--- /dev/null+++ b/spree/core/app/models/spree/company_address.rb@@ -0,0 +1,48 @@+module Spree+ # An entry in a company node's address book — a labeled ship-to or bill-to+ # site. The address row is owned outright, never shared with a customer's+ # own address book, which is why it is destroyed with the entry.+ #+ # How many sites a node has never dictates how many nodes exist: structure+ # is the tree, addresses are just addresses+ # (docs/plans/6.0-b2b-companies-and-catalogs.md).+ class CompanyAddress < Spree.base_class+ has_prefix_id :caddr++ belongs_to :company, class_name: 'Spree::Company', inverse_of: :company_addresses+ belongs_to :address, class_name: 'Spree::Address', dependent: :destroy++ # 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 :address, update_only: true++ # The API reads and writes this under the same name, so the writer takes+ # either a record or the nested hash a client sends.+ def address=(value)+ value.is_a?(Hash) || value.is_a?(ActionController::Parameters) ? self.address_attributes = value : super+ end++ validates :address, presence: true++ # Demote any prior default in the same transaction so the partial unique+ # index ("one default of each kind per node") never sees two TRUE rows.+ # Runs before save so MySQL — which can't enforce a partial unique index —+ # also arrives at a single default (same shape as Channel#default).+ before_save :demote_other_default_billing, if: -> { default_billing? && will_save_change_to_default_billing? }+ before_save :demote_other_default_shipping, if: -> { default_shipping? && will_save_change_to_default_shipping? }++ delegate :store, :store_id, to: :company++ self.whitelisted_ransackable_attributes = %w[label default_billing default_shipping]++ private++ def demote_other_default_billing+ self.class.where(company_id: company_id, default_billing: true).where.not(id: id).update_all(default_billing: false)+ end++ def demote_other_default_shipping+ self.class.where(company_id: company_id, default_shipping: true).where.not(id: id).update_all(default_shipping: false)+ end+ end+enddiff --git a/spree/core/app/models/spree/company_contact.rb b/spree/core/app/models/spree/company_contact.rbdeleted file mode 100644index e7f902b2c8..0000000000--- a/spree/core/app/models/spree/company_contact.rb+++ /dev/null@@ -1,21 +0,0 @@-module Spree- # Links a customer to a branch they buy for. This is what lets a signed-in- # buyer's own cart find its company without staff touching the order.- #- # +role+ is a plain string with no behavior attached in 6.0 — permissions,- # approval limits and purchase authority belong to the dedicated B2B plan.- class CompanyContact < Spree.base_class- has_prefix_id :cc-- belongs_to :company_location, class_name: 'Spree::CompanyLocation', inverse_of: :company_contacts- belongs_to :customer, class_name: Spree.customer_class.to_s, inverse_of: :company_contacts-- has_one :company, through: :company_location-- validates :customer_id, uniqueness: { scope: [:company_location_id, *spree_base_uniqueness_scope] }-- delegate :store, :store_id, to: :company_location-- self.whitelisted_ransackable_attributes = %w[role]- end-enddiff --git a/spree/core/app/models/spree/company_invitation.rb b/spree/core/app/models/spree/company_invitation.rbnew file mode 100644index 0000000000..e72effbd29--- /dev/null+++ b/spree/core/app/models/spree/company_invitation.rb@@ -0,0 +1,81 @@+module Spree+ # An email invited into a company that matches no store customer yet.+ # Memberships stay always-active and customer-backed, so the pending state+ # lives here (mirroring the staff invitation shape): acceptance registers+ # the customer through the customer-creation workflow — or binds an+ # already-authenticated one — and lands as a {Spree::CompanyMembership}.+ #+ # The token is plaintext, like the staff invitation and setup tokens. It+ # grants exactly what a direct membership grants — no roles; Enterprise+ # attaches its role payload through +metadata+ and applies it on the+ # +company_invitation.accepted+ event.+ class CompanyInvitation < Spree.base_class+ has_prefix_id :cinv++ include Spree::Metadata++ publishes_lifecycle_events++ EXPIRY = 30.days++ has_secure_token :token++ belongs_to :company, class_name: 'Spree::Company', inverse_of: :invitations+ # nil when staff invites from the dashboard.+ belongs_to :inviter, class_name: Spree.customer_class.to_s, optional: true+ # Bound at acceptance.+ belongs_to :customer, class_name: Spree.customer_class.to_s, optional: true++ normalizes :email, with: ->(email) { email.strip.downcase }++ validates :email, presence: true, email: true+ validates :email, uniqueness: { scope: :company_id, conditions: -> { pending } }++ after_initialize :set_default_expiry, if: :new_record?++ # Re-inviting after expiry or revocation is allowed, which is why expired+ # rows fall out of +pending+ rather than merely being unusable.+ scope :pending, -> { where(accepted_at: nil, revoked_at: nil).where(arel_table[:expires_at].gt(Time.current)) }++ delegate :store, :store_id, to: :company++ self.whitelisted_ransackable_attributes = %w[email]++ # @return [Boolean]+ def pending?+ accepted_at.nil? && revoked_at.nil? && !expired?+ end++ # @return [Boolean]+ def accepted?+ accepted_at.present?+ end++ # @return [Boolean]+ def revoked?+ revoked_at.present?+ end++ # @return [Boolean]+ def expired?+ expires_at < Time.current+ end++ # Withdraws a pending invitation; its token then 404s on lookup.+ #+ # @return [Boolean]+ def revoke!+ return false unless pending?++ update!(revoked_at: Time.current)+ publish_event('company_invitation.revoked')+ true+ end++ private++ def set_default_expiry+ self.expires_at ||= EXPIRY.from_now+ end+ end+enddiff --git a/spree/core/app/models/spree/company_location.rb b/spree/core/app/models/spree/company_location.rbdeleted file mode 100644index f231f4250b..0000000000--- a/spree/core/app/models/spree/company_location.rb+++ /dev/null@@ -1,43 +0,0 @@-module Spree- # A branch or office of a business customer. Reaches the store through its- # company and so carries no store_id of its own.- #- # Its addresses are created inline and owned outright — a branch address is- # the branch's, not a row shared with the buyer's address book, which is why- # they are destroyed with it (docs/plans/decisions.md 2026-08-07).- class CompanyLocation < Spree.base_class- has_prefix_id :cloc-- include Spree::HasCustomFields- include Spree::Metadata- include Spree::HasExternalReferences-- belongs_to :company, class_name: 'Spree::Company', inverse_of: :company_locations- belongs_to :billing_address, class_name: 'Spree::Address', optional: true, dependent: :destroy- belongs_to :shipping_address, class_name: 'Spree::Address', optional: true, dependent: :destroy-- # 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.- %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_location- has_many :customers, through: :company_contacts, source: :customer-- validates :name, presence: true-- delegate :store, :store_id, to: :company-- self.whitelisted_ransackable_attributes = %w[name]- self.whitelisted_ransackable_associations = %w[external_references]- end-enddiff --git a/spree/core/app/models/spree/company_membership.rb b/spree/core/app/models/spree/company_membership.rbnew file mode 100644index 0000000000..e4619effbd--- /dev/null+++ b/spree/core/app/models/spree/company_membership.rb@@ -0,0 +1,27 @@+module Spree+ # Joins a customer to a company node. Standing covers the node and+ # everything below it — any authorization question ("may this customer act+ # for node N") is a membership check on N's self-and-ancestors, never an+ # equality check on one node.+ #+ # Always active and always customer-backed: the not-yet-registered case is a+ # {Spree::CompanyInvitation}, never a nullable customer or a status here.+ #+ # +role+ is a cosmetic label with no behavior attached — OSS has no company+ # permission model; every member can do everything within their standing.+ # The capability model is Enterprise (docs/plans/6.0-admin-rbac.md).+ class CompanyMembership < Spree.base_class+ has_prefix_id :cmem++ attribute :role, :string, default: 'buyer'++ belongs_to :company, class_name: 'Spree::Company', inverse_of: :memberships+ belongs_to :customer, class_name: Spree.customer_class.to_s, inverse_of: :company_memberships++ validates :customer_id, uniqueness: { scope: [:company_id, *spree_base_uniqueness_scope] }++ delegate :store, :store_id, to: :company++ self.whitelisted_ransackable_attributes = %w[role]+ end+enddiff --git a/spree/core/app/models/spree/store.rb b/spree/core/app/models/spree/store.rbindex 51c81bacb1..4cd3b57d77 100644--- a/spree/core/app/models/spree/store.rb+++ b/spree/core/app/models/spree/store.rb@@ -248,6 +248,7 @@ module Spreehas_many :companies, class_name: 'Spree::Company', dependent: :destroy, inverse_of: :storehas_many :external_references, class_name: 'Spree::ExternalReference', dependent: :destroy, inverse_of: :store+ has_many :catalogs, class_name: 'Spree::Catalog', dependent: :destroy, inverse_of: :storehas_many :api_keys, class_name: 'Spree::ApiKey', dependent: :destroyhas_many :allowed_origins, class_name: 'Spree::AllowedOrigin', dependent: :destroydiff --git a/spree/core/app/models/spree/tax_exemption_certificate.rb b/spree/core/app/models/spree/tax_exemption_certificate.rbindex cc8e99a206..2d9928692b 100644--- a/spree/core/app/models/spree/tax_exemption_certificate.rb+++ b/spree/core/app/models/spree/tax_exemption_certificate.rb@@ -27,6 +27,11 @@ module Spreehas_one_attached :document, service: Spree.private_storage_service_namevalidates :certificate_number, :reason_code, presence: true+ # Certificates exist only on legal-entity nodes — a division's purchases+ # read exemption through its legal entity. A validation rather than a+ # schema difference, so a per-division registration can be allowed later+ # by relaxing this alone.+ validate :company_is_legal_entity# A certificate is a scanned form, not an archive. Bounded because the# download action reads the whole blob into memory to serve it, so an@@ -81,5 +86,10 @@ module Spreeprivate+ def company_is_legal_entity+ return if company.nil? || company.legal_entity?++ errors.add(:company, :must_be_legal_entity)+ endendenddiff --git a/spree/core/app/models/spree/tax_identifier.rb b/spree/core/app/models/spree/tax_identifier.rbindex 99526bd74b..60872e5ff5 100644--- a/spree/core/app/models/spree/tax_identifier.rb+++ b/spree/core/app/models/spree/tax_identifier.rb@@ -73,6 +73,11 @@ module Spreevalidates :validation_status, inclusion: { in: VALIDATION_STATUSES }, allow_nil: truevalidates :source, inclusion: { in: SOURCES }, allow_nil: truevalidate :value_format+ # Registrations exist only on legal-entity nodes — a division's purchases+ # read theirs through the legal entity. A validation rather than a schema+ # difference, so a per-division foreign registration can be allowed later+ # by relaxing this alone.+ validate :company_is_legal_entityscope :for_kind, ->(kind) { where(kind: kind) }scope :verified, -> { where(validation_status: 'verified') }@@ -144,5 +149,14 @@ module Spreepublish_event('tax_identifier.number_changed')end++ # Registrations exist only on legal-entity nodes — a division's purchases+ # read theirs through the legal entity.+ def company_is_legal_entity+ return unless owner.is_a?(Spree::Company)+ return if owner.legal_entity?++ errors.add(:owner, :must_be_legal_entity)+ endendenddiff --git a/spree/core/app/services/spree/carts/split_by_seller.rb b/spree/core/app/services/spree/carts/split_by_seller.rbindex db856d6c80..7b20ce5219 100644--- a/spree/core/app/services/spree/carts/split_by_seller.rb+++ b/spree/core/app/services/spree/carts/split_by_seller.rb@@ -30,7 +30,7 @@ module Spree# Adding a column here is a decision that it describes the checkout# rather than one seller's part of it.CARRIED_TO_SIBLING = %w[- email currency locale market_id channel_id company_location_id+ email currency locale market_id channel_id company_idcustomer_id token accept_marketing preferred_stock_location_idcustomer_note last_ip_address].freezediff --git a/spree/core/app/services/spree/companies/add_member.rb b/spree/core/app/services/spree/companies/add_member.rbnew file mode 100644index 0000000000..69f50d0c8f--- /dev/null+++ b/spree/core/app/services/spree/companies/add_member.rb@@ -0,0 +1,38 @@+module Spree+ module Companies+ # Adds a person to a company node by email — the single convergent path+ # behind both the dashboard's and the storefront's "add member".+ #+ # An email that matches an existing customer becomes a membership+ # immediately; an unknown email becomes a {Spree::CompanyInvitation},+ # whose creation event sends the invite mail. Extension payloads (e.g. an+ # Enterprise role reference) ride +metadata+ on either record.+ class AddMember+ prepend Spree::ServiceModule::Base++ # @param company [Spree::Company]+ # @param email [String]+ # @param inviter [Object, nil] the inviting customer, nil when staff+ # @param role [String, nil] cosmetic membership label+ # @param metadata [Hash, nil] extension payload carried onto the record+ # @return [Spree::ServiceModule::Result] value is the created+ # Spree::CompanyMembership or Spree::CompanyInvitation+ def call(company:, email:, inviter: nil, role: nil, metadata: nil)+ normalized_email = email.to_s.strip.downcase+ customer = Spree.customer_class.find_by(email: normalized_email)++ record =+ if customer+ attributes = { customer: customer }+ attributes[:role] = role if role.present?+ attributes[:metadata] = metadata if metadata.present?+ company.memberships.new(attributes)+ else+ company.invitations.new(email: normalized_email, inviter: inviter, metadata: metadata)+ end++ record.save ? success(record) : failure(record)+ end+ end+ end+enddiff --git a/spree/core/app/services/spree/company_invitations/accept.rb b/spree/core/app/services/spree/company_invitations/accept.rbnew file mode 100644index 0000000000..53c489c29e--- /dev/null+++ b/spree/core/app/services/spree/company_invitations/accept.rb@@ -0,0 +1,44 @@+module Spree+ module CompanyInvitations+ # Turns a pending invitation into a membership. Two ways in, converging+ # here: a registration payload — run through the single customer-creation+ # workflow — or an already-authenticated customer whose account the+ # invitation binds to. Either way the membership is created, the+ # acceptance stamped and the token spent.+ class Accept+ prepend Spree::ServiceModule::Base++ # @param invitation [Spree::CompanyInvitation]+ # @param customer [Object, nil] an authenticated customer accepting+ # @param customer_attributes [Hash, nil] registration payload for a new+ # customer; the account is created with the invited email+ # @return [Spree::ServiceModule::Result] value is the created+ # Spree::CompanyMembership+ def call(invitation:, customer: nil, customer_attributes: nil)+ return failure(invitation, :invitation_not_pending) unless invitation.pending?++ if customer.nil?+ result = Spree.customer_create_workflow.call(+ store: invitation.store,+ **(customer_attributes || {}).to_h.symbolize_keys.merge(email: invitation.email)+ )+ return failure(result.value, result.error) if result.failure?++ customer = result.value+ end++ membership = nil+ ApplicationRecord.transaction do+ membership = invitation.company.memberships.where(customer: customer).first_or_create!+ invitation.update!(accepted_at: Time.current, customer: customer)+ end++ invitation.publish_event('company_invitation.accepted')++ success(membership)+ rescue ActiveRecord::RecordInvalid => e+ failure(e.record)+ end+ end+ end+enddiff --git a/spree/core/app/services/spree/tax/resolve_exemptions.rb b/spree/core/app/services/spree/tax/resolve_exemptions.rbindex 1b91603348..09cd37a001 100644--- a/spree/core/app/services/spree/tax/resolve_exemptions.rb+++ b/spree/core/app/services/spree/tax/resolve_exemptions.rb@@ -22,7 +22,9 @@ module Spree# @param order [Spree::Cart, Spree::Order]# @return [Array<Spree::TaxExemption>]def call(order:)- company = order.company+ # The legal entity, never the node itself: a division holds no+ # certificates, and reading its own would silently lose the exemption.+ company = order.company_legal_entityaddress = order.tax_addressreturn success([]) if company.nil? || address.nil?diff --git a/spree/core/app/workflows/spree/carts/complete.rb b/spree/core/app/workflows/spree/carts/complete.rbindex eb33128d11..c5990a6a0b 100644--- a/spree/core/app/workflows/spree/carts/complete.rb+++ b/spree/core/app/workflows/spree/carts/complete.rb@@ -215,7 +215,7 @@ module Spreelocale: cart.locale,market: cart.market,channel: cart.channel,- company_location: cart.resolved_company_location,+ company: cart.resolved_company,customer: cart.customer,token: cart.token,accept_marketing: cart.accept_marketing,diff --git a/spree/core/config/locales/en.yml b/spree/core/config/locales/en.ymlindex 2527c6c60b..416a24bbf7 100644--- a/spree/core/config/locales/en.yml+++ b/spree/core/config/locales/en.yml@@ -259,6 +259,14 @@ en:attributes:taxon_id:already_linked: is already linked to this product+ spree/company:+ attributes:+ kind:+ holds_tax_registrations: cannot become a division while holding tax registrations or exemption certificates+ root_must_be_legal_entity: must be company for a root node+ parent:+ cycle: cannot be one of the node's own descendants+ too_deep: would exceed the maximum tree depthspree/credit_card:attributes:base:@@ -352,6 +360,14 @@ en:amount_used:cannot_be_greater_than_amount: Cannot be greater than amount.greater_than_zero_restrict_delete: is greater than zero. Can not delete store credit.+ spree/tax_exemption_certificate:+ attributes:+ company:+ must_be_legal_entity: must be a legal entity, not a division+ spree/tax_identifier:+ attributes:+ company:+ must_be_legal_entity: must be a legal entity, not a divisionspree/taxon_image:attributes:attachment:@@ -726,7 +742,19 @@ en:seller_rule:description: Charges this rate only when the seller is one of the selectedname: Seller+ companies: Companiescompany: Company+ company_invitations:+ not_pending: This invitation is no longer pending and cannot be revoked.+ company_mailer:+ invitation_email:+ action: Accept invitation+ expiry_notice: This invitation link will expire in 30 days.+ greeting: Hi,+ ignore_notice: If you were not expecting this invitation, you can safely ignore this email.+ instructions: You have been invited to join %{company} on %{store}. Accept the invitation to start purchasing on the company's behalf.+ subject: invitation to join %{company}+ title: Join %{company}compare_at_amount: Compare at amountcompare_at_price: Compare at pricecomplete: completediff --git a/spree/core/db/migrate/20260807000001_create_spree_companies.rb b/spree/core/db/migrate/20260807000001_create_spree_companies.rbindex 544e3ad7af..cac60097ca 100644--- a/spree/core/db/migrate/20260807000001_create_spree_companies.rb+++ b/spree/core/db/migrate/20260807000001_create_spree_companies.rb@@ -2,9 +2,13 @@ class CreateSpreeCompanies < ActiveRecord::Migration[8.1]def changecreate_table :spree_companies do |t|t.references :store, null: false+ t.references :parent # self-referential tree, nil = roott.string :name, null: false- t.string :external_id # ERP/CRM reference- # No tax_exempt boolean — exemption is a certificate scoped to a+ # 'company' (legal entity) or 'division' (organizational unit). No DB+ # default per the string-column rule; the model normalizes a blank kind.+ t.string :kind, null: false+ # No external_id column — ERP/CRM identity lives on+ # Spree::ExternalReference. No tax_exempt boolean — exemption is a certificate scoped to a# jurisdiction, which a flag cannot express (docs/plans/decisions.md# 2026-08-07).if t.respond_to?(:jsonb)@@ -15,17 +19,50 @@ class CreateSpreeCompanies < ActiveRecord::Migration[8.1]t.timestampsend- add_index :spree_companies, [:store_id, :external_id], unique: true,- where: 'external_id IS NOT NULL', name: 'idx_companies_external_id'+ # The address book: rows a node owns outright, never shared with a+ # customer's own address book.+ create_table :spree_company_addresses do |t|+ t.references :company, null: false+ t.references :address, null: false+ t.string :label+ t.boolean :default_billing, null: false, default: false+ t.boolean :default_shipping, null: false, default: false+ t.timestamps+ end++ # Partial unique indexes: at most one default of each kind per node.+ # Supported on Postgres and SQLite; MySQL ignores +where:+, so the model+ # demotes prior defaults before save (same shape as Channel#default).+ unless ActiveRecord::Base.connection.adapter_name.match?(/mysql/i)+ add_index :spree_company_addresses, :company_id, unique: true,+ where: 'default_billing = TRUE',+ name: 'idx_company_addresses_default_billing'+ add_index :spree_company_addresses, :company_id, unique: true,+ where: 'default_shipping = TRUE',+ name: 'idx_company_addresses_default_shipping'+ end- # No store_id on the children: they reach the store through the company,- # matching spree_return_line_items.- create_table :spree_company_locations do |t|+ # Membership gives a customer standing over the node and its subtree.+ # Always customer-backed — the not-yet-registered case is an invitation.+ create_table :spree_company_memberships do |t|t.references :company, null: false- t.references :billing_address- t.references :shipping_address- t.string :name, null: false- t.string :external_id+ t.references :customer, null: false+ t.string :role # cosmetic label, no behavior in OSS+ t.timestamps+ end++ add_index :spree_company_memberships, [:company_id, :customer_id], unique: true,+ name: 'idx_company_memberships_on_company_and_customer'++ create_table :spree_company_invitations do |t|+ t.references :company, null: false+ t.references :inviter # customer who invited; nil = staff+ t.references :customer # bound at acceptance+ t.string :email, null: false+ t.string :token, null: false # plaintext, like the staff invitation token+ t.datetime :expires_at, null: false+ t.datetime :accepted_at+ t.datetime :revoked_atif t.respond_to?(:jsonb)t.jsonb :metadataelse@@ -34,19 +71,12 @@ class CreateSpreeCompanies < ActiveRecord::Migration[8.1]t.timestampsend- create_table :spree_company_contacts do |t|- t.references :company_location, null: false- t.references :customer, null: false- t.string :role, null: false, default: 'buyer' # no behavior attached in 6.0- t.timestamps- end-- add_index :spree_company_contacts, [:company_location_id, :customer_id], unique: true,- name: 'idx_company_contacts_on_location_and_customer'+ add_index :spree_company_invitations, :token, unique: true+ add_index :spree_company_invitations, [:company_id, :email]# Both sides: exemption has to resolve while the buyer is still in- # checkout, and completion copies the branch onto the order.- add_reference :spree_carts, :company_location- add_reference :spree_orders, :company_location+ # checkout, and completion copies the node onto the order.+ add_reference :spree_carts, :company+ add_reference :spree_orders, :companyendenddiff --git a/spree/core/lib/spree/core/dependencies.rb b/spree/core/lib/spree/core/dependencies.rbindex ea2b86cbc9..053b1a2122 100644--- a/spree/core/lib/spree/core/dependencies.rb+++ b/spree/core/lib/spree/core/dependencies.rb@@ -155,6 +155,14 @@ module Spree# invitationsinvitation_accept_workflow: 'Spree::Invitations::Accept',+ # companies — both member-adding surfaces (dashboard and storefront)+ # converge on these+ company_add_member_service: 'Spree::Companies::AddMember',+ company_invitation_accept_service: 'Spree::CompanyInvitations::Accept',++ # catalog-aware product visibility for a buyer+ products_for_context_service: 'Spree::Products::ForContext',+# imports — the CSV pipeline's stepsimport_start_mapping_workflow: 'Spree::Imports::StartMapping',import_complete_mapping_workflow: 'Spree::Imports::CompleteMapping',diff --git a/spree/core/lib/spree/core/permission_configuration.rb b/spree/core/lib/spree/core/permission_configuration.rbindex 706061abb8..52ead788c2 100644--- a/spree/core/lib/spree/core/permission_configuration.rb+++ b/spree/core/lib/spree/core/permission_configuration.rb@@ -293,7 +293,8 @@ module Spreeregister_resource(:products, group: :catalog, audiences: %i[seller], subjects: -> {[Spree::Product, Spree::ProductType, Spree::Variant, Spree::OptionType,Spree::OptionValue, Spree::Price, Spree::PriceList, Spree::PriceRule,- Spree::ProductPublication, Spree::CustomField]+ Spree::ProductPublication, Spree::Catalog, Spree::CatalogProduct,+ Spree::CatalogAssignment, Spree::CustomField]})# Media is its own resource because a file is no longer a product's# alone: one row can be placed on a category or collection, and the@@ -322,7 +323,8 @@ module Spreeregister_resource(:customers, group: :customers, subjects: -> {[Spree.customer_class, Spree::Address, Spree::CreditCard, Spree::CustomerGroup,- Spree::Company, Spree::CompanyLocation, Spree::CompanyContact,+ Spree::Company, Spree::CompanyAddress, Spree::CompanyMembership,+ Spree::CompanyInvitation,Spree::TaxIdentifier, Spree::TaxExemptionCertificate,Spree::CustomField]})diff --git a/spree/core/lib/spree/testing_support/factories/company_factory.rb b/spree/core/lib/spree/testing_support/factories/company_factory.rbindex 3ee8d87fda..4cba9690a3 100644--- a/spree/core/lib/spree/testing_support/factories/company_factory.rb+++ b/spree/core/lib/spree/testing_support/factories/company_factory.rb@@ -2,21 +2,28 @@ FactoryBot.define dofactory :company, class: Spree::Company dosequence(:name) { |n| "Acme Corp #{n}" }store { Spree::Store.default || create(:store) }+ kind { 'company' }- factory :company_with_location do- after(:create) do |company|- create(:company_location, company: company)- end+ factory :company_division do+ sequence(:name) { |n| "Division #{n}" }+ kind { 'division' }+ parent { association(:company, store: store) }endend- factory :company_location, class: Spree::CompanyLocation do+ factory :company_address, class: Spree::CompanyAddress docompany- sequence(:name) { |n| "Branch #{n}" }+ address+ sequence(:label) { |n| "Site #{n}" }end- factory :company_contact, class: Spree::CompanyContact do- company_location+ factory :company_membership, class: Spree::CompanyMembership do+ companycustomerend++ factory :company_invitation, class: Spree::CompanyInvitation do+ company+ sequence(:email) { |n| "buyer#{n}@example.com" }+ endenddiff --git a/spree/core/spec/models/concerns/spree/purchase/company_spec.rb b/spree/core/spec/models/concerns/spree/purchase/company_spec.rbindex 2d17105386..6da2392efd 100644--- a/spree/core/spec/models/concerns/spree/purchase/company_spec.rb+++ b/spree/core/spec/models/concerns/spree/purchase/company_spec.rb@@ -3,95 +3,88 @@ require 'spec_helper'RSpec.shared_examples 'a company host' dolet(:store) { @default_store }let(:company) { create(:company, store: store) }- let(:location) { create(:company_location, company: company) }- describe '#resolved_company_location' do- it 'prefers the branch named on the sale' do- record.update!(company_location: location)+ describe '#resolved_company' do+ it 'prefers the node named on the sale' do+ create(:company_membership, company: company, customer: record.customer)+ record.update!(company: company)- expect(record.resolved_company_location).to eq(location)+ expect(record.resolved_company).to eq(company)end- context 'with no branch named' do- it 'resolves the one branch the buyer acts for' do- create(:company_contact, company_location: location, customer: record.customer)+ context 'with no node named' do+ it 'resolves the one membership the buyer holds' do+ create(:company_membership, company: company, customer: record.customer)- expect(record.reload.resolved_company_location).to eq(location)+ expect(record.reload.resolved_company).to eq(company)end# Guessing here would invoice one business for another's purchase.- it 'refuses to choose when the buyer acts for several' do- create(:company_contact, company_location: location, customer: record.customer)- create(:company_contact, company_location: create(:company_location, company: company),- customer: record.customer)+ it 'refuses to choose when the buyer holds several memberships' do+ create(:company_membership, company: company, customer: record.customer)+ create(:company_membership, company: create(:company, store: store), customer: record.customer)- expect(record.reload.resolved_company_location).to be_nil+ expect(record.reload.resolved_company).to be_nilendit 'resolves nothing for a guest' dorecord.update!(customer: nil)- expect(record.resolved_company_location).to be_nil+ expect(record.resolved_company).to be_nilend- # Customers are global across stores, so a buyer can be a contact at a+ # Customers are global across stores, so a buyer can be a member at a# business this store does not trade as. Resolving to it would hand this# sale that company's registration and exemption certificates.- it 'ignores a branch belonging to another store' do- elsewhere = create(:company_location, company: create(:company, store: create(:store)))- create(:company_contact, company_location: elsewhere, customer: record.customer)+ it 'ignores a membership belonging to another store' do+ elsewhere = create(:company, store: create(:store))+ create(:company_membership, company: elsewhere, customer: record.customer)- expect(record.reload.resolved_company_location).to be_nil- expect(record.company).to be_nil+ expect(record.reload.resolved_company).to be_nilend- # The foreign branch must not count towards "acts for several" either —+ # The foreign membership must not count towards "holds several" either —# otherwise it would suppress a resolution that is genuinely unambiguous# within this store.- it 'still resolves the one branch in this store when another store has one too' do- create(:company_contact, company_location: location, customer: record.customer)- elsewhere = create(:company_location, company: create(:company, store: create(:store)))- create(:company_contact, company_location: elsewhere, customer: record.customer)+ it 'still resolves the one membership in this store when another store has one too' do+ create(:company_membership, company: company, customer: record.customer)+ elsewhere = create(:company, store: create(:store))+ create(:company_membership, company: elsewhere, customer: record.customer)- expect(record.reload.resolved_company_location).to eq(location)+ expect(record.reload.resolved_company).to eq(company)endendend- describe '#company' do- it 'derives from the resolved branch' do- record.update!(company_location: location)+ describe '#company_legal_entity' do+ it 'reads through the resolved node to its legal entity' do+ division = create(:company, store: store, kind: 'division', parent: company)+ create(:company_membership, company: division, customer: record.customer)- expect(record.company).to eq(company)+ expect(record.reload.company_legal_entity).to eq(company)endit 'is nil for a consumer sale' do- expect(record.company).to be_nil+ expect(record.company_legal_entity).to be_nilendend- describe 'the branch must belong to the same store' do- it 'refuses a branch from another store' do- elsewhere = create(:company_location, company: create(:company, store: create(:store)))+ describe 'the node must belong to the same store' do+ it 'refuses a node from another store' do+ elsewhere = create(:company, store: create(:store))- record.company_location = elsewhere+ record.company = elsewhereexpect(record).not_to be_valid- expect(record.errors[:company_location]).to be_present- end-- it 'accepts one from its own store' do- record.company_location = location-- expect(record).to be_valid+ expect(record.errors[:company]).to be_presentendenddescribe '#b2b?' do- it 'is true once a branch resolves' do- record.update!(company_location: location)+ it 'is true once a node resolves' do+ create(:company_membership, company: company, customer: record.customer)- expect(record).to be_b2b+ expect(record.reload).to be_b2bendit 'is false otherwise' do@@ -113,28 +106,82 @@ RSpec.describe Spree::Purchase::Company doit 'does not acquire a company it was never placed for' doexpect(order.b2b?).to be(false)- location = create(:company_location, company: create(:company, store: store))- create(:company_contact, company_location: location, customer: customer)+ create(:company_membership, company: create(:company, store: store), customer: customer)expect(Spree::Order.find(order.id).b2b?).to be(false)- expect(Spree::Order.find(order.id).company).to be_nil+ expect(Spree::Order.find(order.id).resolved_company).to be_nilend- 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)+ it 'keeps the node it was stamped with' do+ company = create(:company, store: store)+ order.update_columns(company_id: company.id)- expect(Spree::Order.find(order.id).resolved_company_location).to eq(location)+ expect(Spree::Order.find(order.id).resolved_company).to eq(company)end- it 'does not lose it when the buyer later joins a second branch' do+ it 'does not lose it when the buyer later joins a second company' docompany = 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)+ order.update_columns(company_id: company.id)+ create(:company_membership, company: company, customer: customer)+ create(:company_membership, company: create(:company, store: store), customer: customer)++ expect(Spree::Order.find(order.id).resolved_company).to eq(company)+ end+ end++ # Standing is checked where the storefront writes — the cart. An order's+ # company arrives from completion (already validated) or from staff.+ describe 'standing over the named node' do+ let(:store) { @default_store }+ let(:company) { create(:company, store: store) }+ let(:cart) { create(:cart, store: store, customer: customer) }++ it 'refuses a cart naming a node the buyer has no standing over' do+ cart.company = company++ expect(cart).not_to be_valid+ expect(cart.errors[:company]).to be_present+ end++ it 'accepts a node the buyer is a member of' do+ create(:company_membership, company: company, customer: customer)+ cart.company = company++ expect(cart).to be_valid+ end++ # Membership at a node covers everything below it.+ it 'accepts a descendant of the membership node' do+ create(:company_membership, company: company, customer: customer)+ division = create(:company, store: store, kind: 'division', parent: company)+ cart.company = division++ expect(cart).to be_valid+ end++ it 'refuses an ancestor of the membership node' do+ division = create(:company, store: store, kind: 'division', parent: company)+ create(:company_membership, company: division, customer: customer)+ cart.company = company++ expect(cart).not_to be_valid+ end++ it 'does not re-run once the node is stamped' do+ create(:company_membership, company: company, customer: customer)+ cart.update!(company: company)+ customer.company_memberships.destroy_all++ cart.customer_note = 'unrelated change'++ expect(cart).to be_valid+ end++ it 'lets staff name a node on an order without a membership' do+ order = create(:order, store: store, customer: customer)+ order.company = company- expect(Spree::Order.find(order.id).company).to eq(company)+ expect(order).to be_validendenddiff --git a/spree/core/spec/models/concerns/spree/purchase/taxation_spec.rb b/spree/core/spec/models/concerns/spree/purchase/taxation_spec.rbindex 479f6b6355..774b8d2650 100644--- a/spree/core/spec/models/concerns/spree/purchase/taxation_spec.rb+++ b/spree/core/spec/models/concerns/spree/purchase/taxation_spec.rb@@ -50,9 +50,14 @@ RSpec.shared_examples 'a taxation host' docontext 'when the sale is for a business' dolet(:company) { create(:company, store: store) }- let(:location) { create(:company_location, company: company) }+ # The purchase points at a division; the registration resolves through+ # its legal entity — the parent company node.+ let(:division) { create(:company, store: store, kind: 'division', parent: company) }- before { record.update!(company_location: location) }+ before do+ create(:company_membership, company: division, customer: customer)+ record.update!(company: division)+ end# The invoice is addressed to the entity, so its registration wins.it 'prefers the company registration over the buyer own' dodiff --git a/spree/core/spec/models/spree/company_address_spec.rb b/spree/core/spec/models/spree/company_address_spec.rbnew file mode 100644index 0000000000..cb9a3fee21--- /dev/null+++ b/spree/core/spec/models/spree/company_address_spec.rb@@ -0,0 +1,44 @@+require 'spec_helper'++describe Spree::CompanyAddress, type: :model do+ let(:store) { @default_store }+ let(:company) { create(:company, store: store) }++ it 'owns its address row outright' do+ entry = create(:company_address, company: company)++ expect { entry.destroy }.to change(Spree::Address, :count).by(-1)+ end++ it 'accepts a nested address hash under the read name' do+ entry = create(:company_address, company: company)+ entry.update!(address: { city: 'Springfield' })++ expect(entry.reload.address.city).to eq('Springfield')+ end++ describe 'defaults' do+ it 'keeps at most one default billing entry per node' do+ first = create(:company_address, company: company, default_billing: true)+ second = create(:company_address, company: company, default_billing: true)++ expect(first.reload.default_billing).to be(false)+ expect(second.reload.default_billing).to be(true)+ end++ it 'keeps at most one default shipping entry per node' do+ first = create(:company_address, company: company, default_shipping: true)+ second = create(:company_address, company: company, default_shipping: true)++ expect(first.reload.default_shipping).to be(false)+ expect(second.reload.default_shipping).to be(true)+ end++ it 'leaves another node untouched' do+ other = create(:company_address, company: create(:company, store: store), default_billing: true)+ create(:company_address, company: company, default_billing: true)++ expect(other.reload.default_billing).to be(true)+ end+ end+enddiff --git a/spree/core/spec/models/spree/company_contact_spec.rb b/spree/core/spec/models/spree/company_contact_spec.rbdeleted file mode 100644index 2df0765b8a..0000000000--- a/spree/core/spec/models/spree/company_contact_spec.rb+++ /dev/null@@ -1,45 +0,0 @@-require 'spec_helper'--describe Spree::CompanyContact, type: :model do- let(:store) { @default_store }- let(:company) { create(:company, store: store) }- let(:location) { create(:company_location, company: company) }-- it 'reaches the company and store through its location' do- contact = create(:company_contact, company_location: location)-- expect(contact.company).to eq(company)- expect(contact.store).to eq(store)- end-- it 'defaults the role to buyer' do- expect(create(:company_contact, company_location: location).role).to eq('buyer')- end-- it 'allows one contact per customer per location' do- customer = create(:customer)- create(:company_contact, company_location: location, customer: customer)-- duplicate = build(:company_contact, company_location: location, customer: customer)-- expect(duplicate).not_to be_valid- end-- # A buyer purchasing for two branches is the case that makes selection- # ambiguous — see the provisional resolution in Spree::Purchase::Company.- it 'allows the same customer at several locations' do- customer = create(:customer)- create(:company_contact, company_location: location, customer: customer)- other = create(:company_location, company: company)-- expect(build(:company_contact, company_location: other, customer: customer)).to be_valid- end-- it 'is reachable from the customer' do- customer = create(:customer)- contact = create(:company_contact, company_location: location, customer: customer)-- expect(customer.company_contacts).to eq([contact])- expect(customer.company_locations).to eq([location])- end-enddiff --git a/spree/core/spec/models/spree/company_invitation_spec.rb b/spree/core/spec/models/spree/company_invitation_spec.rbnew file mode 100644index 0000000000..8184f438b8--- /dev/null+++ b/spree/core/spec/models/spree/company_invitation_spec.rb@@ -0,0 +1,70 @@+require 'spec_helper'++describe Spree::CompanyInvitation, type: :model do+ let(:store) { @default_store }+ let(:company) { create(:company, store: store) }++ it 'normalizes the email' do+ invitation = create(:company_invitation, company: company, email: ' [email protected] ')++ expect(invitation.email).to eq('[email protected]')+ end++ it 'generates a token and a 30-day expiry' do+ invitation = create(:company_invitation, company: company)++ expect(invitation.token).to be_present+ expect(invitation.expires_at).to be_within(1.minute).of(30.days.from_now)+ end++ describe 'pending uniqueness' do+ it 'refuses a second pending invitation for the same email and node' do+ create(:company_invitation, company: company, email: '[email protected]')++ expect(build(:company_invitation, company: company, email: '[email protected]')).not_to be_valid+ end++ it 'permits re-inviting after revocation' do+ create(:company_invitation, company: company, email: '[email protected]').revoke!++ expect(build(:company_invitation, company: company, email: '[email protected]')).to be_valid+ end++ it 'permits re-inviting after expiry' do+ create(:company_invitation, company: company, email: '[email protected]').update!(expires_at: 1.day.ago)++ expect(build(:company_invitation, company: company, email: '[email protected]')).to be_valid+ end++ it 'permits the same email at another node' do+ create(:company_invitation, company: company, email: '[email protected]')++ expect(build(:company_invitation, company: create(:company, store: store), email: '[email protected]')).to be_valid+ end+ end++ describe '#revoke!' do+ it 'stamps the revocation' do+ invitation = create(:company_invitation, company: company)++ expect(invitation.revoke!).to be(true)+ expect(invitation.reload).to be_revoked+ expect(invitation).not_to be_pending+ end++ it 'refuses on an accepted invitation' do+ invitation = create(:company_invitation, company: company)+ invitation.update!(accepted_at: Time.current)++ expect(invitation.revoke!).to be(false)+ end+ end++ it 'stops being pending once expired' do+ invitation = create(:company_invitation, company: company)+ invitation.update!(expires_at: 1.minute.ago)++ expect(invitation).not_to be_pending+ expect(described_class.pending).not_to include(invitation)+ end+enddiff --git a/spree/core/spec/models/spree/company_location_spec.rb b/spree/core/spec/models/spree/company_location_spec.rbdeleted file mode 100644index 7588aba29b..0000000000--- a/spree/core/spec/models/spree/company_location_spec.rb+++ /dev/null@@ -1,49 +0,0 @@-require 'spec_helper'--describe Spree::CompanyLocation, type: :model do- it_behaves_like 'metadata'-- let(:store) { @default_store }- let(:company) { create(:company, store: store) }-- it 'reaches the store through its company' do- location = create(:company_location, company: company)-- expect(location.store).to eq(store)- expect(location.store_id).to eq(store.id)- end-- describe 'addresses' do- it 'creates them inline from nested attributes' do- location = create(:company_location, company: company,- billing_address_attributes: build(:address).attributes.except('id', 'created_at', 'updated_at'))-- expect(location.billing_address).to be_present- end-- # The branch owns its address rows, so nothing is left behind and nothing- # shared is taken away.- it 'destroys its own address rows with it' do- location = create(:company_location, company: company,- billing_address: create(:address),- shipping_address: create(:address))-- expect { location.destroy }.to change(Spree::Address, :count).by(-2)- end- end-- it 'destroys its contacts' do- location = create(:company_location, company: company)- create(:company_contact, company_location: location)-- expect { location.destroy }.to change(Spree::CompanyContact, :count).by(-1)- end-- it 'exposes the customers who buy for it' do- location = create(:company_location, company: company)- customer = create(:customer)- create(:company_contact, company_location: location, customer: customer)-- expect(location.customers).to eq([customer])- end-enddiff --git a/spree/core/spec/models/spree/company_membership_spec.rb b/spree/core/spec/models/spree/company_membership_spec.rbnew file mode 100644index 0000000000..43b02886aa--- /dev/null+++ b/spree/core/spec/models/spree/company_membership_spec.rb@@ -0,0 +1,56 @@+require 'spec_helper'++describe Spree::CompanyMembership, type: :model do+ let(:store) { @default_store }+ let(:company) { create(:company, store: store) }+ let(:customer) { create(:customer) }++ it 'is unique per customer and node' do+ create(:company_membership, company: company, customer: customer)++ expect(build(:company_membership, company: company, customer: customer)).not_to be_valid+ end++ it 'allows the same customer at another node' do+ create(:company_membership, company: company, customer: customer)++ expect(build(:company_membership, company: create(:company, store: store), customer: customer)).to be_valid+ end++ it 'defaults the cosmetic role label' do+ expect(described_class.new.role).to eq('buyer')+ end++ it 'reaches the store through the company' do+ membership = create(:company_membership, company: company, customer: customer)++ expect(membership.store).to eq(store)+ end++ describe 'standing' do+ it 'covers the membership node and its subtree' do+ division = create(:company, store: store, kind: 'division', parent: company)+ create(:company_membership, company: company, customer: customer)++ expect(customer.standing_for?(company)).to be(true)+ expect(customer.standing_for?(division)).to be(true)+ expect(customer.company_standing(store: store)).to contain_exactly(company, division)+ end++ it 'does not cover ancestors or siblings' do+ division = create(:company, store: store, kind: 'division', parent: company)+ sibling = create(:company, store: store, kind: 'division', parent: company)+ create(:company_membership, company: division, customer: customer)++ expect(customer.standing_for?(company)).to be(false)+ expect(customer.standing_for?(sibling)).to be(false)+ end++ it 'is evaluated per store' do+ elsewhere = create(:company, store: create(:store))+ create(:company_membership, company: elsewhere, customer: customer)++ expect(customer.company_standing(store: store)).to be_empty+ end+ end+enddiff --git a/spree/core/spec/models/spree/company_spec.rb b/spree/core/spec/models/spree/company_spec.rbindex 8db16479ae..1e51525319 100644--- a/spree/core/spec/models/spree/company_spec.rb+++ b/spree/core/spec/models/spree/company_spec.rb@@ -55,19 +55,149 @@ describe Spree::Company, type: :model doendend- describe 'contacts' do- it 'collects the contacts of every location' do- company = create(:company, store: store)- first = create(:company_contact, company_location: create(:company_location, company: company))- second = create(:company_contact, company_location: create(:company_location, company: company))+ describe 'the tree' do+ let(:root) { create(:company, store: store) }++ it 'defaults a node to the company kind' do+ expect(Spree::Company.new.kind).to eq('company')+ end++ it 'refuses a division at the root' do+ expect(build(:company, store: store, kind: 'division')).not_to be_valid+ end++ it 'accepts a division under a company' do+ expect(build(:company, store: store, kind: 'division', parent: root)).to be_valid+ end++ it 'refuses a parent from another store' do+ foreign = create(:company, store: create(:store))++ expect(build(:company, store: store, parent: foreign)).not_to be_valid+ end++ it 'refuses a cycle' do+ child = create(:company, store: store, parent: root)+ root.parent = child++ expect(root).not_to be_valid+ expect(root.errors[:parent]).to be_present+ end++ it 'refuses to become its own parent' do+ root.parent = root++ expect(root).not_to be_valid+ end++ it 'caps the depth' do+ node = root+ (Spree::Company::MAX_DEPTH - 1).times do+ node = create(:company, store: store, parent: node)+ end++ expect(build(:company, store: store, parent: node)).not_to be_valid+ end++ it 'refuses re-parenting that pushes the subtree past the cap' do+ deep = root+ (Spree::Company::MAX_DEPTH - 2).times do+ deep = create(:company, store: store, parent: deep)+ end+ branch = create(:company, store: store)+ create(:company, store: store, parent: create(:company, store: store, parent: branch))++ branch.parent = deep++ expect(branch).not_to be_valid+ expect(branch.errors[:parent]).to be_present+ end++ it 'walks ancestors leaf to root' do+ child = create(:company, store: store, parent: root)+ grandchild = create(:company, store: store, parent: child)++ expect(grandchild.ancestors).to eq([child, root])+ expect(grandchild.self_and_ancestors).to eq([grandchild, child, root])+ expect(grandchild.root).to eq(root)+ end++ it 'collects the subtree' do+ child = create(:company, store: store, parent: root)+ grandchild = create(:company, store: store, parent: child)+ create(:company, store: store) # unrelated++ expect(root.self_and_descendants).to contain_exactly(root, child, grandchild)+ expect(root.descendants).to contain_exactly(child, grandchild)+ end++ it 'destroys the subtree with the node' do+ child = create(:company, store: store, parent: root)+ create(:company, store: store, parent: child)++ expect { root.destroy }.to change(Spree::Company, :count).by(-3)+ end+ end++ describe '#legal_entity' do+ let(:root) { create(:company, store: store) }++ it 'is the node itself for a company' do+ expect(root.legal_entity).to eq(root)+ end++ it 'is the nearest self-or-ancestor company for a division' do+ division = create(:company, store: store, kind: 'division', parent: root)+ nested = create(:company, store: store, kind: 'division', parent: division)++ expect(nested.legal_entity).to eq(root)+ end++ # A subsidiary never borrows its parent's registration: the walk stops at+ # the first company node whether or not it holds anything.+ it 'stops at the nearest company node' do+ subsidiary = create(:company, store: store, parent: root)+ division = create(:company, store: store, kind: 'division', parent: subsidiary)++ expect(division.legal_entity).to eq(subsidiary)+ end+ end++ describe 'kind changes' do+ it 'refuses turning a registration-holding company into a division' do+ root = create(:company, store: store)+ child = create(:company, store: store, parent: root)+ create(:tax_identifier, owner: child)++ child.kind = 'division'++ expect(child).not_to be_valid+ expect(child.errors[:kind]).to be_present+ end+ end++ describe 'default addresses' do+ let(:root) { create(:company, store: store) }+ let(:division) { create(:company, store: store, kind: 'division', parent: root) }++ it 'reads its own default first' do+ own = create(:company_address, company: division, default_billing: true)++ expect(division.default_billing_address).to eq(own.address)+ end++ it 'falls back to the nearest ancestor default' do+ inherited = create(:company_address, company: root, default_shipping: true)++ expect(division.default_shipping_address).to eq(inherited.address)+ end- expect(company.company_contacts).to contain_exactly(first, second)+ it 'is nil when nobody set one' do+ expect(division.default_billing_address).to be_nilendenddescribe 'metadata' do- # Spree::Metadata would shadow the real column with a virtual- # private_metadata and lose the write — see docs/plans/decisions.md.it 'persists to the single metadata column' docompany = create(:company, store: store, metadata: { 'erp_ref' => 'X-1' })@@ -75,11 +205,14 @@ describe Spree::Company, type: :model doendend- it 'destroys its locations and their contacts' do+ it 'destroys its memberships, addresses and invitations' docompany = create(:company, store: store)- create(:company_contact, company_location: create(:company_location, company: company))+ create(:company_membership, company: company)+ create(:company_address, company: company)+ create(:company_invitation, company: company)- expect { company.destroy }.to change(Spree::CompanyLocation, :count).by(-1).- and change(Spree::CompanyContact, :count).by(-1)+ expect { company.destroy }.to change(Spree::CompanyMembership, :count).by(-1).+ and change(Spree::CompanyAddress, :count).by(-1).+ and change(Spree::CompanyInvitation, :count).by(-1)endenddiff --git a/spree/core/spec/models/spree/tax_provider/internal_spec.rb b/spree/core/spec/models/spree/tax_provider/internal_spec.rbindex d4a5d414ef..2991ef344d 100644--- a/spree/core/spec/models/spree/tax_provider/internal_spec.rb+++ b/spree/core/spec/models/spree/tax_provider/internal_spec.rb@@ -157,9 +157,8 @@ describe Spree::TaxProvider::Internal, type: :model docontext 'with a certificate the buyer company holds' dolet!(:rate) { create(:tax_rate, country_code: country&.iso, amount: 0.1, tax_category: line_item.tax_category, included_in_price: false) }let(:company) { create(:company, store: @default_store) }- let(:location) { create(:company_location, company: company) }- before { order.update!(company_location: location) }+ before { order.update!(company: company) }def resolved_exemptionsSpree.tax_resolve_exemptions_service.new.call(order: order.reload).valuediff --git a/spree/core/spec/services/spree/companies/add_member_spec.rb b/spree/core/spec/services/spree/companies/add_member_spec.rbnew file mode 100644index 0000000000..0b5b538913--- /dev/null+++ b/spree/core/spec/services/spree/companies/add_member_spec.rb@@ -0,0 +1,49 @@+require 'spec_helper'++describe Spree::Companies::AddMember do+ let(:store) { @default_store }+ let(:company) { create(:company, store: store) }++ context 'when the email matches an existing customer' do+ let!(:customer) { create(:customer, email: '[email protected]') }++ it 'creates the membership immediately' do+ result = described_class.call(company: company, email: '[email protected]')++ expect(result).to be_success+ expect(result.value).to be_a(Spree::CompanyMembership)+ expect(result.value.customer).to eq(customer)+ end++ it 'refuses a duplicate membership' do+ create(:company_membership, company: company, customer: customer)++ expect(described_class.call(company: company, email: '[email protected]')).to be_failure+ end+ end++ context 'when the email is unknown' do+ it 'creates an invitation instead' do+ result = described_class.call(company: company, email: '[email protected]')++ expect(result).to be_success+ expect(result.value).to be_a(Spree::CompanyInvitation)+ expect(result.value.email).to eq('[email protected]')+ expect(result.value.inviter).to be_nil+ end++ it 'records the inviting member' do+ inviter = create(:customer)++ result = described_class.call(company: company, email: '[email protected]', inviter: inviter)++ expect(result.value.inviter).to eq(inviter)+ end++ it 'refuses a duplicate pending invitation' do+ create(:company_invitation, company: company, email: '[email protected]')++ expect(described_class.call(company: company, email: '[email protected]')).to be_failure+ end+ end+enddiff --git a/spree/core/spec/services/spree/company_invitations/accept_spec.rb b/spree/core/spec/services/spree/company_invitations/accept_spec.rbnew file mode 100644index 0000000000..4c7c545d77--- /dev/null+++ b/spree/core/spec/services/spree/company_invitations/accept_spec.rb@@ -0,0 +1,73 @@+require 'spec_helper'++describe Spree::CompanyInvitations::Accept do+ let(:store) { @default_store }+ let(:company) { create(:company, store: store) }+ let(:invitation) { create(:company_invitation, company: company, email: '[email protected]') }++ context 'with a registration payload' do+ it 'creates the customer through the registration workflow and lands as a membership' do+ result = described_class.call(+ invitation: invitation,+ customer_attributes: { password: 'Sup3r-secret', password_confirmation: 'Sup3r-secret',+ first_name: 'Ada' }+ )++ expect(result).to be_success+ membership = result.value+ expect(membership.company).to eq(company)+ # The account is created with the invited email, never a client-supplied one.+ expect(membership.customer.email).to eq('[email protected]')+ expect(invitation.reload).to be_accepted+ expect(invitation.customer).to eq(membership.customer)+ end++ it 'fails when registration fails and leaves the invitation pending' do+ result = described_class.call(invitation: invitation, customer_attributes: { password: 'short' })++ expect(result).to be_failure+ expect(invitation.reload).to be_pending+ end+ end++ context 'with an authenticated customer' do+ it 'binds the invitation to that customer' do+ customer = create(:customer)++ result = described_class.call(invitation: invitation, customer: customer)++ expect(result).to be_success+ expect(result.value.customer).to eq(customer)+ expect(invitation.reload.customer).to eq(customer)+ end++ it 'is idempotent for an existing member' do+ customer = create(:customer)+ membership = create(:company_membership, company: company, customer: customer)++ result = described_class.call(invitation: invitation, customer: customer)++ expect(result).to be_success+ expect(result.value).to eq(membership)+ expect(invitation.reload).to be_accepted+ end+ end++ it 'refuses an expired invitation' do+ invitation.update!(expires_at: 1.day.ago)++ expect(described_class.call(invitation: invitation, customer: create(:customer))).to be_failure+ end++ it 'refuses a revoked invitation' do+ invitation.revoke!++ expect(described_class.call(invitation: invitation, customer: create(:customer))).to be_failure+ end++ it 'refuses spending the token twice' do+ described_class.call(invitation: invitation, customer: create(:customer))++ expect(described_class.call(invitation: invitation, customer: create(:customer))).to be_failure+ end+enddiff --git a/spree/core/spec/services/spree/tax/resolve_exemptions_spec.rb b/spree/core/spec/services/spree/tax/resolve_exemptions_spec.rbindex 7b2291cef3..4d16fb7e98 100644--- a/spree/core/spec/services/spree/tax/resolve_exemptions_spec.rb+++ b/spree/core/spec/services/spree/tax/resolve_exemptions_spec.rb@@ -13,12 +13,14 @@ describe Spree::Tax::ResolveExemptions docontext 'for a business customer' dolet(:store) { @default_store }let(:company) { create(:company, store: store) }- let(:location) { create(:company_location, company: company) }+ # The purchase points at a division; certificates resolve through its+ # legal entity — the parent company node.+ let(:division) { create(:company, store: store, kind: 'division', parent: company) }let(:germany) { create(:country, iso: 'DE', name: 'Germany') }let(:berlin) { create(:state, country: germany, abbr: 'BE', name: 'Berlin') }before do- order.update!(company_location: location,+ order.update!(company: division,ship_address: create(:address, country: germany, state: berlin),bill_address: create(:address, country: germany, state: berlin))enddiff --git a/spree/core/spec/workflows/spree/carts/complete_spec.rb b/spree/core/spec/workflows/spree/carts/complete_spec.rbindex 8fc8b8d57b..56b79ca19b 100644--- a/spree/core/spec/workflows/spree/carts/complete_spec.rb+++ b/spree/core/spec/workflows/spree/carts/complete_spec.rb@@ -192,31 +192,30 @@ module Spreedescribe 'business customer' dolet(:customer) { create(:customer) }let(:company) { create(:company, store: store) }- let(:location) { create(:company_location, company: company) }before { ready_cart.update!(customer: customer) }# Without this the exemption applies during checkout and vanishes from the# placed order, so commit and refund work from different facts.- it 'carries the branch onto the order' do- ready_cart.update!(company_location: location)+ it 'carries the node onto the order' do+ create(:company_membership, company: company, customer: customer)+ ready_cart.update!(company: company)order = described_class.call(cart: ready_cart).value- expect(order.company_location).to eq(location)expect(order.company).to eq(company)end- it 'carries a branch the buyer resolved to without naming it' do- create(:company_contact, company_location: location, customer: customer)+ it 'carries a node the buyer resolved to without naming it' do+ create(:company_membership, company: company, customer: customer)order = described_class.call(cart: ready_cart.reload).value- expect(order.company_location).to eq(location)+ expect(order.company).to eq(company)end- it 'leaves a consumer order with no branch' do- expect(described_class.call(cart: ready_cart).value.company_location).to be_nil+ it 'leaves a consumer order with no company' do+ expect(described_class.call(cart: ready_cart).value.company).to be_nilendend@@ -248,8 +247,8 @@ module Spreeit 'stamps a company registration as such' docompany = create(:company, store: store)- location = create(:company_location, company: company)- ready_cart.update!(company_location: location)+ create(:company_membership, company: company, customer: customer)+ ready_cart.update!(company: company)create(:tax_identifier, owner: company, kind: 'eu_vat', value: 'DE777777777')order = described_class.call(cart: ready_cart).valuediff --git a/spree/emails/app/mailers/spree/company_mailer.rb b/spree/emails/app/mailers/spree/company_mailer.rbnew file mode 100644index 0000000000..590beddcf2--- /dev/null+++ b/spree/emails/app/mailers/spree/company_mailer.rb@@ -0,0 +1,35 @@+module Spree+ # Functional mail for the company directory — currently the invitation that+ # brings a not-yet-registered buyer into a company node. Like the staff+ # invitation, this is transactional, not marketing: the no-welcome-email+ # rule on customer creation is untouched.+ class CompanyMailer < BaseMailer+ helper Spree::MailHelper++ # The invite carries the plaintext token; the storefront owns the+ # acceptance page, so the link resolves against the store URL like other+ # customer-facing links.+ #+ # @param invitation [Spree::CompanyInvitation, Integer]+ def invitation_email(invitation)+ @invitation = invitation.respond_to?(:id) ? invitation : Spree::CompanyInvitation.find(invitation)+ @company = @invitation.company+ store = @company.store+ @accept_url = append_token(invitation_base_url(store), @invitation.token)++ with_store_locale(store) do+ mail(+ to: @invitation.email,+ subject: "#{store.name} #{Spree.t('company_mailer.invitation_email.subject', company: @company.name)}",+ store_url: store.storefront_url+ )+ end+ end++ private++ def invitation_base_url(store)+ "#{store.storefront_url.to_s.chomp('/')}/account/company-invitation"+ end+ end+enddiff --git a/spree/emails/app/subscribers/spree/company_email_subscriber.rb b/spree/emails/app/subscribers/spree/company_email_subscriber.rbnew file mode 100644index 0000000000..5c72ce7d97--- /dev/null+++ b/spree/emails/app/subscribers/spree/company_email_subscriber.rb@@ -0,0 +1,19 @@+# frozen_string_literal: true++module Spree+ # Sends the company invitation mail when an invitation is created. Riding+ # the event rather than the write path lets a host app silence it (consumer+ # transactional emails off) and send its own instead.+ class CompanyEmailSubscriber < Spree::Subscriber+ subscribes_to 'company_invitation.created'++ def handle(event)+ invitation = Spree::CompanyInvitation.find_by_prefix_id(event.payload['id'])+ return unless invitation+ return unless invitation.pending?+ return unless invitation.store&.prefers_send_consumer_transactional_emails?++ CompanyMailer.invitation_email(invitation.id).deliver_later+ end+ end+enddiff --git a/spree/emails/app/views/spree/company_mailer/invitation_email.html.erb b/spree/emails/app/views/spree/company_mailer/invitation_email.html.erbnew file mode 100644index 0000000000..09d85f7e52--- /dev/null+++ b/spree/emails/app/views/spree/company_mailer/invitation_email.html.erb@@ -0,0 +1,8 @@+<%= render layout: 'spree/shared/mailer_hero' do %>+ <h1><%= Spree.t('company_mailer.invitation_email.title', company: @company.name) %></h1>+ <p class="greeting"><%= Spree.t('company_mailer.invitation_email.greeting') %></p>+ <p><%= Spree.t('company_mailer.invitation_email.instructions', company: @company.name, store: current_store.name) %></p>+ <%= render 'spree/shared/mailer_button', url: @accept_url, label: Spree.t('company_mailer.invitation_email.action') %>+ <p class="sub"><%= Spree.t('company_mailer.invitation_email.expiry_notice') %></p>+ <p class="sub"><%= Spree.t('company_mailer.invitation_email.ignore_notice') %></p>+<% end %>diff --git a/spree/emails/app/views/spree/company_mailer/invitation_email.text.erb b/spree/emails/app/views/spree/company_mailer/invitation_email.text.erbnew file mode 100644index 0000000000..e8a062db66--- /dev/null+++ b/spree/emails/app/views/spree/company_mailer/invitation_email.text.erb@@ -0,0 +1,11 @@+<%= Spree.t('company_mailer.invitation_email.greeting') %>++<%= Spree.t('company_mailer.invitation_email.instructions', company: @company.name, store: current_store.name) %>++<%= Spree.t('company_mailer.invitation_email.action') %>: <%= @accept_url %>++<%= Spree.t('company_mailer.invitation_email.expiry_notice') %>++<%= Spree.t('company_mailer.invitation_email.ignore_notice') %>++<%= Spree.t('order_mailer.store_team', store_name: current_store.name) %>diff --git a/spree/emails/spec/mailers/spree/company_mailer_spec.rb b/spree/emails/spec/mailers/spree/company_mailer_spec.rbnew file mode 100644index 0000000000..585d3b0cab--- /dev/null+++ b/spree/emails/spec/mailers/spree/company_mailer_spec.rb@@ -0,0 +1,29 @@+require 'spec_helper'+require 'email_spec'++describe Spree::CompanyMailer, type: :mailer do+ include EmailSpec::Helpers+ include EmailSpec::Matchers++ let(:store) { @default_store }+ let(:company) { create(:company, store: store, name: 'Acme Industrial') }+ let(:invitation) { create(:company_invitation, company: company, email: '[email protected]') }++ describe '#invitation_email' do+ it 'sends to the invited email with the store-prefixed subject' do+ message = described_class.invitation_email(invitation)++ expect(message.to).to eq(['[email protected]'])+ expect(message.from).to eq([store.mail_from_address])+ expect(message.subject).to include(store.name)+ expect(message.subject).to include('Acme Industrial')+ end++ it 'links to the storefront acceptance page with the token appended' do+ message = described_class.invitation_email(invitation)++ expect(message).to have_body_text("token=#{invitation.token}")+ expect(message).to have_body_text('company-invitation')+ end+ end+enddiff --git a/spree/emails/spec/subscribers/spree/company_email_subscriber_spec.rb b/spree/emails/spec/subscribers/spree/company_email_subscriber_spec.rbnew file mode 100644index 0000000000..631bd4b460--- /dev/null+++ b/spree/emails/spec/subscribers/spree/company_email_subscriber_spec.rb@@ -0,0 +1,35 @@+require 'spec_helper'++describe Spree::CompanyEmailSubscriber do+ let(:store) { @default_store }+ let(:company) { create(:company, store: store) }++ def handle(invitation)+ event = instance_double(Spree::Event, payload: { 'id' => invitation.prefixed_id })+ described_class.new.handle(event)+ end++ it 'mails the invite when an invitation is created' do+ invitation = create(:company_invitation, company: company)++ expect {+ handle(invitation)+ }.to have_enqueued_job(ActionMailer::MailDeliveryJob).with(+ 'Spree::CompanyMailer', 'invitation_email', 'deliver_now', args: [invitation.id]+ )+ end++ it 'stays silent for an invitation that is no longer pending' do+ invitation = create(:company_invitation, company: company)+ invitation.revoke!++ expect { handle(invitation) }.not_to have_enqueued_job(ActionMailer::MailDeliveryJob)+ end++ it 'stays silent when the store has consumer transactional emails off' do+ invitation = create(:company_invitation, company: company)+ store.update!(preferences: store.preferences.merge(send_consumer_transactional_emails: false))++ expect { handle(invitation) }.not_to have_enqueued_job(ActionMailer::MailDeliveryJob)+ end+end