spree-project
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseSpree Commerce Project (Spree 6)
Spree Commerce 项目(Spree 6)
Spree is a headless commerce engine: a Rails app (the gems) that serves the Store, Admin and Seller REST APIs, plus TypeScript apps you own (a React admin dashboard and a Next.js storefront). Customization happens around the engine — configuration, hooks, events, providers — not by forking it.
spreeComing from Spree 5.x? Read theskill first — cart/order split, no state machines, React dashboard, API v2 andspree-upgrade-5-to-6removed.spree_admin
Spree 是一个 headless commerce 引擎:一个 Rails 应用( gems),负责提供 Store、Admin 和 Seller REST API,此外还包括由你自行维护的 TypeScript 应用(一个 React admin dashboard 和一个 Next.js storefront)。定制发生在引擎周围——通过 configuration、hooks、events 和 providers——而不是 fork 引擎。
spree从 Spree 5.x 升级而来吗?先阅读skill——涉及 cart/order 拆分、移除 state machines、React dashboard、API v2,以及移除spree-upgrade-5-to-6。spree_admin
Detect the project flavor FIRST — it changes every command
首先检测项目形态——它会改变每一条命令
| Signal | Flavor | How commands run |
|---|---|---|
| create-spree-app project | |
Rails app at the repo root ( | classic Rails app | Native from the app root: |
If isn't on PATH, use / . The CLI accepts both and the older directory name.
spreenpx spree …pnpm exec spree …server/backend/| Task | Spree CLI | Classic Rails app |
|---|---|---|
| Run the stack | | |
| Rails console | | |
| Shell in the container | | (you're already in one) |
| Install + run migrations | | |
| Generator | | |
| Run specs | | |
| Rake task | | |
| Sample data | | |
| Version upgrade | | |
| Anything else | | |
Paths written in these skills mean in a classic app.
server/app/...app/...| 信号 | 形态 | 命令运行方式 |
|---|---|---|
| create-spree-app 项目 | |
仓库根目录是 Rails 应用( | 经典 Rails 应用 | 在应用根目录直接执行: |
如果 不在 PATH 中,请使用 / 。CLI 同时支持 和较旧的 目录名。
spreenpx spree …pnpm exec spree …server/backend/| 任务 | Spree CLI | 经典 Rails 应用 |
|---|---|---|
| 启动技术栈 | | |
| Rails console | | |
| 进入容器 shell | | (你已经在容器内) |
| 安装并运行 migrations | | |
| Generator | | |
| 运行 specs | | |
| Rake task | Spree tasks 使用 | |
| 示例数据 | | |
| 版本升级 | | |
| 其他操作 | | |
这些 skills 中写作 的路径,在经典应用中表示 。
server/app/...app/...Project layout (create-spree-app)
项目结构(create-spree-app)
text
my-store/
├── server/ # The Spree API — a full Rails 8.1 app (spree-starter). Your Ruby code lives here.
│ ├── app/{models,services,workflows,subscribers,controllers,serializers}/
│ ├── config/initializers/spree.rb # hooks, registries, dependencies, subscribers
│ ├── Dockerfile # builds the production image (API + dashboard)
│ └── Gemfile
├── apps/
│ ├── dashboard/ # React admin (@spree/dashboard) — plugins in src/plugins.ts
│ ├── seller-dashboard/ # Marketplace seller panel (optional)
│ └── storefront/ # Next.js storefront on @spree/sdk (optional)
├── docker-compose.yml # prebuilt ghcr.io/spree/spree image + Postgres (Meilisearch optional, commented out)
├── .env # SECRET_KEY_BASE, ACTIVE_RECORD_ENCRYPTION_* keys, SPREE_PORT, SPREE_VERSION_TAG… (mode 0600)
├── AGENTS.md / CLAUDE.md # generated agent instructions
└── package.json # pins @spree/cli- is the only part that is Spree's. The apps are ordinary Vite/Next.js projects you own.
server/ - By default the stack runs the prebuilt image. To change Ruby code, run once — compose then builds from
spree eject. If eject fails on a fresh stack withserver/, the dev server exited because its database didn't exist yet.service "web" is not running3.1.0 has this bug. Releases after it build the dev image, start and wait for Postgres, and prepare the database in a one-off container before starting the stack (also on@spree/cliof an ejected project), and they switch older dev compose files to aspree inithealth check. Bumppg_isready -h 127.0.0.1in@spree/cliand re-run.package.json - Stack: Rails 8.1, Ruby ≥ 3.2; PostgreSQL, MySQL or SQLite. Background jobs run in-process via Solid Queue (Mission Control at ), Solid Cache; Sidekiq/Redis is optional. The dashboard is served at
/jobsby the/dashboardgem in production (one image, same origin).spree_dashboard - APIs: Store (publishable key
/api/v3/store), Adminpk_…(secret key/api/v3/adminor staff JWT), Sellersk_…(seller JWT +/api/v3/seller). SeeX-Spree-Seller-Id.spree-api-v3
text
my-store/
├── server/ # The Spree API — a full Rails 8.1 app (spree-starter). Your Ruby code lives here.
│ ├── app/{models,services,workflows,subscribers,controllers,serializers}/
│ ├── config/initializers/spree.rb # hooks, registries, dependencies, subscribers
│ ├── Dockerfile # builds the production image (API + dashboard)
│ └── Gemfile
├── apps/
│ ├── dashboard/ # React admin (@spree/dashboard) — plugins in src/plugins.ts
│ ├── seller-dashboard/ # Marketplace seller panel (optional)
│ └── storefront/ # Next.js storefront on @spree/sdk (optional)
├── docker-compose.yml # prebuilt ghcr.io/spree/spree image + Postgres (Meilisearch optional, commented out)
├── .env # SECRET_KEY_BASE, ACTIVE_RECORD_ENCRYPTION_* keys, SPREE_PORT, SPREE_VERSION_TAG… (mode 0600)
├── AGENTS.md / CLAUDE.md # generated agent instructions
└── package.json # pins @spree/cli- **是唯一属于 Spree 的部分。**这些 apps 是由你自行维护的普通 Vite/Next.js 项目。
server/ - 默认情况下,技术栈运行预构建镜像。要修改 Ruby 代码,请先运行一次 ——之后 compose 将基于
spree eject构建。如果在全新技术栈上 eject 失败并出现server/,说明开发服务器已退出,因为数据库尚不存在。service "web" is not running"3.1.0 存在此 bug。3.1.0 之后的版本会构建开发镜像、启动并等待 Postgres,并在启动技术栈前于一次性容器中准备数据库(对已 eject 的项目执行@spree/cli时也同样如此);它们还会将较旧的开发 compose 文件切换为使用spree init的 health check。请升级pg_isready -h 127.0.0.1中的package.json并重新运行。@spree/cli - 技术栈:Rails 8.1、Ruby ≥ 3.2;PostgreSQL、MySQL 或 SQLite。后台任务通过 Solid Queue 在进程内运行(Mission Control 位于 ),并使用 Solid Cache;Sidekiq/Redis 为可选。在生产环境中,dashboard 由
/jobsgem 在spree_dashboard提供(单一镜像,同源)。/dashboard - API:Store (publishable key
/api/v3/store)、Adminpk_…(secret key/api/v3/admin或 staff JWT)、Sellersk_…(seller JWT +/api/v3/seller)。参见X-Spree-Seller-Id。spree-api-v3
Conventions you should always follow
始终应遵循的约定
- Namespace under , files under
Spree::etc. Your own non-Spree classes can use your app namespace (server/app/models/spree/…).MyApp::… - Inherit from (defaults to
Spree.base_class), notSpree::Base. It brings preferences, prefixed IDs, ransack allowlists, document numbers,ApplicationRecord.additional_permitted_attributes - Users are two classes: (default
Spree.customer_class, tableSpree::Customer,spree_customers) andcust_…(Spree.admin_user_class,Spree::AdminUser). Never hardcode either.adm_…is a deprecated alias.Spree.user_class - Scope every query through the store: ,
current_store.products— neverstore.ordersin request code. In dev/testSpree::Order.allflags unscoped queries.SPREE_STORE_SCOPE_GUARD=log|raise|off - carries per-request
Spree::Current,store,channel,market,currency.localefalls back toSpree::Current.store, which can be nil (no store flagged default) — setSpree::Store.defaultexplicitly in jobs, rake tasks and specs. Assigning it also arms the dev/testSpree::Current.store = storefor the rest of that job/script, so unscoped queries there get flagged too (wrap deliberately global lookups inStoreScopeGuard). An installation-wide job (a nightly sweep over every store's records) must run each record in its own store, or its emails, events and store settings come from the default store. UseSpree::StoreScopeGuard.skip { … }, which starts from a clean context and restores the previous one afterwards. Jobs subclassingSpree::Current.with_store(store) { … }can call the privateSpree::BaseJob, which core's own sweeps (stale drafts, expired carts, time-based collections, payouts) use.each_store_of(relation) { |store_records| … } - No state machines, no enums for lifecycles. Statuses are string columns declared with
status(has_status); transitions are workflows (Spree::HasStatus). Extend withapp/workflows— plus your own workflow to move records into it. SeeModel.add_status('on_hold', after: 'approved').spree-workflows - is required by default — pass
belongs_towhen the FK may be nil, or saves fail with "… must exist". Always passoptional: trueand an explicitclass_name:ondependent:.has_many - No DB foreign keys on business tables; add an index instead. Uniqueness validations are store-scoped in core.
- IDs are strings at the API surface — Stripe-style prefixed IDs (,
prod_…,cart_…,or_…). Look up withpy_…; neverModel.find_by_prefix_id!(id)an ID and never expose integer IDs. Full table:.to_i.spree-data-model - Cart ≠ Order. is mutable checkout state; completing it creates an immutable
Spree::Cart(Spree::Orderdraft/placed/canceled). Code that runs on both readsstatus, notline_item.owner..order - Custom data: merchant-facing, typed, filterable → custom fields (,
product.set_custom_field('custom.material', 'Cotton')). Machine/integration data →get_custom_field(schemaless JSON, write-only in Store API). A new column only when your own code queries it heavily.metadata - Side effects go in events / hooks, not callbacks. React after the fact with a (
Spree::Subscriber, …); run inside a flow withorder.placed. Don't addSpree.hooks.register('carts.complete.validate', …)to Spree models.after_save - Writable API attributes: —
Spree::Product.additional_permitted_attributes += [:brand_id], never+=(the default is frozen).<< - Services return results, not exceptions: ; check
result = Spree.cart_add_item_workflow.call(...).result.success? - Money in the API is a string () with a
"135.60"twin — render the display one.display_… - Secrets go in Rails credentials or env vars; Spree's installation settings are all env vars (see
SPREE_*). Active Record encryption keys (spree-customization) must be set in every environment —ACTIVE_RECORD_ENCRYPTION_*generates a dev set;create-spree-appadds one to older projects (seespree encryption init).spree-security
- 在 下使用命名空间,文件位于
Spree::等目录。你自己的非 Spree 类可以使用应用命名空间(server/app/models/spree/…)。MyApp::… - 继承 (默认为
Spree.base_class),而不是Spree::Base。它提供 preferences、带前缀的 ID、ransack allowlists、document numbers 和ApplicationRecord。additional_permitted_attributes - 用户分为两个类:(默认为
Spree.customer_class,表Spree::Customer,ID 前缀为spree_customers)和cust_…(Spree.admin_user_class,ID 前缀为Spree::AdminUser)。永远不要硬编码其中任何一个。adm_…是已弃用的别名。Spree.user_class - **每个查询都必须通过 store 限定作用域:**使用 、
current_store.products——在 request 代码中绝不要使用store.orders。在 dev/test 中,Spree::Order.all会标记未限定作用域的查询。SPREE_STORE_SCOPE_GUARD=log|raise|off - 承载每个请求的
Spree::Current、store、channel、market和currency。locale会回退到Spree::Current.store,而后者可能为 nil(没有任何 store 被标记为默认)——在 jobs、rake tasks 和 specs 中应显式设置Spree::Store.default。赋值后还会为该 job/script 的剩余执行过程启用 dev/test 的Spree::Current.store = store,从而标记未限定作用域的查询(有意进行的全局查找请包裹在StoreScopeGuard中)。覆盖所有 store 记录的安装级 job(例如每晚扫描所有 store 记录的 job)必须让每条记录在各自的 store 中运行,否则它发送的 emails、events 以及使用的 store settings 将来自默认 store。请使用Spree::StoreScopeGuard.skip { … },它会从干净的上下文开始,并在结束后恢复之前的上下文。继承Spree::Current.with_store(store) { … }的 jobs 可以调用私有的Spree::BaseJob,core 自身的定期清理任务(过期草稿、过期购物车、基于时间的 collections、payouts)也使用此方法。each_store_of(relation) { |store_records| … } - **不使用 state machines,生命周期也不使用 enums。**状态是使用 (
has_status)声明的字符串Spree::HasStatus列;状态转换使用 workflows(status)。扩展时使用app/workflows——同时还要编写自己的 workflow,将记录 transition 到该状态。参见Model.add_status('on_hold', after: 'approved')。spree-workflows - 默认情况下 是必需的——当外键可能为 nil 时传入
belongs_to,否则保存会失败并提示"… must exist"。optional: true始终要传入has_many和明确的class_name:。dependent: - 业务表不使用数据库外键;请改为添加 index。core 中的 uniqueness validations 按 store 限定作用域。
- API 层的 ID 是字符串——采用 Stripe 风格的前缀化 ID(、
prod_…、cart_…、or_…)。使用py_…查找;绝不要对 ID 调用Model.find_by_prefix_id!(id),也绝不要暴露整数 ID。完整对照表见.to_i。spree-data-model - Cart ≠ Order。是可变的结账状态;完成购物车后会创建不可变的
Spree::Cart(Spree::Order为 draft/placed/canceled)。同时适用于二者的代码应读取status,而不是line_item.owner。.order - **自定义数据:**面向商家、类型明确且可筛选的数据 → 使用 custom fields(、
product.set_custom_field('custom.material', 'Cotton'))。机器/集成数据 → 使用get_custom_field(无 schema 的 JSON,在 Store API 中为只写)。只有在自有代码会频繁查询某个字段时,才应新增列。metadata - **副作用应放在 events / hooks 中,而不是 callbacks 中。**对已发生的事情作出反应时,使用 (
Spree::Subscriber等);在流程内部执行时,使用order.placed。不要在 Spree models 上添加Spree.hooks.register('carts.complete.validate', …)。after_save - 可写 API attributes:——使用
Spree::Product.additional_permitted_attributes += [:brand_id],绝不要使用+=(默认值已 frozen)。<< - Services 返回结果,而不是抛出异常:;然后检查
result = Spree.cart_add_item_workflow.call(...)。result.success? - API 中的金额是字符串(),并配有一个
"135.60"对应字段——请渲染 display 版本。display_… - Secrets 应存放在 Rails credentials 或环境变量中;Spree 的所有安装设置均使用 环境变量(参见
SPREE_*)。Active Record encryption 密钥(spree-customization)必须在每个环境中设置——ACTIVE_RECORD_ENCRYPTION_*会生成一组开发环境密钥;create-spree-app为旧项目添加密钥(参见spree encryption init)。spree-security
Where customization goes (short version)
自定义放在哪里(简版)
Walk this list top-down — higher options are cheaper and survive upgrades better. The skill has the full decision table.
spree-customization- Store settings (dashboard → Settings; Admin API) — markets, currencies, delivery, taxes, order numbering. Data, not code.
- Configuration — env vars /
SPREE_*; per-recordSpree.configs.preference - Workflow hooks — to veto or extend a core flow (
Spree.hooks.register('<flow>.<hook>', 'MyApp::Handler')).spree-workflows - Events & subscribers — react after something happened ().
spree-events-webhooks - Checkout registry — /
Spree::Checkout::Registry.add_requirement(register_step).spree-checkout - Providers — tax, delivery rates, fulfillment, search, pricing, inventory, payouts, digital assets, auth ().
spree-providers - Ransack allowlists — .
Spree.ransack.add_attribute(Spree::Product, :erp_id) - Webhooks — notify external systems without Ruby.
- Dependencies — replace a whole workflow/service: (
Spree::Dependencies.cart_add_item_workflow = 'MyApp::Carts::AddItem').spree-dependencies - Decorators — last resort, for structural additions (associations, scopes) ().
spree-decorators
Admin UI changes happen in the React dashboard via plugins (, ), not in Rails views.
spree-dashboardspree-dashboard-plugins请自上而下浏览此列表——越靠前的选项成本越低,且越容易在升级后继续使用。 skill 中有完整的决策表。
spree-customization- Store 设置(dashboard → Settings;Admin API)——markets、currencies、delivery、taxes、order numbering。属于数据,而非代码。
- Configuration——环境变量 /
SPREE_*;单条记录的Spree.configs。preference - Workflow hooks——,用于否决或扩展 core flow(
Spree.hooks.register('<flow>.<hook>', 'MyApp::Handler'))。spree-workflows - Events & subscribers——对某件事已经发生作出反应()。
spree-events-webhooks - Checkout registry——/
Spree::Checkout::Registry.add_requirement(register_step)。spree-checkout - Providers——tax、delivery rates、fulfillment、search、pricing、inventory、payouts、digital assets、auth()。
spree-providers - Ransack allowlists——。
Spree.ransack.add_attribute(Spree::Product, :erp_id) - Webhooks——无需 Ruby 即可通知外部系统。
- Dependencies——替换整个 workflow/service:(
Spree::Dependencies.cart_add_item_workflow = 'MyApp::Carts::AddItem')。spree-dependencies - Decorators——最后手段,用于结构性扩展(associations、scopes)()。
spree-decorators
Admin UI 的变更应通过 plugins 在 React dashboard 中完成(、),而不是在 Rails views 中完成。
spree-dashboardspree-dashboard-pluginsCommon CLI commands
常用 CLI 命令
bash
spree dev # run API (+ dashboard dev server if apps/dashboard exists); first run completes setup
spree stop | restart | logs [worker]
spree console | shell | db:console
spree migrate | migrate:status | migrate:rollback
spree generate api_resource Brand name:string # → spree:api_resource
spree generate subscriber ErpSync order.placed # class + registration in initializers/spree.rb
spree test [path[:line]] # tests in RAILS_ENV=test; creates the test DB if missing (CLI 3.6+; older: spree rspec)
spree add --gem <gem> # adds the gem, runs its installer + migrations; a prebuilt project is ejected first (asks; new dev DB)
spree eject # build from server/ instead of the prebuilt image
spree build [--production] # rebuild dev image / build the production image (API + dashboard)
spree add dashboard # add apps/dashboard (also: spree add seller-dashboard)
spree plugin new <name> # scaffold a dashboard plugin monorepo
spree update # pull latest image, recreate containers (migrations run on boot)
spree upgrade [--plan] # bundle update + migrate + spree:upgrade data steps
spree seed | sample-data | user create | api-key create|list|revoke
spree encryption init [--print] # add ACTIVE_RECORD_ENCRYPTION_* keys to .env (never overwrites); --print for production
spree exec bin/rails spree:setup:token # reprint the first-run admin setup link
spree api <verb> <path> # call the Admin API from the terminal (see spree-cli)spree db:resetbash
spree dev # run API (+ dashboard dev server if apps/dashboard exists); first run completes setup
spree stop | restart | logs [worker]
spree console | shell | db:console
spree migrate | migrate:status | migrate:rollback
spree generate api_resource Brand name:string # → spree:api_resource
spree generate subscriber ErpSync order.placed # class + registration in initializers/spree.rb
spree test [path[:line]] # tests in RAILS_ENV=test; creates the test DB if missing (CLI 3.6+; older: spree rspec)
spree add --gem <gem> # adds the gem, runs its installer + migrations; a prebuilt project is ejected first (asks; new dev DB)
spree eject # build from server/ instead of the prebuilt image
spree build [--production] # rebuild dev image / build the production image (API + dashboard)
spree add dashboard # add apps/dashboard (also: spree add seller-dashboard)
spree plugin new <name> # scaffold a dashboard plugin monorepo
spree update # pull latest image, recreate containers (migrations run on boot)
spree upgrade [--plan] # bundle update + migrate + spree:upgrade data steps
spree seed | sample-data | user create | api-key create|list|revoke
spree encryption init [--print] # add ACTIVE_RECORD_ENCRYPTION_* keys to .env (never overwrites); --print for production
spree exec bin/rails spree:setup:token # reprint the first-run admin setup link
spree api <verb> <path> # call the Admin API from the terminal (see spree-cli)spree db:resetWhere to find Spree documentation
在哪里查找 Spree 文档
Read the installed docs before guessing from training data — they match the installed version:
text
node_modules/@spree/docs/dist/
├── developer/
│ ├── getting-started/ create-spree-app/ cli/
│ ├── core-concepts/ # products, carts, orders, payments, fulfillments, markets, …
│ ├── customization/ # quickstart, configuration, workflows, dependencies, decorators, permissions, validations
│ ├── providers/ # ERP, PIM, DAM, fulfillment, payouts, SSO, observability
│ ├── how-to/ # custom payment method, delivery rate provider, search provider, B2B, marketplace…
│ ├── dashboard/ # React admin: customization, plugins, recipes
│ ├── sdk/ storefront/ multi-tenant/ security/ deployment/ upgrades/ tutorial/
└── api-reference/ # Store/Admin API guides + OpenAPI specs- No local package (classic app)? Use https://spreecommerce.org/docs/llms.txt (index) or append to any docs URL.
.md - The Spree docs MCP server () searches the latest published docs:
https://spreecommerce.org/docs/mcp.claude mcp add --transport http spree-docs https://spreecommerce.org/docs/mcp - Never use pages for a Spree 6 project.
docs/v5/
在猜测之前,先阅读已安装的文档——它们与已安装的版本一致:
text
node_modules/@spree/docs/dist/
├── developer/
│ ├── getting-started/ create-spree-app/ cli/
│ ├── core-concepts/ # products, carts, orders, payments, fulfillments, markets, …
│ ├── customization/ # quickstart, configuration, workflows, dependencies, decorators, permissions, validations
│ ├── providers/ # ERP, PIM, DAM, fulfillment, payouts, SSO, observability
│ ├── how-to/ # custom payment method, delivery rate provider, search provider, B2B, marketplace…
│ ├── dashboard/ # React admin: customization, plugins, recipes
│ ├── sdk/ storefront/ multi-tenant/ security/ deployment/ upgrades/ tutorial/
└── api-reference/ # Store/Admin API guides + OpenAPI specs- 没有本地 package(经典应用)吗?使用 https://spreecommerce.org/docs/llms.txt(索引),或在任意文档 URL 后追加 。
.md - Spree docs MCP server(https://spreecommerce.org/docs/mcp)可搜索最新发布的文档:`claude mcp add --transport http spree-docs https://spreecommerce.org/docs/mcp`。
- 对于 Spree 6 项目,绝不要使用 页面。
docs/v5/
When in doubt
不确定时
- Which extension pattern? →
spree-customization - How models relate, which ID prefix, which status values? →
spree-data-model - New model + API endpoint? →
spree-resource - Hooks / writing a workflow? →
spree-workflows - Tests? → . Upgrading? →
spree-testing/spree-upgrade.spree-upgrade-5-to-6
- 不确定该使用哪种扩展模式?→
spree-customization - 模型如何关联、使用哪种 ID 前缀或状态值?→
spree-data-model - 新建 model + API endpoint?→
spree-resource - Hooks / 编写 workflow?→
spree-workflows - 测试?→ 。升级?→
spree-testing/spree-upgrade。spree-upgrade-5-to-6