Skip to content

armgit / spree

Public Imported from GitHub
0

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

Let a purchase ship to its company's address book (#14498)

Damian Legawiec5293f2a9a435
diff --git a/CLAUDE.md b/CLAUDE.md
index 96db461810..e391b730b2 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -12,6 +12,7 @@ When proposing significant architectural changes:
Use `/project:create-plan` and `/project:update-plan` for plan management.
Active plans (6.0 target, work pending):
+- `6.0-b2b-storefront-purchasing.md` — Storefront company self-service (account section: members, invitations, address book, company orders; the invitation acceptance page the mailer already links) + company-aware checkout (buying-for picker on cart **and** checkout, company address book replacing the personal one at the address step). **Implemented, in review 2026-08-27** (spree/spree#14498 + spree/storefront#214). **No polymorphic owner on Cart/Order** — a purchase keeps two buyer-side parties (`customer_id` + `company_id`), the industry dual axis; OSS ships plain machinery, the polished buyer portal is Enterprise. Backend grew past the planned one-guard widening: `Spree::HasAddressBook` lets an owner declare where its default slots live (a customer's `bill_address_id` vs a company's `default_bill_address_id`) so `Addresses::Create`/`Update` work for any owner — they silently dropped a company's default flag before; default flags are three-state (claim / give up / say nothing) and released by conditional UPDATE, never read-then-write; `Company#address_book` is the inherited reading list, and reads inherit while writes stay with the owning node. **Constraints now:** never branch on an address owner's class — ask the owner (`has_address_book`); a new owner declares its slots or its defaults silently no-op; nothing storefront-side may branch on a member's "role" (OSS has none — gate on standing).
- `6.0-multi-vendor-marketplace.md` — Open-source the marketplace core (Seller, OrderGroup-based order splitting, commission engine with EU commission taxation, `SellerTransfer`/`SellerPayout` ledger + pluggable `PayoutProvider`) per spree/spree#13323. 6.0 headline feature; rebuilds the legacy Enterprise multi-seller module as native models on the Cart/Order split. Basic Stripe Connect payouts (Express onboarding + on-fulfillment transfers) ship OSS in the monorepo, alongside the Stripe core gateway pulled in from the standalone `spree_stripe` repo (payment-sessions classes only, likely `spree/core` — decisions.md 2026-07-15); Enterprise keeps refund clawbacks/netting, reconciliation, KYC ops, DAC7 payout reports, facilitator taxes + Shopify/WooCommerce seller apps. **Seller principal + surface (Decision 10, 2026-08-15):** seller staff are `Spree.admin_user_class` (no `SellerUser`; membership by `RoleUser.resource_type`, never `store_id`) on a dedicated `/api/v3/seller` branch — own `seller_api` JWT audience, own `Spree.seller_authentication_strategies` + `/seller/auth/*`, audience-stamped refresh tokens, every endpoint scope-fetched through `current_seller` (store derived from the seller); sellers never call the Admin API and admin controllers are never subclassed into the seller namespace.
- `6.0-seller-onboarding-requirements.md` — Operator-configured seller onboarding checklist (design finalized 2026-08-18): `Spree::SellerRequirement` = store-scoped STI rows (`acts_as_list`, `active`/`required`, per-kind preferences) over developer-written kinds registered in `Spree.seller_requirements` (same `registers_subclasses_via` + `PreferenceSchema` types-discovery pattern as `DeliveryMethodRule`); three completion families — computed from seller data, attested by the seller, verified by the operator/a provider — the last two through one persisted `Spree::SellerRequirementSubmission` (`pending | accepted | rejected | waived`, optional private file attachment; generic `Attestation`/`OperatorReview`/`Document` kinds); evaluated on read by `Spree::Sellers::Requirements` into `SellerRequirementStatus` value objects (`complete | incomplete | pending | rejected`), never denormalized onto sellers. **Exactly two enforcement points:** `Sellers::SubmitForReview` (new; `onboarding → ready_for_review`, `auto_approve_sellers` store preference chains into Approve) and `Sellers::Approve` (refuses unless `override_requirements: true`, recorded on the event); post-approval drift is flagged, never enforced (`sellable?` unchanged, payouts gated by the provider). `Sellers::StartOnboarding` on invitation acceptance, `Sellers::ReopenOnboarding` for send-back. Admin API `/admin/seller_requirements` (+`/types`) under `write_sellers`, `include=onboarding` on sellers, submission accept/reject/waive; seller branch `GET /seller/onboarding`, `POST /seller/onboarding/submit_for_review`, `POST /seller/requirements/:id/submissions`. Defaults provisioned per store (`provision_defaults` + seed); empty = nothing required. **Constraints now:** no `Seller#onboarding_completed?`-style methods or step-done columns on `spree_sellers` — new admission checks are kinds (or `validate` hooks on the seller workflows), per-seller check state is a submission; nothing but the two workflows reads the checklist as a gate.
- `6.0-cart-order-split.md` — Cart/Order model separation, dual-FK owner everywhere (`cart_id`/`order_id` exactly-one, `#owner` as method — NOT polymorphic), idempotent copy-on-completion (`Order#cart_id` unique, order-before-payment), Order state machine removed (Checkout::Requirements for steps; payment/fulfillment statuses derived-then-persisted via one recompute service). **Shipped to 6-0-dev (feature/6-0-core-rewrite Waves 1+5):** Cart owns checkout end to end, machine + `spree_orders.state` gone, `Carts::Complete` three-phase pipeline live, `Orders::UpdateStatuses` sole status writer; only Wave 7 data migration (incomplete orders → carts) remains
diff --git a/docs/plans/6.0-b2b-storefront-purchasing.md b/docs/plans/6.0-b2b-storefront-purchasing.md
new file mode 100644
index 0000000000..fcbd61b81d
--- /dev/null
+++ b/docs/plans/6.0-b2b-storefront-purchasing.md
@@ -0,0 +1,219 @@
+# B2B Storefront Purchasing — company self-service and checkout
+
+**Status:** Implemented, in review (2026-08-27) — backend in spree/spree#14498,
+storefront in spree/storefront#214, both open. Everything in Design Details
+ships except the node rename, noted below.
+
+**Depends on:** `6.0-b2b-companies-and-catalogs.md` (implemented 2026-08-25 — the
+tree, memberships, invitations, the polymorphic address owner, and the Store
+API self-service surface this plan puts a face on).
+
+## Summary
+
+The Store API already let a company's members manage their organization —
+memberships, invitations, the address book, the subtree's orders — but the
+storefront had no UI for any of it, and checkout knew nothing about
+companies: the buyer saw only their personal address book, and the
+invitation email linked to an acceptance page that did not exist.
+
+This plan adds the missing storefront surface (a company section in the
+standard account area, the invitation acceptance page) and makes checkout
+company-aware (buying-for-company context, the company address book at the
+address step). It deliberately does NOT change how carts and orders are
+owned: a purchase keeps its two buyer-side parties — the person who placed
+it and the organization it is for — which is both what shipped and what the
+major B2B platforms converge on.
+
+The storefront lives in its own repo (`spree/storefront`, branch `6-0-dev`,
+cloned into a worktree by `pnpm wt:setup` and run with `pnpm wt:storefront`);
+this plan is the single record for the work in both repos.
+
+## Key Decisions (do not deviate without discussion)
+
+- **No polymorphic owner on Cart/Order.** The address move to
+ `owner_type`/`owner_id` worked because an address has exactly one owner. A
+ B2B purchase has two buyer-side parties with different jobs: the *person*
+ (authentication, "my orders", transactional email, and the party Enterprise
+ approvals and spend limits act on) and the *organization* (tax anchor,
+ catalog and price resolution, the company orders view). Collapsing them
+ into one polymorphic column would make "Alice bought this for Acme"
+ unrepresentable. The industry pattern is the same dual axis: the person
+ stays on the order and the purchasing organization is attached beside them
+ (Shopify's purchasing-entity shape; the B2B builds on Medusa and
+ BigCommerce likewise keep the employee and link the company). Spree already
+ ships exactly this — `customer_id` plus `company_id`, standing-validated,
+ sole-membership resolution, frozen at completion — so the model needs no
+ change; this plan is surface, not schema.
+- **OSS is the machinery, the buyer portal is Enterprise.** The open-source
+ storefront weaves company self-service into the standard account area,
+ plain and unstyled beyond the storefront's own design system: members,
+ invitations, addresses, company orders. The polished buyer portal —
+ approvals inbox, spending dashboards, invoices, roles — is the packaged
+ Enterprise product built on this machinery (tier boundary recorded in the
+ Enterprise plans repo). Nothing in the OSS storefront may grow
+ role-awareness: every member sees every company page, enforced by the
+ server's standing checks, and Enterprise narrows via its access-policy
+ subclass, not via UI flags.
+- **Checkout references the company book; completion still copies.** The
+ storefront submits `shipping_address_id` when a saved address is picked,
+ and the cart's ownership-guarded writers accepted only customer-owned rows.
+ They now also accept an address owned by the cart's
+ resolved company **or an ancestor of it** — the same self-and-ancestors
+ chain `Company#default_billing_address` walks, so the book a division
+ inherits for prefill is the book its buyers can pick from. Standing is
+ already enforced upstream (a cart cannot name a company its customer lacks
+ standing over), and completion keeps copying the address onto the order,
+ so the book row is never frozen by a sale. A company address never enters
+ the *customer's* book and vice versa; the guard refuses ids across that
+ line exactly as it refuses another customer's.
+- **Company context is explicit past one membership.** A buyer with a single
+ standing gets it resolved silently (`sole_standing_company`, shipped); a
+ buyer with several picks the node at checkout, writing the cart's
+ `company_id` (shipped, standing-validated). The storefront never guesses
+ between memberships. Buying personally remains possible: clearing the
+ company clears catalog, pricing and tax anchoring with it.
+- **The invitation acceptance page is part of this plan and is not
+ optional.** `Spree::CompanyMailer` links
+ `<storefront_url>/account/company-invitation?token=…`, and that page used
+ to 404. It handles both audiences the token flow serves: a new person
+ registering (the account is created with the invited email) and an
+ existing customer signing in to accept — refusing, as the API does, when
+ the signed-in account's email is not the invited one.
+
+## Design Details
+
+### Storefront — account area (`spree/storefront`)
+
+New pages under the authenticated account shell, listed in the account
+navigation only when `GET /store/account/companies` returns memberships:
+
+- **`/account/companies`** — the buyer's memberships with ancestor paths;
+ links to each node. Skipped (redirect to the node) when there is exactly
+ one.
+- **`/account/companies/[id]`** — the node page: the name and its ancestor
+ path, members with add-by-email (`POST …/members`, which the server turns
+ into a membership or an invitation), pending invitations with revoke, and
+ the address book (list, create, edit, delete, set-default — all shipped
+ endpoints). The name renders read-only: the API allows a rename and
+ `updateCompany` is wired in the data layer, but no edit control ships yet —
+ see Open Questions. Address rows reuse the storefront's existing
+ address-card conventions; defaults are badges, actions behind a menu, as
+ the dashboard settled.
+- **`/account/companies/[id]/orders`** — the subtree's completed orders
+ (`GET …/orders`), rendered with the existing order-list components beside
+ the buyer's personal "my orders".
+- **`/account/company-invitation`** — the acceptance page (unauthenticated
+ route): token lookup shows who invited them to what
+ (`GET /store/company_invitations/:token` returns company and store names),
+ then either the register form (invited email fixed) or sign-in-and-accept.
+ Success lands on the company page.
+
+### Storefront — checkout
+
+- **Company context.** When the authenticated buyer has standing, the cart
+ page **and** the checkout header show "Buying for {company}" — a picker
+ when several memberships, static text for one, absent for none. Picking
+ writes `company_id` on the cart (shipped API); "buy personally" clears it.
+ It sits on the cart as well as checkout because pricing context reads the
+ cart's company: set later, the buyer reviews a basket priced for the wrong
+ audience and watches the totals move at the last step.
+- **Address step.** With a company on the cart, `AddressSelector` lists the
+ company book **only** — fetched from the company addresses endpoint,
+ walking the same node-then-ancestors chain the server prefills from, with
+ the company's default preselected. The buyer's personal book is hidden: a
+ purchase for the organization ships to the organization's sites, and
+ offering someone's home address beside them invites the mis-click (the
+ Shopify behaviour). Company entries submit by id like personal ones do;
+ the "new address" form is unchanged and writes a plain cart address, never
+ into the company book — curating the book is the account area's job.
+- **Order display.** The order-placed page and the account order page name
+ the company the purchase was for (already on the store order serializer).
+
+### Backend deltas (`spree/api`, `spree/core`)
+
+Planned as "widen one guard", and that part held — no migrations, no
+serializer changes, since cart and order already report the company and
+company addresses already carry `label` and the default flags. What the
+build added beyond it is recorded here because the plan under-read how far
+the customer-shaped assumptions reached.
+
+- `Spree::Purchase::Addresses#ship_address_id=` / `#bill_address_id=` share
+ one `selectable_address` predicate that accepts the buyer's own book or the
+ book of the company the purchase is for **and its ancestors**. Everything
+ else about the writers is unchanged, including silently nulling on a
+ refused id.
+- `Company#address_book` names that inherited reading list, and the store
+ listing scope uses it. Reads inherit, writes stay with the node that owns
+ the row — the Store API authorizes purely by what `scope` returns, so a
+ division member must not reach its parent's entries through it.
+- **`Spree::HasAddressBook`** (new): owners declare where their default slots
+ live (`bill_address_id` for a customer, `default_bill_address_id` for a
+ company node), and every caller asks the owner instead of branching on its
+ class. `Addresses::Create` / `Update` then work for any owner — before
+ this, running a company entry through `Update` returned success while the
+ default flag was silently dropped, because every branch that would have set
+ it asked for the customer behind the address.
+- Each default flag carries three states, not two: `true` claims the slot,
+ `false` gives it up when this address is what holds it, and silence leaves
+ it alone. The release is a conditional `UPDATE` rather than a read-then-
+ write, so a promotion landing in between is not undone.
+- Both company address controllers write through the address services and
+ share one `CompanyAddressWrites` concern, matching the customer surface.
+- Specs: the company-book id accepted on a cart with standing; refused
+ without a company, across companies the buyer has no standing over, for a
+ descendant node, and for another customer's rows. The three-state flag rule
+ is proved against both a customer and a company node in the
+ `HasAddressBook` spec, including the race.
+
+### Explicitly out of scope
+
+- Roles, approvals, spend limits, order-on-behalf, invoices — Enterprise
+ (buyer portal).
+- Guest checkout for a company; a company must be bought for by a signed-in
+ member.
+- Terms/net-payment and quotes — future plans on the Enterprise side.
+- The `(wholesale)` demo route group in the storefront stays what it is — a
+ customer-group gated catalog demo. The company flow composes with it (a
+ wholesale buyer may also be a company member) but shares no code paths.
+
+## Migration Path
+
+Nothing to migrate: no schema changes, no renames. The storefront work is
+additive pages in a separate repo; the backend delta widens an acceptance
+guard.
+
+## Constraints on Current Work
+
+- New storefront company UI calls only the shipped Store API self-service
+ endpoints — no new bespoke endpoints without updating this plan.
+- Nothing storefront-side may branch on a member's "role" — OSS has none;
+ gate on standing (the server already does) and nothing else.
+- Cart/order code must keep treating `customer_id` and `company_id` as two
+ independent axes; nothing may infer one from the other beyond the shipped
+ `sole_standing_company` fallback.
+
+## Open Questions
+
+Both first-cut questions were answered 2026-08-26 and folded into Design
+Details: the address step hides the personal book once a company is on the
+cart (strict B2B, the Shopify behaviour), and the company picker appears on
+the cart page as well as checkout so catalog pricing is honest while the
+buyer is still filling the basket.
+
+1. **Should a member be able to rename their own company node from the
+ storefront?** The Store API allows it and `updateCompany` is wired in the
+ storefront data layer, but no edit control ships — the node page renders
+ the name read-only. OSS has no company roles, so shipping it means *any*
+ member can rename the organization every other member buys under, which
+ is a larger blast radius than the rest of the surface (adding a member is
+ additive; renaming is not). Left out deliberately rather than forgotten:
+ the merchant can rename from the dashboard, and Enterprise's roles decide
+ who may in the portal.
+
+## References
+
+- `6.0-b2b-companies-and-catalogs.md` — the shipped substrate.
+- Enterprise plans repo — buyer-portal roadmap entry (tier boundary).
+- `spree/storefront` `6-0-dev` — account shell, `AddressSelector`,
+ `AddressSection` (submits `shipping_address_id`), the `(wholesale)` demo
+ group.
diff --git a/packages/sdk/src/store-client.ts b/packages/sdk/src/store-client.ts
index cc52ff12aa..5e233a2759 100644
--- a/packages/sdk/src/store-client.ts
+++ b/packages/sdk/src/store-client.ts
@@ -19,6 +19,7 @@ import type {
Collection,
CollectionListParams,
Company,
+ CompanyAddressParams,
CompanyInvitation,
CompanyMembership,
CompletePaymentSessionParams,
@@ -1205,11 +1206,7 @@ export class StoreClient {
create: (
companyId: string,
- params: Record<string, unknown> & {
- label?: string
- default_billing?: boolean
- default_shipping?: boolean
- },
+ params: CompanyAddressParams,
options?: RequestOptions,
): Promise<Address> =>
this.request<Address>('POST', `/companies/${companyId}/addresses`, {
@@ -1220,11 +1217,7 @@ export class StoreClient {
update: (
companyId: string,
id: string,
- params: Record<string, unknown> & {
- label?: string
- default_billing?: boolean
- default_shipping?: boolean
- },
+ params: Partial<CompanyAddressParams>,
options?: RequestOptions,
): Promise<Address> =>
this.request<Address>('PATCH', `/companies/${companyId}/addresses/${id}`, {
diff --git a/packages/sdk/src/types/index.ts b/packages/sdk/src/types/index.ts
index 73c3fc0589..8b7fb8c9a8 100644
--- a/packages/sdk/src/types/index.ts
+++ b/packages/sdk/src/types/index.ts
@@ -231,6 +231,12 @@ export interface UpdateCartParams {
use_shipping?: boolean
/** Items to upsert (sets quantity for existing, creates new) */
items?: LineItemInput[]
+ /**
+ * The company node this purchase is for. The buyer must have standing over
+ * it; null clears it, and with it the company's catalog, pricing and tax
+ * anchoring.
+ */
+ company_id?: string | null
}
// Payments
@@ -334,3 +340,14 @@ export interface ProductFiltersParams {
category_id?: string
q?: Record<string, unknown>
}
+
+/**
+ * An address book entry for a company node: address fields, plus the two
+ * things only a book entry has — what it is filed under, and which defaults
+ * it holds for its node.
+ */
+export type CompanyAddressParams = AddressParams & {
+ label?: string
+ default_billing?: boolean
+ default_shipping?: boolean
+}
diff --git a/spree/api/app/controllers/concerns/spree/api/v3/company_address_writes.rb b/spree/api/app/controllers/concerns/spree/api/v3/company_address_writes.rb
new file mode 100644
index 0000000000..ae6636d541
--- /dev/null
+++ b/spree/api/app/controllers/concerns/spree/api/v3/company_address_writes.rb
@@ -0,0 +1,37 @@
+module Spree
+ module Api
+ module V3
+ # Writing an entry in a company node's address book, on either API.
+ #
+ # An entry is an ordinary address the node owns, so the payload is
+ # address attributes plus the label it is filed under. The two defaults
+ # are not columns on the row — they are pointers on the node — so they
+ # travel to the address services as flags, which apply them once the
+ # address itself is written.
+ module CompanyAddressWrites
+ extend ActiveSupport::Concern
+
+ protected
+
+ def permitted_params
+ params.permit(:label, *Spree::Api::V3::AddressParams::ADDRESS_KEYS)
+ end
+
+ # @return [Hash] default keywords for Spree::Addresses::Create / Update
+ def default_flags
+ { default_billing: flag_param(:default_billing), default_shipping: flag_param(:default_shipping) }
+ end
+
+ # Each flag has three meanings and they are all different: true claims
+ # the slot, false gives it up, and saying nothing leaves it alone.
+ #
+ # @return [Boolean, nil] nil when the client said nothing about it
+ def flag_param(name)
+ return nil unless params.key?(name)
+
+ ActiveModel::Type::Boolean.new.cast(params[name])
+ end
+ end
+ end
+ end
+end
diff --git a/spree/api/app/controllers/spree/api/v3/admin/companies/addresses_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/companies/addresses_controller.rb
index 9230143ab4..052455a08e 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/companies/addresses_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/companies/addresses_controller.rb
@@ -6,10 +6,40 @@ module Spree
# A node's address book — an entry is an ordinary address the node
# owns, so the whole of it is reached through the node.
class AddressesController < BaseController
- include Spree::Api::V3::Admin::Concerns::CompanyAddressParams
+ include Spree::Api::V3::CompanyAddressWrites
before_action :authorize_parent_access!
+ # POST /api/v3/admin/companies/:company_id/addresses
+ def create
+ result = Spree.address_create_service.call(
+ address_params: permitted_params,
+ owner: @parent,
+ **default_flags
+ )
+
+ if result.success?
+ render json: serialize_resource(result.value), status: :created
+ else
+ render_errors(result.value.errors)
+ end
+ end
+
+ # PATCH /api/v3/admin/companies/:company_id/addresses/:id
+ def update
+ result = Spree.address_update_service.call(
+ address: @resource,
+ address_params: permitted_params,
+ **default_flags
+ )
+
+ if result.success?
+ render json: serialize_resource(result.value)
+ else
+ render_errors(result.value.errors)
+ end
+ end
+
protected
def model_class
diff --git a/spree/api/app/controllers/spree/api/v3/admin/concerns/company_address_params.rb b/spree/api/app/controllers/spree/api/v3/admin/concerns/company_address_params.rb
deleted file mode 100644
index e69c55c844..0000000000
--- a/spree/api/app/controllers/spree/api/v3/admin/concerns/company_address_params.rb
+++ /dev/null
@@ -1,63 +0,0 @@
-module Spree
- module Api
- module V3
- module Admin
- module Concerns
- # Shared by the two places an address-book entry is written: nested
- # creation under a company, and direct edits by entry id.
- #
- # An entry is an ordinary address owned by the node, so the payload is
- # address attributes plus the label it is filed under. The two default
- # flags are not columns on the row — they are pointers on the node —
- # so they are applied after the save.
- module CompanyAddressParams
- extend ActiveSupport::Concern
-
- protected
-
- def permitted_params
- params.permit(:label, *Spree::Api::V3::AddressParams::ADDRESS_KEYS)
- end
-
- # The default flags are pointers on the node, not columns on the
- # row, so they are applied once the address itself has been written.
- def save_and_render(resource, status: :ok)
- saved = resource.save
- apply_default_flags!(resource) if saved
-
- if saved
- render json: serialize_resource(resource.reload), status: status
- else
- render_errors(resource.errors)
- end
- end
-
- def apply_default_flags!(address)
- company = address.owner
- return if company.nil?
-
- attributes = {}
- attributes[:default_bill_address_id] = address.id if flag_param(:default_billing) == true
- attributes[:default_ship_address_id] = address.id if flag_param(:default_shipping) == true
- # Clearing a flag only unsets it when this row is the one holding
- # it — another entry's default is not this request's business.
- attributes[:default_bill_address_id] = nil if flag_param(:default_billing) == false &&
- company.default_bill_address_id == address.id
- attributes[:default_ship_address_id] = nil if flag_param(:default_shipping) == false &&
- company.default_ship_address_id == address.id
-
- company.update!(attributes) if attributes.any?
- end
-
- # @return [Boolean, nil] nil when the client said nothing about it
- def flag_param(name)
- return nil unless params.key?(name)
-
- ActiveModel::Type::Boolean.new.cast(params[name])
- end
- end
- end
- end
- end
- end
-end
diff --git a/spree/api/app/controllers/spree/api/v3/store/companies/addresses_controller.rb b/spree/api/app/controllers/spree/api/v3/store/companies/addresses_controller.rb
index 15e03ef770..e79cfca0fb 100644
--- a/spree/api/app/controllers/spree/api/v3/store/companies/addresses_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/store/companies/addresses_controller.rb
@@ -7,27 +7,35 @@ module Spree
# reached through its node, so standing over that node is the only
# thing that authorizes reading or writing one.
class AddressesController < BaseController
- include Spree::Api::V3::Store::Concerns::CompanyAddressDefaults
+ include Spree::Api::V3::CompanyAddressWrites
# POST /api/v3/store/companies/:company_id/addresses
def create
- address = @parent.addresses.new(permitted_params)
+ result = Spree.address_create_service.call(
+ address_params: permitted_params,
+ owner: @parent,
+ **default_flags
+ )
- if address.save
- apply_default_flags!(address)
- render json: serialize_resource(address), status: :created
+ if result.success?
+ render json: serialize_resource(result.value), status: :created
else
- render_validation_error(address.errors)
+ render_validation_error(result.value.errors)
end
end
# PATCH /api/v3/store/companies/:company_id/addresses/:id
def update
- if @resource.update(permitted_params)
- apply_default_flags!(@resource)
- render json: serialize_resource(@resource.reload)
+ result = Spree.address_update_service.call(
+ address: @resource,
+ address_params: permitted_params,
+ **default_flags
+ )
+
+ if result.success?
+ render json: serialize_resource(result.value)
else
- render_validation_error(@resource.errors)
+ render_validation_error(result.value.errors)
end
end
@@ -49,8 +57,13 @@ module Spree
Spree.api.address_serializer
end
+ # Reading a book and keeping one are different rights: the listing
+ # includes what this node inherits, writes stay with the node that
+ # owns the row. The Store API authorizes purely by what this scope
+ # returns, so widening it for every action would let a division
+ # member rename or re-point its parent's entries.
def scope
- @parent.addresses
+ action_name == 'index' ? @parent.address_book : @parent.addresses
end
def parent_association
diff --git a/spree/api/app/controllers/spree/api/v3/store/concerns/company_address_defaults.rb b/spree/api/app/controllers/spree/api/v3/store/concerns/company_address_defaults.rb
deleted file mode 100644
index 8be6ed7134..0000000000
--- a/spree/api/app/controllers/spree/api/v3/store/concerns/company_address_defaults.rb
+++ /dev/null
@@ -1,43 +0,0 @@
-module Spree
- module Api
- module V3
- module Store
- module Concerns
- # An address-book entry's "is this the default" flags are pointers on
- # the node rather than columns on the row, so they are applied after
- # the address itself is saved. Shared by the two places the storefront
- # writes one: nested creation under a company, and direct edits.
- module CompanyAddressDefaults
- extend ActiveSupport::Concern
-
- protected
-
- def apply_default_flags!(address)
- company = address.owner
- return if company.nil?
-
- attributes = {}
- attributes[:default_bill_address_id] = address.id if flag_param(:default_billing) == true
- attributes[:default_ship_address_id] = address.id if flag_param(:default_shipping) == true
- # Clearing a flag only unsets it when this row is the one holding
- # it — another entry's default is not this request's business.
- attributes[:default_bill_address_id] = nil if flag_param(:default_billing) == false &&
- company.default_bill_address_id == address.id
- attributes[:default_ship_address_id] = nil if flag_param(:default_shipping) == false &&
- company.default_ship_address_id == address.id
-
- company.update!(attributes) if attributes.any?
- end
-
- # @return [Boolean, nil] nil when the client said nothing about it
- def flag_param(name)
- return nil unless params.key?(name)
-
- ActiveModel::Type::Boolean.new.cast(params[name])
- end
- end
- end
- end
- end
- end
-end
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/companies/addresses_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/companies/addresses_controller_spec.rb
index bf031e99c5..96e0a456de 100644
--- a/spree/api/spec/controllers/spree/api/v3/admin/companies/addresses_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/admin/companies/addresses_controller_spec.rb
@@ -77,4 +77,27 @@ RSpec.describe Spree::Api::V3::Admin::Companies::AddressesController, type: :con
expect(company.addresses.sole.first_name).to be_blank
end
end
+ describe 'PATCH #update' do
+ let!(:entry) { create(:company_address, owner: company, label: 'HQ') }
+
+ it 'promotes an entry to the node default' do
+ patch :update, params: { company_id: company.prefixed_id, id: entry.prefixed_id, default_billing: true },
+ as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(company.reload.default_bill_address_id).to eq(entry.id)
+ end
+
+ # The three-state rule itself is proved once, against both owner types,
+ # in the HasAddressBook spec; this only shows the flag reaches the model.
+ it 'clears the default it holds' do
+ company.update!(default_bill_address: entry)
+
+ patch :update, params: { company_id: company.prefixed_id, id: entry.prefixed_id, default_billing: false },
+ as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(company.reload.default_bill_address_id).to be_nil
+ end
+ end
end
diff --git a/spree/api/spec/controllers/spree/api/v3/store/companies/addresses_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/store/companies/addresses_controller_spec.rb
index 9f3056fd1f..2049957bc0 100644
--- a/spree/api/spec/controllers/spree/api/v3/store/companies/addresses_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/store/companies/addresses_controller_spec.rb
@@ -45,4 +45,66 @@ RSpec.describe Spree::Api::V3::Store::Companies::AddressesController, type: :con
expect(company.reload.default_ship_address_id).to eq(company.addresses.sole.id)
end
end
+ # A division ships to what it inherits, so its book shows the ancestors'
+ # sites as well as its own — the chain checkout accepts an id from.
+ describe 'GET #index for a division' do
+ it 'includes the addresses it inherits from its ancestors' do
+ division = create(:company, store: store, kind: 'division', parent: company)
+ inherited = create(:company_address, owner: company, label: 'Headquarters')
+ own = create(:company_address, owner: division, label: 'Dock 4')
+
+ get :index, params: { company_id: division.prefixed_id }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(json_response['data'].map { |row| row['id'] }).
+ to contain_exactly(own.prefixed_id, inherited.prefixed_id)
+ end
+ end
+ # Reading what you inherit is not the same as editing it. A division member
+ # ships to the headquarters address but has no standing over the node that
+ # keeps it, so the entry itself — and the defaults it holds — stay the
+ # parent's to change.
+ describe 'writing an inherited address' do
+ let(:division) { create(:company, store: store, kind: 'division', parent: company) }
+ let!(:inherited) { create(:company_address, owner: company, label: 'Headquarters') }
+
+ it 'refuses to edit an ancestor entry through the division' do
+ patch :update, params: { company_id: division.prefixed_id, id: inherited.prefixed_id, label: 'Hijacked' },
+ as: :json
+
+ expect(response).to have_http_status(:not_found)
+ expect(inherited.reload.label).to eq('Headquarters')
+ end
+
+ it 'refuses to delete an ancestor entry through the division' do
+ delete :destroy, params: { company_id: division.prefixed_id, id: inherited.prefixed_id }, as: :json
+
+ expect(response).to have_http_status(:not_found)
+ expect(inherited.reload).to be_persisted
+ end
+
+ it 'refuses to move an ancestor default through the division' do
+ patch :update, params: { company_id: division.prefixed_id, id: inherited.prefixed_id, default_billing: true },
+ as: :json
+
+ expect(response).to have_http_status(:not_found)
+ expect(company.reload.default_bill_address_id).to be_nil
+ end
+ end
+ # Members curate the book from the storefront too, so clearing a default has
+ # to work there — not only on the admin surface.
+ describe 'PATCH #update clearing a default' do
+ let!(:entry) { create(:company_address, owner: company, label: 'HQ') }
+
+ it 'clears the billing default it holds' do
+ company.update!(default_bill_address: entry)
+
+ patch :update, params: { company_id: company.prefixed_id, id: entry.prefixed_id, default_billing: false },
+ as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(company.reload.default_bill_address_id).to be_nil
+ end
+
+ end
end
diff --git a/spree/core/app/models/concerns/spree/has_address_book.rb b/spree/core/app/models/concerns/spree/has_address_book.rb
new file mode 100644
index 0000000000..4f4c3f09e2
--- /dev/null
+++ b/spree/core/app/models/concerns/spree/has_address_book.rb
@@ -0,0 +1,89 @@
+module Spree
+ # Anything that keeps an address book: a customer, a company node, and
+ # whatever comes next.
+ #
+ # Owners already differ in what they call their default slots — a customer
+ # has +bill_address_id+ / +ship_address_id+, a company node
+ # +default_bill_address_id+ / +default_ship_address_id+ — so the columns are
+ # declared once here and every caller asks the owner instead of knowing
+ # which of them it is holding.
+ #
+ # class Spree::Company < Spree.base_class
+ # has_address_book bill: :default_bill_address_id, ship: :default_ship_address_id
+ # end
+ module HasAddressBook
+ extend ActiveSupport::Concern
+
+ class_methods do
+ # @param bill [Symbol] column holding the default billing address id
+ # @param ship [Symbol] column holding the default shipping address id
+ def has_address_book(bill:, ship:)
+ class_attribute :default_address_columns, instance_writer: false, default: { bill: bill, ship: ship }
+ end
+ end
+
+ # Points this owner's default slots at an address.
+ #
+ # Writes the columns directly: callers have already established that the
+ # address is this owner's, so the ownership validation this skips cannot
+ # fail, and skipping it avoids re-running a whole validation set to move
+ # one foreign key.
+ #
+ # Each flag has three meanings, and they are all different: true promotes
+ # this address, false gives up the slot — but only when this address is
+ # what currently holds it, since another entry's default is not this
+ # caller's business — and nil leaves the slot alone.
+ #
+ # @param address_id [Integer]
+ # @param billing [Boolean, nil] promote to, or release, the billing slot
+ # @param shipping [Boolean, nil] promote to, or release, the shipping slot
+ def assign_default_address(address_id:, billing: true, shipping: true)
+ promoted = {}
+ released = []
+
+ { bill: billing, ship: shipping }.each do |kind, flag|
+ column = default_address_columns[kind]
+
+ if flag
+ promoted[column] = address_id
+ elsif flag == false
+ released << column
+ end
+ end
+
+ promote_default_columns(promoted)
+ release_default_columns(released, address_id)
+
+ # Promotion writes the in-memory attributes on its way through; a
+ # release goes around them, so only that leaves this instance stale.
+ reload if persisted? && released.any?
+ end
+
+ # @param kind [Symbol] :bill or :ship
+ # @return [Integer, nil] the address this owner prefills that slot with
+ def default_address_id(kind)
+ public_send(default_address_columns.fetch(kind))
+ end
+
+ private
+
+ def promote_default_columns(columns)
+ return if columns.empty?
+
+ update_columns(**columns, updated_at: Time.current)
+ end
+
+ # Released in one conditional statement rather than read-then-write: a
+ # request giving up a slot must not undo a promotion that landed between
+ # the two. The WHERE clause is the check, so a slot already moved on is
+ # simply not matched.
+ def release_default_columns(columns, address_id)
+ return if columns.empty?
+
+ columns.each do |column|
+ self.class.where(id: id, column => address_id).
+ update_all(column => nil, updated_at: Time.current)
+ end
+ end
+ end
+end
diff --git a/spree/core/app/models/concerns/spree/purchase/addresses.rb b/spree/core/app/models/concerns/spree/purchase/addresses.rb
index 2173cfc7dc..69bc774936 100644
--- a/spree/core/app/models/concerns/spree/purchase/addresses.rb
+++ b/spree/core/app/models/concerns/spree/purchase/addresses.rb
@@ -128,22 +128,16 @@ module Spree
true
end
- # Ownership-guarded writer: the id is applied only when the address
- # belongs to the record's customer; anything else — including any id on
- # a guest record — resolves to nil.
+ # Ownership-guarded writer: the id is applied only when the address is
+ # one this purchase may ship to — the buyer's own book, or the book of
+ # the company it is for. Anything else, including any id on a guest
+ # record, resolves to nil.
#
# @param id [Integer, String, nil]
def bill_address_id=(id)
return if bill_address_id == id
- address = Spree::Address.find_by(id: id)
- # rubocop:disable Style/ConditionalAssignment
- if address && customer_id.present? && address.owner_id == customer_id && address.customer_owned?
- self['bill_address_id'] = address.id
- else
- self['bill_address_id'] = nil
- end
- # rubocop:enable Style/ConditionalAssignment
+ self['bill_address_id'] = selectable_address(id)&.id
reset_bill_address
end
@@ -163,14 +157,7 @@ module Spree
def ship_address_id=(id)
return if ship_address_id == id
- address = Spree::Address.find_by(id: id)
- # rubocop:disable Style/ConditionalAssignment
- if address && customer_id.present? && address.owner_id == customer_id && address.customer_owned?
- self['ship_address_id'] = address.id
- else
- self['ship_address_id'] = nil
- end
- # rubocop:enable Style/ConditionalAssignment
+ self['ship_address_id'] = selectable_address(id)&.id
reset_ship_address
end
@@ -187,6 +174,33 @@ module Spree
private
+ # The address behind an id a client may select, or nil when the id names
+ # one this purchase has no business shipping to.
+ #
+ # Two books qualify. The buyer's own is the ordinary case. The company's
+ # is the B2B one: a purchase for a node ships to that node's sites, and
+ # to its ancestors' — the same self-and-ancestors chain the node's
+ # default address is prefilled from, so a division can pick the
+ # headquarters address it already inherits.
+ #
+ # Standing is not re-checked here: a cart cannot name a company its
+ # customer lacks standing over, so reaching this point already means the
+ # buyer may act for the node.
+ #
+ # @param id [Integer, String, nil]
+ # @return [Spree::Address, nil]
+ def selectable_address(id)
+ address = ::Spree::Address.find_by(id: id)
+ return nil if address.nil?
+
+ return address if customer_id.present? && address.customer_owned? && address.owner_id == customer_id
+
+ company = resolved_company
+ return nil if company.nil? || address.owner_type != 'Spree::Company'
+
+ company.self_and_ancestors.any? { |node| node.id == address.owner_id } ? address : nil
+ end
+
def update_or_create_address(attributes = {})
return if attributes.blank?
diff --git a/spree/core/app/models/concerns/spree/user_address.rb b/spree/core/app/models/concerns/spree/user_address.rb
index 80331ce324..4c2aa04542 100644
--- a/spree/core/app/models/concerns/spree/user_address.rb
+++ b/spree/core/app/models/concerns/spree/user_address.rb
@@ -3,6 +3,9 @@ module Spree
extend ActiveSupport::Concern
included do
+ include Spree::HasAddressBook
+ has_address_book bill: :bill_address_id, ship: :ship_address_id
+
belongs_to :bill_address, foreign_key: :bill_address_id, class_name: 'Spree::Address',
optional: true
alias_method :billing_address, :bill_address
diff --git a/spree/core/app/models/spree/address.rb b/spree/core/app/models/spree/address.rb
index 99c4307339..8b3bb803ee 100644
--- a/spree/core/app/models/spree/address.rb
+++ b/spree/core/app/models/spree/address.rb
@@ -200,11 +200,9 @@ module Spree
# @param kind [Symbol] :bill or :ship
# @return [Integer, nil] the owner's chosen address of that kind
def default_address_id(kind)
- return nil if owner.nil?
- return owner.public_send(:"#{kind}_address_id") if customer_owned?
- return owner.public_send(:"default_#{kind}_address_id") if owner.is_a?(Spree::Company)
+ return nil unless owner.respond_to?(:default_address_id)
- nil
+ owner.default_address_id(kind)
end
# @deprecated The address's owner may be a customer, a company node or a
diff --git a/spree/core/app/models/spree/company.rb b/spree/core/app/models/spree/company.rb
index bba36391a4..ef3eb69cd4 100644
--- a/spree/core/app/models/spree/company.rb
+++ b/spree/core/app/models/spree/company.rb
@@ -37,6 +37,9 @@ module Spree
# default is a pointer at one of them rather than a flag on the row, so
# two entries can never both claim the same default.
has_many :addresses, class_name: 'Spree::Address', as: :owner, dependent: :destroy
+ include Spree::HasAddressBook
+ has_address_book bill: :default_bill_address_id, ship: :default_ship_address_id
+
belongs_to :default_bill_address, class_name: 'Spree::Address', optional: true
belongs_to :default_ship_address, class_name: 'Spree::Address', optional: true
has_many :memberships, class_name: 'Spree::CompanyMembership', dependent: :destroy,
@@ -185,6 +188,19 @@ module Spree
default_address(:default_ship_address)
end
+ # Everything this node may ship to: its own sites and the ones it inherits
+ # from the nodes above it — the same chain its default address is
+ # prefilled from, and the one checkout accepts an address id from.
+ #
+ # Deliberately wider than {#addresses}: a division reads its headquarters'
+ # entries but keeps none of them, so this is a reading list and never a
+ # write target.
+ #
+ # @return [ActiveRecord::Relation]
+ def address_book
+ Spree::Address.where(owner_type: 'Spree::Company', owner_id: self_and_ancestors.map(&:id))
+ end
+
private
def ensure_can_be_deleted
diff --git a/spree/core/app/services/spree/addresses/create.rb b/spree/core/app/services/spree/addresses/create.rb
index 60ece797da..18409801ad 100644
--- a/spree/core/app/services/spree/addresses/create.rb
+++ b/spree/core/app/services/spree/addresses/create.rb
@@ -4,22 +4,30 @@ module Spree
prepend Spree::ServiceModule::Base
include Spree::Addresses::Helper
- def call(address_params: {}, user: nil, **opts)
+ # @param owner [Object, nil] who keeps the address — a customer, a
+ # company node, anything with an address book. +user:+ is the older
+ # name for the same thing, from when only customers had one.
+ def call(address_params: {}, owner: nil, user: nil, **opts)
+ owner ||= user
order = opts[:order]
- default_billing = address_params.key?(:is_default_billing) ? address_params.delete(:is_default_billing) : opts.fetch(:default_billing, false)
- default_shipping = address_params.key?(:is_default_shipping) ? address_params.delete(:is_default_shipping) : opts.fetch(:default_shipping, false)
+ # nil, not false — the same three-state contract Update keeps, so
+ # silence means the same thing on both.
+ default_billing = address_params.key?(:is_default_billing) ? address_params.delete(:is_default_billing) : opts.fetch(:default_billing, nil)
+ default_shipping = address_params.key?(:is_default_shipping) ? address_params.delete(:is_default_shipping) : opts.fetch(:default_shipping, nil)
address = Spree::Address.new(address_params)
- address.owner = user if user.present?
+ address.owner = owner if owner.present?
ApplicationRecord.transaction do
if address.save
- if user.present?
- if user.addresses.pluck(:id) == [address.id]
- user.update(bill_address_id: address.id, ship_address_id: address.id)
+ if owner.present?
+ # The first address a book gets is its default of both kinds —
+ # there is nothing for it to displace.
+ if owner.addresses.pluck(:id) == [address.id]
+ assign_owner_default(owner: owner, address_id: address.id)
else
- assign_to_user_as_default(
- user: user,
+ assign_owner_default(
+ owner: owner,
address_id: address.id,
default_billing: default_billing,
default_shipping: default_shipping
diff --git a/spree/core/app/services/spree/addresses/helper.rb b/spree/core/app/services/spree/addresses/helper.rb
index e310d71191..b29c554f32 100644
--- a/spree/core/app/services/spree/addresses/helper.rb
+++ b/spree/core/app/services/spree/addresses/helper.rb
@@ -3,22 +3,23 @@ module Spree
module Helper
private
- # Points the customer's default billing/shipping slots at an address.
+ # Points an owner's default billing/shipping slots at an address.
#
- # Writes the columns directly: both callers have already established
- # that the address is the customer's own — Create assigns the owner,
- # Update pins it from the record being edited — so the ownership
- # validation this skips cannot fail, and skipping it avoids re-running
- # the customer's whole validation set to move one foreign key. The
- # checkout path promotes defaults by plain assignment instead, because
- # there the address ownership is exactly what is still in question.
- def assign_to_user_as_default(user:, address_id:, default_billing: true, default_shipping: true)
- attributes_to_update = {
- ship_address_id: (address_id if default_shipping),
- bill_address_id: (address_id if default_billing),
- }.compact_blank
+ # Which columns those are is the owner's business — a customer and a
+ # company node name them differently — so the owner is asked rather
+ # than assumed. The checkout path promotes defaults by plain assignment
+ # instead, because there the address ownership is exactly what is still
+ # in question.
+ #
+ # @param owner [Object, nil] anything including Spree::HasAddressBook
+ def assign_owner_default(owner:, address_id:, default_billing: true, default_shipping: true)
+ return if owner.nil? || !owner.respond_to?(:assign_default_address)
- user.update_columns(**attributes_to_update, updated_at: Time.current) if attributes_to_update.present?
+ owner.assign_default_address(
+ address_id: address_id,
+ billing: default_billing,
+ shipping: default_shipping
+ )
end
end
end
diff --git a/spree/core/app/services/spree/addresses/update.rb b/spree/core/app/services/spree/addresses/update.rb
index 27333b448e..0efdfad00b 100644
--- a/spree/core/app/services/spree/addresses/update.rb
+++ b/spree/core/app/services/spree/addresses/update.rb
@@ -15,8 +15,10 @@ module Spree
private
def perform(address:, address_params:, **opts)
- default_billing = address_params.key?(:is_default_billing) ? address_params.delete(:is_default_billing) : opts.fetch(:default_billing, false)
- default_shipping = address_params.key?(:is_default_shipping) ? address_params.delete(:is_default_shipping) : opts.fetch(:default_shipping, false)
+ # nil, not false: saying nothing about a flag leaves the owner's slot
+ # where it is, while false is a request to give it up.
+ default_billing = address_params.key?(:is_default_billing) ? address_params.delete(:is_default_billing) : opts.fetch(:default_billing, nil)
+ default_shipping = address_params.key?(:is_default_shipping) ? address_params.delete(:is_default_shipping) : opts.fetch(:default_shipping, nil)
address_changes_except = opts.fetch(:address_changes_except, [])
prepare_address_params!(address, address_params)
@@ -31,8 +33,8 @@ module Spree
address_changed = address_changes.any?
if !address_changed && defaults_changed?(address, default_billing, default_shipping)
- assign_to_user_as_default(
- user: address.customer_owner,
+ assign_owner_default(
+ owner: address.owner,
address_id: address.id,
default_billing: default_billing,
default_shipping: default_shipping
@@ -44,14 +46,12 @@ module Spree
if address.editable?
address.update!(address_params)
- if address.customer_owner.present?
- assign_to_user_as_default(
- user: address.customer_owner,
- address_id: address.id,
- default_billing: default_billing,
- default_shipping: default_shipping
- )
- end
+ assign_owner_default(
+ owner: address.owner,
+ address_id: address.id,
+ default_billing: default_billing,
+ default_shipping: default_shipping
+ )
reassign_incomplete_orders(address.id, address)
@@ -60,12 +60,14 @@ module Spree
old_address_id = address.id
address.destroy!
- if new_address.customer_owner.present?
+ if new_address.owner.present?
+ # A replacement inherits whatever the row it replaces was default
+ # for, so the owner keeps prefilling with the same site.
default_billing = address.is_default_billing? || default_billing
- default_shipping = address.is_default_shipping || default_shipping
+ default_shipping = address.is_default_shipping? || default_shipping
- assign_to_user_as_default(
- user: new_address.customer_owner,
+ assign_owner_default(
+ owner: new_address.owner,
address_id: new_address.id,
default_billing: default_billing,
default_shipping: default_shipping
@@ -89,19 +91,36 @@ module Spree
address_params.transform_values!(&:presence)
end
+ # Keyed on the customer who started the order — which for a guest is no
+ # customer at all, so a guest's carts are matched by the same nil. A
+ # company book's entries are skipped: an order belongs to the person who
+ # placed it, never to the organization's address book.
def reassign_incomplete_orders(old_address_id, new_address)
+ return if new_address.business_owned?
+
orders = Spree::Order.incomplete.where(customer_id: new_address.owner_id)
orders.where(ship_address_id: old_address_id).update_all(ship_address_id: new_address.id, updated_at: Time.current)
orders.where(bill_address_id: old_address_id).update_all(bill_address_id: new_address.id, updated_at: Time.current)
end
+ # Whether this edit only moves the owner's default pointers, leaving the
+ # address itself untouched — asked of whichever owner keeps the book.
+ #
+ # A flag of false is a request in its own right ("stop defaulting to
+ # this one"), so what matters is whether the slot would end up somewhere
+ # different, not whether the flag is truthy.
def defaults_changed?(address, default_billing, default_shipping)
- user = address.customer_owner
+ owner = address.owner
+ return false unless owner.respond_to?(:default_address_id)
+
+ default_moves?(owner, :bill, default_billing, address) ||
+ default_moves?(owner, :ship, default_shipping, address)
+ end
+
+ def default_moves?(owner, kind, flag, address)
+ held = owner.default_address_id(kind) == address.id
- user.present? && (
- (default_billing.present? && user.bill_address != address) ||
- (default_shipping.present? && user.ship_address != address)
- )
+ flag ? !held : (flag == false && held)
end
def new_address(address_params = {})
diff --git a/spree/core/spec/models/concerns/spree/has_address_book_spec.rb b/spree/core/spec/models/concerns/spree/has_address_book_spec.rb
new file mode 100644
index 0000000000..0c3d85b79d
--- /dev/null
+++ b/spree/core/spec/models/concerns/spree/has_address_book_spec.rb
@@ -0,0 +1,79 @@
+require 'spec_helper'
+
+# Owners name their default slots differently — a customer keeps
+# bill_address_id, a company node default_bill_address_id — so the flags are
+# exercised against both to prove the concern, not one owner's columns.
+RSpec.describe Spree::HasAddressBook do
+ let(:store) { @default_store }
+
+ shared_examples 'an address book owner' do
+ it 'promotes the address to both slots' do
+ owner.assign_default_address(address_id: address.id)
+
+ expect(owner.default_address_id(:bill)).to eq(address.id)
+ expect(owner.default_address_id(:ship)).to eq(address.id)
+ end
+
+ it 'promotes only the slot asked for' do
+ owner.assign_default_address(address_id: address.id, billing: true, shipping: false)
+
+ expect(owner.default_address_id(:bill)).to eq(address.id)
+ expect(owner.default_address_id(:ship)).to be_nil
+ end
+
+ it 'gives up a slot this address holds' do
+ owner.assign_default_address(address_id: address.id)
+ owner.assign_default_address(address_id: address.id, billing: false, shipping: false)
+
+ expect(owner.default_address_id(:bill)).to be_nil
+ expect(owner.default_address_id(:ship)).to be_nil
+ end
+
+ # Another entry's default is not this caller's business.
+ it 'leaves a slot another address holds' do
+ owner.assign_default_address(address_id: other_address.id)
+ owner.assign_default_address(address_id: address.id, billing: false, shipping: false)
+
+ expect(owner.default_address_id(:bill)).to eq(other_address.id)
+ end
+
+ # The release is a conditional update, not a read-then-write: a promotion
+ # that lands between the two must survive. Simulated by moving the slot
+ # behind this instance's back, which is exactly what the other request
+ # would have done.
+ it 'does not undo a promotion that landed after it read the slot' do
+ owner.assign_default_address(address_id: address.id)
+ owner.default_address_id(:bill) # the stale read this request would hold
+
+ owner.class.where(id: owner.id).
+ update_all(owner.default_address_columns[:bill] => other_address.id)
+
+ owner.assign_default_address(address_id: address.id, billing: false, shipping: nil)
+
+ expect(owner.reload.default_address_id(:bill)).to eq(other_address.id)
+ end
+
+ it 'leaves a slot alone when the flag is nil' do
+ owner.assign_default_address(address_id: other_address.id)
+ owner.assign_default_address(address_id: address.id, billing: nil, shipping: nil)
+
+ expect(owner.default_address_id(:bill)).to eq(other_address.id)
+ end
+ end
+
+ context 'a customer' do
+ let(:owner) { create(:user) }
+ let(:address) { create(:address, owner: owner) }
+ let(:other_address) { create(:address, owner: owner) }
+
+ it_behaves_like 'an address book owner'
+ end
+
+ context 'a company node' do
+ let(:owner) { create(:company, store: store) }
+ let(:address) { create(:company_address, owner: owner) }
+ let(:other_address) { create(:company_address, owner: owner) }
+
+ it_behaves_like 'an address book owner'
+ end
+end
diff --git a/spree/core/spec/models/concerns/spree/purchase/addresses_spec.rb b/spree/core/spec/models/concerns/spree/purchase/addresses_spec.rb
index 799af42210..114d690fe2 100644
--- a/spree/core/spec/models/concerns/spree/purchase/addresses_spec.rb
+++ b/spree/core/spec/models/concerns/spree/purchase/addresses_spec.rb
@@ -81,6 +81,65 @@ RSpec.shared_examples 'an addresses host' do
expect(guest_record.ship_address_id).to be_nil
end
+
+ # A purchase for a company ships to that company's sites, so its address
+ # book is selectable alongside the buyer's own.
+ context 'when the purchase is for a company' do
+ let(:company) { create(:company, store: store) }
+ let(:division) { create(:company, store: store, kind: 'division', parent: company) }
+ let(:company_address) { create(:company_address, owner: company) }
+
+ before { create(:company_membership, company: company, customer: user) }
+
+ it 'accepts an address from the company book' do
+ record.company = company
+ record.ship_address_id = company_address.id
+
+ expect(record.ship_address_id).to eq(company_address.id)
+ end
+
+ # The same self-and-ancestors chain the node's default address is
+ # prefilled from: a division may ship to the headquarters it inherits.
+ it 'accepts an address from an ancestor of the purchase node' do
+ create(:company_membership, company: division, customer: user)
+ record.company = division
+ record.ship_address_id = company_address.id
+
+ expect(record.ship_address_id).to eq(company_address.id)
+ end
+
+ # Sole standing resolves the node without an explicit choice, so the
+ # book is selectable for a one-membership buyer who never picked.
+ it 'accepts the book of the sole standing company without an explicit choice' do
+ record.ship_address_id = company_address.id
+
+ expect(record.ship_address_id).to eq(company_address.id)
+ end
+
+ it 'refuses a company book to a buyer with no standing anywhere' do
+ outsider = create(:cart, store: store, customer: create(:user))
+ outsider.ship_address_id = company_address.id
+
+ expect(outsider.ship_address_id).to be_nil
+ end
+
+ it 'refuses the book of a company the purchase is not for' do
+ other = create(:company, store: store)
+ record.company = company
+ record.ship_address_id = create(:company_address, owner: other).id
+
+ expect(record.ship_address_id).to be_nil
+ end
+
+ # Ancestors, not descendants: a purchase for the parent has no claim on
+ # a division's own sites.
+ it 'refuses a descendant node address' do
+ record.company = company
+ record.ship_address_id = create(:company_address, owner: division).id
+
+ expect(record.ship_address_id).to be_nil
+ end
+ end
end
describe '#clone_shipping_address' do
diff --git a/spree/core/spec/services/spree/addresses/update_spec.rb b/spree/core/spec/services/spree/addresses/update_spec.rb
index f00399340f..63af4ac2a1 100644
--- a/spree/core/spec/services/spree/addresses/update_spec.rb
+++ b/spree/core/spec/services/spree/addresses/update_spec.rb
@@ -337,4 +337,29 @@ RSpec.describe Spree::Addresses::Update do
end
end
end
+ # The service used to reach for the customer behind an address, so a company
+ # node's book reported success while its default pointer never moved.
+ describe 'a company book entry' do
+ let(:store) { @default_store }
+ let(:company) { create(:company, store: store) }
+ let!(:entry) { create(:company_address, owner: company, label: 'HQ') }
+
+ it 'promotes the entry to the node default' do
+ result = Spree.address_update_service.call(
+ address: entry, address_params: { city: 'Shelbyville' }, default_billing: true
+ )
+
+ expect(result).to be_success
+ expect(company.reload.default_bill_address_id).to eq(entry.id)
+ end
+
+ it 'moves only the pointer when nothing about the address changed' do
+ result = Spree.address_update_service.call(
+ address: entry, address_params: {}, default_shipping: true
+ )
+
+ expect(result).to be_success
+ expect(company.reload.default_ship_address_id).to eq(entry.id)
+ end
+ end
end