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.

Fix: generators and scaffolds produce working Spree 6 code (#14703)

Damian Legawiec9e41f7da03a9
diff --git a/.changeset/admin-sdk-refund-reason-prefix.md b/.changeset/admin-sdk-refund-reason-prefix.md
new file mode 100644
index 0000000000..91eb739677
--- /dev/null
+++ b/.changeset/admin-sdk-refund-reason-prefix.md
@@ -0,0 +1,5 @@
+---
+"@spree/admin-sdk": patch
+---
+
+The `refund_reason_id` documentation now shows the refund reason ID prefix Spree actually uses (`rr_…`).
diff --git a/.changeset/cli-plugin-template-peers.md b/.changeset/cli-plugin-template-peers.md
new file mode 100644
index 0000000000..f7ba5308fe
--- /dev/null
+++ b/.changeset/cli-plugin-template-peers.md
@@ -0,0 +1,7 @@
+---
+"@spree/cli": patch
+---
+
+`spree plugin new` now scaffolds a dashboard plugin that installs against the current dashboard. Its `@spree/admin-sdk` and `@spree/dashboard-*` peer ranges come from the versions released alongside the CLI, instead of old `0.x` ranges no published package matched. The plugin package also gains a `build` script, so `pnpm build` at the plugin root no longer fails, and a `sideEffects` entry so bundlers never drop the import that registers the plugin. The generated README no longer describes an `engine/` directory the CLI does not create.
+
+`spree build --production` builds from the project root again with the current starter Dockerfile, so a customized `apps/dashboard` is included in the image instead of being left out.
diff --git a/.changeset/create-spree-app-admin-and-render.md b/.changeset/create-spree-app-admin-and-render.md
new file mode 100644
index 0000000000..15c0dfb54f
--- /dev/null
+++ b/.changeset/create-spree-app-admin-and-render.md
@@ -0,0 +1,5 @@
+---
+"create-spree-app": patch
+---
+
+The generated README and the closing summary no longer point at a Rails admin at `/admin`, which Spree 6 does not have; without the React Dashboard, the summary shows the command that adds it. The subscriber example uses `order.placed` rather than the deprecated `order.completed`. The relocated `render.yaml` always builds `server/Dockerfile`, whether the starter's Blueprint was written for this layout or for deploying the starter on its own.
diff --git a/docs/developer/cli/quickstart.mdx b/docs/developer/cli/quickstart.mdx
index 38b7e31030..1307b0b0fd 100644
--- a/docs/developer/cli/quickstart.mdx
+++ b/docs/developer/cli/quickstart.mdx
@@ -233,7 +233,7 @@ spree generate subscriber OmsOrderSync order.placed # runs spree:su
spree generate migration AddPositionToSpreeBrands position:integer # Rails built-in, forwarded as-is
```
-`spree:api_resource` scaffolds the full v3 surface: model, migration, Store + Admin controllers and serializers, factory, controller specs, and routes.
+`spree:api_resource` scaffolds the full v3 surface: model, migration, Store + Admin controllers and serializers, factory, controller specs, routes, and the `read_<resources>` / `write_<resources>` permissions that let staff roles and secret API keys reach the Admin API.
### `spree migrate`
diff --git a/docs/developer/contributing/creating-an-extension.mdx b/docs/developer/contributing/creating-an-extension.mdx
index e0075d284d..05becd3fda 100644
--- a/docs/developer/contributing/creating-an-extension.mdx
+++ b/docs/developer/contributing/creating-an-extension.mdx
@@ -25,10 +25,10 @@ In this guide we build `spree_reviews`: customers read product reviews through t
## Generate the extension
-Install the Spree extension generator:
+Install the Spree extension generator. Spree 6 needs version 2.0 or newer — earlier versions generate a Spree 5 scaffold built around the Rails admin:
```bash
-gem install spree_extension
+gem install spree_extension -v '>= 2.0'
```
Run the following command from a directory outside your Spree application:
@@ -37,16 +37,12 @@ Run the following command from a directory outside your Spree application:
spree-extension create reviews
```
-This creates a `spree_reviews` directory containing the engine, a gemspec, a test setup and continuous integration configuration. Change to its directory:
+This creates a `spree_reviews` directory containing the engine, a gemspec, a test setup and continuous integration configuration. Its `config/routes.rb` and `config/initializers/spree.rb` come with commented-out Spree 6 examples — API routes, permission scopes, workflow hooks and event subscribers — that the steps below fill in. Change to its directory:
```bash
cd spree_reviews
```
-<Warning>
- The generated scaffold still declares a dependency on `spree_admin`, the Spree 5 Rails admin, which does not exist in Spree 6. Remove the `spree_admin` lines from both the `.gemspec` and the `Gemfile` before running `bundle install`. The JavaScript, importmap and asset setup in the scaffold is only used by the Spree 5 admin, so you can delete it too.
-</Warning>
-
## Add a model
Create the migration in `db/migrate/`:
@@ -292,10 +288,10 @@ module SpreeReviews
end
```
-Subscribers are not discovered automatically. Register them from the engine:
+Subscribers are not discovered automatically. Register them in the extension's initializer — `bin/rails g spree:subscriber` adds the line for you:
-```ruby lib/spree_reviews/engine.rb
-config.after_initialize do
+```ruby config/initializers/spree.rb
+Rails.application.config.after_initialize do
Spree.subscribers << SpreeReviews::ReviewRequestSubscriber
end
```
@@ -316,15 +312,7 @@ end
Spree::Product.prepend SpreeReviews::ProductDecorator
```
-Decorators are not loaded automatically. Load them from your engine:
-
-```ruby lib/spree_reviews/engine.rb
-config.to_prepare do
- Dir.glob(root.join('app/**/*_decorator*.rb')) do |decorator|
- Rails.configuration.cache_classes ? require(decorator) : load(decorator)
- end
-end
-```
+Rails does not load decorators on its own, so the scaffold's engine does it for you: `lib/spree_reviews/engine.rb` loads every `app/**/*_decorator*.rb` file at boot and again on each code reload in development. Name the file with a `_decorator` suffix and there is nothing else to wire up.
## Add admin screens
diff --git a/docs/developer/dashboard/plugins/publishing.mdx b/docs/developer/dashboard/plugins/publishing.mdx
index 90ba1a3f86..6273501fcb 100644
--- a/docs/developer/dashboard/plugins/publishing.mdx
+++ b/docs/developer/dashboard/plugins/publishing.mdx
@@ -27,13 +27,13 @@ Your plugin imports React, the dashboard, Tailwind, i18next, etc., but **you don
}
```
-Use ranges, not exact versions — pin too tightly and consumers can't upgrade the dashboard without you cutting a release. One pre-release caveat: a range like `^1.0.0-beta.3` accepts later `1.0.0` betas and every stable `1.x` release, but not betas of other versions — so keep your `@spree/dashboard-*` peers in step with the dashboard until 1.0 ships. Check the ranges `spree plugin new` scaffolds against the versions your host app installs.
+Use ranges, not exact versions — pin too tightly and consumers can't upgrade the dashboard without you cutting a release. One pre-release caveat: a range like `^1.0.0-beta.3` accepts later `1.0.0` betas and every stable `1.x` release, but not betas of other versions — so keep your `@spree/dashboard-*` peers in step with the dashboard until 1.0 ships. `spree plugin new` scaffolds ranges starting at the admin SDK and dashboard versions released alongside your `@spree/cli`.
`dependencies` is for things your plugin *uses* that the host *doesn't* — small utilities (e.g., `clsx`, `date-fns` if you need a specific version, your own helper packages). When in doubt, peer-dep it. The trade-off is "user has to install one more thing" vs. "user has two copies of React" — always pay the first cost.
## Choose what to publish
-The scaffold's `package.json` ships TS source by default. Two options:
+The scaffold's `package.json` ships TS source by default, and its `build` script type-checks that source. Two options:
### Option A — Ship pre-built JS
@@ -70,7 +70,7 @@ Pick A if you're going to npm in earnest. Pick B for internal-only packages used
## Side-effects flag
-The plugin's whole purpose is side effects (`defineDashboardPlugin` registers stuff at module-load time). **Tell bundlers not to tree-shake it:**
+The plugin's whole purpose is side effects (`defineDashboardPlugin` registers stuff at module-load time). **Tell bundlers not to tree-shake it.** The scaffold lists its source entry, `./src/index.tsx`; add the `dist/` entries if you ship pre-built JS:
```json
{
@@ -133,7 +133,7 @@ Set `"private": false` and remove the `"publishConfig.access": "restricted"` if
## Avoiding lock-step releases
-Your plugin should compile against a **range** of dashboard versions. Run the build against the lowest supported version locally (`pnpm add -D @spree/[email protected]`) and add a CI matrix job that bumps to the next minor and rebuilds. That's the cheapest way to catch "I depended on something that doesn't exist in 6.0.0".
+Your plugin should compile against a **range** of dashboard versions. Run the build against the lowest version your peer range allows (for example `pnpm add -D @spree/[email protected]`) and add a CI matrix job that bumps to the next minor and rebuilds. That's the cheapest way to catch "I depended on something the oldest supported dashboard doesn't have".
## Reference
diff --git a/docs/developer/dashboard/plugins/scaffolding.mdx b/docs/developer/dashboard/plugins/scaffolding.mdx
index dce0291a5f..64e44778c3 100644
--- a/docs/developer/dashboard/plugins/scaffolding.mdx
+++ b/docs/developer/dashboard/plugins/scaffolding.mdx
@@ -1,7 +1,7 @@
---
title: Scaffolding
sidebarTitle: Scaffolding
-description: Generate a new dashboard plugin monorepo with `@spree/cli` in one command. Includes TypeScript, biome, tsup, a working example entry-point, and translations.
+description: Generate a new dashboard plugin monorepo with `@spree/cli` in one command. Includes TypeScript, biome, a working example entry-point, and translations.
---
`@spree/cli` ships a `plugin new` command that scaffolds the whole plugin monorepo for you. Generated layout:
@@ -68,14 +68,14 @@ For CI and scripted use, `-y` / `--yes` accepts the default for anything the fla
npx @spree/cli plugin new my-plugin -y
```
-`--force` overwrites an existing directory. `--no-dashboard` skips the dashboard package (Rails-engine-only plugins). `--no-engine` is reserved — engine scaffolding lands later.
+`--force` overwrites an existing directory. `--no-dashboard` and `--no-engine` are reserved for when engine scaffolding lands — today the dashboard package is the only half the CLI generates, so `--no-dashboard` leaves nothing to scaffold.
## After scaffolding
```bash
cd my-plugin
pnpm install # runs by default unless --no-install
-pnpm build
+pnpm build # type-checks the plugin — it ships TypeScript source
```
You now have a buildable plugin. The next page covers what to put in `package.json` for publishing — but if you're using it internally and importing by path, you can stop here and skip [Publishing](/developer/dashboard/plugins/publishing).
diff --git a/docs/developer/deployment/background_jobs.mdx b/docs/developer/deployment/background_jobs.mdx
index d5b975c92e..17060294a7 100644
--- a/docs/developer/deployment/background_jobs.mdx
+++ b/docs/developer/deployment/background_jobs.mdx
@@ -23,7 +23,21 @@ Every deployment ships [Mission Control](https://github.com/rails/mission_contro
## Recurring Jobs
-Scheduled work — releasing expired stock reservations, pruning price history, queue housekeeping — is defined in `config/recurring.yml`, Solid Queue's built-in cron. Add your own:
+Scheduled work is defined in `config/recurring.yml`, Solid Queue's built-in cron. A new project already schedules everything Spree needs:
+
+| Schedule | Job | What it does |
+|---|---|---|
+| Every minute | `Spree::StockReservations::ExpireJob` | Releases checkout stock reservations whose hold expired |
+| Every 5 minutes | `Spree::Orders::FinalizeStaleDraftsJob` | Finishes orders whose payment succeeded but whose completion never committed; never refunds |
+| Hourly | `Spree::Carts::ReapExpiredJob` | Deletes abandoned carts past their expiry; carts with a live payment are kept |
+| Hourly | `Spree::Collections::RegenerateTimeBasedJob` | Refreshes automatic collections with time-based rules, such as "available on" |
+| Daily | `spree:price_history:prune` task | Deletes price history older than each store's retention period (EU Omnibus) |
+| Daily | `Spree::SellerPayouts::SweepDueJob` | Settles marketplace sellers who are due a payout (see below) |
+| Hourly | `Spree::SellerTransfers::ExecutePendingDueJob` | Retries seller earnings a payout provider refused |
+
+The marketplace jobs do nothing on a store with no sellers, so keep them enabled. If your project predates any of these, copy the missing entries from the [starter's `config/recurring.yml`](https://github.com/spree/spree-starter/blob/main/config/recurring.yml).
+
+Add your own:
```yaml config/recurring.yml
production:
@@ -110,6 +124,37 @@ Move the `config/recurring.yml` schedules to sidekiq-cron (it auto-loads `config
expire_stock_reservations:
cron: "* * * * *"
class: Spree::StockReservations::ExpireJob
+finalize_stale_draft_orders:
+ cron: "*/5 * * * *"
+ class: Spree::Orders::FinalizeStaleDraftsJob
+reap_expired_carts:
+ cron: "7 * * * *"
+ class: Spree::Carts::ReapExpiredJob
+regenerate_time_based_collections:
+ cron: "17 * * * *"
+ class: Spree::Collections::RegenerateTimeBasedJob
+prune_price_history:
+ cron: "0 4 * * *"
+ class: PrunePriceHistoryJob
+sweep_due_seller_payouts:
+ cron: "0 3 * * *"
+ class: Spree::SellerPayouts::SweepDueJob
+execute_pending_seller_transfers:
+ cron: "27 * * * *"
+ class: Spree::SellerTransfers::ExecutePendingDueJob
+```
+
+sidekiq-cron schedules jobs, not commands, so price history pruning needs a small job that runs the task:
+
+```ruby app/jobs/prune_price_history_job.rb
+require 'rake'
+
+class PrunePriceHistoryJob < ApplicationJob
+ def perform
+ Rails.application.load_tasks unless Rake::Task.task_defined?('spree:price_history:prune')
+ Rake::Task['spree:price_history:prune'].tap(&:reenable).invoke
+ end
+end
```
The `/jobs` dashboard is Solid Queue-specific — mount [Sidekiq's Web UI](https://github.com/sidekiq/sidekiq/wiki/Monitoring) instead:
diff --git a/docs/developer/tutorial/model-and-api.mdx b/docs/developer/tutorial/model-and-api.mdx
index 29583d97e5..411cb3f981 100644
--- a/docs/developer/tutorial/model-and-api.mdx
+++ b/docs/developer/tutorial/model-and-api.mdx
@@ -28,6 +28,8 @@ The generator reports what it created:
create spec/factories/spree/brand_factory.rb
create spec/controllers/spree/api/v3/store/brands_controller_spec.rb
create spec/controllers/spree/api/v3/admin/brands_controller_spec.rb
+ append config/initializers/spree.rb
+ create config/locales/spree_brands.en.yml
✓ Generated Spree::Brand API resource
@@ -57,7 +59,7 @@ Attributes follow the familiar `name:type:index` form, with the Spree convention
| `active:boolean` | A boolean column with a default |
| `user:belongs_to` | A reference with the class name resolved |
-Useful flags: `--paranoid` for soft delete, `--custom-fields` for [custom fields](/developer/core-concepts/metafields) support, `--writable` to give the Store API create, update and destroy as well, and `--no-store` or `--no-admin` to generate only one side. Run the generator with `--help` for the full list.
+Useful flags: `--paranoid` for soft delete, `--custom-fields` for [custom fields](/developer/core-concepts/metafields) support, `--writable` to give the Store API create, update and destroy as well, `--permission-group` to choose where the brand permissions appear in the role editor (`catalog` by default), and `--no-store` or `--no-admin` to generate only one side. Run the generator with `--help` for the full list.
## Step 2: What you got
@@ -78,8 +80,10 @@ The Store API is read-only by default — a shopper cannot create a brand. Pass
**Brands belong to a store.** Every resource you generate is scoped to one, because commerce data — catalog, configuration, orders — is always per-store. A new record picks up its store automatically, and a field marked unique is unique *within* a store, so two stores can each have a brand called `wilson`. Only genuinely global reference data, like countries, opts out with `--no-store-scoped`.
+**Access to the Admin API is a permission.** The generator registers `read_brands` and `write_brands` in `config/initializers/spree.rb`, so you can grant them to a staff role in **Settings → Roles** or to a secret API key, and labels them for the role editor in `config/locales/spree_brands.en.yml`. Until you grant them, only store admins and full-access keys reach the endpoint. See [Permissions](/developer/customization/permissions).
+
<Warning>
- One decision is still yours: **authorization**. Give the resource a permission rule before exposing it, and read lookups through the store (`current_store.brands`) rather than the whole table. Scoping by association is the cheapest defence against one store reading another's records — filtering by role is not a substitute.
+ Read lookups through the store (`current_store.brands`) rather than the whole table. Scoping by association is the cheapest defence against one store reading another's records — a permission decides *whether* someone may read brands, not *which* ones.
</Warning>
## Step 3: Try it
diff --git a/docs/developer/upgrades/5.6-to-6.0.mdx b/docs/developer/upgrades/5.6-to-6.0.mdx
index a39bb00ddb..afd394add8 100644
--- a/docs/developer/upgrades/5.6-to-6.0.mdx
+++ b/docs/developer/upgrades/5.6-to-6.0.mdx
@@ -740,7 +740,7 @@ Old initializers fail loudly at boot: the set constants raise `NameError`, and `
```ruby
# db/seeds.rb — "roles as code" is plain ActiveRecord now
-Spree::Role.find_or_create_by!(name: 'support')
+Spree::Store.default.roles.find_or_create_by!(name: 'support')
.update!(permissions: %w[read_orders read_customers])
```
diff --git a/packages/admin-sdk/examples/order-refunds/create.ts b/packages/admin-sdk/examples/order-refunds/create.ts
index cb09319988..12637015af 100644
--- a/packages/admin-sdk/examples/order-refunds/create.ts
+++ b/packages/admin-sdk/examples/order-refunds/create.ts
@@ -9,7 +9,7 @@ const client = createAdminClient({
const refund = await client.orders.refunds.create('or_UkLWZg9DAJ', {
payment_id: 'pay_UkLWZg9DAJ',
amount: '5.00',
- refund_reason_id: 'refrsn_UkLWZg9DAJ',
+ refund_reason_id: 'rr_UkLWZg9DAJ',
})
// endregion:example
diff --git a/packages/admin-sdk/src/params.ts b/packages/admin-sdk/src/params.ts
index 41a17607f6..7962b85484 100644
--- a/packages/admin-sdk/src/params.ts
+++ b/packages/admin-sdk/src/params.ts
@@ -204,7 +204,7 @@ export interface RefundCreateParams {
payment_id: string
/** Decimal amount; see `PaymentCreateParams.amount` for the string rationale. */
amount: string | number
- /** Refund reason ID (`refrsn_…`). Omitted → the store's first refund reason. */
+ /** Refund reason ID (`rr_…`). Omitted → the store's first refund reason. */
refund_reason_id?: string
}
diff --git a/packages/admin-sdk/tests/orders.test.ts b/packages/admin-sdk/tests/orders.test.ts
index 3db3a2a528..31551d558c 100644
--- a/packages/admin-sdk/tests/orders.test.ts
+++ b/packages/admin-sdk/tests/orders.test.ts
@@ -247,10 +247,10 @@ describe('orders', () => {
await createTestClient().orders.refunds.create('order_abc123', {
payment_id: 'pay_1',
amount: '5.00',
- refund_reason_id: 'refrsn_1',
+ refund_reason_id: 'rr_1',
})
- expect(body).toEqual({ payment_id: 'pay_1', amount: '5.00', refund_reason_id: 'refrsn_1' })
+ expect(body).toEqual({ payment_id: 'pay_1', amount: '5.00', refund_reason_id: 'rr_1' })
})
})
diff --git a/packages/cli/scripts/plugin-peer-ranges.mjs b/packages/cli/scripts/plugin-peer-ranges.mjs
new file mode 100644
index 0000000000..cdffb166d2
--- /dev/null
+++ b/packages/cli/scripts/plugin-peer-ranges.mjs
@@ -0,0 +1,29 @@
+import { readFileSync } from 'node:fs'
+import { dirname, join } from 'node:path'
+import { fileURLToPath } from 'node:url'
+
+const packagesDir = join(dirname(fileURLToPath(import.meta.url)), '../..')
+
+// Workspace packages a scaffolded dashboard plugin peer-depends on, keyed by
+// the template variable that carries each range.
+const PEERS = {
+ spree_admin_sdk_range: 'admin-sdk',
+ spree_dashboard_core_range: 'dashboard-core',
+ spree_dashboard_ui_range: 'dashboard-ui',
+}
+
+/**
+ * Caret ranges on the versions currently in the workspace, so `spree plugin
+ * new` scaffolds peers that match the dashboard released alongside this CLI.
+ * Injected at build time (tsup) and test time (vitest).
+ *
+ * @returns {Record<string, string>}
+ */
+export function pluginPeerRanges() {
+ return Object.fromEntries(
+ Object.entries(PEERS).map(([variable, dir]) => {
+ const { version } = JSON.parse(readFileSync(join(packagesDir, dir, 'package.json'), 'utf8'))
+ return [variable, `^${version}`]
+ }),
+ )
+}
diff --git a/packages/cli/src/commands/build.ts b/packages/cli/src/commands/build.ts
index 5a4dcce075..06dd9bd968 100644
--- a/packages/cli/src/commands/build.ts
+++ b/packages/cli/src/commands/build.ts
@@ -151,10 +151,11 @@ export function planProductionBuild(
const hasDashboard = fs.existsSync(path.join(projectDir, 'apps', 'dashboard', 'package.json'))
- // The layout-normalizing Dockerfile leaves a distinctive marker; without
- // it, root context would break the build (the old file expects the Rails
- // app at the context root), so fall back to the old API-directory context.
- if (!fs.readFileSync(dockerfile, 'utf-8').includes('.spree-custom-dashboard')) {
+ // The layout-normalizing Dockerfile leaves a distinctive marker
+ // (`.spree-custom-app`; `.spree-custom-dashboard` in its first release);
+ // without it, root context would break the build (the old file expects the
+ // Rails app at the context root), so fall back to the old API-directory context.
+ if (!/\.spree-custom-(app|dashboard)\b/.test(fs.readFileSync(dockerfile, 'utf-8'))) {
return {
args: ['build', apiPath, '-f', dockerfile, '-t', imageTag],
imageTag,
diff --git a/packages/cli/src/commands/plugin.ts b/packages/cli/src/commands/plugin.ts
index 2347145b36..c5ca6390ab 100644
--- a/packages/cli/src/commands/plugin.ts
+++ b/packages/cli/src/commands/plugin.ts
@@ -5,6 +5,7 @@ import * as p from '@clack/prompts'
import type { Command } from 'commander'
import { execaCommand } from 'execa'
import pc from 'picocolors'
+import { PLUGIN_PEER_RANGES } from '../lib/plugin-peer-ranges.js'
import { render, type TemplateVars } from '../lib/template.js'
const TEMPLATE_RELATIVE_PATH = '../../templates/plugin'
@@ -396,6 +397,7 @@ function buildVars(a: Answers): TemplateVars {
author_email: a.authorEmail,
license: a.license,
year: String(new Date().getFullYear()),
+ ...PLUGIN_PEER_RANGES,
}
}
diff --git a/packages/cli/src/lib/plugin-peer-ranges.ts b/packages/cli/src/lib/plugin-peer-ranges.ts
new file mode 100644
index 0000000000..22c864380d
--- /dev/null
+++ b/packages/cli/src/lib/plugin-peer-ranges.ts
@@ -0,0 +1,10 @@
+import type { TemplateVars } from './template.js'
+
+declare const __SPREE_PLUGIN_PEER_RANGES__: TemplateVars
+
+/**
+ * `@spree/admin-sdk` and `@spree/dashboard-*` peer ranges for a scaffolded
+ * plugin, derived from the workspace versions when this CLI was built (see
+ * scripts/plugin-peer-ranges.mjs) so they never lag behind a release.
+ */
+export const PLUGIN_PEER_RANGES: TemplateVars = __SPREE_PLUGIN_PEER_RANGES__
diff --git a/packages/cli/templates/plugin/.gitignore b/packages/cli/templates/plugin/.gitignore
index 44846ac2b2..cf475c7931 100644
--- a/packages/cli/templates/plugin/.gitignore
+++ b/packages/cli/templates/plugin/.gitignore
@@ -3,13 +3,6 @@ dist/
.DS_Store
*.log
-# Rails engine
-engine/Gemfile.lock
-engine/tmp/
-engine/log/
-engine/spec/dummy/
-engine/coverage/
-
# IDE
.idea/
.vscode/
diff --git a/packages/cli/templates/plugin/README.md.tt b/packages/cli/templates/plugin/README.md.tt
index 907b87e247..43dc706114 100644
--- a/packages/cli/templates/plugin/README.md.tt
+++ b/packages/cli/templates/plugin/README.md.tt
@@ -2,32 +2,25 @@
A Spree plugin: **{{name}}**.
-This is a hybrid Node/Ruby monorepo with two halves:
+This monorepo holds the dashboard half of the plugin:
- `packages/dashboard/` — TypeScript dashboard plugin (extends the Spree 6.0 admin via [`@spree/dashboard-core`](https://www.npmjs.com/package/@spree/dashboard-core))
-- `engine/` — Ruby Rails engine (Spree extension gem) that ships the Admin API endpoints and ActiveRecord models
-Both halves work together: the engine ships `/api/v3/admin/...` endpoints, the dashboard plugin calls them via the SDK's `request` method.
+The example pages call `/api/v3/admin/{{name}}` endpoints through the SDK's `request` method. Those endpoints don't exist yet — they belong in a Spree extension gem (a Rails engine) that you create separately, with its model, Admin API controller and permission scope, as described in [Creating an extension](https://spreecommerce.org/docs/developer/contributing/creating-an-extension). Then point your Spree host's Gemfile at it:
+
+```ruby
+gem '{{ruby_name}}', path: '../path/to/{{ruby_name}}'
+```
## Development setup
```bash
-# Install JavaScript dependencies
pnpm install
-
-# Install Ruby dependencies for the engine
-cd engine && bundle install && cd ..
+pnpm build # type-checks the plugin (it ships TypeScript source)
```
## Running against a Spree host app
-The engine needs to live alongside a Spree host (typically scaffolded via `create-spree-app`). Point your host's Gemfile at the local engine:
-
-```ruby
-# in your Spree host's Gemfile
-gem '{{ruby_name}}', path: '../path/to/{{plugin_name}}/engine'
-```
-
Activate the dashboard plugin with a side-effect import in the host's `main.tsx`, before the router mounts. This runs `defineDashboardPlugin` so the nav entry, route, slot widget, and table column register:
```tsx
@@ -45,7 +38,7 @@ If you'd rather opt out of auto-discovery and register manually, pass an explici
- [Plugin overview](https://spreecommerce.org/docs/developer/dashboard/plugins/overview) — packaging + publishing your plugin to npm
- [Slots catalog](https://spreecommerce.org/docs/developer/dashboard/slots-catalog) — every named slot the dashboard exposes
- [Custom Admin Endpoints](https://spreecommerce.org/docs/developer/sdk/admin/extending) — adding your own API endpoints
-- [Spree Extensions guide](https://spreecommerce.org/docs/developer/customization/extensions) — the Rails-engine side
+- [Creating an extension](https://spreecommerce.org/docs/developer/contributing/creating-an-extension) — the Rails-engine side
## License
diff --git a/packages/cli/templates/plugin/packages/dashboard/package.json.tt b/packages/cli/templates/plugin/packages/dashboard/package.json.tt
index 76b03fdc91..b32666b06a 100644
--- a/packages/cli/templates/plugin/packages/dashboard/package.json.tt
+++ b/packages/cli/templates/plugin/packages/dashboard/package.json.tt
@@ -12,11 +12,15 @@
"exports": {
".": "./src/index.tsx"
},
+ "sideEffects": [
+ "./src/index.tsx"
+ ],
"files": [
"src",
"README.md"
],
"scripts": {
+ "build": "tsc --noEmit",
"lint": "biome check src",
"lint:fix": "biome check --fix src",
"typecheck": "tsc --noEmit"
@@ -28,9 +32,9 @@
}
},
"peerDependencies": {
- "@spree/admin-sdk": "^0.6.0",
- "@spree/dashboard-core": "^0.10.0",
- "@spree/dashboard-ui": "^0.10.0",
+ "@spree/admin-sdk": "{{spree_admin_sdk_range}}",
+ "@spree/dashboard-core": "{{spree_dashboard_core_range}}",
+ "@spree/dashboard-ui": "{{spree_dashboard_ui_range}}",
"@tanstack/react-query": "^5",
"@tanstack/react-router": "^1",
"i18next": "^26",
diff --git a/packages/cli/tests/build-production.test.ts b/packages/cli/tests/build-production.test.ts
index b326714b35..10b99a1b9b 100644
--- a/packages/cli/tests/build-production.test.ts
+++ b/packages/cli/tests/build-production.test.ts
@@ -24,7 +24,8 @@ describe('planProductionBuild', () => {
})
// The marker the layout-normalizing starter Dockerfile carries.
- const NORMALIZING_DOCKERFILE = 'FROM alpine AS ctx\n# .spree-custom-dashboard\nFROM ruby\n'
+ const NORMALIZING_DOCKERFILE =
+ 'FROM alpine AS ctx\n# touch /dashboard-src/.spree-custom-app\nFROM ruby\n'
function writeDockerfile(content: string) {
fs.writeFileSync(path.join(projectDir, 'backend', 'Dockerfile'), content)
@@ -57,6 +58,13 @@ describe('planProductionBuild', () => {
])
})
+ it('still recognizes the marker from the first layout-normalizing release', () => {
+ writeDockerfile('FROM alpine AS ctx\n# .spree-custom-dashboard\nFROM ruby\n')
+ writeDashboardApp()
+
+ expect(planProductionBuild(projectDir).dashboard).toBe('custom')
+ })
+
it('writes the root .dockerignore when missing, never overwriting', () => {
writeDockerfile(NORMALIZING_DOCKERFILE)
diff --git a/packages/cli/tests/plugin-template.test.ts b/packages/cli/tests/plugin-template.test.ts
index eb1ae54623..6ebe75833c 100644
--- a/packages/cli/tests/plugin-template.test.ts
+++ b/packages/cli/tests/plugin-template.test.ts
@@ -8,6 +8,7 @@ import fs from 'node:fs'
import os from 'node:os'
import path from 'node:path'
import { afterEach, describe, expect, it } from 'vitest'
+import { PLUGIN_PEER_RANGES } from '../src/lib/plugin-peer-ranges'
import { render, type TemplateVars } from '../src/lib/template'
const TEMPLATE_SRC = path.resolve(__dirname, '../templates/plugin')
@@ -24,6 +25,12 @@ const SAMPLE_VARS: TemplateVars = {
author_email: '[email protected]',
license: 'MIT',
year: '2026',
+ ...PLUGIN_PEER_RANGES,
+}
+
+function workspaceVersion(dir: string): string {
+ return JSON.parse(fs.readFileSync(path.resolve(__dirname, `../../${dir}/package.json`), 'utf8'))
+ .version
}
describe('bundled plugin template', () => {
@@ -83,7 +90,34 @@ describe('bundled plugin template', () => {
fs.readFileSync(path.join(dst, 'packages/dashboard/package.json'), 'utf8'),
)
expect(pkg.name).toBe('@acme/brands-dashboard')
- expect(pkg.peerDependencies['@spree/dashboard-core']).toBeDefined()
+ })
+
+ // Hand-written ranges drifted to versions no published package matched.
+ it('peer-depends on the admin SDK and dashboard packages released with this CLI', () => {
+ const dst = path.join(tempDir(), 'out')
+ render({ src: TEMPLATE_SRC, dst, vars: SAMPLE_VARS })
+
+ const pkg = JSON.parse(
+ fs.readFileSync(path.join(dst, 'packages/dashboard/package.json'), 'utf8'),
+ )
+ expect(pkg.peerDependencies).toMatchObject({
+ '@spree/admin-sdk': `^${workspaceVersion('admin-sdk')}`,
+ '@spree/dashboard-core': `^${workspaceVersion('dashboard-core')}`,
+ '@spree/dashboard-ui': `^${workspaceVersion('dashboard-ui')}`,
+ })
+ })
+
+ it('makes the dashboard package buildable and safe from tree-shaking', () => {
+ const dst = path.join(tempDir(), 'out')
+ render({ src: TEMPLATE_SRC, dst, vars: SAMPLE_VARS })
+
+ const pkg = JSON.parse(
+ fs.readFileSync(path.join(dst, 'packages/dashboard/package.json'), 'utf8'),
+ )
+ // The root `pnpm build` runs `pnpm -r build`, which fails when no package has one.
+ expect(pkg.scripts.build).toBeDefined()
+ // The entry registers the plugin at import time; bundlers must keep it.
+ expect(pkg.sideEffects).toContain(pkg.exports['.'])
})
it('substitutes module names + paths consistently in the dashboard entry', () => {
@@ -122,6 +156,8 @@ describe('bundled plugin template', () => {
expect(readme).toContain("gem 'spree_brands'")
expect(readme).toContain('Jane Developer')
expect(readme).not.toContain('{{')
+ // The CLI generates no engine/ directory (yet), so the README must not describe one.
+ expect(readme).not.toContain('engine/')
})
it('skips the dashboard subtree when asked', () => {
diff --git a/packages/cli/tsup.config.ts b/packages/cli/tsup.config.ts
index d7f0f38ef9..41f10625a6 100644
--- a/packages/cli/tsup.config.ts
+++ b/packages/cli/tsup.config.ts
@@ -1,5 +1,6 @@
import { cpSync } from 'node:fs'
import { defineConfig } from 'tsup'
+import { pluginPeerRanges } from './scripts/plugin-peer-ranges.mjs'
export default defineConfig({
entry: ['src/index.ts'],
@@ -8,6 +9,7 @@ export default defineConfig({
platform: 'node',
noExternal: [/.*/],
splitting: false,
+ define: { __SPREE_PLUGIN_PEER_RANGES__: JSON.stringify(pluginPeerRanges()) },
clean: true,
minify: true,
banner: {
diff --git a/packages/cli/vitest.config.ts b/packages/cli/vitest.config.ts
index 9eef0e8a80..cbe51da45f 100644
--- a/packages/cli/vitest.config.ts
+++ b/packages/cli/vitest.config.ts
@@ -1,6 +1,8 @@
import { defineConfig } from 'vitest/config'
+import { pluginPeerRanges } from './scripts/plugin-peer-ranges.mjs'
export default defineConfig({
+ define: { __SPREE_PLUGIN_PEER_RANGES__: JSON.stringify(pluginPeerRanges()) },
test: {
environment: 'node',
include: ['tests/**/*.test.ts'],
diff --git a/packages/create-spree-app/src/scaffold.ts b/packages/create-spree-app/src/scaffold.ts
index 54d20589c2..2626fcf14e 100644
--- a/packages/create-spree-app/src/scaffold.ts
+++ b/packages/create-spree-app/src/scaffold.ts
@@ -206,13 +206,7 @@ export async function scaffold(options: ScaffoldOptions): Promise<void> {
// summary already leads with it (served at /dashboard, plus the
// customize command).
} else {
- printSuccessWithoutDocker(
- projectName,
- storefrontReady,
- dashboardReady,
- port,
- options.packageManager,
- )
+ printSuccessWithoutDocker(projectName, storefrontReady, dashboardReady, options.packageManager)
}
}
@@ -220,7 +214,6 @@ function printSuccessWithoutDocker(
projectName: string,
hasStorefront: boolean,
hasDashboard: boolean,
- port: number,
pm: PackageManager,
): void {
const run = runCommand(pm)
@@ -244,7 +237,8 @@ function printSuccessWithoutDocker(
// With the React Dashboard chosen, its dev server IS the admin — and
// `spree dev` co-runs it with the API, so the URL is live the moment the
- // stack is up. One admin block; the classic admin gets a one-line pointer.
+ // stack is up. Without it there is no admin to open yet — Spree 6 has no
+ // Rails admin — so point at the command that adds one.
if (hasDashboard) {
lines.push(
'',
@@ -258,8 +252,8 @@ function printSuccessWithoutDocker(
lines.push(
'',
`${pc.bold('Admin Dashboard')}`,
- ` http://localhost:${port}/admin`,
- ` ${pc.dim("# you'll create the admin account on first run")}`,
+ ` ${run} spree add dashboard`,
+ ` ${pc.dim('# scaffolds the React admin into apps/dashboard/')}`,
'',
)
}
diff --git a/packages/create-spree-app/src/server.ts b/packages/create-spree-app/src/server.ts
index 10aa99592e..3906ed012c 100644
--- a/packages/create-spree-app/src/server.ts
+++ b/packages/create-spree-app/src/server.ts
@@ -56,17 +56,32 @@ export function prepareServerTemplate(projectDir: string): void {
fs.rmSync(path.join(serverDir, '.github'), { recursive: true, force: true })
}
- // Render reads a single Blueprint from the repository root. The starter ships
- // The starter authors render.yaml for exactly this project layout (Docker
- // runtime, server/Dockerfile built with the repo root as context, so the
- // ejected server and apps/dashboard ship in one image) — Render just needs
- // it at the repo root where Blueprints are read.
+ // Render reads a single Blueprint from the repository root. Each service
+ // builds server/Dockerfile with the repo root as context, so the ejected
+ // server and apps/dashboard ship in one image.
const srcRenderYaml = path.join(serverDir, 'render.yaml')
if (fs.existsSync(srcRenderYaml)) {
- fs.renameSync(srcRenderYaml, path.join(projectDir, 'render.yaml'))
+ const content = fs.readFileSync(srcRenderYaml, 'utf-8')
+ fs.writeFileSync(path.join(projectDir, 'render.yaml'), adaptRenderYamlForNestedServer(content))
+ fs.rmSync(srcRenderYaml)
}
}
+/**
+ * Point every Render service's `dockerfilePath` at `server/Dockerfile`. The
+ * starter may author its Blueprint for standalone deploys (`./Dockerfile`) or
+ * already for this layout; either way the relocated file builds the nested
+ * server. Commented-out services (the worker template) are rewritten too, so
+ * uncommenting one works as-is. The Dockerfile detects the layout from its
+ * build context, so `dockerContext` stays the repo root.
+ */
+export function adaptRenderYamlForNestedServer(content: string): string {
+ return content.replace(
+ /^([ \t]*(?:#[ \t]*)?dockerfilePath:[ \t]*)(?:\.\/)?Dockerfile[ \t]*$/gm,
+ '$1./server/Dockerfile',
+ )
+}
+
/**
* Rewrite a Ruby/Rails CI workflow so its steps run against the `server/`
* subdirectory instead of the repo root. The starter's workflow is authored for
diff --git a/packages/create-spree-app/src/templates/readme.ts b/packages/create-spree-app/src/templates/readme.ts
index 332a64199b..b8e2e9ffcd 100644
--- a/packages/create-spree-app/src/templates/readme.ts
+++ b/packages/create-spree-app/src/templates/readme.ts
@@ -77,8 +77,7 @@ ${pm} run dev
\`\`\`
Open http://localhost:${DASHBOARD_PORT} and sign in with the admin email and
-password you chose during the first run. The classic admin remains at
-http://localhost:${port}/admin.
+password you chose during the first run.
When you deploy, the production image builds your dashboard and serves it at
\`/dashboard\` on the same origin as the API (\`${run} spree build --production\`).
@@ -143,7 +142,7 @@ This project uses [\`@spree/cli\`](https://spreecommerce.org/docs/developer/cli/
|---------|-------------|
| \`spree generate model Brand name:string slug:string:uniq\` | Generate a new database model |
| \`spree generate api_resource Brand name:string slug:string:uniq\` | Generate a new Spree API resource |
-| \`spree generate subscriber OmsOrderSync order.completed\` | Generate a new event subscriber |
+| \`spree generate subscriber OmsOrderSync order.placed\` | Generate a new event subscriber |
| \`spree generate migration AddPositionToSpreeBrands position:integer\` | Generate a new database migration |
### Admin API
diff --git a/packages/create-spree-app/tests/server.test.ts b/packages/create-spree-app/tests/server.test.ts
index 0c42c2c12f..8896bc2db1 100644
--- a/packages/create-spree-app/tests/server.test.ts
+++ b/packages/create-spree-app/tests/server.test.ts
@@ -2,7 +2,11 @@ import fs from 'node:fs'
import os from 'node:os'
import path from 'node:path'
import { afterEach, describe, expect, it } from 'vitest'
-import { adaptWorkflowForNestedServer, prepareServerTemplate } from '../src/server'
+import {
+ adaptRenderYamlForNestedServer,
+ adaptWorkflowForNestedServer,
+ prepareServerTemplate,
+} from '../src/server'
// Mirrors spree-starter's .github/workflows/server-ci.yml (the workflow that
// create-spree-app relocates to the generated project root).
@@ -56,23 +60,23 @@ jobs:
context: .
`
-// A trimmed render.yaml covering the three shapes the transform distinguishes:
-// a buildable service (has `runtime:`), the commented-out worker template
-// (`runtime:` behind a `#`), and a managed service (no `runtime:`).
+// A trimmed render.yaml in the starter's shape: a Docker web service plus the
+// commented-out worker template, both building the nested server.
const RENDER_YAML = `services:
- type: web
- runtime: ruby
- plan: free
+ runtime: docker
+ dockerfilePath: ./server/Dockerfile
+ dockerContext: .
# - type: worker
- # runtime: ruby
- # plan: standard
-
- - type: redis
- name: spree-redis
- plan: free
+ # runtime: docker
+ # dockerfilePath: ./server/Dockerfile
+ # dockerContext: .
`
+// The same Blueprint authored for deploying the starter on its own.
+const STANDALONE_RENDER_YAML = RENDER_YAML.replaceAll('./server/Dockerfile', './Dockerfile')
+
describe('adaptWorkflowForNestedServer', () => {
it('points ruby/setup-ruby at the server/ subdirectory', () => {
const result = adaptWorkflowForNestedServer(SERVER_CI)
@@ -111,10 +115,20 @@ describe('adaptWorkflowForNestedServer', () => {
})
})
+describe('adaptRenderYamlForNestedServer', () => {
+ it('leaves a Blueprint already written for the nested server untouched', () => {
+ expect(adaptRenderYamlForNestedServer(RENDER_YAML)).toBe(RENDER_YAML)
+ })
+
+ it('points a standalone Blueprint, commented services included, at server/Dockerfile', () => {
+ expect(adaptRenderYamlForNestedServer(STANDALONE_RENDER_YAML)).toBe(RENDER_YAML)
+ })
+})
+
describe('prepareServerTemplate', () => {
const tempDirs: string[] = []
- function seedClonedServer(): string {
+ function seedClonedServer(renderYaml = RENDER_YAML): string {
const projectDir = fs.mkdtempSync(path.join(os.tmpdir(), 'create-spree-app-server-'))
tempDirs.push(projectDir)
@@ -123,7 +137,7 @@ describe('prepareServerTemplate', () => {
fs.writeFileSync(path.join(workflows, 'server-ci.yml'), SERVER_CI)
fs.writeFileSync(path.join(workflows, 'release.yml'), RELEASE)
fs.writeFileSync(path.join(projectDir, 'server', 'README.md'), '# Spree starter')
- fs.writeFileSync(path.join(projectDir, 'server', 'render.yaml'), RENDER_YAML)
+ fs.writeFileSync(path.join(projectDir, 'server', 'render.yaml'), renderYaml)
return projectDir
}
@@ -157,13 +171,12 @@ describe('prepareServerTemplate', () => {
expect(fs.existsSync(path.join(projectDir, 'server', 'README.md'))).toBe(false)
})
- it('relocates render.yaml to the project root verbatim', () => {
- const projectDir = seedClonedServer()
+ it('relocates render.yaml to the project root, building server/Dockerfile', () => {
+ const projectDir = seedClonedServer(STANDALONE_RENDER_YAML)
prepareServerTemplate(projectDir)
const moved = path.join(projectDir, 'render.yaml')
expect(fs.existsSync(moved)).toBe(true)
- // Authored by the starter for exactly this layout — no rewriting.
expect(fs.readFileSync(moved, 'utf-8')).toBe(RENDER_YAML)
// The original in server/ is removed so Render never reads a stale copy.
expect(fs.existsSync(path.join(projectDir, 'server', 'render.yaml'))).toBe(false)
diff --git a/packages/create-spree-app/tests/templates.test.ts b/packages/create-spree-app/tests/templates.test.ts
index 1c1e2e2012..68e566818a 100644
--- a/packages/create-spree-app/tests/templates.test.ts
+++ b/packages/create-spree-app/tests/templates.test.ts
@@ -194,7 +194,8 @@ describe('readmeContent', () => {
// The dashboard's dev server IS the admin in Spree 6 — the Rails admin
// engine is gone, so the README must not point at /admin.
expect(content).toContain('http://localhost:5173')
- expect(content).not.toContain('Classic admin')
+ expect(content).not.toMatch(/classic admin/i)
+ expect(content).not.toContain('localhost:3000/admin')
expect(content).toContain('Seller Panel')
expect(content).toContain('docs/developer/dashboard')
})
diff --git a/spree/core/lib/generators/spree/api_resource/api_resource_generator.rb b/spree/core/lib/generators/spree/api_resource/api_resource_generator.rb
index 7d1cf194f6..d70e42cad8 100644
--- a/spree/core/lib/generators/spree/api_resource/api_resource_generator.rb
+++ b/spree/core/lib/generators/spree/api_resource/api_resource_generator.rb
@@ -17,6 +17,7 @@ module Spree
# - Factory (managed — overwrite on re-run)
# - Controller specs (managed — overwrite on re-run)
# - Routes (idempotent inject between sentinels)
+ # - Permission scope + label (idempotent inject; locale owned-once)
#
# Owned-once contract: if the model file already exists, the generator
# leaves it (and the migration) alone — domain code is yours after
@@ -59,6 +60,11 @@ module Spree
default: false,
desc: "Don't inject routes into spree/api/config/routes.rb"
+ class_option :permission_group,
+ type: :string,
+ default: 'catalog',
+ desc: 'Permission picker group for the read_/write_ keys (orders, catalog, customers, settings, …)'
+
class_option :skip_specs,
type: :boolean,
default: false,
@@ -182,6 +188,35 @@ module Spree
inject_route_for(:admin, admin_route_line) if options[:admin]
end
+ # The Admin controller declares `scoped_resource :<plural>`; without a
+ # matching catalog scope its keys cannot be granted to a staff role or
+ # minted on a secret API key, so only full-access principals get in.
+ def register_permission_scope
+ return unless options[:admin]
+
+ if File.exist?(File.join(destination_root, INITIALIZER_PATH))
+ if File.read(File.join(destination_root, INITIALIZER_PATH)).include?("register_scope(:#{plural_name},")
+ say_status :identical, "#{INITIALIZER_PATH} (#{plural_name} permission scope)", :blue
+ else
+ append_to_file INITIALIZER_PATH, permission_scope_block
+ end
+ else
+ create_file INITIALIZER_PATH, permission_scope_block.lstrip
+ end
+ end
+
+ def create_permission_locale
+ return unless options[:admin]
+
+ path = "config/locales/spree_#{plural_name}.en.yml"
+ if File.exist?(File.join(destination_root, path))
+ say_status :skip, "#{path} (owned-once; already exists)", :yellow
+ return
+ end
+
+ template 'permissions.en.yml.tt', path
+ end
+
no_tasks do
# A host app declares its API routes in config/routes.rb, inside the
# engine's route hook that spree-starter ships ready to fill in. The
@@ -253,7 +288,11 @@ module Spree
say ' Next steps:', :yellow
say ' 1. Review the generated model — add validations, scopes, callbacks'
say ' 2. Apply the migration: pnpm exec spree migrate'
- say ' 3. Set up authorization (CanCanCan ability) for the resource'
+ if options[:admin]
+ say " 3. Grant read_#{plural_name} / write_#{plural_name} to staff roles or secret API keys"
+ else
+ say ' 3. Add an Admin API resource later to manage it from the dashboard'
+ end
say " 4. Add `has_many :#{plural_name}` to Spree::Store" if store_scoped?
if options[:store] || options[:admin]
say " #{store_scoped? ? 5 : 4}. Run the specs: pnpm exec spree rspec spec/controllers/spree/api/v3/"
@@ -295,6 +334,13 @@ module Spree
file_name.pluralize
end
+ def permission_group
+ group = options[:permission_group].to_s
+ raise Thor::Error, "--permission-group must be a lowercase identifier (got #{group.inspect})" unless group.match?(/\A[a-z][a-z0-9_]*\z/)
+
+ group
+ end
+
# Attributes the controller permits on write. By default, every column
# except references (FKs come through nested), attachments, rich text.
def permitted_attribute_names
@@ -306,6 +352,17 @@ module Spree
private
+ INITIALIZER_PATH = 'config/initializers/spree.rb'.freeze
+
+ def permission_scope_block
+ <<~RUBY
+
+ # Permissions for the #{bare_class_name} API — grants read_#{plural_name} / write_#{plural_name}
+ # to staff roles and secret API keys. Labels: config/locales/spree_#{plural_name}.en.yml
+ Spree.permissions.register_scope(:#{plural_name}, group: :#{permission_group}, resources: -> { [Spree::#{bare_class_name}] })
+ RUBY
+ end
+
# Where the model file lands. We use parent's class_path + file_name so
# this stays in sync with whatever Spree::ModelGenerator decides.
def model_file_destination
diff --git a/spree/core/lib/generators/spree/api_resource/templates/admin_controller.rb.tt b/spree/core/lib/generators/spree/api_resource/templates/admin_controller.rb.tt
index 9d0b16b388..2f79a41974 100644
--- a/spree/core/lib/generators/spree/api_resource/templates/admin_controller.rb.tt
+++ b/spree/core/lib/generators/spree/api_resource/templates/admin_controller.rb.tt
@@ -3,9 +3,10 @@ module Spree
module V3
module Admin
class <%= plural_name.camelize %>Controller < ResourceController
- # Which API key scope authorizes this endpoint — `read_<%= plural_name %>`
- # and `write_<%= plural_name %>`. Point it at an existing resource name
- # instead if this endpoint belongs under one.
+ # The permission that authorizes this endpoint — `read_<%= plural_name %>` and
+ # `write_<%= plural_name %>`, registered in config/initializers/spree.rb so
+ # they can be granted to staff roles and secret API keys. Point it at an
+ # existing resource name instead if this endpoint belongs under one.
scoped_resource :<%= plural_name %>
protected
@@ -18,8 +19,8 @@ module Spree
Spree::Api::V3::Admin::<%= bare_class_name %>Serializer
end
- def permitted_params
- params.permit(<%= permitted_attribute_names.map { |a| ":#{a}" }.join(', ') %>)
+ def resource_permitted_attributes
+ [<%= permitted_attribute_names.map { |a| ":#{a}" }.join(', ') %>]
end
end
end
diff --git a/spree/core/lib/generators/spree/api_resource/templates/permissions.en.yml.tt b/spree/core/lib/generators/spree/api_resource/templates/permissions.en.yml.tt
new file mode 100644
index 0000000000..d7c8470c23
--- /dev/null
+++ b/spree/core/lib/generators/spree/api_resource/templates/permissions.en.yml.tt
@@ -0,0 +1,6 @@
+en:
+ spree:
+ permissions_catalog:
+ resources:
+ <%= plural_name %>:
+ label: <%= plural_name.humanize %>
diff --git a/spree/core/lib/generators/spree/api_resource/templates/store_controller.rb.tt b/spree/core/lib/generators/spree/api_resource/templates/store_controller.rb.tt
index 0499b6e8f1..221f340570 100644
--- a/spree/core/lib/generators/spree/api_resource/templates/store_controller.rb.tt
+++ b/spree/core/lib/generators/spree/api_resource/templates/store_controller.rb.tt
@@ -20,8 +20,8 @@ module Spree
<% end -%>
<% if writable? -%>
- def permitted_params
- params.permit(<%= permitted_attribute_names.map { |a| ":#{a}" }.join(', ') %>)
+ def resource_permitted_attributes
+ [<%= permitted_attribute_names.map { |a| ":#{a}" }.join(', ') %>]
end
<% end -%>
end
diff --git a/spree/core/lib/generators/spree/subscriber/subscriber_generator.rb b/spree/core/lib/generators/spree/subscriber/subscriber_generator.rb
index d65bf2e220..0a13210bc0 100644
--- a/spree/core/lib/generators/spree/subscriber/subscriber_generator.rb
+++ b/spree/core/lib/generators/spree/subscriber/subscriber_generator.rb
@@ -3,9 +3,9 @@
module Spree
# spree:subscriber — scaffold an event subscriber and register it.
#
- # bin/rails g spree:subscriber OmsOrderSync order.completed order.canceled
+ # bin/rails g spree:subscriber OmsOrderSync order.placed order.canceled
# bin/rails g spree:subscriber MyApp::BrandSync brand.created brand.updated
- # bin/rails g spree:subscriber CriticalSync order.completed --sync
+ # bin/rails g spree:subscriber CriticalSync order.placed --sync
#
# Subscribers are not auto-discovered — they must be appended to the
# Spree.subscribers array. Forgetting that step produces a silent no-op,
@@ -64,7 +64,7 @@ module Spree
def warn_about_missing_events
return if events.any?
- say_status :note, "no events given — edit `subscribes_to` in the generated subscriber (e.g. 'order.completed')", :yellow
+ say_status :note, "no events given — edit `subscribes_to` in the generated subscriber (e.g. 'order.placed')", :yellow
end
private
diff --git a/spree/core/spec/lib/generators/spree/api_resource/api_resource_generator_spec.rb b/spree/core/spec/lib/generators/spree/api_resource/api_resource_generator_spec.rb
index 454a6a7c30..850404251d 100644
--- a/spree/core/spec/lib/generators/spree/api_resource/api_resource_generator_spec.rb
+++ b/spree/core/spec/lib/generators/spree/api_resource/api_resource_generator_spec.rb
@@ -97,20 +97,78 @@ RSpec.describe Spree::ApiResourceGenerator, type: :generator do
expect(Dir[File.join(destination, 'app/controllers/spree/api/v3/admin/*')]).to be_empty
end
- it 'permits flat params on the Admin controller for full CRUD' do
+ # Overriding permitted_params would drop the attributes extensions add
+ # through Spree::Brand.additional_permitted_attributes.
+ it 'declares writable attributes on the Admin controller without overriding permitted_params' do
result = run_generator(['Brand', 'name:string', 'active:boolean'])
- expect(result[:admin_controller]).to include('params.permit(:name, :active)')
+ expect(result[:admin_controller]).to include('def resource_permitted_attributes')
+ expect(result[:admin_controller]).to include('[:name, :active]')
+ expect(result[:admin_controller]).not_to include('permitted_params')
end
- it 'permits flat params on the Store controller only when --writable is set' do
+ it 'declares writable attributes on the Store controller only when --writable is set' do
read_only = run_generator(['Brand', 'name:string'])
- expect(read_only[:store_controller]).not_to include('params.permit')
+ expect(read_only[:store_controller]).not_to include('resource_permitted_attributes')
FileUtils.rm_rf(destination)
FileUtils.mkdir_p(destination)
writable = run_generator(['Brand', 'name:string', '--writable'])
- expect(writable[:store_controller]).to include('params.permit')
+ expect(writable[:store_controller]).to include('def resource_permitted_attributes')
+ expect(writable[:store_controller]).not_to include('permitted_params')
+ end
+ end
+
+ describe 'permissions' do
+ let(:initializer_path) { File.join(destination, 'config/initializers/spree.rb') }
+ let(:locale_path) { File.join(destination, 'config/locales/spree_brands.en.yml') }
+
+ it 'registers the scope the Admin controller declares' do
+ result = run_generator(['Brand', 'name:string'])
+
+ expect(result[:admin_controller]).to include('scoped_resource :brands')
+ expect(File.read(initializer_path)).to include(
+ 'Spree.permissions.register_scope(:brands, group: :catalog, resources: -> { [Spree::Brand] })'
+ )
+ end
+
+ it 'appends to an existing initializer once, however often it re-runs' do
+ FileUtils.mkdir_p(File.dirname(initializer_path))
+ File.write(initializer_path, "Spree.customer_class = 'Spree::Customer'\n")
+
+ 2.times { run_generator(['Brand', 'name:string']) }
+
+ content = File.read(initializer_path)
+ expect(content).to start_with("Spree.customer_class = 'Spree::Customer'\n")
+ expect(content.scan('register_scope(:brands,').size).to eq(1)
+ end
+
+ it 'places the scope in the group passed with --permission-group' do
+ run_generator(['Brand', 'name:string', '--permission-group', 'settings'])
+
+ expect(File.read(initializer_path)).to include('register_scope(:brands, group: :settings,')
+ end
+
+ it 'rejects a group that is not an identifier' do
+ expect {
+ described_class.new(['Brand', 'name:string'], { permission_group: 'catalog; system("x")' }, destination_root: destination).permission_group
+ }.to raise_error(Thor::Error, /--permission-group/)
+ end
+
+ it 'labels the permission for the role editor, and leaves an edited label alone on re-run' do
+ run_generator(['Brand', 'name:string'])
+ expect(YAML.load_file(locale_path).dig('en', 'spree', 'permissions_catalog', 'resources', 'brands', 'label')).to eq('Brands')
+
+ File.write(locale_path, File.read(locale_path).sub('label: Brands', 'label: Our brands'))
+ run_generator(['Brand', 'name:string'])
+ expect(File.read(locale_path)).to include('label: Our brands')
+ end
+
+ it 'registers nothing without an Admin controller' do
+ run_generator(['Brand', 'name:string', '--no-admin'])
+
+ expect(File.exist?(initializer_path)).to be(false)
+ expect(File.exist?(locale_path)).to be(false)
end
end
diff --git a/spree/lib/generators/spree/install/templates/config/initializers/spree.rb b/spree/lib/generators/spree/install/templates/config/initializers/spree.rb
index 18089118a8..70ae855c8c 100644
--- a/spree/lib/generators/spree/install/templates/config/initializers/spree.rb
+++ b/spree/lib/generators/spree/install/templates/config/initializers/spree.rb
@@ -38,7 +38,7 @@ Spree.dependencies do |dependencies|
# dependencies.cart_add_item_service = 'MyNewAwesomeService'
end
-# Spree::Api::Dependencies.storefront_cart_serializer = 'MyRailsApp::CartSerializer'
+# Spree.api.cart_serializer = 'MyRailsApp::CartSerializer'
# uncomment lines below to add your own custom business logic
# such as promotions, shipping methods, etc
@@ -58,8 +58,8 @@ Rails.application.config.after_initialize do
# Spree.promotions.rules << Spree::Promotions::Rules::OnlyForVIPCustomers
# Spree.promotions.actions << Spree::Promotions::Actions::GiftWithPurchase
- # Taxon rules
- # Spree.taxon_rules << Spree::TaxonRules::ProductsWithColor
+ # Collection rules
+ # Rails.application.config.spree.collection_rules << Spree::CollectionRules::ProductsWithColor
# Exports
# Spree.export_types << Spree::Exports::Payments
@@ -68,7 +68,7 @@ Rails.application.config.after_initialize do
# Staff roles and their permissions are managed as data — in the dashboard
# (Settings → Roles), via the Admin API, or in db/seeds.rb:
#
- # Spree::Role.find_or_create_by!(name: 'support')
+ # Spree::Store.default.roles.find_or_create_by!(name: 'support')
# .update!(permissions: %w[read_orders read_customers])
#
# Extensions can register additional permission resources: