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.

Unify customer registration behind Customers::Create workflow (#14393)

Damian Legawiec84ca43e79fef
diff --git a/CLAUDE.md b/CLAUDE.md
index c89ad80f01..e9dcbe3206 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -30,7 +30,7 @@ Active plans (6.0 target, work pending):
- `6.0-inventory-operations.md` — StockTransfer lifecycle (draft → ready_to_ship → in_transit → received with partial receive), new `Spree::PurchaseOrder` + `Spree::Supplier` (renamed from Vendor — `Spree::Vendor` is the marketplace seller, see decisions.md 2026-07-14) replacing today's "external receive" hack, variant + stock-location stock history panels. Consumes the typed-movement primitives from `6.0-typed-stock-movements.md`.
- `6.0-replace-taxons-with-categories.md` — Split Taxon into Category (hierarchy) + Collection (flat/rule-based). **Shipped to 6-0-dev (PR #14302):** the Category surface (5.5–5.6) plus the 6.0 core — `spree_taxons`→`spree_categories` table rename + inheritance flip (`Spree::Category < Spree.base_class`, `Spree::Taxon` alias kept), the full `Collection` stack (model + rules + DB/Meilisearch manual sort + API), the taxon→category/collection data migration, and de-ruling Category. Pending (all 6.1): channel-aware `CollectionRules::AvailableOn` (ships interim now, rides with channels) + dropping `spree_taxon_rules`/`Taxonomy`. No brand feature in 6.0 — brands are modeled as a Category/Collection; `brand_taxon`/`brand_name` removed with `Taxonomy`.
- `6.0-delivery-method-rules.md` — `Spree::DeliveryMethodRule` STI on DeliveryMethod (design finalized 2026-07-29): ItemTotal/Weight rules first (Channel/Market/CustomerGroup later in lockstep with payment-method-rules), enforced solely in `Stock::Estimator`'s method filter so calculator- AND provider-priced methods obey eligibility; replaces the FlatRate-only bound preferences (one-release bridge + data task). Phase 1 rides the 6.0 core-rewrite finishing work.
-- `6.0-service-workflows.md` — Two-tier services doctrine (2026-07-30). **Tier 1 `app/services/`:** plain `ServiceModule` classes, hand-written `def call(cart:, ...)`, Ruby kwargs as the contract — the permanent default; no DSL, no new `run`-pipelines, no hand-rolled sagas. **Tier 2 `app/workflows/`:** `Spree::Workflow` — named steps inside a plain `def perform(order:, ...)` (the ActiveJob::Continuable shape; bare `super` turns parameters into readers). Vocabulary: `step`/`external_step` (+ `with:`, `on_flow_failure:`), `run_hooks` + class-level `hooks`, `failure`/`halt!`; plain `ApplicationRecord.transaction`/`with_lock`/`rescue`/`publish_event`; every step instrumented as `step.spree_workflow`. Money lives in `Carts::RecalculateTotals` (single totals seam; the completed-order branch is the post-placement resum — rows re-summed, never regenerated), statuses in `Orders::UpdateStatuses` (refreshes each fulfillment's state, then rolls up); Order/CartUpdater are 6.1-removed warning shells. Shared Cart/Order surface lives in `Spree::Purchase::*` concerns; completion side effects (newsletter, account creation, risk) run in the sync `OrderPlacedSubscriber` on order.placed. Reserved for flows needing hooks, compensation/external I/O, or replay — currently `Carts::Complete`, `Carts::AddItem`, `Carts::Recalculate`, `Carts::RecalculateTotals` (+ order twins) and `Orders::Cancel` (absorbed `Order#after_cancel`; gateway settlement is an external_step). A service graduates to the workflow tier when it earns a hook, never speculatively — but hooks on flows already in the tier ship deliberately on the 6.0 boundary (2026-08-02), since hook keys are public API and moving one later is breaking. **New models get no state machine** — plain `status` string + inclusion validation, transitions through workflows; gateway I/O never in a save callback. Three hook families, contracts settled 2026-08-02: **lifecycle** (past tense, read-only), **validate** (handler calls `workflow.reject!(message)` to veto), **context** (`set_*_context`/`get_provider_data` — handler returns a hash, `run_hooks` deep-merges all handlers and returns it; last writer wins on collision). Phase 3 **shipped (2026-08-02)**: `run_hooks` returns the merged hash and `Workflow#reject!` is public API; `validate`/context/lifecycle hooks live on AddItem, Complete, Recalculate, RecalculateTotals, Cancel and Resume; `Fulfillments::Create`, `Payments::Capture`/`Refund`, `Payments::HandleWebhook` and `Carts::Merge` moved to `app/workflows/` (seams `fulfillment_create_workflow`, `payment_capture_workflow`, `payment_refund_workflow`, `payments_handle_webhook_workflow`, `cart_merge_workflow`; legacy names readable one release). Payment workflows own the transaction boundary and guards — money movement stays in the model, called from an `external_step`. No workflows for plain CRUD. Workflow Dependencies seams use `*_workflow` keys; legacy `*_service` names stay settable/readable with warnings until 6.1 but writes are stashed, never applied (old service classes aren't workflow-contract compatible). `Carts::Complete` battery must pass unmodified. **Durability = plain Rails:** long-running background work uses `ActiveJob::Continuable` directly (reference: `Spree::Imports::ProcessJob` — CSV spine with a row-number cursor; `CreateRowsJob`/`ProcessRowsJob` deprecated shells); workflows are synchronous request-cycle flows and are NOT jobs — Workflow-level durable execution ships only if the payout run proves the need.
+- `6.0-service-workflows.md` — Two-tier services doctrine (2026-07-30). **Tier 1 `app/services/`:** plain `ServiceModule` classes, hand-written `def call(cart:, ...)`, Ruby kwargs as the contract — the permanent default; no DSL, no new `run`-pipelines, no hand-rolled sagas. **Tier 2 `app/workflows/`:** `Spree::Workflow` — named steps inside a plain `def perform(order:, ...)` (the ActiveJob::Continuable shape; bare `super` turns parameters into readers). Vocabulary: `step`/`external_step` (+ `with:`, `on_flow_failure:`), `run_hooks` + class-level `hooks`, `failure`/`halt!`; plain `ApplicationRecord.transaction`/`with_lock`/`rescue`/`publish_event`; every step instrumented as `step.spree_workflow`. Money lives in `Carts::RecalculateTotals` (single totals seam; the completed-order branch is the post-placement resum — rows re-summed, never regenerated), statuses in `Orders::UpdateStatuses` (refreshes each fulfillment's state, then rolls up); Order/CartUpdater are 6.1-removed warning shells. Shared Cart/Order surface lives in `Spree::Purchase::*` concerns; completion side effects (newsletter, account creation, risk) run in the sync `OrderPlacedSubscriber` on order.placed. Reserved for flows needing hooks, compensation/external I/O, or replay — currently `Carts::Complete`, `Carts::AddItem`, `Carts::Recalculate`, `Carts::RecalculateTotals` (+ order twins) and `Orders::Cancel` (absorbed `Order#after_cancel`; gateway settlement is an external_step). A service graduates to the workflow tier when it earns a hook, never speculatively — but hooks on flows already in the tier ship deliberately on the 6.0 boundary (2026-08-02), since hook keys are public API and moving one later is breaking. **New models get no state machine** — plain `status` string + inclusion validation, transitions through workflows; gateway I/O never in a save callback. Three hook families, contracts settled 2026-08-02: **lifecycle** (past tense, read-only), **validate** (handler calls `workflow.reject!(message)` to veto), **context** (`set_*_context`/`get_provider_data` — handler returns a hash, `run_hooks` deep-merges all handlers and returns it; last writer wins on collision). Phase 3 **shipped (2026-08-02)**: `run_hooks` returns the merged hash and `Workflow#reject!` is public API; `validate`/context/lifecycle hooks live on AddItem, Complete, Recalculate, RecalculateTotals, Cancel and Resume; `Fulfillments::Create`, `Payments::Capture`/`Refund`, `Payments::HandleWebhook` and `Carts::Merge` moved to `app/workflows/` (seams `fulfillment_create_workflow`, `payment_capture_workflow`, `payment_refund_workflow`, `payments_handle_webhook_workflow`, `cart_merge_workflow`; legacy names readable one release). **Customer registration (2026-08-05):** `Customers::Create` (seam `customer_create_workflow`, hooks `customers.create.validate`/`after_create`) is the single storefront customer-creation flow — self-registration + checkout account box (optional `order:` adopts addresses and links the order); absorbs `Orders::CreateUserAccount` (deprecated shell); admin create stays plain CRUD; token issuance stays in controllers; core sends NO welcome email — signup email is host-app code on `user.created` or the `after_create` hook. Payment workflows own the transaction boundary and guards — money movement stays in the model, called from an `external_step`. No workflows for plain CRUD. Workflow Dependencies seams use `*_workflow` keys; legacy `*_service` names stay settable/readable with warnings until 6.1 but writes are stashed, never applied (old service classes aren't workflow-contract compatible). `Carts::Complete` battery must pass unmodified. **Durability = plain Rails:** long-running background work uses `ActiveJob::Continuable` directly (reference: `Spree::Imports::ProcessJob` — CSV spine with a row-number cursor; `CreateRowsJob`/`ProcessRowsJob` deprecated shells); workflows are synchronous request-cycle flows and are NOT jobs — Workflow-level durable execution ships only if the payout run proves the need.
- `6.0-store-scoped-configuration.md` — Move nine commerce-behavior globals (`auto_capture`, `auto_capture_on_dispatch`, `allow_checkout_on_gateway_error`, `track_inventory_levels`, `stock_reservations_enabled`, `track_price_history`, `show_products_without_price`, `address_requires_phone`, `disable_sku_validation`) from `Spree::Config` to `Spree::Store` preferences. Store preference is **authoritative — no runtime fallback** (a fallback chain is what made `default_stock_reservation_ttl_minutes` silently unreachable); upgrade carries values over via `spree:store_settings:backfill_from_config`; globals are deprecated shells until 6.1. Storeless readers (`Address`, the product availability scope) use `Spree::Current.store` with a default fallback. Seven dead settings (`products_per_page`, `storefront_*_path`, …) get shells then deletion. **Constraints now:** no new `Spree::Config` reads of the movers; new behavior flags are born on Store, never global; jobs that validate addresses or query the catalog must set `Spree::Current.store`.
- `6.0-store-scoped-custom-field-definitions.md` — Add `store_id` + persisted `filter_key` to `Spree::MetafieldDefinition` (today global and computed), making uniqueness `(store_id, resource_type, filter_key)` with a DB index. Deferred from the 5.6 custom-field search/sort/filter work (schema change, not patch-safe). **Until then:** `filter_key` is a computed method — no Ransack predicates or `where`/`order` against it; definitions are global; uniqueness rests on a `CONCAT` validation with no index behind it.
diff --git a/docs/developer/customization/workflows.mdx b/docs/developer/customization/workflows.mdx
index e445195994..cfd686c052 100644
--- a/docs/developer/customization/workflows.mdx
+++ b/docs/developer/customization/workflows.mdx
@@ -255,6 +255,8 @@ is reported through `Rails.error` so it's visible rather than mysterious.
| `payments.refund` | `before_refund` | lifecycle | Immediately before the gateway call |
| `payments.refund` | `after_refund` | lifecycle | After a successful refund |
| `payments.handle_webhook` | `after_handle` | lifecycle | After the gateway callback is processed |
+| `customers.create` | `validate` | validate | After the customer is built, before it is saved — the registration-policy veto (bot screening, B2B approval) |
+| `customers.create` | `after_create` | lifecycle | After the customer is created and the newsletter subscriber linked |
`before_cancel` and `before_resume` accept `reject!` like a `validate` hook.
diff --git a/docs/plans/6.0-service-workflows.md b/docs/plans/6.0-service-workflows.md
index 6b8f468d42..b0a3f3b8b5 100644
--- a/docs/plans/6.0-service-workflows.md
+++ b/docs/plans/6.0-service-workflows.md
@@ -1,10 +1,10 @@
# Service Workflows — one step DSL for services, sagas, hooks and events
-**Status:** In Progress — Phase 1 shipped to 6-0-dev as a two-tier split (2026-07-30): `Spree::Workflow` (the DSL) powers the curated flows in `app/workflows/`; every other service stays a plain ServiceModule class. Phase 3 (extension surface: `run_hooks` returning a merged hash, `reject!`, validate/context hooks, four service graduations) shipped 2026-08-02. See **Workflow and hook inventory** below for the 30 shipped workflows and their extension points, **To deliver** for what is still planned, and **Known gaps** for what is wrong in what shipped
+**Status:** In Progress — Phase 1 shipped to 6-0-dev as a two-tier split (2026-07-30): `Spree::Workflow` (the DSL) powers the curated flows in `app/workflows/`; every other service stays a plain ServiceModule class. Phase 3 (extension surface: `run_hooks` returning a merged hash, `reject!`, validate/context hooks, four service graduations) shipped 2026-08-02. See **Workflow and hook inventory** below for the 31 shipped workflows and their extension points, **To deliver** for what is still planned, and **Known gaps** for what is wrong in what shipped
**Target:** Spree 6.0
**Depends on:** `6.0-cart-order-split.md` (Carts::Complete is the reference implementation and stress test). Coordinates with: `6.0-multi-vendor-marketplace.md` (payout runs are the first durable-flow consumer), the Rails 8.1 floor decision (decisions.md 2026-07-29 — ActiveJob Continuations are the durability primitive).
**Author:** Damian Legawiec + Claude (design session 2026-07-30)
-**Last updated:** 2026-08-03
+**Last updated:** 2026-08-05
## Summary
@@ -163,6 +163,32 @@ green and its observable semantics byte-identical.
where an extension would plausibly inject behaviour, and every hook ships
documented. Speculative *workflows* are still forbidden.
+13. **Customer registration is a workflow; the welcome email leaves core
+ (2026-08-05).** `Spree::Customers::Create` graduates on real demand, not
+ speculation: registration is the canonical veto point (bot and
+ disposable-email screening, fraud checks, B2B "registration requires
+ approval" — all need to *reject* a signup, which the `user.created`
+ lifecycle event cannot do), and creation today carries multi-record side
+ effects scattered inconsistently across three paths (newsletter-subscriber
+ linking and consent propagation on self-registration only, address
+ adoption and welcome email on the checkout path only, neither on admin
+ create). The workflow absorbs `Orders::CreateUserAccount` via an optional
+ `order:` argument — one flow, one workflow — so store self-registration,
+ the checkout "create an account" box, and (later) storefront OIDC
+ auto-provisioning all flow through one seam
+ (`customer_create_workflow`); the old service class stays as a deprecated
+ one-release shell. Deliberately **not** routed through it: the Admin API
+ create action (plain CRUD, and staff creation must not be blockable by
+ registration-policy hooks) and JWT/refresh-token issuance (an HTTP
+ session concern that stays in the controller — the workflow returns the
+ customer, the controller mints tokens). **The welcome email is dropped
+ from core entirely**: no `send_welcome_email` call anywhere; signup email
+ is host-app implementation via a `user.created` subscriber or the
+ `customers.create.after_create` hook, consistent with headless
+ storefronts owning consumer email. The host-app migration step is
+ written up in decisions.md 2026-08-05 ("Upgrade step (host
+ applications)") and belongs in the 6.0 upgrade manifest.
+
## Hooks
Three families, because they solve different problems:
@@ -455,6 +481,20 @@ admin draft-order edits without touching storefront carts.
| `Claims::Deny` | `claim_deny_workflow` | `validate` (V), `after_deny` (L) | ✅ |
| `Claims::Cancel` | `claim_cancel_workflow` | `validate` (V), `after_cancel` (L) | ✅ |
+### Customer
+
+| Workflow | Seam | Hooks | |
+|---|---|---|---|
+| `Customers::Create` | `customer_create_workflow` | `validate` (V), `after_create` (L) | ✅ |
+
+Callers: store self-registration (`Store::CustomersController#create`) and
+the checkout "create an account" box (`OrderPlacedSubscriber`), which passes
+`order:` so the workflow also adopts the order's addresses and links the
+order to the new customer. Absorbs `Orders::CreateUserAccount` (deprecated
+one-release shell). Admin API create stays plain CRUD and does not dispatch
+these hooks (decision 13). No welcome email — signup email is host-app
+implementation on `user.created` or `after_create`.
+
**Core handlers registered on these hooks.** Only one:
`Spree::Returns::EligibilityValidator` on `returns.create.validate` and
`exchanges.create.validate` — a per-market return window that staff bypass
@@ -501,10 +541,11 @@ still holds that a service graduates when it earns a hook, not speculatively.
Not new workflows — things wrong or missing in what already shipped.
- ⬜ **Extension-facing docs list only the pre-returns hooks.**
- `docs/developer/customization/workflows.mdx` documents 24 hook points; the
- fifteen returns/exchanges/claims workflows added since are missing from the
- reference table. The table is spec-asserted in core, so the spec needs
- extending alongside it.
+ `docs/developer/customization/workflows.mdx` documents the pre-returns hook
+ points (plus `customers.create`, added 2026-08-05); the fifteen
+ returns/exchanges/claims workflows added since are missing from the
+ reference table. (Earlier revisions claimed the table is spec-asserted in
+ core — no such spec exists, which is part of this gap.)
- ⬜ **`Spree.hooks.clear!` wipes core registrations permanently.** The
boot-time initializer runs once, so any spec or extension calling it
silently disables `EligibilityValidator` for the rest of the process. Either
@@ -556,7 +597,9 @@ Workflows are earned by orchestration, not by being a write.
## Open Questions
- Whether the sweeper that resumes stuck completions generalizes into flow
- infrastructure in Phase 2 or stays completion-specific.
+ infrastructure in Phase 2 or stays completion-specific. Deferred: unblocked
+ only by a second consumer — the marketplace payout run is the first
+ candidate (see "Candidates" above).
## References
diff --git a/docs/plans/decisions.md b/docs/plans/decisions.md
index 61e1170b90..63ba712a98 100644
--- a/docs/plans/decisions.md
+++ b/docs/plans/decisions.md
@@ -14,6 +14,58 @@ get v6 variants). Also renamed `6.0-split-adjustments.md` →
the remainder (legacy-table drop, promotion stacking) is 6.1 work, so
the plan spans two releases like the other `X.Y-X.Z` plans.
+## 2026-08-05: Customer registration graduates to a workflow; core sends no welcome email
+
+Customer creation today runs through three paths with three different
+side-effect sets: store self-registration links a matching newsletter
+subscriber but sends no email; the checkout "create an account" box
+(`Orders::CreateUserAccount`) adopts addresses and sends a welcome email but
+skips subscriber linking; Admin API create does neither. A fourth path —
+storefront OIDC auto-provisioning — is coming and would have reinvented all
+of it again.
+
+`Spree::Customers::Create` (seam `customer_create_workflow`, hooks
+`customers.create.validate` + `customers.create.after_create`) unifies the
+storefront paths. The `validate` hook is the point of the exercise:
+bot/disposable-email screening, fraud checks and B2B registration approval
+all need to *veto* a signup, which the `user.created` lifecycle event
+cannot do. The workflow takes an optional `order:` and absorbs
+`Orders::CreateUserAccount` entirely (one flow = one workflow — the
+Orders::Complete precedent); the old class stays as a deprecated one-release
+shell. Explicitly outside the workflow: Admin API create (plain CRUD — staff
+creation must not be blockable by registration-policy hooks; handlers that
+want to distinguish anyway read `created_by`, the return-eligibility
+pattern) and JWT/refresh-token issuance (HTTP session concern, stays in the
+controller).
+
+Checkout-created accounts are **password-less** (the old service generated a
+random password): blank is the one unclaimed-account state — same as
+admin-created customers — `Customer#valid_password?` guards the blank digest,
+the account is claimed via password reset, and a generated value could fail a
+host's swapped-in `Spree.password_validator`. Self-registration still requires
+a password, because the caller issues a JWT on success. The
+`password_required:` keyword carries that rule: it defaults to **false when
+`order:` is present** (guest checkout collects no password) and **true
+otherwise**, and an explicit value always wins — which is how a future
+provisioning caller with no order (OIDC, invitations) waives the requirement
+deliberately rather than by faking an order.
+
+**The welcome email leaves core.** The only sender was the checkout path
+(`user.send_welcome_email if user.respond_to?` — self-registration never
+sent one, which was an accident of the split, not a choice). Signup email is
+host-app implementation via a `user.created` subscriber or the
+`after_create` hook — the same stance `spree/emails` already takes for
+headless storefronts owning consumer email.
+
+**Upgrade step (host applications).** A host that relied on the checkout
+welcome email — i.e. defines `send_welcome_email` on its customer class — must
+move the send itself, since core no longer calls it. Either subscribe to
+`user.created` (fires on every creation path, including admin and imports) or
+register a handler on `customers.create.after_create` (storefront registration
+only). The method itself can stay; nothing in core invokes it any more.
+
+Plan: `6.0-service-workflows.md` decision 13.
+
## 2026-08-04: Commerce-behavior globals move to Store preferences; app configuration stays global
A full usage audit of `Spree::Config` (multi-agent trace with adversarial
diff --git a/spree/api/app/controllers/spree/api/v3/store/customers_controller.rb b/spree/api/app/controllers/spree/api/v3/store/customers_controller.rb
index 3cb6b572af..29d2db9da4 100644
--- a/spree/api/app/controllers/spree/api/v3/store/customers_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/store/customers_controller.rb
@@ -10,21 +10,18 @@ module Spree
prepend_before_action :require_authentication!, only: [:show, :update]
# POST /api/v3/store/customers
+ # Registration runs through the customer_create_workflow seam
+ # (password requirement, newsletter-subscriber linking, registration
+ # policy hooks); token issuance is an HTTP session concern and
+ # stays here.
def create
- user = Spree.customer_class.new(permitted_params.except(:current_password))
-
- # The model allows a blank password (admin-created customers claim
- # their account via password reset), so self-registration — which
- # issues a JWT + refresh token on success — must require one itself,
- # otherwise a caller with the publishable key could obtain an
- # authenticated session for any unclaimed email.
- if user.password.blank?
- user.errors.add(:password, :blank)
- return render_errors(user.errors)
- end
+ result = Spree.customer_create_workflow.call(
+ store: current_store,
+ **permitted_params.except(:current_password).to_h.symbolize_keys
+ )
- if user.save
- link_matching_newsletter_subscriber!(user)
+ if result.success?
+ user = result.value
refresh_token = Spree::RefreshToken.create_for(user, request_env: {
ip_address: request.remote_ip,
user_agent: request.user_agent&.truncate(255)
@@ -35,7 +32,7 @@ module Spree
user: user_serializer.new(user, params: serializer_params).to_h
}, status: :created
else
- render_errors(user.errors)
+ render_result_error(result)
end
end
@@ -107,11 +104,6 @@ module Spree
def user_serializer
Spree.api.customer_serializer
end
-
- def link_matching_newsletter_subscriber!(user)
- subscriber = Spree::NewsletterSubscriber.find_by(email: user.email, store: current_store)
- Spree::Newsletter::LinkUser.new(subscriber: subscriber, user: user).call
- end
end
end
end
diff --git a/spree/core/app/services/spree/orders/create_user_account.rb b/spree/core/app/services/spree/orders/create_user_account.rb
index 0472a40232..a5e11f9335 100644
--- a/spree/core/app/services/spree/orders/create_user_account.rb
+++ b/spree/core/app/services/spree/orders/create_user_account.rb
@@ -1,73 +1,20 @@
-# this service creates a user account when someone places an order
-# and checks the box to create an account
module Spree
module Orders
+ # @deprecated Use {Spree::Customers::Create}; removed in 6.1. Note that
+ # core no longer sends a welcome email — implement it on the
+ # `user.created` event or the `customers.create.after_create` hook.
class CreateUserAccount
- prepend ::Spree::ServiceModule::Base
-
- def call(order:, accepts_email_marketing: false)
- existing_user = Spree.customer_class.find_by(email: order.email)
- if existing_user.present?
- order.update_columns(customer_id: existing_user.id, updated_at: Time.current)
- order.customer = existing_user
- return success(existing_user)
- end
-
- user = create_new_user(order, accepts_email_marketing)
- return failure(:user_creation_failed) unless user.persisted?
-
- assign_ship_address(order, user)
- assign_bill_address(order, user)
-
- # assign newly created user to the order
- # using update_columns to avoid running validations/callbacks
- order.update_columns(customer_id: user.id, updated_at: Time.current)
- order.customer = user
-
- # send welcome email
- user.send_welcome_email if user.respond_to?(:send_welcome_email)
-
- success(user.reload)
- end
-
- private
-
- def create_new_user(order, accepts_email_marketing = false)
- firstname = order.bill_address&.firstname || order.ship_address&.firstname
- lastname = order.bill_address&.lastname || order.ship_address&.lastname
- phone = order.bill_address&.phone || order.ship_address&.phone
-
- # we need to generate a password for the user
- password = SecureRandom.base58(16)
-
- user = Spree.customer_class.new
- user.email = order.email
- user.first_name = firstname if user.respond_to?(:first_name)
- user.last_name = lastname if user.respond_to?(:last_name)
- user.phone = phone if user.respond_to?(:phone)
- user.accepts_email_marketing = accepts_email_marketing.to_b if user.respond_to?(:accepts_email_marketing)
- user.password = password if user.respond_to?(:password)
- user.password_confirmation = password if user.respond_to?(:password_confirmation)
-
- user.save
-
- user
- end
-
- def assign_bill_address(order, user)
- if order.bill_address.present?
- order.bill_address.update_columns(customer_id: user.id, updated_at: Time.current)
-
- user.update_columns(bill_address_id: order.bill_address_id, updated_at: Time.current) unless user.bill_address_id.present?
- end
- end
-
- def assign_ship_address(order, user)
- if order.ship_address.present?
- order.ship_address.update_columns(customer_id: user.id, updated_at: Time.current)
-
- user.update_columns(ship_address_id: order.ship_address_id, updated_at: Time.current) unless user.ship_address_id.present?
- end
+ def self.call(order:, accepts_email_marketing: false)
+ Spree::Deprecation.warn(
+ 'Spree::Orders::CreateUserAccount is deprecated and will be removed in Spree 6.1. ' \
+ 'Use Spree::Customers::Create (Spree.customer_create_workflow) instead. ' \
+ 'Core no longer sends a welcome email — send it from a user.created subscriber or the customers.create.after_create hook.'
+ )
+ Spree.customer_create_workflow.call(
+ store: order.store,
+ order: order,
+ accepts_email_marketing: accepts_email_marketing.to_b
+ )
end
end
end
diff --git a/spree/core/app/subscribers/spree/order_placed_subscriber.rb b/spree/core/app/subscribers/spree/order_placed_subscriber.rb
index 1edd0b1440..d154823690 100644
--- a/spree/core/app/subscribers/spree/order_placed_subscriber.rb
+++ b/spree/core/app/subscribers/spree/order_placed_subscriber.rb
@@ -25,7 +25,7 @@ module Spree
return if order.customer.present?
return unless order.signup_for_an_account?
- Spree::Orders::CreateUserAccount.call(order: order, accepts_email_marketing: order.accept_marketing?)
+ Spree.customer_create_workflow.call(store: order.store, order: order)
end
end
end
diff --git a/spree/core/app/workflows/spree/customers/create.rb b/spree/core/app/workflows/spree/customers/create.rb
new file mode 100644
index 0000000000..56ffb2fe83
--- /dev/null
+++ b/spree/core/app/workflows/spree/customers/create.rb
@@ -0,0 +1,171 @@
+module Spree
+ module Customers
+ # Creates a customer account — the single storefront registration flow
+ # (docs/plans/6.0-service-workflows.md decision 13).
+ #
+ # Two callers today: store self-registration and the checkout "create an
+ # account" box, which passes `order:` — the customer is built from the
+ # order without a password (the account is claimed via password reset,
+ # like an admin-created one), the order's addresses become the account's
+ # defaults and the order is linked to the new account.
+ #
+ # The `validate` hook is the veto seam for registration policy —
+ # bot/disposable-email screening, fraud checks, B2B approval. Handlers
+ # read the built (unsaved) `customer` plus `order`/`created_by`; staff
+ # bypass is a handler decision via `created_by`, the same pattern as
+ # return eligibility. Core sends no welcome email — signup email is
+ # host-app code on the `user.created` event or the `after_create` hook.
+ class Create < Spree::Workflow
+ hooks :validate, :after_create
+
+ # The customer record — built (unsaved) while :validate runs.
+ attr_reader :customer
+
+ # @param store [Spree::Store] the store the registration happens on;
+ # exposed to hook handlers and scopes the newsletter-subscriber link
+ # @param email [String, nil] defaults to the order email with `order:`
+ # @param password [String, nil]
+ # @param password_confirmation [String, nil]
+ # @param first_name [String, nil] defaults from the order addresses
+ # with `order:`, as do last_name and phone
+ # @param last_name [String, nil]
+ # @param phone [String, nil]
+ # @param accepts_email_marketing [Boolean, nil] defaults from the
+ # order's marketing opt-in with `order:`
+ # @param metadata [Hash, nil]
+ # @param order [Spree::Order, nil] a placed order adopting the new
+ # account; when its email already belongs to a customer, the order is
+ # linked to that account and no new customer is created
+ # @param password_required [Boolean, nil] whether a missing password
+ # fails the registration (the account is created password-less
+ # otherwise and claimed via password reset). Defaults to true except
+ # with `order:` — guest checkout collects no password, while
+ # self-registration must, because the caller issues a JWT on success
+ # @param created_by [Object, nil] the staff actor; nil for storefront
+ # self-registration
+ def perform(store:, email: nil, password: nil, password_confirmation: nil,
+ first_name: nil, last_name: nil, phone: nil,
+ accepts_email_marketing: nil, metadata: nil,
+ order: nil, password_required: nil, created_by: nil)
+ super
+
+ step :adopt_existing_customer
+ step :build_customer
+ step :ensure_password
+
+ # Veto point — registration policy. The customer is built but not
+ # yet persisted.
+ run_hooks :validate
+
+ ApplicationRecord.transaction do
+ step :create_customer
+ step :link_order
+ end
+
+ step :link_newsletter_subscriber
+ run_hooks :after_create
+ success(order ? customer.reload : customer)
+ end
+
+ private
+
+ # Checkout only: an account with the order's email already exists, so
+ # the order joins it instead of registering a duplicate. Registration
+ # policy hooks don't run — nothing is being registered.
+ def adopt_existing_customer
+ return unless order
+
+ existing_customer = Spree.customer_class.find_by(email: order.email)
+ return unless existing_customer
+
+ assign_order_to(existing_customer)
+ halt!(existing_customer)
+ end
+
+ def build_customer
+ @customer = Spree.customer_class.new(customer_attributes)
+ end
+
+ def customer_attributes
+ order_address = order && (order.bill_address || order.ship_address)
+
+ {
+ email: email || order&.email,
+ password: password,
+ password_confirmation: password_confirmation,
+ first_name: first_name || order_address&.firstname,
+ last_name: last_name || order_address&.lastname,
+ phone: phone || order_address&.phone,
+ accepts_email_marketing: accepts_email_marketing.nil? ? order&.accept_marketing? : accepts_email_marketing,
+ metadata: metadata
+ }.compact
+ end
+
+ # The model itself allows a blank password — a password-less account
+ # cannot log in (Customer#valid_password? guards the blank digest) and
+ # is claimed via password reset; whether registration accepts that
+ # state is the password_required policy. No password is generated:
+ # blank is the one unclaimed-account state everywhere, and a generated
+ # value could fail a host's swapped-in Spree.password_validator.
+ def ensure_password
+ return if customer.password.present? || !password_required?
+
+ customer.errors.add(:password, :blank)
+ failure(customer)
+ end
+
+ def password_required?
+ password_required.nil? ? order.nil? : password_required
+ end
+
+ def create_customer
+ failure(customer) unless customer.save
+ end
+
+ def link_order
+ return unless order
+
+ adopt_addresses
+ assign_order_to(customer)
+ end
+
+ # The order's addresses become the new account's defaults — but only
+ # unowned ones: an address already in another customer's address book
+ # must not be re-homed onto the new account.
+ # update_columns because the order is already placed and the address
+ # already validated — re-running validations here could reject a
+ # linkage the checkout accepted.
+ def adopt_addresses
+ addresses = { bill_address_id: order.bill_address, ship_address_id: order.ship_address }.
+ select { |_, address| address.present? && address.customer_id.nil? }
+ return if addresses.empty?
+
+ addresses.values.uniq.each do |address|
+ address.update_columns(customer_id: customer.id, updated_at: Time.current)
+ end
+
+ customer.update_columns(addresses.transform_values(&:id).merge(updated_at: Time.current))
+ end
+
+ # Only the customer link is written. Deliberately NOT
+ # Order#associate_customer! — that backfills the cart's missing
+ # addresses from the customer's address book, which on an order the
+ # buyer already placed would rewrite historical data. The event is
+ # published by hand for the same reason Carts::Associate does it:
+ # update_columns bypasses callbacks.
+ def assign_order_to(account)
+ order.update_columns(customer_id: account.id, updated_at: Time.current)
+ order.customer = account
+ order.publish_event("#{order.event_prefix}.updated")
+ end
+
+ # Someone who subscribed to the newsletter before registering gets their
+ # subscription linked to the new account, with verified opt-in carried
+ # over. Best-effort by design — see Spree::Newsletter::LinkUser.
+ def link_newsletter_subscriber
+ subscriber = Spree::NewsletterSubscriber.find_by(email: customer.email, store: store)
+ Spree::Newsletter::LinkUser.new(subscriber: subscriber, user: customer).call
+ end
+ end
+ end
+end
diff --git a/spree/core/lib/spree/core/dependencies.rb b/spree/core/lib/spree/core/dependencies.rb
index bcc2211c9c..108e421c92 100644
--- a/spree/core/lib/spree/core/dependencies.rb
+++ b/spree/core/lib/spree/core/dependencies.rb
@@ -89,6 +89,9 @@ module Spree
claim_deny_workflow: 'Spree::Claims::Deny',
claim_cancel_workflow: 'Spree::Claims::Cancel',
+ # customers
+ customer_create_workflow: 'Spree::Customers::Create',
+
# tracking numbers
tracking_number_service: 'Spree::TrackingNumbers::BaseService',
diff --git a/spree/core/spec/services/spree/orders/create_user_account_spec.rb b/spree/core/spec/services/spree/orders/create_user_account_spec.rb
index 1e3d767fec..8a4f9dadd4 100644
--- a/spree/core/spec/services/spree/orders/create_user_account_spec.rb
+++ b/spree/core/spec/services/spree/orders/create_user_account_spec.rb
@@ -1,5 +1,7 @@
require 'spec_helper'
+# Deprecated shell — delegates to Spree::Customers::Create. The behavior
+# examples stay to prove the delegation preserves the old contract.
describe Spree::Orders::CreateUserAccount do
subject(:service) { described_class.call(order: order, accepts_email_marketing: accepts_email_marketing) }
@@ -10,6 +12,14 @@ describe Spree::Orders::CreateUserAccount do
create(:completed_order_with_totals, bill_address: address, ship_address: address, store: store, customer: nil, email: '[email protected]')
end
+ before { allow(Spree::Deprecation).to receive(:warn) }
+
+ it 'warns about the deprecation' do
+ service
+
+ expect(Spree::Deprecation).to have_received(:warn).with(/Spree::Customers::Create/)
+ end
+
context 'when order has no user' do
let(:new_user) { Spree.customer_class.find_by!(email: order.email) }
diff --git a/spree/core/spec/subscribers/spree/order_placed_subscriber_spec.rb b/spree/core/spec/subscribers/spree/order_placed_subscriber_spec.rb
index 841d074f21..7bd2e24df5 100644
--- a/spree/core/spec/subscribers/spree/order_placed_subscriber_spec.rb
+++ b/spree/core/spec/subscribers/spree/order_placed_subscriber_spec.rb
@@ -41,4 +41,28 @@ RSpec.describe Spree::OrderPlacedSubscriber do
end
end
end
+
+ describe '#handle account creation on order.placed' do
+ let(:guest_order) do
+ create(:completed_order_with_totals, store: store, customer: nil, email: '[email protected]')
+ end
+
+ context 'when the order asked for an account' do
+ before { guest_order.update!(signup_for_an_account: true) }
+
+ it 'creates the account through the registration workflow' do
+ expect { subscriber.handle(mock_event(guest_order)) }.
+ to change { Spree.customer_class.count }.by(1)
+
+ expect(guest_order.reload.customer.email).to eq('[email protected]')
+ end
+ end
+
+ context 'when the order did not ask for an account' do
+ it 'creates nothing' do
+ expect { subscriber.handle(mock_event(guest_order)) }.
+ not_to change { Spree.customer_class.count }
+ end
+ end
+ end
end
diff --git a/spree/core/spec/workflows/spree/customers/create_spec.rb b/spree/core/spec/workflows/spree/customers/create_spec.rb
new file mode 100644
index 0000000000..d4995ccb93
--- /dev/null
+++ b/spree/core/spec/workflows/spree/customers/create_spec.rb
@@ -0,0 +1,165 @@
+require 'spec_helper'
+
+RSpec.describe Spree::Customers::Create do
+ let(:store) { @default_store }
+
+ before { Spree.hooks.clear! }
+ after { Spree.hooks.clear! }
+
+ describe 'self-registration' do
+ subject(:result) do
+ described_class.call(
+ store: store,
+ email: '[email protected]',
+ password: 'password123',
+ password_confirmation: 'password123',
+ first_name: 'John',
+ last_name: 'Snow'
+ )
+ end
+
+ it 'creates the customer' do
+ expect { result }.to change { Spree.customer_class.count }.by(1)
+
+ expect(result).to be_success
+ expect(result.value.email).to eq('[email protected]')
+ expect(result.value.first_name).to eq('John')
+ end
+
+ it 'refuses a blank password without creating a record' do
+ result = described_class.call(store: store, email: '[email protected]')
+
+ expect(result).to be_failure
+ expect(result.value.errors[:password]).to be_present
+ expect(Spree.customer_class.find_by(email: '[email protected]')).to be_nil
+ end
+
+ it 'creates a password-less account when the caller waives the requirement' do
+ result = described_class.call(store: store, email: '[email protected]', password_required: false)
+
+ expect(result).to be_success
+ expect(result.value.password_digest).to be_blank
+ expect(result.value.valid_password?('anything')).to be(false)
+ end
+
+ it 'surfaces validation errors on the unsaved record' do
+ result = described_class.call(store: store, email: '', password: 'password123')
+
+ expect(result).to be_failure
+ expect(result.value.errors[:email]).to be_present
+ end
+
+ it 'links a pre-existing newsletter subscriber to the new account' do
+ subscriber = create(:newsletter_subscriber, email: '[email protected]', store: store)
+
+ expect(result).to be_success
+ expect(subscriber.reload.customer_id).to eq(result.value.id)
+ end
+
+ it 'propagates verified newsletter opt-in onto the customer' do
+ create(:newsletter_subscriber, :verified, email: '[email protected]', store: store)
+
+ expect(result.value.accepts_email_marketing).to be(true)
+ end
+
+ it 'lets a validate handler reject the registration' do
+ Spree.hooks.register('customers.create.validate') do |workflow|
+ workflow.reject!('disposable emails are not accepted') if workflow.customer.email.end_with?('@customer.com')
+ end
+
+ expect(result).to be_failure
+ expect(result.error.value).to eq('disposable emails are not accepted')
+ expect(Spree.customer_class.find_by(email: '[email protected]')).to be_nil
+ end
+
+ it 'dispatches after_create with the persisted customer' do
+ seen = nil
+ Spree.hooks.register('customers.create.after_create') { |workflow| seen = workflow.customer }
+
+ expect(result).to be_success
+ expect(seen).to eq(result.value)
+ expect(seen).to be_persisted
+ end
+ end
+
+ describe 'checkout account creation (order:)' do
+ subject(:result) { described_class.call(store: store, order: order) }
+
+ let(:address) { create(:address, country: store.default_country, firstname: 'John', lastname: 'Snow') }
+ let(:order) do
+ create(:completed_order_with_totals, bill_address: address, ship_address: address, store: store, customer: nil, email: '[email protected]')
+ end
+
+ it 'creates the customer from the order' do
+ expect { result }.to change { Spree.customer_class.count }.by(1)
+
+ customer = result.value
+ expect(customer.email).to eq(order.email)
+ expect(customer.first_name).to eq(order.bill_address.firstname)
+ expect(customer.last_name).to eq(order.bill_address.lastname)
+ end
+
+ it 'creates the account password-less, claimable via password reset' do
+ expect(result.value.password_digest).to be_blank
+ end
+
+ it 'adopts the order addresses' do
+ customer = result.value
+
+ expect(customer.ship_address).to eq(order.ship_address)
+ expect(customer.bill_address).to eq(order.bill_address)
+ expect(order.bill_address.reload.customer_id).to eq(customer.id)
+ end
+
+ it 'links the order to the customer' do
+ result
+
+ expect(order.reload.customer).to eq(result.value)
+ end
+
+ it 'does not adopt an address that belongs to another customer' do
+ other_customer = create(:user)
+ address.update_columns(customer_id: other_customer.id)
+
+ customer = result.value
+
+ expect(address.reload.customer_id).to eq(other_customer.id)
+ expect(customer.bill_address_id).to be_nil
+ expect(customer.ship_address_id).to be_nil
+ end
+
+ it 'carries the marketing opt-in from the order' do
+ order.update!(accept_marketing: true)
+
+ expect(result.value.accepts_email_marketing).to be(true)
+ end
+
+ context 'when a customer with the order email already exists' do
+ let!(:existing_customer) { create(:user, email: '[email protected]') }
+
+ it 'links the order to the existing account instead of registering' do
+ expect { result }.not_to change { Spree.customer_class.count }
+
+ expect(result).to be_success
+ expect(result.value).to eq(existing_customer)
+ expect(order.reload.customer).to eq(existing_customer)
+ end
+
+ it 'does not run registration policy hooks' do
+ Spree.hooks.register('customers.create.validate') { |workflow| workflow.reject!('never') }
+
+ expect(result).to be_success
+ end
+
+ # The order is already placed — adopting it must never rewrite what
+ # the buyer actually checked out with.
+ it 'does not backfill order addresses from the adopting account' do
+ existing_customer.update!(bill_address: create(:address, country: store.default_country))
+ order.update_columns(bill_address_id: nil)
+
+ expect(result).to be_success
+ expect(order.reload.bill_address_id).to be_nil
+ end
+ end
+ end
+end