Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
Fix: invited company members instead of adding existing accounts directly
Damian Legawieccb92ce3371c3
diff --git a/.changeset/sdk-company-members-invite.md b/.changeset/sdk-company-members-invite.mdnew file mode 100644index 0000000000..564b65344c--- /dev/null+++ b/.changeset/sdk-company-members-invite.md@@ -0,0 +1,5 @@+---+"@spree/sdk": patch+---++`companies.members.create` now always returns the `CompanyInvitation`: adding a member from the storefront sends an invitation even to an existing customer, who joins by accepting it.diff --git a/docs/developer/how-to/build-a-b2b-store.mdx b/docs/developer/how-to/build-a-b2b-store.mdxindex f806ce09c6..5083cbd354 100644--- a/docs/developer/how-to/build-a-b2b-store.mdx+++ b/docs/developer/how-to/build-a-b2b-store.mdx@@ -135,7 +135,9 @@ A delivery site is an address, not a node. Ten warehouses do not mean ten compan### Add the buyers-People join a company by email. An existing customer becomes a member immediately. An unknown email receives an invitation that is valid for 30 days, and accepting it creates their account and their membership in one step. The ID prefix tells you which happened: `cmem_` for a membership, `cinv_` for an invitation.+People join a company by email. When staff add someone through the Admin API, an existing customer becomes a member immediately, and an unknown email receives an invitation. The ID prefix tells you which happened: `cmem_` for a membership, `cinv_` for an invitation.++When a member adds a colleague from the storefront, the colleague always receives an invitation, even if they already have an account. Anyone can type an email address, so joining requires accepting the emailed invitation, which proves the person owns that address. An invitation is valid for 30 days. Accepting it creates the account and the membership in one step, or links an existing signed-in customer whose email matches.<CodeGroup>@@ -146,8 +148,8 @@ const result = await adminClient.companies.memberships.create('comp_xxx', {``````typescript Store SDK-// A member can add colleagues from the storefront in the same way-const result = await client.companies.members.create('comp_xxx', {+// A member invites colleagues from the storefront; they join by accepting+const invitation = await client.companies.members.create('comp_xxx', {customer_email: '[email protected]',})```diff --git a/packages/sdk/examples/companies/members-create.ts b/packages/sdk/examples/companies/members-create.tsindex 98ec55fd2c..d29af958d3 100644--- a/packages/sdk/examples/companies/members-create.ts+++ b/packages/sdk/examples/companies/members-create.ts@@ -6,9 +6,8 @@ const client = createClient({})// region:example-// An existing customer joins immediately (cmem_…); anyone else is emailed an-// invitation (cinv_…).-const member = await client.companies.members.create(+// Always an emailed invitation (cinv_…), even for an existing customer.+const invitation = await client.companies.members.create('comp_86Rf07xd4z',{ customer_email: '[email protected]' },{ token: '<token>' },@@ -16,4 +15,4 @@ const member = await client.companies.members.create(// endregion:example-export { member }+export { invitation }diff --git a/packages/sdk/src/store-client.ts b/packages/sdk/src/store-client.tsindex 845136eebf..6df9c013f2 100644--- a/packages/sdk/src/store-client.ts+++ b/packages/sdk/src/store-client.ts@@ -1287,20 +1287,19 @@ export class StoreClient {),/**- * Adds a person by email: an existing customer becomes a member- * immediately, anyone else gets an emailed invitation — check the- * returned id prefix (`cmem_` vs `cinv_`).+ * Invites a person by email. Even an existing customer joins only by+ * accepting the emailed invitation, so this always returns the+ * invitation.*/create: (companyId: string,params: { customer_email: string },options?: RequestOptions,- ): Promise<CompanyMembership | CompanyInvitation> =>- this.request<CompanyMembership | CompanyInvitation>(- 'POST',- `/companies/${companyId}/members`,- { ...options, body: params },- ),+ ): Promise<CompanyInvitation> =>+ this.request<CompanyInvitation>('POST', `/companies/${companyId}/members`, {+ ...options,+ body: params,+ }),/** Withdraws the member's standing. The customer account is untouched. */delete: (companyId: string, id: string, options?: RequestOptions): Promise<void> =>diff --git a/spree/api/app/controllers/spree/api/v3/store/companies/members_controller.rb b/spree/api/app/controllers/spree/api/v3/store/companies/members_controller.rbindex 6d0831d492..f906d5e49c 100644--- a/spree/api/app/controllers/spree/api/v3/store/companies/members_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/store/companies/members_controller.rb@@ -4,26 +4,25 @@ module Spreemodule Storemodule Companies# The people with standing over one node, listed and added by its- # members. Adding takes an email and does the right thing: a- # membership for an existing customer, an invitation otherwise —- # the same convergent behavior as the dashboard endpoint. Any member- # can invite; restraint is Enterprise's policy layer.+ # members. Adding takes an email and always sends an invitation,+ # even to an existing customer: a member typing an address cannot+ # vouch that it is the person they mean, so the invitee accepts with+ # the emailed token. The response is the same whether or not the+ # email has an account. Any member can invite; restraint is+ # Enterprise's policy layer.class MembersController < BaseController# POST /api/v3/store/companies/:company_id/membersdef createresult = Spree.company_add_member_service.call(company: @parent,email: params.require(:customer_email),- inviter: current_user+ inviter: current_user,+ require_acceptance: true)if result.success?- serializer = if result.value.is_a?(Spree::CompanyInvitation)- Spree.api.company_invitation_serializer- else- serializer_class- end- render json: serializer.new(result.value, params: serializer_params).to_h, status: :created+ render json: Spree.api.company_invitation_serializer.new(result.value, params: serializer_params).to_h,+ status: :createdelserender_validation_error(result.value.errors)enddiff --git a/spree/api/spec/controllers/spree/api/v3/store/companies/members_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/store/companies/members_controller_spec.rbindex 7a1c214cf9..fbe6b13b20 100644--- a/spree/api/spec/controllers/spree/api/v3/store/companies/members_controller_spec.rb+++ b/spree/api/spec/controllers/spree/api/v3/store/companies/members_controller_spec.rb@@ -30,14 +30,18 @@ RSpec.describe Spree::Api::V3::Store::Companies::MembersController, type: :contrenddescribe 'POST #create' do- it 'adds an existing customer as a member immediately' do+ # A member typing an address cannot vouch that it is the person they+ # mean, so even an existing customer joins only by accepting the emailed+ # token — and the response does not reveal that the email has an account.+ it 'invites an existing customer rather than adding them' dobuyer = create(:customer, email: '[email protected]')post :create, params: { company_id: company.prefixed_id, customer_email: '[email protected]' }, as: :jsonexpect(response).to have_http_status(:created)- expect(json_response['id']).to start_with('cmem_')- expect(company.memberships.reload.map(&:customer)).to include(buyer)+ expect(json_response['id']).to start_with('cinv_')+ expect(company.memberships.reload.map(&:customer)).not_to include(buyer)+ expect(company.invitations.sole.email).to eq('[email protected]')endit 'invites an unknown email, recording the inviter' 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.rbindex 64b23e5168..d370e91069 100644--- a/spree/api/spec/integration/spree/api/v3/store/companies_spec.rb+++ b/spree/api/spec/integration/spree/api/v3/store/companies_spec.rb@@ -140,9 +140,11 @@ RSpec.describe 'Company Self-Service API', type: :request, swagger_doc: 'api-refproduces '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.+ Invites a person to the node by email (a `cinv_...` id) and sends the invite email.+ This is an invitation even when the email already belongs to a customer: they join+ by accepting the emailed token, which proves they own the address and agree to join.+ The response is the same either way, so it does not reveal whether the email has an+ account.DESCsdk_example 'companies/members-create'@@ -155,7 +157,7 @@ RSpec.describe 'Company Self-Service API', type: :request, swagger_doc: 'api-refrequired: ['customer_email']}- response '201', 'member added or invitation sent' do+ response '201', 'invitation sent' dolet!(:membership) { create(:company_membership, company: company, customer: user) }let!(:colleague) { create(:customer, email: '[email protected]') }let(:company_id) { company.prefixed_id }diff --git a/spree/core/app/services/spree/companies/add_member.rb b/spree/core/app/services/spree/companies/add_member.rbindex 60e63087f8..2348e0b97c 100644--- a/spree/core/app/services/spree/companies/add_member.rb+++ b/spree/core/app/services/spree/companies/add_member.rb@@ -18,11 +18,17 @@ module Spree# (memberships have no metadata column; a direct-membership payload is# applied by the caller through the `company_membership.form_fields`# contract, not stored here)+ # @param require_acceptance [Boolean] always invite, even an existing+ # customer — for callers who cannot vouch that the email is the+ # person they mean (a storefront member typing an address). The+ # emailed token is what proves the invitee owns the address and+ # agrees to join; a direct membership would hand the company to+ # whoever happens to hold that email.# @return [Spree::ServiceModule::Result] value is the created# Spree::CompanyMembership or Spree::CompanyInvitation- def call(company:, email:, inviter: nil, metadata: nil)+ def call(company:, email:, inviter: nil, metadata: nil, require_acceptance: false)normalized_email = email.to_s.strip.downcase- customer = Spree.customer_class.find_by(email: normalized_email)+ customer = Spree.customer_class.find_by(email: normalized_email) unless require_acceptancerecord =if customerdiff --git a/spree/core/spec/services/spree/companies/add_member_spec.rb b/spree/core/spec/services/spree/companies/add_member_spec.rbindex 0b5b538913..4fe26e50cf 100644--- a/spree/core/spec/services/spree/companies/add_member_spec.rb+++ b/spree/core/spec/services/spree/companies/add_member_spec.rb@@ -15,6 +15,15 @@ describe Spree::Companies::AddMember doexpect(result.value.customer).to eq(customer)end+ # The token proves the invitee owns the address; a member typing an email+ # cannot vouch for that.+ it 'invites instead when acceptance is required' do+ result = described_class.call(company: company, email: '[email protected]', require_acceptance: true)++ expect(result.value).to be_a(Spree::CompanyInvitation)+ expect(company.memberships).to be_empty+ end+it 'refuses a duplicate membership' docreate(:company_membership, company: company, customer: customer)