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.

15.2 KB
Raw Blame

Action Actors

Status: Implemented — merged to main 2026-09-16 (PR #14659): Spree::Actor, acted_by, Spree.actor_classes, the 8 order-operation associations, the migration and backfill, current_actor and the call-site sweep, serializer fields, dashboard labels and docs. Explicitly 6.1: the remaining 13 associations and removal of the transitional reader (Migration Path step 6). Target: Spree 6.0 — before 6.0-mcp-server.md, which depends on it Depends on: 5.5-admin-api-key-scopes.md (shipped — the API key is the second kind of actor), 6.0-service-workflows.md (workflows already take the actor as a keyword), 6.0-platform-auth.md (the admin user class the columns point at today) Author: Damian Legawiec (design driven with Claude) Last updated: 2026-09-16 (implemented) Tracking: Linear V-3646 · GitHub spree/spree#14658

Summary

Every record that remembers who performed an action on it — who cancelled or approved an order, who created a return, who received a stock transfer — points at the admin user class and nothing else. A write made with a secret API key therefore records nobody: the WMS connector that receives stock, the integration that approves returns, and soon every MCP client, all leave canceler, approver, created_by and their siblings empty. This plan makes those associations polymorphic so an API key is a valid actor, adds the current_actor the Admin API passes to workflows instead of the user alone, backfills existing rows, and exposes the actor's kind on the wire. The 6.0 cut covers the order operations — 8 associations on 6 tables — because those are the paths the MCP server and warehouse connectors hit first; the remaining 13 follow in 6.1 through the same macro. It is a schema change first, which is why it ships before the MCP server rather than inside it. Personal user-bound keys are not built: the industry is moving attribution to apps and credentials, and staff identity for machine clients arrives with OAuth in a later release.

Key Decisions (do not deviate without discussion)

  • The actor of a key-authenticated write is the API key (2026-09-16). Not a personal key, not a service user. The key is what gets named, scoped and revoked, so it is the stable thing to attribute to; when an App model arrives a key can belongs_to :app and displays through it, while the row on the order keeps pointing at the key. Rejected: user-bound personal keys (platforms are retiring them, and a WMS connector is not a person) and deferring attribution to OAuth (leaves every key write unattributed through 6.0).
  • Two actor kinds at 6.0, registered, not open-ended (2026-09-16). Spree.actor_classes holds the admin user class and Spree::ApiKey; the polymorphic type column is validated against it. Extensions register an App or a bot class the same way they register providers. An unregistered class is refused at write time, so a _type column can never hold a customer or an arbitrary model.
  • 6.0 converts the order operations; the rest converts in 6.1 (2026-09-16). Orders (created_by, approver, canceler), refunds (refunder), returns, exchanges and claims (created_by) and stock receipts (received_by): 8 columns on 6 tables, the writes an MCP client or a warehouse connector performs. Purchase orders, stock transfers, gift cards and batches, store credits, tax exemption certificates, product and seller requirement submissions and data requests (13 columns on 9 tables) convert in 6.1 with a second migration and the same backfill task. Accepted trade-off: for one release the same idea is recorded two ways, and a key-created purchase order still records nobody. Rejected: all 21 at once (a wider migration than the 6.0 timeline wants) and all 24 including ownership (a key cannot open the dashboard to see "its" exports).
  • Ownership associations are not actors and stay user-only (2026-09-16). Import#user, Export#user and SavedReport#user gate visibility ("my exports"), they do not record an action. A key-created export has no owner, as today.
  • Existing rows keep working before the backfill runs (2026-09-16). A polymorphic association with a _type of nil answers nil in Rails, so the reader falls back to the admin user class while the type column is empty and warns through Spree::Deprecation. The backfill rake task makes the fallback unnecessary; the fallback is removed in 6.1.
  • The wire exposes the kind as a shorthand next to the id (2026-09-16). canceler_id stays a prefixed id (admin_… or key_…); a sibling canceler_type carries admin_user or api_key through Spree::Base.polymorphic_api_type, the house pattern for polymorphic columns. No nested actor object: the dashboard resolves a name from the id when it needs one, and the payload of every order does not grow by an object per actor.
  • Workflows are not touched (2026-09-16). They already take the actor as a keyword (canceler:, approver:, created_by:, reviewer:) typed [Object, nil], and assign it to the association. Only the callers change: the Admin API passes current_actor where it passed the user.
  • An expanded actor serializes as { id, type, label } (2026-09-16). The order serializer already expands approver, canceler and created_by through the admin user serializer, and the dashboard reads full_name || email off them — neither of which a key has. Those expansions point at a small ActorSerializer instead, which renders any registered actor as its prefixed id, its actor_kind and its actor_label. One code path in the dashboard covers both kinds. Rejected: dropping the expansions (a breaking change to a payload the dashboard consumes, and no name without a second request per actor) and expanding only user actors (the dashboard would show nothing for exactly the key-performed actions this plan exists to record).
  • The API key's own actor columns are fixed here (2026-09-16). spree_api_keys.created_by / revoked_by were already polymorphic, but ApiKeySerializer#created_by_email calls .email on whatever they hold, so a key minted or revoked by another key raises. The serializer gains created_by_type and a label read through actor_label, keeps created_by_email for user actors, and the two api_keys_controller call sites pass current_actor. The plan originally left this file alone; that left a live 500 waiting for the first key-creates-key call.
  • current_actor lives on the shared v3 base and prefers the key only on the Admin branch (2026-09-16). Spree::Api::V3::BaseController#current_actor answers try_spree_current_user; AdminAuthentication overrides it to prefer current_api_key. The post-sale concerns are shared with the seller panel, which is JWT-only, so a single definition is needed — but a publishable Store API key must never become an actor, which is what a bare current_api_key || try_spree_current_user on the base would allow.
  • A create path stamps an actor only where the column can hold one (2026-09-16). ResourceController#build_resource stamps created_by on every model with that column, but only the order operations are polymorphic until 6.1 — so a key-authenticated create of a gift card, batch, store credit, purchase order or transfer would raise on the type mismatch. The build path asks the association whether it accepts the actor and records nobody when it does not, which is what those rows held before keys became actors. The alternative, converting all 21 associations at once, is the wider migration this plan's scope decision already rejected.
  • Attribution and audit are different things (2026-09-16). This plan answers "who". "Through which surface" (dashboard, REST, MCP) is an event the MCP adapter publishes per mutating tool call, defined in 6.0-mcp-server.md; no _via columns here.

Design Details

The Spree::Actor contract and the acted_by macro

# spree/core/app/models/concerns/spree/actor.rb — included in the admin user
# class and Spree::ApiKey; an extension's App class includes it too.
module Spree::Actor
  def actor_label      # what a timeline shows: full name / email, or the key's name
  def actor_kind       # 'admin_user' | 'api_key' | … — polymorphic_api_type of the class
end

# spree/core/app/models/concerns/spree/acted_by.rb
class Spree::Order < Spree.base_class
  include Spree::ActedBy
  acted_by :created_by, :approver, :canceler
end

acted_by :name declares belongs_to :name, polymorphic: true, optional: true, validates name_type against Spree.actor_classes when present, and defines the transitional reader: when name_type is nil and name_id is present, resolve through the admin user class and warn once per process. The association names, readers and writers do not change, so every workflow that does order.canceler = canceler keeps working with either kind of actor. The macro replaces 8 belongs_to … class_name: Spree.admin_user_class lines at 6.0 and the remaining 13 at 6.1.

What converts

6.0 — order operations

Table Associations
spree_orders created_by, approver, canceler
spree_refunds refunder
spree_returns created_by
spree_exchanges created_by
spree_claims created_by
spree_stock_receipts received_by

6.1 — the rest, same macro, second migration

Table Associations
spree_purchase_orders created_by
spree_stock_transfers created_by
spree_gift_cards created_by
spree_gift_card_batches created_by
spree_store_credits created_by
spree_tax_exemption_certificates verified_by
spree_product_submissions submitted_by, reviewed_by
spree_seller_requirement_submissions submitted_by, reviewed_by
spree_data_requests requested_by

Never converted: spree_imports.user, spree_exports.user, spree_saved_reports.user (ownership), and spree_api_keys.created_by / revoked_by (already polymorphic).

Migration

One migration, OrderOperationActorsPolymorphic, targeting [8.1]: for each 6.0 association above, add_column :<table>, :<name>_type, :string (nullable, no default — the type is data, filled by the backfill) and add_index :<table>, [:<name>_type, :<name>_id]. The existing _id indexes stay. No foreign keys, per the migration rules.

Backfill

spree:upgrade:backfill_actor_types sets <name>_type to Spree.admin_user_class.name wherever <name>_id is present and _type is nil, table by table with update_all in batches, over whatever associations are declared with acted_by at the time, so the 6.1 conversion reuses it unchanged. Idempotent. Listed in the 6.0 upgrade guide after migrations; the transitional reader means nothing breaks if an installation runs it late.

The Admin API passes current_actor

Spree::Api::V3::Admin::BaseController#current_actor answers the signed-in admin for a JWT request and current_api_key for a key request. The ten call sites that pass try_spree_current_user as an actor keyword (canceler:, approver:, created_by:, reviewer:, refunder:, user:) pass current_actor instead. Controllers that assign an actor directly (@resource.approved_by(try_spree_current_user)) do the same. A workflow that needs a person specifically — none does today — would check actor.is_a?(Spree.admin_user_class) itself.

Serializers

Every admin serializer exposing <name>_id gains <name>_type (typelize … enum_type_name: 'ActorKind', an open list because extensions register kinds). The id stays the actor's prefixed id, so an api_key actor reads key_…. Store serializers expose no actors and are unchanged.

The order serializer's existing approver / canceler / created_by expansions render through Spree::Api::V3::Admin::ActorSerializer — { id, type, label } for any registered actor — rather than the admin user serializer, which only a person can satisfy. Spree::Api::V3::Admin::ApiKeySerializer gains created_by_type and created_by_label; its created_by_email stays for user actors.

Dashboard

Order, return and claim pages that show "cancelled by" or "created by" render the actor's label from the id: a person's name for admin_user, the key's name with a key icon for api_key. Strings through i18next in every locale. No new screens.

Events

Event payloads carrying actor ids already use prefixed ids, so an api_key actor is visible to subscribers as key_… with no payload change.

Migration Path

  1. Core — ✅ shipped (PR #14659): Spree::Actor, Spree::ActedBy, Spree.actor_classes, the macro applied to the 8 order-operation associations, the migration, the backfill task, model specs for the type validation and the transitional reader.
  2. API — ✅ shipped: current_actor, the call-site changes, <name>_type on the serializers, regenerated types and OpenAPI, controller specs asserting a key-authenticated cancel records the key.
  3. Dashboard — ✅ shipped: actor labels where actors are shown.
  4. Docs — ✅ shipped: the 6.0 upgrade guide gains the backfill step; the Admin API docs note that *_id actors may be keys and what *_type says.
  5. 6.0-mcp-server.md then injects context.actor (user or key) into workflow principal parameters with no further change.
  6. 6.1: the macro on the remaining 13 associations, one migration, the same backfill task, the serializer fields, and removal of the transitional reader.

Constraints on Current Work

  • A new "who did this" association is declared with acted_by, never with belongs_to … class_name: Spree.admin_user_class. Ownership associations that gate visibility keep the plain form.
  • Controllers pass current_actor to workflows, not try_spree_current_user, for any actor keyword.
  • A caller writing an actor through update_columns or update_all uses Spree::ActedBy.columns_for, never a hand-written id/type pair — an id without its type names nothing, and the two workflows that write this way both got it wrong before the helper existed.
  • Workflow principal parameters stay typed [Object, nil] and are assigned, not inspected; a workflow that must refuse non-human actors says so explicitly and documents why.
  • A new actor kind registers in Spree.actor_classes in the same PR that introduces the class.

Open Questions

Nothing blocks implementation. Deferred by decision, not by uncertainty: the 13 remaining associations (6.1, step 6), and OAuth-issued identity for machine clients, which will resolve a token to one of the two actor kinds defined here (6.0-mcp-server.md, OAuth lane).

References

  • docs/plans/6.0-mcp-server.md — the consumer; its principal injection depends on this plan
  • docs/plans/5.5-admin-api-key-scopes.md — the API key model and its already-polymorphic created_by
  • docs/plans/6.0-service-workflows.md — actor keywords on workflows
  • Precedents for attributing to apps and credentials rather than people: Shopify order timeline "by app", Stripe request attribution to keys and OAuth apps, GitHub's move from classic personal tokens to app installations