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
Close the gaps the review found in companies and catalogs
Damian Legawiec0a5eec15e1b9
diff --git a/docs/developer/core-concepts/companies-and-catalogs.mdx b/docs/developer/core-concepts/companies-and-catalogs.mdxindex 37030bb1b0..15f072cc7c 100644--- a/docs/developer/core-concepts/companies-and-catalogs.mdx+++ b/docs/developer/core-concepts/companies-and-catalogs.mdx@@ -39,7 +39,7 @@ erDiagramThree ideas carry the whole model:- **The tree is structure.** `Spree::Company` is self-referential (`parent_id`), store-scoped, and shallow — depth is capped at five levels. How many ship-to sites a node has never dictates how many nodes exist; addresses are just an address book.-- **Nodes are typed, and the type decides tax.** A `company` node is a legal entity; a `division` is an organizational unit. Tax registrations and exemption certificates exist only on legal entities, and a purchase's tax always resolves through the node's `legal_entity` — the nearest self-or-ancestor `company` node. A division *is* its legal entity; a subsidiary never borrows its parent's registration.+- **Nodes are typed, and the type decides tax.** A `company` node is a legal entity; a `division` is an organizational unit. Tax registrations and exemption certificates exist only on legal entities, and a purchase's tax always resolves through the node's `legal_entity` — for a `company` that is the node itself, and for a `division` it is its nearest `company` ancestor, whose registrations then cover the division's purchases. The walk stops at that first `company` node whether or not it holds any registration, so a subsidiary with no VAT number of its own has none — it never borrows its parent's.- **Membership is standing over a subtree.** A `CompanyMembership` joins a customer to a node, and that standing covers the node and everything below it. Any authorization question — "may this customer act for node N?" — is a membership check on N and its ancestors, never an equality check on one node.## Members and invitationsdiff --git a/packages/admin-sdk/examples/catalogs/list.ts b/packages/admin-sdk/examples/catalogs/list.tsindex 5c48ee2ab6..1a88f69995 100644--- a/packages/admin-sdk/examples/catalogs/list.ts+++ b/packages/admin-sdk/examples/catalogs/list.ts@@ -10,4 +10,5 @@ const { data: catalogs } = await client.catalogs.list({ active_eq: true })// endregion:example+/** Active catalogs in the store. */export { catalogs }diff --git a/packages/dashboard/src/hooks/use-companies.ts b/packages/dashboard/src/hooks/use-companies.tsindex 19c036055a..4af422fc4d 100644--- a/packages/dashboard/src/hooks/use-companies.ts+++ b/packages/dashboard/src/hooks/use-companies.ts@@ -88,6 +88,7 @@ export function useCompanyAddresses(companyId: string | undefined, page = 1, lim})}+/** Adds a labeled address to the node; the address row is owned by the entry. */export function useCreateCompanyAddress(companyId: string) {return useResourceMutation<CompanyAddress, Error, CompanyAddressParams>({mutationFn: (params) => adminClient.companies.addresses.create(companyId, params),@@ -97,6 +98,7 @@ export function useCreateCompanyAddress(companyId: string) {})}+/** Edits an entry in place — the address row is updated, never replaced. */export function useUpdateCompanyAddress(companyId: string) {return useResourceMutation<CompanyAddress, Error, { id: string; params: CompanyAddressParams }>({mutationFn: ({ id, params }) => adminClient.companyAddresses.update(id, params),@@ -106,6 +108,7 @@ export function useUpdateCompanyAddress(companyId: string) {})}+/** Removes an entry and the address row it owned. */export function useDeleteCompanyAddress(companyId: string) {return useResourceMutation<void, Error, string>({mutationFn: (id) => adminClient.companyAddresses.delete(id),@@ -149,6 +152,7 @@ export function useAddCompanyMember(companyId: string) {})}+/** Withdraws a member's standing; the customer account is untouched. */export function useDeleteCompanyMembership(companyId: string) {return useResourceMutation<void, Error, string>({mutationFn: (id) => adminClient.companyMemberships.delete(id),@@ -171,6 +175,7 @@ export function useCompanyInvitations(companyId: string | undefined, page = 1, l})}+/** Revokes a pending invitation, so its emailed token stops resolving. */export function useRevokeCompanyInvitation(companyId: string) {return useResourceMutation<void, Error, string>({mutationFn: (id) => adminClient.companyInvitations.delete(id),diff --git a/packages/dashboard/src/locales/pl.json b/packages/dashboard/src/locales/pl.jsonindex 88b3d1583f..e19b167c1a 100644--- a/packages/dashboard/src/locales/pl.json+++ b/packages/dashboard/src/locales/pl.json@@ -150,7 +150,7 @@"remove_confirm": {"message_few": "Usunąć {{count}} produkty z tego katalogu? Zmiana działa natychmiast. Produkty pozostają w sklepie.","message_many": "Usunąć {{count}} produktów z tego katalogu? Zmiana działa natychmiast. Produkty pozostają w sklepie.",- "message_named": "Usunąć „{{name}}\" z tego katalogu? Zmiana działa natychmiast. Produkt pozostaje w sklepie.",+ "message_named": "Usunąć „{{name}}” z tego katalogu? Zmiana działa natychmiast. Produkt pozostaje w sklepie.","message_one": "Usunąć {{count}} produkt z tego katalogu? Zmiana działa natychmiast. Produkty pozostają w sklepie.","message_other": "Usunąć {{count}} produktów z tego katalogu? Zmiana działa natychmiast. Produkty pozostają w sklepie.","title": "Usuń z katalogu"diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/companies/$companyId.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/companies/$companyId.tsxindex ed8e4264df..cc214e5c06 100644--- a/packages/dashboard/src/routes/_authenticated/$storeId/companies/$companyId.tsx+++ b/packages/dashboard/src/routes/_authenticated/$storeId/companies/$companyId.tsx@@ -734,7 +734,9 @@ function PendingInvitations({ company, canEdit }: { company: Company; canEdit: bconst { data } = useCompanyInvitations(company.id, page)const revokeMutation = useRevokeCompanyInvitation(company.id)- const pending = (data?.data ?? []).filter((invitation) => invitation.status === 'pending')+ // The endpoint returns pending invitations only, so the count and pages+ // describe the same set the panel renders.+ const pending = data?.data ?? []const meta = data?.metaif (pending.length === 0) return nulldiff --git a/packages/dashboard/src/routes/_authenticated/$storeId/products/catalogs/$catalogId.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/products/catalogs/$catalogId.tsxindex 759192a51e..a36c3d6e2d 100644--- a/packages/dashboard/src/routes/_authenticated/$storeId/products/catalogs/$catalogId.tsx+++ b/packages/dashboard/src/routes/_authenticated/$storeId/products/catalogs/$catalogId.tsx@@ -67,6 +67,7 @@ import {catalogValuesToParams,} from '../../../../../schemas/catalog'+/** One catalog: its assortment, pricing and the audiences that see it. */export const Route = createFileRoute('/_authenticated/$storeId/products/catalogs/$catalogId')({component: CatalogDetailPage,})diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/products/catalogs/index.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/products/catalogs/index.tsxindex 2cebf7b9bd..f19196e5f7 100644--- a/packages/dashboard/src/routes/_authenticated/$storeId/products/catalogs/index.tsx+++ b/packages/dashboard/src/routes/_authenticated/$storeId/products/catalogs/index.tsx@@ -44,6 +44,7 @@ const catalogsSearchSchema = resourceSearchSchema.extend({new: z.coerce.boolean().optional(),})+/** Catalogs list: assortments and their audiences, under Products. */export const Route = createFileRoute('/_authenticated/$storeId/products/catalogs/')({validateSearch: catalogsSearchSchema,component: CatalogsPage,@@ -120,11 +121,18 @@ function CatalogsPage() {</Button></Can>}- reorder={{- onReorder: async (id, position) => {- await adminClient.catalogs.update(id, { position })- },- }}+ // Dragging fires an update request, so offer it only to callers who+ // may actually update — otherwise the row moves and springs back on+ // the 403.+ reorder={+ permissions.can('update', Subject.Catalog)+ ? {+ onReorder: async (id, position) => {+ await adminClient.catalogs.update(id, { position })+ },+ }+ : undefined+ }/>{isCreating && <CreateCatalogSheet open onOpenChange={(o) => !o && closeSheet()} />}diff --git a/packages/dashboard/src/schemas/catalog.ts b/packages/dashboard/src/schemas/catalog.tsindex 98164b3b19..0ca41bbeed 100644--- a/packages/dashboard/src/schemas/catalog.ts+++ b/packages/dashboard/src/schemas/catalog.ts@@ -3,6 +3,7 @@ import { blankToNull } from '@spree/dashboard-core'import { requiredMessage } from '@spree/dashboard-ui'import { z } from 'zod/v4'+/** Validation for the catalog create sheet and settings card. */export const catalogFormSchema = z.object({name: z.string().min(1, { error: requiredMessage('name') }),active: z.boolean(),@@ -10,10 +11,16 @@ export const catalogFormSchema = z.object({price_list_id: z.string().optional(),})+/** Values the catalog form holds. */export type CatalogFormValues = z.infer<typeof catalogFormSchema>+/** A new catalog: named on create, active, priced by base prices. */export const CATALOG_DEFAULTS: CatalogFormValues = { name: '', active: true, price_list_id: '' }+/**+ * Maps form values to the Admin API payload; a blank price list means+ * "no list", which leaves the catalog pricing through base prices.+ */export function catalogValuesToParams(values: CatalogFormValues): CatalogParams {return {name: values.name,diff --git a/packages/sdk/examples/account-companies/list.ts b/packages/sdk/examples/account-companies/list.tsnew file mode 100644index 0000000000..607bdcdbc8--- /dev/null+++ b/packages/sdk/examples/account-companies/list.ts@@ -0,0 +1,14 @@+import { createClient } from '@spree/sdk'++const client = createClient({+ baseUrl: 'https://your-store.com',+ publishableKey: '<api-key>',+})++// region:example+// The buyer's memberships, each carrying its node and the path above it.+const { data: memberships } = await client.account.companies({ token: '<token>' })++// endregion:example++export { memberships }diff --git a/packages/sdk/examples/companies/get.ts b/packages/sdk/examples/companies/get.tsnew file mode 100644index 0000000000..3c6da87a15--- /dev/null+++ b/packages/sdk/examples/companies/get.ts@@ -0,0 +1,13 @@+import { createClient } from '@spree/sdk'++const client = createClient({+ baseUrl: 'https://your-store.com',+ publishableKey: '<api-key>',+})++// region:example+const company = await client.companies.get('comp_86Rf07xd4z', { token: '<token>' })++// endregion:example++export { company }diff --git a/packages/sdk/examples/companies/members-create.ts b/packages/sdk/examples/companies/members-create.tsnew file mode 100644index 0000000000..98ec55fd2c--- /dev/null+++ b/packages/sdk/examples/companies/members-create.ts@@ -0,0 +1,19 @@+import { createClient } from '@spree/sdk'++const client = createClient({+ baseUrl: 'https://your-store.com',+ publishableKey: '<api-key>',+})++// region:example+// An existing customer joins immediately (cmem_…); anyone else is emailed an+// invitation (cinv_…).+const member = await client.companies.members.create(+ 'comp_86Rf07xd4z',+ { customer_email: '[email protected]' },+ { token: '<token>' },+)++// endregion:example++export { member }diff --git a/packages/sdk/examples/company-invitations/accept.ts b/packages/sdk/examples/company-invitations/accept.tsnew file mode 100644index 0000000000..21a2643a68--- /dev/null+++ b/packages/sdk/examples/company-invitations/accept.ts@@ -0,0 +1,19 @@+import { createClient } from '@spree/sdk'++const client = createClient({+ baseUrl: 'https://your-store.com',+ publishableKey: '<api-key>',+})++// region:example+// Unauthenticated: the token from the invite email is the credential, and the+// registration payload creates the account with the invited address.+const membership = await client.companyInvitations.accept('<invitation-token>', {+ first_name: 'Ada',+ password: 'a-strong-password',+ password_confirmation: 'a-strong-password',+})++// endregion:example++export { membership }diff --git a/spree/api/app/controllers/spree/api/v3/admin/catalogs_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/catalogs_controller.rbindex 9d1df967f8..018425b800 100644--- a/spree/api/app/controllers/spree/api/v3/admin/catalogs_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/admin/catalogs_controller.rb@@ -86,11 +86,17 @@ module Spree'market' => ->(store) { store.markets }}.freeze+ # Scoped by the store AND by what this caller may see: a role that+ # reaches only some companies must not be able to assign a catalog+ # to one it cannot read, and an unreadable record is not-found+ # rather than refused so its existence does not leak.def find_assignablescope_builder = ASSIGNABLE_SCOPES[params.require(:assignable_type).to_s]raise ActiveRecord::RecordNotFound if scope_builder.nil?- scope_builder.call(current_store).find_by_prefix_id!(params.require(:assignable_id))+ scope_builder.call(current_store).+ accessible_by(current_ability, :show).+ find_by_prefix_id!(params.require(:assignable_id))endendenddiff --git a/spree/api/app/controllers/spree/api/v3/admin/companies/invitations_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/companies/invitations_controller.rbindex a9f76f52a9..ec0ffbd057 100644--- a/spree/api/app/controllers/spree/api/v3/admin/companies/invitations_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/admin/companies/invitations_controller.rb@@ -18,8 +18,12 @@ module SpreeSpree.api.admin_company_invitation_serializerend+ # Pending only, and narrowed before pagination: a page of spent+ # invitations would otherwise push live ones out of the first+ # page and make the row count describe the wrong set. Spent and+ # revoked rows are history, not a work list.def scope- @parent.invitations+ @parent.invitations.pendingenddef parent_associationdiff --git a/spree/api/spec/controllers/spree/api/v3/admin/catalogs_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/catalogs_controller_spec.rbindex 0fb3aee64f..55c7cb8ac7 100644--- a/spree/api/spec/controllers/spree/api/v3/admin/catalogs_controller_spec.rb+++ b/spree/api/spec/controllers/spree/api/v3/admin/catalogs_controller_spec.rb@@ -98,6 +98,18 @@ RSpec.describe Spree::Api::V3::Admin::CatalogsController, type: :controller doexpect(response).to have_http_status(:not_found)end+ # Store scope is not enough: a role that cannot see a company must not be+ # able to assign a catalog to it, and not-found keeps its existence quiet.+ it '404s an audience the caller may not see' do+ company = create(:company, store: store)+ allow_any_instance_of(described_class).to receive(:current_ability).+ and_return(Spree::Ability.new(nil))++ post :assign, params: { id: catalog.prefixed_id, assignable_type: 'company', assignable_id: company.prefixed_id }, as: :json++ expect(response).to have_http_status(:not_found)+ end+it '404s an unknown audience type' dopost :assign, params: { id: catalog.prefixed_id, assignable_type: 'order', assignable_id: 'x' }, as: :jsondiff --git a/spree/api/spec/controllers/spree/api/v3/admin/companies/invitations_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/companies/invitations_controller_spec.rbindex 1407d3c81d..05a1a67ee3 100644--- a/spree/api/spec/controllers/spree/api/v3/admin/companies/invitations_controller_spec.rb+++ b/spree/api/spec/controllers/spree/api/v3/admin/companies/invitations_controller_spec.rb@@ -10,17 +10,21 @@ RSpec.describe Spree::Api::V3::Admin::Companies::InvitationsController, type: :cbefore { request.headers.merge!(headers) }describe 'GET #index' do- it 'lists the node invitations with their derived status' do+ # Narrowed in the endpoint, before pagination — a page of spent rows would+ # otherwise push live invitations off the first page and make the count+ # describe the wrong set.+ it 'lists the pending invitations and leaves spent ones out' dopending_invitation = create(:company_invitation, company: company)expired = create(:company_invitation, company: company)expired.update!(expires_at: 1.day.ago)+ revoked = create(:company_invitation, company: company)+ revoked.revoke!get :index, params: { company_id: company.prefixed_id }, as: :jsonexpect(response).to have_http_status(:ok)- statuses = json_response['data'].to_h { |row| [row['id'], row['status']] }- expect(statuses[pending_invitation.prefixed_id]).to eq('pending')- expect(statuses[expired.prefixed_id]).to eq('expired')+ rows = json_response['data'].to_h { |row| [row['id'], row['status']] }+ expect(rows).to eq(pending_invitation.prefixed_id => 'pending')endit '404s under another store company' dodiff --git a/spree/api/spec/integration/spree/api/v3/store/companies_spec.rb b/spree/api/spec/integration/spree/api/v3/store/companies_spec.rbnew file mode 100644index 0000000000..58958f68a2--- /dev/null+++ b/spree/api/spec/integration/spree/api/v3/store/companies_spec.rb@@ -0,0 +1,304 @@+# frozen_string_literal: true++require 'swagger_helper'++RSpec.describe 'Company Self-Service API', type: :request, swagger_doc: 'api-reference/store.yaml' do+ include_context 'API v3 Store'++ let(:user) { create(:user_with_addresses) }+ let(:company) { create(:company, store: store, name: 'Acme Industrial') }++ path '/api/v3/store/account/companies' do+ get 'List my company memberships' do+ tags 'Companies'+ produces 'application/json'+ security [api_key: [], bearer_auth: []]+ description <<~DESC+ Returns the authenticated customer's company memberships, each with the node it+ is held on and the path of nodes above it. Standing covers the node and every+ node below it, so a membership on a parent authorizes buying for its divisions.+ DESC++ sdk_example 'account-companies/list'++ parameter name: 'x-spree-api-key', in: :header, type: :string, required: true+ parameter name: 'Authorization', in: :header, type: :string, required: true++ response '200', 'memberships listed' do+ let!(:membership) { create(:company_membership, company: company, customer: user) }+ let(:'x-spree-api-key') { api_key.token }+ let(:'Authorization') { "Bearer #{jwt_token}" }++ run_test! do |response|+ data = JSON.parse(response.body)+ expect(data['data'].first['company']['name']).to eq('Acme Industrial')+ end+ end++ response '401', 'not authenticated' do+ let(:'x-spree-api-key') { api_key.token }+ let(:'Authorization') { nil }++ run_test!+ end+ end+ end++ path '/api/v3/store/companies/{id}' do+ parameter name: :id, in: :path, type: :string, required: true, description: 'Company node ID (comp_...)'++ get 'Get a company node' do+ tags 'Companies'+ produces 'application/json'+ security [api_key: [], bearer_auth: []]+ description <<~DESC+ Returns one node of the buyer's organization. Requires standing — a membership on+ the node or on one of its ancestors; any other node is not found rather than+ refused, so its existence is not disclosed.+ DESC++ sdk_example 'companies/get'++ parameter name: 'x-spree-api-key', in: :header, type: :string, required: true+ parameter name: 'Authorization', in: :header, type: :string, required: true++ response '200', 'company found' do+ let!(:membership) { create(:company_membership, company: company, customer: user) }+ let(:id) { company.prefixed_id }+ let(:'x-spree-api-key') { api_key.token }+ let(:'Authorization') { "Bearer #{jwt_token}" }++ run_test! do |response|+ expect(JSON.parse(response.body)['name']).to eq('Acme Industrial')+ end+ end++ response '404', 'no standing over this node' do+ let(:id) { company.prefixed_id }+ let(:'x-spree-api-key') { api_key.token }+ let(:'Authorization') { "Bearer #{jwt_token}" }++ run_test!+ end+ end++ patch 'Update a company node' do+ tags 'Companies'+ consumes 'application/json'+ produces 'application/json'+ security [api_key: [], bearer_auth: []]+ description 'Renames the node. Structure — the parent and the kind — is managed by the merchant, not by buyers.'++ parameter name: 'x-spree-api-key', in: :header, type: :string, required: true+ parameter name: 'Authorization', in: :header, type: :string, required: true+ parameter name: :body, in: :body, schema: {+ type: :object,+ properties: { name: { type: :string, example: 'Acme Industrial Group' } }+ }++ response '200', 'company updated' do+ let!(:membership) { create(:company_membership, company: company, customer: user) }+ let(:id) { company.prefixed_id }+ let(:body) { { name: 'Acme Industrial Group' } }+ let(:'x-spree-api-key') { api_key.token }+ let(:'Authorization') { "Bearer #{jwt_token}" }++ run_test! do |response|+ expect(JSON.parse(response.body)['name']).to eq('Acme Industrial Group')+ end+ end+ end+ end++ path '/api/v3/store/companies/{company_id}/members' do+ parameter name: :company_id, in: :path, type: :string, required: true, description: 'Company node ID (comp_...)'++ get 'List company members' do+ tags 'Companies'+ produces 'application/json'+ security [api_key: [], bearer_auth: []]+ description 'The people with standing over this node. Within a company every member may read and manage the directory.'++ parameter name: 'x-spree-api-key', in: :header, type: :string, required: true+ parameter name: 'Authorization', in: :header, type: :string, required: true++ response '200', 'members listed' do+ let!(:membership) { create(:company_membership, company: company, customer: user) }+ let(:company_id) { company.prefixed_id }+ let(:'x-spree-api-key') { api_key.token }+ let(:'Authorization') { "Bearer #{jwt_token}" }++ run_test! do |response|+ expect(JSON.parse(response.body)['data'].first['email']).to eq(user.email)+ end+ end+ end++ post 'Add a member by email' do+ tags 'Companies'+ consumes 'application/json'+ produces 'application/json'+ security [api_key: [], bearer_auth: []]+ description <<~DESC+ Adds a person to the node by email. An email that already belongs to a customer of+ this store becomes a membership immediately (a `cmem_...` id); any other email+ becomes an invitation (a `cinv_...` id) and the invite email goes out.+ DESC++ sdk_example 'companies/members-create'++ parameter name: 'x-spree-api-key', in: :header, type: :string, required: true+ parameter name: 'Authorization', in: :header, type: :string, required: true+ parameter name: :body, in: :body, schema: {+ type: :object,+ properties: { customer_email: { type: :string, example: '[email protected]' } },+ required: ['customer_email']+ }++ response '201', 'member added or invitation sent' do+ let!(:membership) { create(:company_membership, company: company, customer: user) }+ let!(:colleague) { create(:customer, email: '[email protected]') }+ let(:company_id) { company.prefixed_id }+ let(:body) { { customer_email: '[email protected]' } }+ let(:'x-spree-api-key') { api_key.token }+ let(:'Authorization') { "Bearer #{jwt_token}" }++ run_test! do |response|+ expect(JSON.parse(response.body)['email']).to eq('[email protected]')+ end+ end+ end+ end++ path '/api/v3/store/companies/{company_id}/addresses' do+ parameter name: :company_id, in: :path, type: :string, required: true, description: 'Company node ID (comp_...)'++ get 'List the company address book' do+ tags 'Companies'+ produces 'application/json'+ security [api_key: [], bearer_auth: []]+ description 'The labeled ship-to and bill-to sites this node owns. A node with no default of its own falls back to its nearest ancestor when prefilling checkout.'++ parameter name: 'x-spree-api-key', in: :header, type: :string, required: true+ parameter name: 'Authorization', in: :header, type: :string, required: true++ response '200', 'addresses listed' do+ let!(:membership) { create(:company_membership, company: company, customer: user) }+ let!(:entry) { create(:company_address, company: company, label: 'Headquarters') }+ let(:company_id) { company.prefixed_id }+ let(:'x-spree-api-key') { api_key.token }+ let(:'Authorization') { "Bearer #{jwt_token}" }++ run_test! do |response|+ expect(JSON.parse(response.body)['data'].first['label']).to eq('Headquarters')+ end+ end+ end+ end++ path '/api/v3/store/companies/{company_id}/orders' do+ parameter name: :company_id, in: :path, type: :string, required: true, description: 'Company node ID (comp_...)'++ get 'List the company purchases' do+ tags 'Companies'+ produces 'application/json'+ security [api_key: [], bearer_auth: []]+ description 'Completed orders placed for this node and every node below it, so a parent sees what its divisions bought.'++ parameter name: 'x-spree-api-key', in: :header, type: :string, required: true+ parameter name: 'Authorization', in: :header, type: :string, required: true++ response '200', 'orders listed' do+ let!(:membership) { create(:company_membership, company: company, customer: user) }+ let!(:order) do+ create(:completed_order_with_totals, store: store).tap { |o| o.update_columns(company_id: company.id) }+ end+ let(:company_id) { company.prefixed_id }+ let(:'x-spree-api-key') { api_key.token }+ let(:'Authorization') { "Bearer #{jwt_token}" }++ run_test! do |response|+ expect(JSON.parse(response.body)['data'].map { |o| o['id'] }).to include(order.prefixed_id)+ end+ end+ end+ end++ path '/api/v3/store/company_invitations/{token}' do+ parameter name: :token, in: :path, type: :string, required: true, description: 'Plaintext invitation token from the invite email'++ get 'Look up an invitation' do+ tags 'Companies'+ produces 'application/json'+ security [api_key: []]+ description <<~DESC+ Shows what is being joined, so the acceptance page can render before the invitee+ has an account. Deliberately unauthenticated — the token from the email is the+ credential. Spent, revoked and expired tokens are not found.+ DESC++ parameter name: 'x-spree-api-key', in: :header, type: :string, required: true++ response '200', 'invitation found' do+ let!(:invitation) { create(:company_invitation, company: company, email: '[email protected]') }+ let(:token) { invitation.token }+ let(:'x-spree-api-key') { api_key.token }++ run_test! do |response|+ data = JSON.parse(response.body)+ expect(data['company_name']).to eq('Acme Industrial')+ expect(data).not_to have_key('token')+ end+ end++ response '404', 'token spent, revoked or expired' do+ let(:token) { 'no-such-token' }+ let(:'x-spree-api-key') { api_key.token }++ run_test!+ end+ end+ end++ path '/api/v3/store/company_invitations/{token}/accept' do+ parameter name: :token, in: :path, type: :string, required: true, description: 'Plaintext invitation token from the invite email'++ post 'Accept an invitation' do+ tags 'Companies'+ consumes 'application/json'+ produces 'application/json'+ security [api_key: []]+ description <<~DESC+ Turns the invitation into a membership. Send a registration payload to create the+ account — it is always created with the invited email — or call it authenticated as+ the customer who owns that email to bind the invitation to the existing account.+ DESC++ sdk_example 'company-invitations/accept'++ parameter name: 'x-spree-api-key', in: :header, type: :string, required: true+ parameter name: :body, in: :body, schema: {+ type: :object,+ properties: {+ first_name: { type: :string, example: 'Ada' },+ last_name: { type: :string, example: 'Lovelace' },+ password: { type: :string, example: 'a-strong-password' },+ password_confirmation: { type: :string, example: 'a-strong-password' }+ }+ }++ response '201', 'membership created' do+ let!(:invitation) { create(:company_invitation, company: company, email: '[email protected]') }+ let(:token) { invitation.token }+ let(:body) do+ { first_name: 'Ada', password: 'a-strong-password', password_confirmation: 'a-strong-password' }+ end+ let(:'x-spree-api-key') { api_key.token }++ run_test! do |response|+ expect(JSON.parse(response.body)['email']).to eq('[email protected]')+ end+ end+ end+ end+enddiff --git a/spree/core/app/models/spree/catalog.rb b/spree/core/app/models/spree/catalog.rbindex 18b53d987e..ab1d564a23 100644--- a/spree/core/app/models/spree/catalog.rb+++ b/spree/core/app/models/spree/catalog.rb@@ -49,8 +49,13 @@ module Spreereturn [] if company.nil?nodes = company.self_and_ancestors+ # Constrained to the company's own store as well as its nodes: the+ # assignment validates same-store on write, but a read that trusts the+ # write path would hand another tenant's catalog to this buyer if a row+ # ever arrived past it (raw SQL, an import, a bypass).assignments = Spree::CatalogAssignment.where(assignable_type: 'Spree::Company', assignable_id: nodes.map(&:id)).+ where(catalog_id: for_store(company.store).select(:id)).includes(:catalog).group_by(&:assignable_id)@@ -62,13 +67,20 @@ module Spree# The catalogs assigned to any of the given customer groups, by position.## @param customer_groups [Enumerable<Spree::CustomerGroup>]+ # @param store [Spree::Store, nil] narrows to that store's catalogs;+ # defaults to the groups' own store, which is the same thing whenever+ # the caller passed one store's groups# @return [Array<Spree::Catalog>]- def self.effective_for_customer_groups(customer_groups)- ids = Array(customer_groups).map(&:id)+ def self.effective_for_customer_groups(customer_groups, store: nil)+ groups = Array(customer_groups)+ ids = groups.map(&:id)return [] if ids.empty?+ store ||= groups.first.store+Spree::CatalogAssignment.where(assignable_type: 'Spree::CustomerGroup', assignable_id: ids).+ where(catalog_id: for_store(store).select(:id)).includes(:catalog).map(&:catalog).select(&:active?).sort_by { |catalog| catalog.position.to_i }.uniqenddiff --git a/spree/core/app/models/spree/company.rb b/spree/core/app/models/spree/company.rbindex f01915da10..ffc22d2e13 100644--- a/spree/core/app/models/spree/company.rb+++ b/spree/core/app/models/spree/company.rb@@ -59,6 +59,12 @@ module Spreevalidate :depth_within_capvalidate :kind_change_keeps_tax_anchor+ # prepend: `dependent: :destroy` on children registers its own+ # before_destroy when the association is declared, so without this the+ # subtree would already be deleted by the time the guard reads it — and+ # each child skips its own guard as destroyed_by_association.+ before_destroy :ensure_can_be_deleted, prepend: true+scope :roots, -> { where(parent_id: nil) }# The subtree rooted at the given node(s) — the node itself plus every@@ -149,6 +155,18 @@ module Spreeancestors.length + 1end+ # Whether the node can be destroyed. Deleting takes the whole subtree+ # (+dependent: :destroy+ on children), and there is no foreign key behind+ # +spree_orders.company_id+ — so a placed order anywhere below would be+ # left pointing at nothing, losing the tax anchor that explains how it+ # was taxed. Carts are not counted: an in-flight basket is not a record+ # anyone has to explain later, and the column simply clears.+ #+ # @return [Boolean]+ def can_be_deleted?+ !Spree::Order.where(company_id: self_and_descendants.select(:id)).exists?+ 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.@@ -165,6 +183,17 @@ module Spreeprivate+ def ensure_can_be_deleted+ # Descendants are destroyed by the association, and the root's own guard+ # already covered the whole subtree; the store's destruction cascades+ # past this the same way it does for markets.+ return if destroyed_by_association+ return if can_be_deleted?++ errors.add(:base, :cannot_destroy_with_orders)+ throw(:abort)+ end+def default_address(flag)self_and_ancestors.each do |node|row = node.company_addresses.where(flag => true).firstdiff --git a/spree/core/app/services/spree/company_invitations/accept.rb b/spree/core/app/services/spree/company_invitations/accept.rbindex 53c489c29e..c2208eb039 100644--- a/spree/core/app/services/spree/company_invitations/accept.rb+++ b/spree/core/app/services/spree/company_invitations/accept.rb@@ -16,6 +16,11 @@ module Spree# Spree::CompanyMembershipdef call(invitation:, customer: nil, customer_attributes: nil)return failure(invitation, :invitation_not_pending) unless invitation.pending?+ # The token names one person. Without this, anyone holding it could+ # spend it from an unrelated signed-in account and take standing over+ # the company — which authorizes buying, reading the subtree's orders+ # and revoking the other members' invitations.+ return failure(invitation, :invitation_email_mismatch) unless invited_email?(invitation, customer)if customer.nil?result = Spree.customer_create_workflow.call(@@ -39,6 +44,17 @@ module Spreerescue ActiveRecord::RecordInvalid => efailure(e.record)end++ private++ # Compared the way the invitation stores it — normalized, since a+ # customer signed up as "[email protected]" is the same person the+ # invitation went to.+ def invited_email?(invitation, customer)+ return true if customer.nil?++ customer.email.to_s.strip.downcase == invitation.email+ endendendenddiff --git a/spree/core/app/services/spree/products/for_context.rb b/spree/core/app/services/spree/products/for_context.rbindex 36d01a61ac..0392ab935a 100644--- a/spree/core/app/services/spree/products/for_context.rb+++ b/spree/core/app/services/spree/products/for_context.rb@@ -48,22 +48,33 @@ module Spreeprivate+ # The node a buyer browses as when they name none: the single node they+ # hold a membership on.+ #+ # Deliberately the membership node rather than+ # +Customer#company_standing+, which expands to the whole subtree — a+ # buyer with one membership over a parent with three divisions has+ # standing for four nodes but is still unambiguous, and counting the+ # expansion would refuse to resolve. Where standing covers several+ # nodes the buyer picks one on the cart, and catalogs follow that+ # choice; matches +Purchase::Company#resolved_company+ exactly, so+ # what they browse and what they are charged agree.def sole_standing_company(store, customer)return nil if customer.nil?- memberships = customer.company_memberships.- joins(:company).- merge(Spree::Company.where(store_id: store.id)).- to_a.uniq+ companies = customer.company_memberships.+ joins(:company).+ merge(Spree::Company.where(store_id: store.id)).+ map(&:company).uniq- memberships.one? ? memberships.first.company : nil+ companies.one? ? companies.first : nilenddef customer_group_catalogs(store, customer)return [] if customer.nil?groups = customer.customer_groups.where(store_id: store.id)- Spree::Catalog.effective_for_customer_groups(groups)+ Spree::Catalog.effective_for_customer_groups(groups, store: store)endendenddiff --git a/spree/core/config/locales/en.yml b/spree/core/config/locales/en.ymlindex 3e75c6ef7f..e2f3d0e72f 100644--- a/spree/core/config/locales/en.yml+++ b/spree/core/config/locales/en.yml@@ -261,6 +261,8 @@ en:already_linked: is already linked to this productspree/company:attributes:+ base:+ cannot_destroy_with_orders: Cannot delete a company that has placed orders, or whose divisions have.kind:anchors_descendant_divisions: cannot become a division while divisions below it anchor their tax identity hereholds_tax_registrations: cannot become a division while holding tax registrations or exemption certificates@@ -748,6 +750,7 @@ en:companies: Companiescompany: Companycompany_invitations:+ email_mismatch: This invitation was sent to a different email address.not_pending: This invitation is no longer pending and cannot be revoked.company_mailer:invitation_email:diff --git a/spree/core/spec/models/spree/catalog_spec.rb b/spree/core/spec/models/spree/catalog_spec.rbindex b95593a1c1..8f68d4c801 100644--- a/spree/core/spec/models/spree/catalog_spec.rb+++ b/spree/core/spec/models/spree/catalog_spec.rb@@ -98,6 +98,27 @@ describe Spree::Catalog, type: :model doendend+ # The assignment validates same-store on write; the read must not trust it,+ # or a row that arrived past the validation would hand another tenant's+ # catalog to this buyer.+ describe 'store scoping in resolution' do+ it 'ignores an assignment pointing at another store catalog' do+ company = create(:company, store: store)+ foreign_catalog = create(:catalog, store: create(:store))+ Spree::CatalogAssignment.new(catalog: foreign_catalog, assignable: company).save(validate: false)++ expect(described_class.effective_for_company(company)).to eq([])+ end++ it 'ignores a foreign catalog assigned to a customer group' do+ group = create(:customer_group, store: store)+ foreign_catalog = create(:catalog, store: create(:store))+ Spree::CatalogAssignment.new(catalog: foreign_catalog, assignable: group).save(validate: false)++ expect(described_class.effective_for_customer_groups([group], store: store)).to eq([])+ end+ end+describe '#import_products_from_price_list' dolet(:product) { create(:product, store: store, price: 100) }let(:price_list) dodiff --git a/spree/core/spec/models/spree/company_spec.rb b/spree/core/spec/models/spree/company_spec.rbindex 3f31dadb3c..3b7fa30c94 100644--- a/spree/core/spec/models/spree/company_spec.rb+++ b/spree/core/spec/models/spree/company_spec.rb@@ -229,6 +229,39 @@ describe Spree::Company, type: :model doendend+ describe 'deletion' do+ # There is no foreign key behind spree_orders.company_id and children are+ # destroyed with the node, so an unguarded delete would strand a placed+ # order — losing the anchor that explains how it was taxed.+ it 'refuses while an order was placed for the node' do+ company = create(:company, store: store)+ order = create(:completed_order_with_totals, store: store)+ order.update_columns(company_id: company.id)++ expect(company.destroy).to be(false)+ expect(company.errors[:base]).to be_present+ expect(Spree::Company.where(id: company.id)).to exist+ end++ it 'refuses while a division below it has orders' do+ root = create(:company, store: store)+ division = create(:company, store: store, kind: 'division', parent: root)+ order = create(:completed_order_with_totals, store: store)+ order.update_columns(company_id: division.id)++ expect(root.destroy).to be(false)+ expect(Spree::Company.where(id: division.id)).to exist+ end++ # An in-flight basket is not a record anyone has to explain later.+ it 'allows deletion with only carts attached' do+ company = create(:company, store: store)+ create(:cart, store: store).update_columns(company_id: company.id)++ expect(company.destroy).to be_truthy+ end+ end+it 'destroys its memberships, addresses and invitations' docompany = create(:company, store: store)create(:company_membership, company: company)diff --git a/spree/core/spec/services/spree/company_invitations/accept_spec.rb b/spree/core/spec/services/spree/company_invitations/accept_spec.rbindex 4c7c545d77..f11ad25a16 100644--- a/spree/core/spec/services/spree/company_invitations/accept_spec.rb+++ b/spree/core/spec/services/spree/company_invitations/accept_spec.rb@@ -4,6 +4,7 @@ describe Spree::CompanyInvitations::Accept dolet(:store) { @default_store }let(:company) { create(:company, store: store) }let(:invitation) { create(:company_invitation, company: company, email: '[email protected]') }+ let(:invited_customer) { create(:customer, email: '[email protected]') }context 'with a registration payload' doit 'creates the customer through the registration workflow and lands as a membership' do@@ -31,8 +32,8 @@ describe Spree::CompanyInvitations::Accept doendcontext 'with an authenticated customer' do- it 'binds the invitation to that customer' do- customer = create(:customer)+ it 'binds the invitation to the customer it was addressed to' do+ customer = create(:customer, email: '[email protected]')result = described_class.call(invitation: invitation, customer: customer)@@ -41,8 +42,25 @@ describe Spree::CompanyInvitations::Accept doexpect(invitation.reload.customer).to eq(customer)end+ it 'matches the email however it was capitalised on signup' do+ customer = create(:customer, email: '[email protected]')++ expect(described_class.call(invitation: invitation, customer: customer)).to be_success+ end++ # The token names one person. Spending it from another signed-in account+ # would hand that account standing over the company — buying, reading the+ # subtree's orders, revoking the other members' invitations.+ it 'refuses a customer the invitation was not addressed to' do+ result = described_class.call(invitation: invitation, customer: create(:customer))++ expect(result).to be_failure+ expect(invitation.reload).to be_pending+ expect(company.memberships.reload).to be_empty+ end+it 'is idempotent for an existing member' do- customer = create(:customer)+ customer = create(:customer, email: '[email protected]')membership = create(:company_membership, company: company, customer: customer)result = described_class.call(invitation: invitation, customer: customer)@@ -56,18 +74,18 @@ describe Spree::CompanyInvitations::Accept doit 'refuses an expired invitation' doinvitation.update!(expires_at: 1.day.ago)- expect(described_class.call(invitation: invitation, customer: create(:customer))).to be_failure+ expect(described_class.call(invitation: invitation, customer: invited_customer)).to be_failureendit 'refuses a revoked invitation' doinvitation.revoke!- expect(described_class.call(invitation: invitation, customer: create(:customer))).to be_failure+ expect(described_class.call(invitation: invitation, customer: invited_customer)).to be_failureendit 'refuses spending the token twice' do- described_class.call(invitation: invitation, customer: create(:customer))+ described_class.call(invitation: invitation, customer: invited_customer)- expect(described_class.call(invitation: invitation, customer: create(:customer))).to be_failure+ expect(described_class.call(invitation: invitation, customer: invited_customer)).to be_failureendenddiff --git a/spree/emails/app/mailers/spree/company_mailer.rb b/spree/emails/app/mailers/spree/company_mailer.rbindex 590beddcf2..3eacf0893e 100644--- a/spree/emails/app/mailers/spree/company_mailer.rb+++ b/spree/emails/app/mailers/spree/company_mailer.rb@@ -13,6 +13,11 @@ module Spree# @param invitation [Spree::CompanyInvitation, Integer]def invitation_email(invitation)@invitation = invitation.respond_to?(:id) ? invitation : Spree::CompanyInvitation.find(invitation)+ # Re-checked here, not only where the job was enqueued: a queue can sit+ # for minutes, and an invitation revoked in that window must not still+ # arrive carrying a working token.+ return message.perform_deliveries = false unless @invitation.reload.pending?+@company = @invitation.companystore = @company.store@accept_url = append_token(invitation_base_url(store), @invitation.token)diff --git a/spree/emails/spec/mailers/spree/company_mailer_spec.rb b/spree/emails/spec/mailers/spree/company_mailer_spec.rbindex 585d3b0cab..a64a9cf63e 100644--- a/spree/emails/spec/mailers/spree/company_mailer_spec.rb+++ b/spree/emails/spec/mailers/spree/company_mailer_spec.rb@@ -19,6 +19,16 @@ describe Spree::CompanyMailer, type: :mailer doexpect(message.subject).to include('Acme Industrial')end+ # The queue can sit for minutes; an invitation revoked in that window must+ # not still arrive carrying a working token.+ it 'sends nothing when the invitation stopped being pending after enqueue' do+ invitation.revoke!++ expect {+ described_class.invitation_email(invitation.id).deliver_now+ }.not_to change { ActionMailer::Base.deliveries.count }+ end+it 'links to the storefront acceptance page with the token appended' domessage = described_class.invitation_email(invitation)