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.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
Added maintenance tasks (#14972)
Damian Legawiec1224549522e4
diff --git a/docs/api-reference/admin.yaml b/docs/api-reference/admin.yamlindex c5558a15a0..c02daac35c 100644--- a/docs/api-reference/admin.yaml+++ b/docs/api-reference/admin.yaml@@ -490,6 +490,8 @@ paths:- write_email_templates- read_integrations- write_integrations+ - read_maintenance_tasks+ - write_maintenance_tasks- read_api_keys- write_api_keys- read_oauth_applications@@ -631,6 +633,8 @@ paths:- write_email_templates- read_integrations- write_integrations+ - read_maintenance_tasks+ - write_maintenance_tasks- read_api_keys- write_api_keys- read_oauth_applications@@ -13988,6 +13992,415 @@ paths:in: 1previous:next:+ "/api/v3/admin/maintenance_task_runs":+ get:+ summary: List maintenance task runs+ tags:+ - Maintenance Tasks+ security:+ - api_key: []+ bearer_auth: []+ description: |-+ The record of every maintenance task run: who started it, with which+ arguments, how far it got and how it ended.++ Runs are installation-wide rather than per store — an upgrade step+ converts every store's data — so this list is not filtered by the+ store the request is made against.+++ **Required scope:** `read_maintenance_tasks` (for API-key authentication).+ x-codeSamples:+ - lang: javascript+ label: Spree Admin SDK+ source: |-+ import { createAdminClient } from '@spree/admin-sdk'++ const client = createAdminClient({+ baseUrl: 'https://your-store.com',+ secretKey: 'sk_xxx',+ })++ const { data: runs } = await client.maintenanceTaskRuns.list({ status_eq: 'succeeded' })+ - lang: bash+ label: Spree CLI+ source: spree api get /maintenance_task_runs -d '{"status_eq":"succeeded"}'+ parameters:+ - name: x-spree-api-key+ in: header+ required: true+ schema:+ type: string+ - name: Authorization+ in: header+ required: true+ description: Bearer token for admin authentication+ schema:+ type: string+ - name: page+ in: query+ required: false+ description: Page number+ schema:+ type: integer+ - name: limit+ in: query+ required: false+ description: Number of records per page+ schema:+ type: integer+ - name: q[task_name_cont]+ in: query+ required: false+ description: Filter by task name (contains), e.g. `capture`+ schema:+ type: string+ - name: q[status_eq]+ in: query+ required: false+ description: Filter by status (enqueued, running, succeeded, errored, cancelled,+ …)+ schema:+ type: string+ - name: sort+ in: query+ required: false+ description: Sort by field. Prefix with `-` for descending (e.g., `-created_at`).+ schema:+ type: string+ responses:+ '200':+ description: maintenance task runs found+ content:+ application/json:+ example:+ data:+ - id: mtr_UkLWZg9DAJ+ status: succeeded+ dry_run: false+ initiated_via: dashboard+ tick_count: 0+ tick_total:+ error_class:+ error_message:+ started_at:+ ended_at:+ created_at: '2026-01-15T12:00:00.000Z'+ updated_at: '2026-01-15T12:00:00.000Z'+ task_name: capture_methods+ duration: 0.0+ tallies: {}+ arguments: {}+ error_backtrace:+ active: false+ admin_user_id:+ meta:+ page: 1+ limit: 25+ count: 1+ pages: 1+ from: 1+ to: 1+ in: 1+ previous:+ next:+ schema:+ type: object+ properties:+ data:+ type: array+ items:+ "$ref": "#/components/schemas/MaintenanceTaskRun"+ meta:+ "$ref": "#/components/schemas/PaginationMeta"+ required:+ - data+ - meta+ '401':+ description: unauthorized+ content:+ application/json:+ example:+ error:+ code: authentication_required+ message: Authentication required+ schema:+ "$ref": "#/components/schemas/ErrorResponse"+ post:+ summary: Start a maintenance task+ tags:+ - Maintenance Tasks+ security:+ - api_key: []+ bearer_auth: []+ description: |-+ Starts a run of a registered maintenance task and returns it. The run+ is enqueued, so poll it while `active` is true.++ `arguments` are validated by the task's own Active Model validations,+ so a bad value is rejected here rather than failing on the first+ record. `dry_run` is honored only by tasks whose `supports_dry_run` is+ true — recording a run as a preview that would in fact have written+ would misrepresent what happened.++ Only one run of a task can be in flight at a time: two would race over+ the same records and their cursors would leapfrog.+++ **Required scope:** `write_maintenance_tasks` (for API-key authentication).+ x-codeSamples:+ - lang: javascript+ label: Spree Admin SDK+ source: |-+ import { createAdminClient } from '@spree/admin-sdk'++ const client = createAdminClient({+ baseUrl: 'https://your-store.com',+ secretKey: 'sk_xxx',+ })++ const run = await client.maintenanceTaskRuns.create({+ task_name: 'capture_methods',+ dry_run: true,+ })+ - lang: bash+ label: Spree CLI+ source: spree api post /maintenance_task_runs -d '{"task_name":"capture_methods","dry_run":true}'+ parameters:+ - name: x-spree-api-key+ in: header+ required: true+ schema:+ type: string+ - name: Authorization+ in: header+ required: true+ description: Bearer token for admin authentication+ schema:+ type: string+ responses:+ '201':+ description: maintenance task started+ content:+ application/json:+ example:+ id: mtr_UkLWZg9DAJ+ status: enqueued+ dry_run: true+ initiated_via: dashboard+ tick_count: 0+ tick_total:+ error_class:+ error_message:+ started_at:+ ended_at:+ created_at: '2026-01-15T12:00:00.000Z'+ updated_at: '2026-01-15T12:00:00.000Z'+ task_name: capture_methods+ duration: 0.0+ tallies: {}+ arguments: {}+ error_backtrace:+ active: true+ admin_user_id: adm_UkLWZg9DAJ+ schema:+ "$ref": "#/components/schemas/MaintenanceTaskRun"+ '422':+ description: task is not registered+ content:+ application/json:+ example:+ error:+ code: validation_error+ message: Task name nope is not a registered maintenance task+ schema:+ "$ref": "#/components/schemas/ErrorResponse"+ requestBody:+ content:+ application/json:+ schema:+ "$ref": "#/components/schemas/MaintenanceTaskRunCreateParams"+ required: true+ "/api/v3/admin/maintenance_task_runs/{id}":+ parameters:+ - name: id+ in: path+ description: Maintenance task run ID+ required: true+ schema:+ type: string+ get:+ summary: Retrieve a maintenance task run+ tags:+ - Maintenance Tasks+ security:+ - api_key: []+ bearer_auth: []+ description: |-+ A single run, with the progress a dashboard polls while it works.++ `progress` is `0..1` when the task could count its collection and+ `null` when it could not, in which case `tick_count` alone reports what+ has been processed. `arguments` are rendered through the task's masking+ rules, so a secret passed as a parameter is stored for reproducibility+ but never echoed back.+++ **Required scope:** `read_maintenance_tasks` (for API-key authentication).+ x-codeSamples:+ - lang: javascript+ label: Spree Admin SDK+ source: |-+ import { createAdminClient } from '@spree/admin-sdk'++ const client = createAdminClient({+ baseUrl: 'https://your-store.com',+ secretKey: 'sk_xxx',+ })++ const run = await client.maintenanceTaskRuns.get('mtr_UkLWZg9DAJ')+ - lang: bash+ label: Spree CLI+ source: spree api get /maintenance_task_runs/{id}+ parameters:+ - name: x-spree-api-key+ in: header+ required: true+ schema:+ type: string+ - name: Authorization+ in: header+ required: true+ description: Bearer token for admin authentication+ schema:+ type: string+ responses:+ '200':+ description: maintenance task run found+ content:+ application/json:+ example:+ id: mtr_UkLWZg9DAJ+ status: running+ dry_run: false+ initiated_via: api+ tick_count: 5+ tick_total: 20+ error_class:+ error_message:+ started_at:+ ended_at:+ created_at: '2026-01-15T12:00:00.000Z'+ updated_at: '2026-01-15T12:00:00.000Z'+ task_name: capture_methods+ duration: 0.0+ tallies: {}+ arguments: {}+ error_backtrace:+ active: true+ admin_user_id:+ schema:+ "$ref": "#/components/schemas/MaintenanceTaskRun"+ '404':+ description: maintenance task run not found+ content:+ application/json:+ example:+ error:+ code: record_not_found+ message: Maintenance task run not found+ schema:+ "$ref": "#/components/schemas/ErrorResponse"+ "/api/v3/admin/maintenance_task_runs/{maintenance_task_run_id}/cancellation":+ parameters:+ - name: maintenance_task_run_id+ in: path+ description: Maintenance task run ID+ required: true+ schema:+ type: string+ post:+ summary: Cancel a maintenance task run+ tags:+ - Maintenance Tasks+ security:+ - api_key: []+ bearer_auth: []+ description: |-+ Asks the runner to stop for good at its next checkpoint.++ Cancelling is not a rollback — work already committed stays committed.+ What a cancelled run keeps is its cursor, so an operator can see how+ far it got. A run that is still `cancelling` because its worker has+ gone is cancelled outright by a second request.+++ **Required scope:** `write_maintenance_tasks` (for API-key authentication).+ x-codeSamples:+ - lang: javascript+ label: Spree Admin SDK+ source: |-+ import { createAdminClient } from '@spree/admin-sdk'++ const client = createAdminClient({+ baseUrl: 'https://your-store.com',+ secretKey: 'sk_xxx',+ })++ const run = await client.maintenanceTaskRuns.cancel('mtr_UkLWZg9DAJ')+ - lang: bash+ label: Spree CLI+ source: spree api post /maintenance_task_runs/{maintenance_task_run_id}/cancellation+ -d '{ ... }'+ parameters:+ - name: x-spree-api-key+ in: header+ required: true+ schema:+ type: string+ - name: Authorization+ in: header+ required: true+ description: Bearer token for admin authentication+ schema:+ type: string+ responses:+ '200':+ description: maintenance task run cancelling+ content:+ application/json:+ example:+ id: mtr_UkLWZg9DAJ+ status: cancelling+ dry_run: false+ initiated_via: api+ tick_count: 0+ tick_total:+ error_class:+ error_message:+ started_at:+ ended_at:+ created_at: '2026-01-15T12:00:00.000Z'+ updated_at: '2026-01-15T12:00:00.000Z'+ task_name: capture_methods+ duration: 0.0+ tallies: {}+ arguments: {}+ error_backtrace:+ active: true+ admin_user_id:+ schema:+ "$ref": "#/components/schemas/MaintenanceTaskRun"+ '422':+ description: maintenance task run cannot be cancelled+ content:+ application/json:+ example:+ error:+ code: validation_error+ message: a run with status succeeded cannot be cancelled+ schema:+ "$ref": "#/components/schemas/ErrorResponse""/api/v3/admin/markets":get:summary: List markets@@ -33263,6 +33676,20 @@ paths:group_label: Settingslabel: Integrationsdescription: ''+ - key: read_maintenance_tasks+ resource: maintenance_tasks+ kind: read+ group: access+ group_label: Access+ label: Maintenance tasks+ description: ''+ - key: write_maintenance_tasks+ resource: maintenance_tasks+ kind: write+ group: access+ group_label: Access+ label: Maintenance tasks+ description: ''- key: read_api_keysresource: api_keyskind: read@@ -33306,7 +33733,7 @@ paths:label: Staff & rolesdescription: Team members, invitations, roles and their permissionsmeta:- count: 59+ count: 61"/api/v3/admin/roles":get:summary: List roles@@ -33442,6 +33869,8 @@ paths:- write_email_templates- read_integrations- write_integrations+ - read_maintenance_tasks+ - write_maintenance_tasks- read_api_keys- write_api_keys- read_oauth_applications@@ -37730,6 +38159,54 @@ paths:credential: falsedeprecated: falsereplaced_by:+ - name: maintenance_task_run.cancelled+ group: maintenance_task_run+ credential_permission:+ credential: false+ deprecated: false+ replaced_by:+ - name: maintenance_task_run.created+ group: maintenance_task_run+ credential_permission:+ credential: false+ deprecated: false+ replaced_by:+ - name: maintenance_task_run.deleted+ group: maintenance_task_run+ credential_permission:+ credential: false+ deprecated: false+ replaced_by:+ - name: maintenance_task_run.errored+ group: maintenance_task_run+ credential_permission:+ credential: false+ deprecated: false+ replaced_by:+ - name: maintenance_task_run.interrupted+ group: maintenance_task_run+ credential_permission:+ credential: false+ deprecated: false+ replaced_by:+ - name: maintenance_task_run.started+ group: maintenance_task_run+ credential_permission:+ credential: false+ deprecated: false+ replaced_by:+ - name: maintenance_task_run.succeeded+ group: maintenance_task_run+ credential_permission:+ credential: false+ deprecated: false+ replaced_by:+ - name: maintenance_task_run.updated+ group: maintenance_task_run+ credential_permission:+ credential: false+ deprecated: false+ replaced_by:- name: media.createdgroup: mediacredential_permission:@@ -38733,7 +39210,7 @@ paths:deprecated: falsereplaced_by:meta:- count: 252+ count: 260"/api/v3/admin/catalogs":get:summary: List catalogs@@ -57435,6 +57912,8 @@ paths:- write_package_types- read_email_templates- write_email_templates+ - read_maintenance_tasks+ - write_maintenance_tasksbearer_methods_supported:- headerresource_documentation: https://spreecommerce.org/docs/developer/mcp/overview@@ -57483,6 +57962,9 @@ tags:- name: Importsdescription: Async CSV imports of admin resources, with per-row status and failed-rowretry+- name: Maintenance Tasks+ description: Operator-run data work — backfills, reindexes and upgrade steps — and+ the record of every run- name: Marketsdescription: Markets — geographic groupings of countries used for pricing, tax,and fulfillment rules@@ -64384,6 +64866,90 @@ components:- default- rtlx-typelizer: true+ MaintenanceTaskRun:+ type: object+ properties:+ id:+ type: string+ status:+ anyOf:+ - type: string+ enum:+ - enqueued+ - running+ - interrupted+ - cancelling+ - cancelled+ - succeeded+ - errored+ - type: string+ description: The values listed are the built-in ones; extensions may add+ more.+ dry_run:+ type: boolean+ initiated_via:+ type: string+ tick_count:+ type: number+ tick_total:+ type: number+ nullable: true+ error_class:+ type: string+ nullable: true+ error_message:+ type: string+ nullable: true+ started_at:+ type: string+ nullable: true+ ended_at:+ type: string+ nullable: true+ created_at:+ type: string+ updated_at:+ type: string+ task_name:+ type: string+ duration:+ type: number+ nullable: true+ tallies:+ type: object+ arguments:+ type: object+ error_backtrace:+ type: string+ nullable: true+ active:+ type: boolean+ admin_user_id:+ type: string+ nullable: true+ admin_user:+ "$ref": "#/components/schemas/AdminUser"+ required:+ - id+ - status+ - dry_run+ - initiated_via+ - tick_count+ - tick_total+ - error_class+ - error_message+ - started_at+ - ended_at+ - created_at+ - updated_at+ - task_name+ - duration+ - tallies+ - arguments+ - error_backtrace+ - active+ - admin_user_id+ x-typelizer: trueMarket:type: objectproperties:@@ -80153,6 +80719,24 @@ components:metadata:type: objectadditionalProperties: true+ MaintenanceTaskRunCreateParams:+ type: object+ properties:+ task_name:+ type: string+ description: The task to run, as `task_name` from `GET /upgrade_steps`.+ example: capture_methods+ arguments:+ type: object+ additionalProperties: true+ description: Values for the task's declared parameters, keyed by parameter+ name. A key the task does not declare is rejected.+ dry_run:+ type: boolean+ description: Report what would change without writing. Ignored by tasks+ that do not support a dry run, which run for real.+ required:+ - task_nameMarketCreateParams:type: objectproperties:diff --git a/docs/developer/customization/configuration.mdx b/docs/developer/customization/configuration.mdxindex ce72403b9b..76668f1e8b 100644--- a/docs/developer/customization/configuration.mdx+++ b/docs/developer/customization/configuration.mdx@@ -92,6 +92,7 @@ boot rather than silently reverting to the default.| `SPREE_LARGE_IMPORT_THRESHOLD` | `500` | Row count above which a CSV import switches to bulk processing — faster, with less live progress detail. || `SPREE_EVENTS_LOG_ENABLED` | `true` | Writes every Spree event to the Rails log. || `SPREE_DISABLE_MIGRATION_CHECK` | `false` | Silences the boot warning about pending engine migrations. |+| `SPREE_MAINTENANCE_TASKS_DASHBOARD_ENABLED` | `true` | Set to `false` to refuse maintenance tasks in the dashboard and the Admin API, leaving upgrade steps to `spree upgrade` on the command line. See [Maintenance tasks](/developer/how-to/maintenance-tasks#turning-off-the-dashboard). |## API authenticationdiff --git a/docs/developer/how-to/maintenance-tasks.mdx b/docs/developer/how-to/maintenance-tasks.mdxnew file mode 100644index 0000000000..eaca7a043b--- /dev/null+++ b/docs/developer/how-to/maintenance-tasks.mdx@@ -0,0 +1,104 @@+---+title: Maintenance Tasks+description: How Spree runs the data steps of an upgrade — from the dashboard or the command line, with a progress bar and a record of who ran what.+---++## Overview++An upgrade between Spree releases changes data as well as code: values move to new columns, records gain the store they belong to, old formats are converted. Each of those data steps runs as a **maintenance task**.++A maintenance task gives an upgrade step what a bare rake task lacks. A step that walks rows runs in batches with a checkpoint that survives a deploy, any step can be cancelled, and every run is recorded: who started it, from where, what it reported and, if it stopped, why. A half-finished upgrade therefore tells you exactly which step stopped and what already ran.++The steps of each upgrade are listed in its manifest, in the order they must run. See the [5.6 to 6.0 upgrade guide](/developer/upgrades/5.6-to-6.0) for what each one does.++## Running the upgrade++**From the command line**, the whole upgrade runs in order:++<Tabs>+ <Tab title="Spree CLI">+ ```bash+ spree upgrade+ ```+ </Tab>+ <Tab title="Without CLI">+ ```bash+ bin/rails spree:install:migrations db:migrate+ bin/rake spree:upgrade+ ```+ </Tab>+</Tabs>++The walk stops at the first step that fails or does not finish, and records nothing as complete until every step has succeeded. Re-running is safe: each step only changes data that still needs it.++To re-run one step after fixing the data that stopped it, name the step:++<Tabs>+ <Tab title="Spree CLI">+ ```bash+ spree upgrade --step migrate_returns+ ```+ </Tab>+ <Tab title="Without CLI">+ ```bash+ STEP=migrate_returns bin/rake spree:upgrade+ ```+ </Tab>+</Tabs>++A step that walks rows can preview what it would change, and a step that takes parameters reads them from `ARGS`:++```bash+DRY_RUN=1 bin/rake "spree:maintenance_tasks:perform[capture_methods]"+ARGS='batch_size=200' bin/rake "spree:maintenance_tasks:perform[deliveries]"+```++**From the dashboard**, under Settings → Maintenance tasks, the Upgrade tab lists the steps the store still needs as a checklist, each with its notes and a Run button. This is how an operator without a shell runs an upgrade. The History tab lists every run, whether it started in the dashboard, through the Admin API or on the command line.++## While a step is running++The run page shows progress and what the step has reported so far. **Cancel** stops the run for good: a step that walks rows stops at its next batch, and a single-pass step stops once its pass ends. Work already committed stays committed — cancelling is not an undo.++A step that fails or is cancelled is started again rather than resumed, and the new run starts from the beginning. Every step is written to be safe to repeat, so running it again leaves data that is already converted as it is. Only one run of a step can be in flight at a time, so a second start is refused.++## Permissions++An upgrade step converts the data of every store in the installation, not only the store you are working in, and its runs are recorded for the installation as a whole. The grant therefore sits with the other sensitive permissions:++- `read_maintenance_tasks` — see the upgrade steps and run history.+- `write_maintenance_tasks` — start and cancel runs.++Only the admin role holds these by default. Error backtraces are shown only to callers who may act on a run, since they name internal paths.++### Turning off the dashboard++On a platform that serves many merchants from one installation, the people holding a store's admin role are not the ones who operate the installation. Set `SPREE_MAINTENANCE_TASKS_DASHBOARD_ENABLED=false` to take maintenance tasks out of the dashboard and the Admin API for everyone, API keys included. Upgrade steps then run only from the command line, as part of your deploy.++```ruby server/config/initializers/spree.rb+Spree::Config.maintenance_tasks_dashboard_enabled = false+```++The setting in an initializer takes precedence over the environment variable. See [Configuration](/developer/customization/configuration) for the other settings read from the environment.++## What a store is shown++A store installed fresh at this release has no historical data to convert, so its Upgrade tab says the store is up to date and that the steps of a later upgrade will appear there. For a store that was upgraded, the tab shows the release it is moving to, with the releases it has already crossed below as completed history that cannot be re-run from the dashboard. The tab starts at the 5.6 → 6.0 upgrade, the first whose runs are recorded; steps of earlier releases run only from the command line, which `spree upgrade` walks in full.++Which those are comes from `Spree::UpgradeRecord`, a stamp written when an upgrade walk completes and when a store is first installed. Without a stamp — a store upgraded before this record existed — the tab assumes the release immediately below the installed one. A store that skipped releases runs the earlier steps from the command line.++Stamp a boundary by hand when you know a store already ran those steps:++```ruby+Spree::UpgradeRecord.stamp!('5.6', source: 'manual')+```++## Adding an upgrade step++A step is declared once, in the upgrade's `manifest.yml`, and names exactly one of:++- **`task`** — a rake task, for a step that is a single pass of updates. It runs through a shared runner that records it like any other run.+- **`task_class`** — a `Spree::MaintenanceTask` subclass, for a step that walks rows and benefits from progress, checkpoints and a dry run, or that takes parameters.++A task class lists the records it walks and handles them one at a time, recording counts the run page shows. `Spree::MaintenanceTasks::Upgrade::CaptureMethods` is a worked example with a dry run.++Its records must come in primary-key order, since the checkpoint is the last record handled, and they must include every record the conversion applies to, soft-deleted ones too. Each batch must be safe to run again: an interruption between applying a batch and recording its checkpoint repeats that batch. A task class named by a manifest is registered from it, so it needs no other wiring.diff --git a/docs/developer/upgrades/5.6-to-6.0.mdx b/docs/developer/upgrades/5.6-to-6.0.mdxindex d011671b84..c921713f53 100644--- a/docs/developer/upgrades/5.6-to-6.0.mdx+++ b/docs/developer/upgrades/5.6-to-6.0.mdx@@ -70,6 +70,18 @@ Dashboard plugins should widen their peer dependency ranges on `@spree/admin-sdkRe-running is safe — `bundle exec rake spree:upgrade` figures out what still needs to happen and does nothing on data that's already migrated. It also runs every data backfill from earlier upgrades (5.4 → 5.5 and 5.5 → 5.6), so any you missed along the way are caught up. That does not remove the requirement above: upgrade your application to 5.6 first.+### Watching it, and picking it back up++Every data step is a [maintenance task](/developer/how-to/maintenance-tasks), which changes what a long upgrade looks like. Each step records a run: who started it, when, what it reported, and — if it stops — the cause. So a half-finished upgrade tells you which step stopped and why, rather than leaving a stack trace and no record of what already ran.++Three consequences worth knowing before you start:++- **Watch it from the dashboard.** Settings → Maintenance tasks shows each step with a progress bar while it works. On a large store this is the difference between a silent hour and a visible one.+- **Run it without a shell.** Every step can be started from the dashboard, which is how operators on a managed platform run an upgrade at all.+- **Re-run one step.** `STEP=migrate_returns bundle exec rake spree:upgrade` runs a single step by id — useful when one step needed a data fix and the rest already succeeded.++Preview first where it is offered. Steps that can report what they would change without writing show a preview toggle in the dashboard, or take `DRY_RUN=1` on the command line.+## What the upgrade doesReference material — the data backfills `bundle exec rake spree:upgrade` executes. Every task is idempotent.@@ -177,7 +189,7 @@ bundle exec rake spree:backfill_order_coupon_codes```bashbundle exec rake spree:markets:migrate_checkout_zones-bundle exec rake spree:backfill_order_markets+bundle exec rake "spree:maintenance_tasks:perform[backfill_order_markets]"```A store without a market gets a default one covering its old checkout zone's countries (or its default country), and the checkout zone is cleared. Orders missing a market then get the store default — `market` is required on carts and orders in 6.0.diff --git a/docs/docs.json b/docs/docs.jsonindex 38def057a6..d37e680eed 100644--- a/docs/docs.json+++ b/docs/docs.json@@ -1082,7 +1082,8 @@"developer/how-to/extend-reporting","developer/how-to/custom-document-numbers","developer/how-to/custom-order-routing",- "developer/how-to/custom-stock-splitter"+ "developer/how-to/custom-stock-splitter",+ "developer/how-to/maintenance-tasks"],"icon": "compass"},diff --git a/docs/plans/6.0-maintenance-tasks.md b/docs/plans/6.0-maintenance-tasks.mdnew file mode 100644index 0000000000..ccbf033fe0--- /dev/null+++ b/docs/plans/6.0-maintenance-tasks.md@@ -0,0 +1,662 @@+# Maintenance Tasks — reviewed, deployed, resumable data work run from the dashboard++**Status:** Complete — all six phases shipped 2026-08-15+**Target:** Spree 6.0+**Depends on:** `6.0-service-workflows.md` (Durability = plain Rails / `ActiveJob::Continuable`), `6.0-admin-rbac.md` (permission catalog), `6.0-admin-api.md`, `6.0-admin-spa.md`, `5.6-solid-queue-single-container.md` (default job backend), `6.0-opentelemetry.md` (notification surface)+**Author:** Damian Legawiec (design driven with Claude, 2026-08-15)+**Last updated:** 2026-10-25++> **Narrowed 2026-10-25 (decisions.md): upgrade steps only.** Nothing outside+> the upgrade manifests registers a task, so the general-purpose surface was+> removed before release: the dashboard's Tasks tab and run form, the+> `GET /maintenance_tasks` endpoints and SDK methods, CSV input, throttling,+> error reporting, masked arguments, preconditions, task descriptions, the+> run-time limit setting, unused lifecycle hooks, parent runs, and pause and+> resume. The runner, run history, cancel, dry run and step parameters stay. The+> sections below describe the original, wider design; re-adding any of it is+> a new decision.++## Summary++Spree has no sanctioned way to run one-off data work — backfills, reindexes,+bulk corrections, the fix after a bad import — other than a rake task typed at+a shell or code pasted into a production console. That is the wrong shape for+three audiences at once: developers (a console session records what was+typed, not what it did), merchants on the cloud offering (nobody wants to hand+out shell access to run a backfill), and Spree itself (the 5.6→6.0 upgrade+manifest is twenty-two data migrations that every live store must run, and+today the instruction is "run this rake task and wait").++This plan adds a first-class **maintenance task** primitive to `spree_core`,+modeled on Shopify's `maintenance_tasks` engine but built natively on Rails+8.1's `ActiveJob::Continuable` (already the 6.0 durability doctrine, reference+`Spree::Imports::ProcessJob`): a task is a reviewed, deployed Ruby class with+a `collection` and a `process(item)`; running it creates a persistent **run**+row that carries the cursor, progress, arguments, outcome and *who fired it*;+the runner is a Continuable job that checkpoints per batch, survives deploys,+pauses, resumes and cancels; the Admin API exposes task discovery and run+control; the dashboard shows a task list, a generated parameter form, a+progress bar and the run history. Plugin gems ship tasks the same way core+does. Schema migrations stay where they are (deploy pipeline,+`strong_migrations`); this is only for data work.++Shipping it in 6.0 rather than 6.1 is deliberate: the 6.0 upgrade is the+largest data migration in Spree's history, and the runner turns it into a+list of tasks with progress bars and resume buttons instead of a rake+walk that dies at row 400k and starts over. We build it for our own migration+path and get the cloud capability as a side effect. It lives in BSD-3 core —+infrastructure, not money or compliance; self-hosted merchants need it exactly+as much.++## Key Decisions (do not deviate without discussion)++- **Named `Spree::MaintenanceTask` (2026-08-15).** Shopify parity — the term+ developers already search for and can port from — over `OpsTask` (the+ branch name) or `DataTask` (excludes reindex/cache work by name). Table+ `spree_maintenance_task_runs`, registry `Spree.maintenance_tasks`, keys+ `read_/write_maintenance_tasks`, routes `/maintenance_tasks` ++ `/maintenance_task_runs`, dashboard `/settings/maintenance-tasks`, rake+ `spree:maintenance_tasks:*`. Accepted trade-off: "maintenance" can read as+ downtime to merchants — the dashboard copy says what a task does, never+ "maintenance mode".+- **Native on `ActiveJob::Continuable`, not a dependency on the+ `maintenance_tasks` gem (2026-08-15).** The gem's runner rides `job-iteration` (a second+ interruption/cursor mechanism beside Continuable, which 6.0 already+ standardized on), and its UI is a server-rendered Rails engine on+ `ActionController::Base` + views — a surface Spree 6.0 removed. We would use+ neither half. What we DO copy is the **authoring contract**, nearly+ verbatim (`collection` / `process` / `count`, `no_collection`,+ `csv_collection`, ActiveModel attributes as parameters, `throttle_on`,+ `report_on`, lifecycle callbacks), so anyone who knows the Shopify gem+ knows how to write a Spree task, and a task can be ported between the two+ by changing the superclass.+- **Task authoring lives in the core gem; discovery through an explicit+ registry (`Spree.maintenance_tasks`), the same+ `Rails.application.config.spree.*` array every other class family uses+ (`Spree.integrations`, `Spree.adjusters`, `Spree.export_types`, …).** Core,+ provider gems, extensions and host apps append class names from an+ initializer. Explicit registration keeps "a task class exists somewhere+ under `app/`" from meaning "operators can fire it", and it is what the+ Admin API lists. Subclass autodiscovery (Shopify's model) was rejected+ (2026-08-15): it makes eager loading load-bearing in every gem that ships+ tasks and offers no way to say "not for operators".+- **The run row IS the audit.** `Spree::MaintenanceTaskRun` records the task+ name, serialized arguments, who initiated it (staff member or API key),+ through which surface (`dashboard` / `api` / `cli`), the store context,+ timestamps, cursor, tick counts, error, and task-reported tallies. Runs are+ never deleted through the API (no `destroy` action — cancel instead, same+ as returns/claims). Lifecycle events+ (`maintenance_task_run.started` / `.succeeded` / `.errored` / `.canceled` /+ `.paused`) fire through `publishes_lifecycle_events` so webhooks and the+ event log see them — consistent with decisions.md 2026-08-07 ("lifecycle+ events are the only audit"). No separate audit-log model.+- **RBAC: one catalog resource, `maintenance_tasks`, in the `access` group —+ admins only by default, nothing per task (2026-08-15).** `read_maintenance_tasks`+ lists tasks and runs; `write_maintenance_tasks` fires, pauses, resumes and+ cancels any registered task. It sits beside `staff` and `api_keys` — the+ sensitive group — so out of the box only the immutable `admin` role holds+ it, and secret keys need `write_maintenance_tasks` or `write_all`. A+ merchant who wants a narrower "release engineer" role grants the key+ explicitly. A per-task declared permission (`requires_permission+ :write_orders` beside the runner key) was considered and dropped as+ over-engineering; a hard "admin role only" controller check was also+ rejected because it would be the first gate in the v3 API outside the+ catalog (`6.0-admin-rbac.md`: the catalog plus a class swap is the whole+ authorization surface). Accepted trade-off: a role granted the write key+ can run every task, including ones that touch orders — the run row's+ audit trail, not the grant, is what makes that reviewable.+- **Installation-wide resource, store-aware execution (2026-08-15).** Tasks and runs are+ not store-owned data (a backfill walks every store; roles are global). But+ every run records the `store_id` the operator was acting in when it was+ fired from the dashboard/API (nullable — CLI runs may have none), and the+ runner sets `Spree::Current.store` from it for the whole execution, because+ `6.0-store-scoped-configuration.md` requires jobs that validate addresses+ or query the catalog to carry a store. A task that must be run per store+ takes the store as an explicit argument; the context store is a default,+ not a filter.+- **Dry-run is a task capability, not a runner trick (2026-08-15).** A task opts in with+ `supports_dry_run`; the run row carries `dry_run: true`; the task reads+ `dry_run?` and reports what it *would* change through the tally channel+ (`tally(:would_update)`). The runner never wraps batches in rolled-back+ transactions to fake it — that breaks external I/O tasks and cursor+ semantics silently. The dashboard shows the toggle only for tasks that+ declare support.+- **One active run per task.** A task with a run in `enqueued` / `running` /+ `pausing` / `paused` / `interrupted` / `cancelling` cannot be started+ again (422). Re-running is explicit: cancel or wait, then fire anew.+- **Interruption has three sources and one cursor.** (1) Worker shutdown —+ Continuable's checkpoint sees `queue_adapter.stopping?` and re-enqueues+ with the cursor in the job data (status `interrupted` → back to `running`).+ (2) Time slicing — the runner interrupts itself after `max_run_time`+ (task-declared, default 5 minutes) so one task cannot hog a worker;+ same mechanism. (3) Operator pause/cancel — the run row's status is+ re-read at every checkpoint (default every batch, at most once a second);+ `pausing` stops the job and leaves `paused` + cursor, `cancelling` stops+ it and leaves `cancelled`. Resume enqueues a fresh job seeded from the run+ row's cursor. **The run row's cursor is the durable truth**; Continuable's+ serialized progress is a fast path for case (1) and must never disagree+ with it — the runner writes both in the same checkpoint.+- **CSV input reuses the import upload flow.** `csv_collection` tasks take+ an Active Storage blob created through the same signed direct-upload+ endpoint the dashboard CSV import uses; the run row holds the attachment.+ Phase 2, not first cut.+- **The CLI entry is `spree:maintenance_tasks:perform` and it writes a run+ row too.** Shell runs are audited like dashboard runs (`initiated_via:+ cli`, staff nil). Inline (`perform_now`) execution for seeds/tests.+- **Every 5.6→6.0 upgrade step is a task class and the manifest names+ classes (2026-08-15).** All 22 steps are rewritten as+ `Spree::MaintenanceTasks::Upgrade::*`; older, already-released manifests+ keep rake steps and the walker runs both kinds inside run rows. The+ cheaper cuts (a generic wrapper only, or wrapper + the four heavy steps)+ were rejected: the 6.0 upgrade is the reason this ships in 6.0, and a+ progress bar on four steps with twenty-two rows of "indeterminate" is not+ the experience the plan is for. Accepted cost: 22 rewrites + spec ports+ before 6.0 GA. Sequencing lives in `Upgrade::Walk`, an orchestrating task+ whose steps are child runs (`parent_run_id`).+ *Superseded 2026-10-25 (decisions.md): a one-pass step names its rake+ task and runs through `UpgradeStep`; only steps that walk rows or take+ parameters are task classes, and a step is never both.*+- **Schema migrations are out of scope, permanently.** No task ever runs+ `db:migrate` or alters schema; the deploy pipeline owns that. A task that+ needs a column the migration has not added yet is a task with a+ precondition (`precondition { column_exists? }`) that fails fast with a+ message.++## Design Details++### Task class contract++```ruby+module Spree+ module MaintenanceTasks+ # A backfill written the way every task is written: a stable-ordered+ # relation, a per-record body, a permission, and an optional dry-run.+ class BackfillOrderMarkets < Spree::MaintenanceTask+ description 'Assign a market to orders placed before markets existed'+ supports_dry_run+ max_run_time 5.minutes+ collection_batch_size 500++ attribute :market_id, :string+ validates :market_id, presence: true++ def collection+ Spree::Order.where(market_id: nil).order(:id)+ end++ def process(order)+ if dry_run?+ tally(:would_update)+ else+ order.update_columns(market_id: market_id)+ tally(:updated)+ end+ end+ end+ end+end+```++Vocabulary (all class-level unless noted):++| Declaration | Meaning |+|---|---|+| `description(text)` | Shown in the task list; localizable through `Spree.t` when a key is given |+| `supports_dry_run` | Exposes the dry-run toggle; task must honor `dry_run?` |+| `no_collection` | Task has no iteration; `process` runs once |+| `csv_collection(in_batches: n)` | Rows come from an uploaded CSV (phase 2) |+| `collection_batch_size(n)` | Records per checkpoint (default 100) |+| `max_run_time(duration)` | Time slice before self-interruption (default 5 min) |+| `throttle_on(backoff:) { }` | Skip work and back off while the block is true (replica lag, queue depth) |+| `report_on(ErrorClass, severity:)` | Rescue per-item errors, report to `Rails.error`, continue |+| `precondition(message) { }` | Checked before enqueue; failing → 422 |+| `after_start` / `after_pause` / `after_interrupt` / `after_cancel` / `after_complete` / `after_error` | Instance callbacks |+| `attribute` + `validates` | ActiveModel parameters; inclusion validators become selects; `mask_attribute` hides values in run history |++Instance surface: `collection` (an `ActiveRecord::Relation` with an explicit+`order`, an `Array`, an `ActiveRecord::Batches::BatchEnumerator` from+`in_batches`, or `nil` for `no_collection`), `process(item_or_batch)`, `count`+(defaults to `collection.count`; `nil` = unknown, progress shows ticks only),+`dry_run?`, `tally(key, by = 1)`, `store` (context store, may be nil), `run`+(the run row, read-only), `cursor_for(item)` (defaults to primary key; tasks+whose relation is ordered by something else override it).++Cursors: an `ActiveRecord::Relation` is walked as `where(pk > cursor).order(pk).limit(batch)` —+the same pattern as `ProductTypes::ApplyToProductsJob`; that is why the+relation must be ordered by a stable unique column and why the cursor is a+string (UUID-safe). Arrays cursor by index. `no_collection` has no cursor.++### The run row — `Spree::MaintenanceTaskRun`++`spree_maintenance_task_runs` (installation-wide, no `store_id` ownership;+`store_id` is context):++| Column | Type | Notes |+|---|---|---|+| `task_name` | string, null: false, indexed | Registered class name |+| `status` | string, null: false | `HasStatus` — see below |+| `arguments` | JSON | Serialized attribute values (masked ones stored encrypted-at-rest via `encrypts`) |+| `dry_run` | boolean, default false | |+| `cursor` | string | Last processed cursor |+| `tick_count` / `tick_total` | integer, default 0 / nullable | Progress |+| `tallies` | JSON | Task-reported counters |+| `time_running` | decimal seconds, default 0 | Summed across executions |+| `started_at` / `ended_at` | datetime | |+| `error_class` / `error_message` / `error_backtrace` | string / text / text | Cleaned with `Rails.backtrace_cleaner` |+| `job_id` | string | Current/last ActiveJob id |+| `parent_run_id` | reference, nullable | Set on child runs of an orchestrating task (the upgrade walk) |+| `store_id` | reference, nullable | Context store |+| `admin_user_id` | reference, nullable | Staff who fired it |+| `api_key_id` | reference, nullable | Secret key that fired it |+| `initiated_via` | string, null: false | `dashboard` / `api` / `cli` / `inline` |+| `csv_file` | Active Storage attachment | Phase 2 |+| `metadata` | JSON | `Spree::Metadata` |+| timestamps | | |++**No optimistic locking (2026-08-15, found in implementation).** A+`lock_version` column was in the original design and was removed: writers+here are already disjoint — the control services only ever write a *request*+(`pausing`, `cancelling`) and the runner alone writes the resulting state —+so it guarded nothing, while breaking the runner's own per-batch progress+writes against its in-memory copy. Silently, at that: `update_columns` puts+`lock_version` in the WHERE clause and reports no error when it matches no+row, so a run would have resumed from a cursor it never saved. The runner+reloads before each status write instead.++Statuses (`has_status`, additive, no transition graph — transitions live in+the runner and the three control services):+`enqueued → running → succeeded | errored | cancelled`, with `pausing`,+`paused`, `interrupted`, `cancelling` as the operator/worker-driven detours.+Predicates: `active?` (anything not terminal), `resumable?` (`paused` or+`errored` with a cursor).++`publishes_lifecycle_events` + `Spree::Api::V3::Events::MaintenanceTaskRunSerializer`.++### Runner — `Spree::MaintenanceTasks::RunJob`++A `Spree::BaseJob` including `ActiveJob::Continuable`, queue+`Spree.queues.maintenance_tasks` (new key, defaults to `:default` like all+others). Shape follows `Imports::ProcessJob`:++```ruby+def perform(run_id)+ @run = Spree::MaintenanceTaskRun.find(run_id) # every execution, resumes included+ return unless @run.status.in?(%w[enqueued running interrupted])+ Spree::Current.store = @run.store++ step :start do ... status running, started_at, after_start+ step :process_collection, start: @run.cursor # cursor seeded from the ROW+ step :complete do ... status succeeded, ended_at, after_complete+end+```++`process_collection` loops batches; after each batch it (a) increments ticks++ merges tallies + writes the cursor on the row, (b) `step.set!(cursor)` —+Continuable's checkpoint, which raises `Interrupt` if the adapter is+stopping — and (c) runs the runner's own checkpoint: re-read the row's+status; on `pausing` → mark `paused`, return; on `cancelling` → mark+`cancelled`, `after_cancel`, return; if elapsed > `max_run_time` →+`interrupt!` (re-enqueue). The status re-read happens **every batch, not on+a timer** (2026-08-15, found in implementation): a primary-key read costs+nothing beside the batch of writes it follows, and a time-based throttle made+a fast task ignore a pause altogether, since all its batches landed inside+one interval. Errors after progress: Continuable+resumes them (`resume_errors_after_advancing`), so the runner rescues+`StandardError` inside the step, records the error on the row (`errored`,+`after_error`) and returns — never `discard_on`, for the same reason+`Imports::ProcessJob` rescues inside the step. `Interrupt` inherits+`Exception` and is never rescued.++`throttle_on` blocks are evaluated before each batch; when one is true the+runner sleeps up to `backoff` (bounded, then re-checks) — it does not+re-enqueue, because Solid Queue's minimum polling granularity would make+sub-minute backoffs coarse.++Notifications (`6.0-opentelemetry.md` catalog, additive):+`run.spree_maintenance_task` (payload: `task_name`, `run_id` prefixed,+`status`, `tick_count`, `dry_run`), `batch.spree_maintenance_task`+(`task_name`, `run_id`, `size`, `cursor`). No arguments in payloads (they can+carry PII).++### Control services++Plain services (`Spree::MaintenanceTasks::Start`, `Pause`, `Resume`, `Cancel`),+tier 1 per `6.0-service-workflows.md` — no hooks needed. `Start` validates+the task's attributes and preconditions, enforces the one-active-run rule+(row lookup + `with_lock` on a per-task advisory row is overkill; a+uniqueness validation over the active statuses plus the enqueue happening+inside `after_commit` keeps the race window sub-millisecond and the worst+case is a second run that the runner refuses on load — logged, not silent),+creates the row and enqueues `RunJob`. `Resume` re-enqueues from the row's+cursor. `Pause`/`Cancel` flip status under `lock_version`.++### Registry++```ruby+# core engine initializer+Rails.application.config.spree.maintenance_tasks = ['Spree::MaintenanceTasks::BackfillOrderMarkets', ...]++# an extension / host app initializer — class-name strings, like Spree.integrations+Spree.maintenance_tasks << 'SpreeReviews::MaintenanceTasks::RecountRatings'++Spree::MaintenanceTask.registered_classes # constantized, sorted+Spree::MaintenanceTask.find_registered('Spree::MaintenanceTasks::BackfillOrderMarkets')+```++Only registered classes appear in the API and can be run; a run row naming+an unregistered class is refused on load. Task classes live in+`app/maintenance_tasks/` inside each gem (Rails autoloads any `app/*`+directory), namespaced under the gem's own module (`Spree::MaintenanceTasks::*`+in core, `SpreeEasyPost::MaintenanceTasks::*` in a provider). Class-name+strings keep registration initializer-safe and reload-safe, the same reason+`Spree.hooks` stores handler names. Registry resolution is a small+`Spree::RegisteredSubclasses` concern — the extraction `PreferenceSchema`'s+header already asks for ("a family that needs the registry without+preferences") — rather than a fourth idiom.++### Admin API v3++Scope `maintenance_tasks` (read/write). All installation-wide — the+`X-Spree-Store-Id` header only sets the run's context store.++```+GET /api/v3/admin/maintenance_tasks # registered tasks: name, description, parameters schema,+ # supports_dry_run, csv?, active_run, last_run+GET /api/v3/admin/maintenance_tasks/:name # one task, by short name (`capture_methods`)+GET /api/v3/admin/maintenance_task_runs # Ransack: task_name, status, admin_user_id, created_at+GET /api/v3/admin/maintenance_task_runs/:id # `expand=admin_user` embeds who started it+POST /api/v3/admin/maintenance_task_runs # { task_name, arguments: {}, dry_run:, csv_file: } → 201 enqueued / 422+POST /api/v3/admin/maintenance_task_runs/:id/pause+POST /api/v3/admin/maintenance_task_runs/:id/resumption+POST /api/v3/admin/maintenance_task_runs/:id/cancellation+```++A task is named on the wire by its short name (`Spree::ApiTyped`: the+demodulized, underscored class), never its class name; the run row keeps+storing the class name. Pause, resumption and cancellation are nested+singular resources rather than member actions (2026-10-16).++No `destroy`. The parameters schema reuses the shape the integrations+`types` endpoint emits from `PreferenceSchema` (`name`, `type`, `required`,+`options`, `masked`, `label`, `help`) — one form renderer in the dashboard.+Run serializer: admin-only (there is no store counterpart), prefixed ids,+`progress` (`0..1 | null`), `admin_user_id` plus an expandable `admin_user`+(the Admin user serializer), tallies, error+fields, `resumable`, `cancelable`. `error_backtrace` is served only to+callers holding `write_maintenance_tasks`.++### Dashboard++`/settings/maintenance-tasks` in the `audit` settings-nav group beside+Imports, gated on `Subject.MaintenanceTask` read.++- **Task list** — name, description, last run (status + when + who), *Run*+ button (`<Can>`-gated on `write_maintenance_tasks`; disabled with a+ tooltip while a run is active).+- **Run dialog** — generated from the parameters schema; dry-run switch+ when supported; CSV drop zone for CSV tasks (phase 2, reusing the import+ upload sheet); confirm copy states the task's effect and — for non-dry+ runs — "This starts immediately and cannot be undone by the runner".+- **Run page** — status, progress bar (`tick_count / tick_total`, or an+ indeterminate bar with the count), tallies, elapsed, initiated by, store,+ arguments (masked where declared), error class/message with an expandable+ backtrace, and Pause / Resume / Cancel (destructive confirm on cancel).+ Status by **polling** while active (same as imports — no ActionCable in the+ SPA), 2s while running, stopped when terminal.+- **History** — paginated table across all tasks with filters (task,+ status, who, date), linking to run pages.++Translations in all six locales; per-task `description` is server-provided+so plugin authors localize with `Spree.t`.++### CLI and inline++- `bin/rails "spree:maintenance_tasks:perform[Spree::MaintenanceTasks::BackfillOrderMarkets]" ARGS='market_id=mkt_x' DRY_RUN=1` —+ runs synchronously (`perform_now`), prints progress lines, exits non-zero on+ error, writes a run row (`initiated_via: cli`).+- `bin/rails spree:maintenance_tasks:list`.+- `Spree::MaintenanceTasks::Start.call(task_name:, arguments:, inline: true)`+ for seeds/tests.++### Upgrade manifest integration — every 6.0 step is a task class++*Amended 2026-10-25 (decisions.md): one-pass steps run their rake task+through `UpgradeStep`; only row walks and steps with parameters are task+classes.*++Today's shape: `spree:upgrade` (`spree/core/lib/tasks/upgrade.rake`) walks+`lib/spree/upgrades/<from>_to_<to>/manifest.yml` after `db:migrate`; every+step is a standalone rake task with `puts` progress, `abort` as the failure+signal, ENV knobs (`BATCH_SIZE`, `SKIP_FAILED_ROWS`, `CONFIRM_NO_PEPPER`, …)+and no shared base class, cursor or status row. Idempotency is a contract,+and the row-by-row migrators (`Spree::ReturnsMigrator`,+`Spree::CountryStateCodeMigrator`, defined inside their rake files) are+"resumable by construction" — what is left is a query, never tracked state.+That property carries straight over: such a query IS a `collection`.++Doctrine that stays: decisions.md 2026-08-07 — the data tasks are manifest+steps that run at deploy; "code deployed, task not yet run" is not a state+Spree designs for. This plan does not move the steps out of the deploy+window; it gives the same steps an audited, resumable, progress-reporting+entry point that also works where there is no shell.++**Decision (2026-08-15): all 22 steps of the 5.6→6.0 manifest are rewritten+as `Spree::MaintenanceTask` subclasses under+`Spree::MaintenanceTasks::Upgrade::*`, and the manifest names classes, not+rake tasks.** The 5.6→6.0 tasks have never shipped in a release, so nobody+has scripted their rake names — there is nothing to bridge. Older manifests+(5.4→5.5, 5.5→5.6) are already released and keep their `task:` rake steps;+the walker understands both step kinds.++```yaml+# lib/spree/upgrades/5_6_to_6_0/manifest.yml+steps:+ - id: migrate_returns+ task_class: Spree::MaintenanceTasks::Upgrade::MigrateReturns+ notes: |+ ...operator prose stays here and is shown on the run page...+```++```ruby+module Spree::MaintenanceTasks::Upgrade+ class MigrateReturns < Spree::MaintenanceTask+ description 'Move return authorizations onto the 6.0 Return/Exchange models'+ supports_dry_run+ attribute :batch_size, :integer, default: 500+ attribute :skip_failed_rows, :boolean, default: false++ def collection = legacy_authorizations.where.not(number: Spree::Return.select(:number)).order(:id)+ def process(legacy_authorization) = ... # migrate_one, tally(:returns)/(:exchanges)/(:failed)+ end+end+```++What changes per step:++- The rake body becomes `collection` + `process` (row-by-row steps) or a+ `no_collection` `process` (set-based SQL steps — still one run row,+ tallies from `update_all` counts). Migrator classes defined inside rake+ files move into the task class; anonymous-AR readers stay as they are.+- ENV knobs become validated attributes with defaults; `abort` becomes a+ raised error (run `errored`, message on the row) or, for the+ reconcile-then-continue cases, `skip_failed_rows`-style attributes plus+ `report_on`.+- `puts` progress becomes ticks + tallies; `DRY_RUN=1` on the walker stays+ a plan printer, and steps that can preview declare `supports_dry_run`.+- Ordering constraints (run X after Y) are expressed as `precondition`+ blocks that check the upstream step's last successful run — the manifest+ order remains the source of truth, the precondition is the guard.+- `spec/lib/tasks/six_zero_data_migrations_spec.rb` and the per-task specs+ port to task specs run through `Start.call(inline: true)`; the+ idempotency examples (re-run, assert no change) carry over unchanged.++**The walk.** `spree:upgrade` keeps its interface (`TO`, `STEP`, `DRY_RUN`)+and the `spree upgrade` CLI keeps sequencing `bundle update` → `db:migrate` →+`bin/rake spree:upgrade`. Internally the walker runs each `task_class` step+through `Start.call(inline: true)` — so a shell walk writes run rows too —+and each legacy `task:` step through `Rake::Task#invoke` wrapped in a run row+of the generic `Spree::MaintenanceTasks::UpgradeStep` task (audit parity for+old manifests). From the dashboard the same walk is+`Spree::MaintenanceTasks::Upgrade::Walk`: a task whose `collection` is the+eligible steps in manifest order and whose `process(step)` runs the step+task inline as a **child run** (`parent_run_id` on the run row). Each child+keeps its own cursor and progress bar; the walk's cursor is the step index.+Interruption inside a child propagates up (Continuable's `Interrupt` is an+`Exception`), the walk re-enqueues at step N, and on resume step N's task+resumes from its own row — one mechanism, nested once. A step that errors+stops the walk (`errored`, pointing at the child); the operator fixes the+data, resumes the child or re-runs the walk, which skips steps whose last+run succeeded.++**Dashboard.** Settings → Maintenance tasks gets an *Upgrade* panel when a+manifest ahead of the recorded installed version exists: the steps in order+with the status of each step's last run, the notes, per-step *Run* and a+*Run all remaining* that fires the walk. Elsewhere the upgrade tasks are+ordinary tasks in the list.++## Migration Path++1. **Core primitive** — ✅ **shipped 2026-08-15**: `Spree::MaintenanceTask`,+ `MaintenanceTaskRun` + migration, `RunJob`, `Start`/`Pause`/`Resume`/`Cancel`,+ registry (`Spree.maintenance_tasks`), `Spree.queues.maintenance_tasks`,+ `spree:maintenance_tasks:{list,perform}`, the `maintenance_tasks` catalog+ resource, `Upgrade::BackfillOrderMarkets` as the reference task, and the+ spec battery (55 examples: interruption + resume via+ `ActiveJob::Continuation::TestHelper`, pause, cancel, dry-run, `report_on`,+ preconditions, one-active-run, unregistered task, masked arguments).+2. **RBAC + API** — catalog resource `maintenance_tasks` (group `access`,+ subjects `MaintenanceTaskRun` + `:maintenance_task`), controllers, serializers,+ typelizer → admin-sdk `client.maintenanceTasks` / `client.maintenanceTaskRuns`,+ rswag docs.+3. **Dashboard** — ✅ **shipped 2026-08-15**: `/settings/maintenance-tasks`+ in the audit nav group, task cards with live progress, a run dialog whose+ fields are generated from the server's parameter schema (dry-run defaults+ ON for tasks that support it), a run detail sheet with progress, tallies,+ arguments, error + backtrace and Pause/Resume/Cancel, and the paginated+ run history table; translations in all six locales. Verified against a+ live store: preview run reported `would_update: 3` and wrote nothing, the+ subsequent real run wrote all three. Pending: an e2e spec.+4. **Upgrade integration** — ✅ **shipped 2026-08-15**: `Spree::Upgrade`+ extracted from the rake file so app code can read the manifests; the+ walker runs both step kinds through `MaintenanceTasks::Start` so a shell+ walk records the same rows a dashboard run does; all 22 steps of the+ 5.6→6.0 manifest are `Spree::MaintenanceTasks::Upgrade::*` classes named+ by `task_class:`; `UpgradeStep` wraps rake-backed steps of released+ manifests. Verified by walking all 31 steps of all three manifests+ against a real database.++ **Refinement (2026-08-15, found in implementation):** the set-based steps+ keep their rake body as the implementation rather than being rewritten as+ row walks. Their bodies are covered by a spec suite that invokes them by+ task name — 193 examples — and reimplementing set-based SQL as a row walk+ would trade tested code for a progress bar on work that reports no rows.+ Each is still a task class with its own run row, parameters (the ENV knobs+ became attributes via `passes_to_environment`) and preconditions; what it+ is not is a `collection`. Steps that genuinely walk rows —+ `CaptureMethods` and the reference `BackfillOrderMarkets` — are real+ collection tasks with cursors.+5. **CSV tasks** — ✅ **shipped 2026-08-15**: `csv_collection` on the task+ contract, the uploaded blob attached to the run (private storage, so the+ file stays the record of what was applied), a row-number cursor so an+ interrupted run re-reads the file but re-applies nothing, the imports+ direct-upload endpoint reused for the upload, a file field on the run+ dialog, and `UpdateVariantPrices` as the reference CSV task.+6. **Docs** — ✅ **shipped 2026-08-15**: `docs/developer/how-to/maintenance-tasks.mdx`+ (authoring, the ordered-collection rule, parameters from validators,+ dry-run, long-running work, CSV tasks, running from dashboard/CLI/code,+ permissions, shipping tasks from an extension, what tasks are not for) ++ nav entry + the 5.6→6.0 upgrade guide gaining the dashboard path, the+ `STEP=` re-run form and the preview note.++## Constraints on Current Work++- **New bulk/backfill work is a maintenance task, not a bare rake task or a+ README console snippet.** A rake entry may exist for scripting but its body+ is `Spree::MaintenanceTasks::Start.call(inline: true)`.+- **New 5.6→6.0 upgrade steps are born as `Spree::MaintenanceTasks::Upgrade::*`+ classes referenced by `task_class:` in the manifest** — no new+ `spree:migrate_*` rake tasks. Until the primitive lands, a step written+ today must keep its body in a plain class with a `collection`-shaped+ "what's left" query and a per-row `process`, so the port is mechanical.+- **Nothing gates on the `admin` role by name.** Authorization is the+ `maintenance_tasks` catalog key; the dashboard uses `<Can>` on it, secret+ keys use the scope. Sensitivity is expressed by which group the key sits+ in, not by a bespoke check.+- **Long-running background jobs still use `ActiveJob::Continuable`+ directly** when they are system-triggered (imports, product-type apply);+ the task primitive is for *operator-triggered* work. Do not convert+ `Imports::ProcessJob` into a task.+- **Task classes must be idempotent per batch** (re-running the batch in+ flight at interruption changes nothing) — the same rule the upgrade+ manifest already imposes on its steps.+- **Never store secrets or PII in `arguments` unmasked**; use+ `mask_attribute` for anything sensitive, and never put arguments in+ notification payloads or event payloads beyond the masked serializer.+- **A task never runs schema changes.**++## Open Questions++None open. All seven design questions were resolved on 2026-08-15 and are+recorded in Key Decisions; the upgrade panel and its step filtering shipped+2026-08-16.++**Fresh installs see no upgrade at all (2026-08-16).** `Spree::UpgradeRecord`+records *how* a boundary was reached (`walk` / `install` / `manual`), so a+store installed at its current release — every stamp an `install` — has the+whole panel hidden rather than being shown a manifest of work that does not+exist for it. Upgrade steps are also marked `upgrade_step` on the tasks+endpoint, so they stay out of the loose task list on such an installation,+where the upgrade endpoint returns nothing to filter by.++**Panel shape (2026-08-16).** One card per release: the current boundary open+with runnable steps, past boundaries below as collapsed "Completed" cards,+newest first, with no Run buttons — re-running a conversion the store already+applied is how an upgrade does damage. The page is three tabs (Upgrade /+Tasks / History) on a new `Tabs` primitive in dashboard-ui, the first in the+design system.++**No sample tasks ship in core (2026-08-16).** The reference CSV task written+during Phase 5 was deleted: it was example code, and registering it put a task+nobody asked for in every merchant's dashboard. The CSV machinery is covered+by a spec-local task, and the authoring guide keeps a worked example.++**Superseded steps (2026-08-16).** The panel first shipped listing every step+of every manifest — 31 on a 6.0 install, nine of which a store already on 5.6+must never re-run, and growing with each release. Fixed by recording the+boundary rather than inferring it: `Spree::UpgradeRecord` is stamped by a+completed walk and by a fresh install, `pending_steps` starts from it, and+steps are grouped by release boundary. Where no stamp exists the boundary is+assumed (one release back) and **reported as assumed**, so a store that+skipped releases is pointed at the earlier steps rather than having them+silently disappear — the failure mode of a plain auto-mark.++One deferred item, with what unblocks it:++- **Per-task permission scoping** (`requires_permission :write_orders`+ beside the runner key) — revisit only if a merchant asks for a role that+ may run some tasks but not others; the run audit is expected to make that+ unnecessary.++## References++- Shopify `maintenance_tasks` — https://github.com/Shopify/maintenance_tasks+ (authoring contract, run statuses, `throttle_on`/`report_on`, CLI)+- Rails 8.1 `ActiveJob::Continuable` / `ActiveJob::Continuation`+- `spree/core/app/jobs/spree/imports/process_job.rb`,+ `spree/core/app/jobs/spree/product_types/apply_to_products_job.rb` —+ Continuable references in core+- `spree/core/lib/tasks/upgrade.rake`,+ `spree/core/lib/spree/upgrades/5_6_to_6_0/manifest.yml`+- `docs/plans/6.0-service-workflows.md` — "Durability = plain Rails"+- `docs/plans/6.0-admin-rbac.md` — permission catalog registration+- `docs/plans/5.6-admin-spa-csv-import.md` — direct-upload flow, polling+- `docs/plans/decisions.md` 2026-08-07 — lifecycle events are the only audit;+ same date — "the data tasks are steps in the upgrade manifest, 'code+ deployed, task not yet run' is not a state Spree supports"+- `spree/core/lib/spree/core/permission_configuration.rb` (`register_resource`),+ `spree/core/app/models/spree/setup_tasks.rb` (a registry object precedent),+ `spree/core/app/models/concerns/spree/preference_schema.rb` (the+ `RegisteredSubclasses` extraction note)+- `packages/dashboard/src/hooks/use-imports.ts` (2s polling while active),+ `packages/dashboard/src/routes/_authenticated/$storeId/settings/integrations.tsx`+ (gallery of registered classes — closest existing page shape)diff --git a/docs/plans/6.0-service-workflows.md b/docs/plans/6.0-service-workflows.mdindex 31029d1965..d502d2d0c3 100644--- a/docs/plans/6.0-service-workflows.md+++ b/docs/plans/6.0-service-workflows.md@@ -413,7 +413,10 @@ plan.durability tool (`Spree::Imports::ProcessJob` is the reference;`Spree::ProductTypes::ApplyToProductsJob` is the second adopter, cursoringon the last product id of a catalog-sized backfill); the- upgrade data migrations adopt the same pattern. Workflow-level durable+ upgrade data migrations adopt the same pattern — refined 2026-08-15 by+ `6.0-maintenance-tasks.md`: they become `Spree::MaintenanceTask` classes+ run by one shared Continuable runner with a persistent run row, rather+ than each carrying its own Continuable job. Workflow-level durableexecution is deliberately not shipped — revisit with the payout runper the note above.diff --git a/docs/plans/decisions.md b/docs/plans/decisions.mdindex e3b3aed5cf..9cc823443e 100644--- a/docs/plans/decisions.md+++ b/docs/plans/decisions.md@@ -18,6 +18,26 @@**Plan amended:** `6.0-beta-release.md` (Key Decisions 2 and 3).+## 2026-10-25: Maintenance tasks ship for upgrade steps only++**Context:** The maintenance tasks plan built a general-purpose surface for operator-run data work: a dashboard list of tasks with a form built from each task's parameters, endpoints to list and describe tasks, CSV input, throttling, per-record error reporting, masked arguments, preconditions and parent runs for an orchestrating walk. By release, only the upgrade manifests register tasks, and none of those uses any of it. The unused surface was most of the pull request's size and still needed review, tests and documentation.++**Decision:** 6.0 ships maintenance tasks as the runner for upgrade steps. Removed before release: the dashboard's Tasks tab and run form, `GET /maintenance_tasks` and its SDK methods, `csv_collection` and the run's CSV attachment, `throttle_on`, `report_on`, `mask_attribute`, `precondition`, `description`, `max_run_time`, the `after_start`/`after_pause`/`after_interrupt`/`after_cancel`/`after_error` hooks, `parent_run` and `spree:maintenance_tasks:list`. Pause and resume went too: upgrade steps are short or safe to re-run, so a step that fails or is cancelled is started again, and the `pausing`/`paused` statuses, their services, endpoints, events and dashboard buttons are gone. Kept: the runner and its checkpoints, run history, cancel, dry run, batch size, step parameters, `after_complete`, the permissions and `spree:maintenance_tasks:perform`.++**Consequences:** A task an extension or host wants to run outside an upgrade has no dashboard surface; adding one back is a new decision, built when there is a task that needs it. Runs no longer mask argument values, since no step takes a secret. Runs are installation-wide and belong to no store: an upgrade step converts every store's data, so a run no longer records the store the operator was in, and the runner no longer sets a current store while a step works. The guide at `docs/developer/how-to/maintenance-tasks.mdx` now documents upgrade steps.++**Plan amended:** `6.0-maintenance-tasks.md` (header note).++## 2026-10-25: An upgrade step is a rake task or a task class, never both++**Context:** The 2026-08-15 maintenance tasks decision made every 5.6 → 6.0 upgrade step a task class. In practice most steps are one-pass updates that kept their rake body, so each step was declared in up to five places: the manifest, the rake task, a ten-line wrapper class naming that rake task, a line in the engine's registration list and a translated description repeating the manifest name. Six steps went further and carried the same logic twice, once in the rake task and once in the class, so a fix to one could miss the other.++**Decision:** The manifest is the only list of steps, and each step names exactly one of `task` or `task_class`. A one-pass step names its rake task and runs through the shared `UpgradeStep` runner, which records it like any other run. A step gets a class of its own only when it walks rows (progress, resume, dry run) or asks the operator for parameters, and then it has no rake twin. Task classes named by a manifest are registered from it, so neither core nor a provider gem keeps a second list. The history labels a one-pass step by its step id.++**Consequences:** Adding a step is a manifest entry plus either a rake task or a class. One-pass steps share one task name, so the history filter cannot single one out and two of them cannot run at once, which an ordered upgrade does not need. 38 classes (34 wrappers and four one-pass steps), their registrations and descriptions, and two duplicate rake tasks are removed; seven classes remain (five with parameters, two row walks).++**Plan amended:** `6.0-maintenance-tasks.md` (Key Decisions, Upgrade manifest integration).+## 2026-10-24: A marketplace decides whether, what and under review its sellers may upload**Context:** With sellers able to attach downloadable files to their products (the entry below), any approved seller can put a file on the marketplace's domain that buyers download trusting the marketplace's brand. Nothing in Spree scans a file's contents, and before this there was no way to keep seller uploads off, to narrow what they may be, or to re-check an approved listing whose file changed. Digital asset writes were also plain model saves in two places, so a host had no point at which to refuse an upload.@@ -4761,6 +4781,51 @@ Getting Started list. Never add `Seller#onboarding_completed?`-style predicatesor step-done columns; a new admission check is a kind or a `validate` hook onthe seller workflows. Plan: `6.0-seller-onboarding-requirements.md`.+## 2026-08-15 — Maintenance tasks: operator-run data work is a task class with a run row, and every 6.0 upgrade step is one++**Decision:** Spree 6.0 core gains a first-class maintenance-task primitive —+`Spree::MaintenanceTask` (Shopify `maintenance_tasks` authoring contract:+`collection`/`process`/`count`, ActiveModel attributes as parameters,+`throttle_on`, `report_on`, `no_collection`, later `csv_collection`) run by a+native `ActiveJob::Continuable` job, with a persistent+`Spree::MaintenanceTaskRun` row carrying cursor, progress, arguments, tallies,+outcome and who fired it from where. It is built natively, not by depending+on Shopify's gem: the gem's runner is a second interruption mechanism+(`job-iteration`) beside the one 6.0 already standardized on, and its UI is+a server-rendered engine Spree 6.0 has no place to mount. Tasks are+registered explicitly (`Spree.maintenance_tasks`, the same+`Rails.application.config.spree.*` array as every class family) — never+autodiscovered. Authorization is **one catalog resource,+`maintenance_tasks`, in the `access` group**: admins hold it by default,+nothing is gated per task and nothing checks the `admin` role by name.+Runs are installation-wide with a recorded context store the runner loads+into `Spree::Current.store`. Dry-run is opt-in and task-honored+(`supports_dry_run` + `dry_run?`), never a runner-faked rollback. The run+row is the audit; lifecycle events fire; no audit-log model. Schema+migrations stay in the deploy pipeline forever.++**All 22 steps of the 5.6→6.0 upgrade manifest are rewritten as+`Spree::MaintenanceTasks::Upgrade::*` classes and the manifest names+`task_class:` instead of rake tasks** (those rake names never shipped, so+there is nothing to bridge; older manifests keep rake steps and the walker+runs both kinds inside run rows). `spree:upgrade` keeps its interface and+becomes an inline walk that writes the same run rows; the dashboard gets an+Upgrade panel and `Upgrade::Walk`, an orchestrating task whose steps are+child runs.++**Why:** A console session records what was typed, not what it did; a+managed platform cannot hand out shells; and the 6.0 upgrade is the largest+data migration Spree has shipped. Building the runner for our own migration+path yields the cloud capability as a side effect and turns "run this rake+task and wait" into progress bars and resume buttons. It lives in BSD-3 core+because it is infrastructure self-hosted merchants need exactly as much.++**Consequences:** New bulk/backfill work is a task, not a bare rake task or+a README console snippet; new 6.0 upgrade steps are born as task classes;+`Imports::ProcessJob`-style system-triggered jobs stay plain Continuable+jobs (the primitive is for operator-triggered work). Plan:+`6.0-maintenance-tasks.md`.+## 2026-08-24 — Media library reuses files by sharing blobs, never by a shared asset entityThe 6.0 media library is a store-scoped view over `Spree::Media` (which gains adiff --git a/packages/admin-sdk/examples/maintenance-task-runs/cancel.ts b/packages/admin-sdk/examples/maintenance-task-runs/cancel.tsnew file mode 100644index 0000000000..22e625a1db--- /dev/null+++ b/packages/admin-sdk/examples/maintenance-task-runs/cancel.ts@@ -0,0 +1,13 @@+import { createAdminClient } from '@spree/admin-sdk'++const client = createAdminClient({+ baseUrl: 'https://your-store.com',+ secretKey: 'sk_xxx',+})++// region:example+const run = await client.maintenanceTaskRuns.cancel('mtr_UkLWZg9DAJ')++// endregion:example++export { run }diff --git a/packages/admin-sdk/examples/maintenance-task-runs/create.ts b/packages/admin-sdk/examples/maintenance-task-runs/create.tsnew file mode 100644index 0000000000..ae616f372e--- /dev/null+++ b/packages/admin-sdk/examples/maintenance-task-runs/create.ts@@ -0,0 +1,16 @@+import { createAdminClient } from '@spree/admin-sdk'++const client = createAdminClient({+ baseUrl: 'https://your-store.com',+ secretKey: 'sk_xxx',+})++// region:example+const run = await client.maintenanceTaskRuns.create({+ task_name: 'capture_methods',+ dry_run: true,+})++// endregion:example++export { run }diff --git a/packages/admin-sdk/examples/maintenance-task-runs/get.ts b/packages/admin-sdk/examples/maintenance-task-runs/get.tsnew file mode 100644index 0000000000..923b0739c0--- /dev/null+++ b/packages/admin-sdk/examples/maintenance-task-runs/get.ts@@ -0,0 +1,13 @@+import { createAdminClient } from '@spree/admin-sdk'++const client = createAdminClient({+ baseUrl: 'https://your-store.com',+ secretKey: 'sk_xxx',+})++// region:example+const run = await client.maintenanceTaskRuns.get('mtr_UkLWZg9DAJ')++// endregion:example++export { run }diff --git a/packages/admin-sdk/examples/maintenance-task-runs/list.ts b/packages/admin-sdk/examples/maintenance-task-runs/list.tsnew file mode 100644index 0000000000..20cdc83818--- /dev/null+++ b/packages/admin-sdk/examples/maintenance-task-runs/list.ts@@ -0,0 +1,13 @@+import { createAdminClient } from '@spree/admin-sdk'++const client = createAdminClient({+ baseUrl: 'https://your-store.com',+ secretKey: 'sk_xxx',+})++// region:example+const { data: runs } = await client.maintenanceTaskRuns.list({ status_eq: 'succeeded' })++// endregion:example++export { runs }diff --git a/packages/admin-sdk/src/admin-client.ts b/packages/admin-sdk/src/admin-client.tsindex 9dcfda5339..a62e249913 100644--- a/packages/admin-sdk/src/admin-client.ts+++ b/packages/admin-sdk/src/admin-client.ts@@ -503,6 +503,7 @@ import type {InvitationCreateParams,LineItemCreateParams,LineItemUpdateParams,+ MaintenanceTaskRunCreateParams,MarketCreateParams,MarketUpdateParams,MediaCreateParams,@@ -684,6 +685,7 @@ import type {InvitationAcceptanceLink,LineItem,Locale,+ MaintenanceTaskRun,Market,Media,OauthAccessToken,@@ -745,6 +747,8 @@ import type {TranslationBatchEntry,TranslationCoverage,UpdateStatus,+ UpgradeStep,+ UpgradeStepsMeta,Variant,WebhookDelivery,WebhookEndpoint,@@ -4456,6 +4460,74 @@ export class AdminClient {this.request<void>('DELETE', `/exports/${id}`, options),}+ // ============================================+ // Maintenance tasks+ // ============================================++ /**+ * The upgrade manifest as an ordered checklist: what this release still+ * needs run, the operator notes each step carries, and how each last went.+ *+ * Read-only — running a step is starting the task it names through+ * `maintenanceTaskRuns.create()` with the step's own `task_name` and+ * `arguments`.+ */+ readonly upgradeSteps = {+ list: (options?: RequestOptions): Promise<{ data: UpgradeStep[]; meta: UpgradeStepsMeta }> =>+ this.request<{ data: UpgradeStep[]; meta: UpgradeStepsMeta }>(+ 'GET',+ '/upgrade_steps',+ options,+ ),+ }++ /**+ * Runs of a maintenance task — the progress to poll while one is working and+ * the audit trail afterwards (who ran what, with which arguments, and how it+ * ended).+ *+ * After `create()`, poll `get(id)` while `active` is true; show `tick_count`+ * against `tick_total`, or `tick_count` alone when the task could not count+ * its collection. `cancel` stops an active run for good. There is no delete:+ * a run records work that touched merchant data.+ */+ readonly maintenanceTaskRuns = {+ list: (+ params?: ListParams & Record<string, unknown>,+ options?: RequestOptions,+ ): Promise<PaginatedResponse<MaintenanceTaskRun>> =>+ this.request<PaginatedResponse<MaintenanceTaskRun>>('GET', '/maintenance_task_runs', {+ ...options,+ params: params ? transformListParams(params) : undefined,+ }),++ get: (+ id: string,+ params?: { expand?: string[] },+ options?: RequestOptions,+ ): Promise<MaintenanceTaskRun> =>+ this.request<MaintenanceTaskRun>('GET', `/maintenance_task_runs/${id}`, {+ ...options,+ params: getParams(params),+ }),++ create: (+ params: MaintenanceTaskRunCreateParams,+ options?: RequestOptions,+ ): Promise<MaintenanceTaskRun> =>+ this.request<MaintenanceTaskRun>('POST', '/maintenance_task_runs', {+ ...options,+ body: params,+ }),++ cancel: (id: string, options?: RequestOptions): Promise<MaintenanceTaskRun> =>+ this.request<MaintenanceTaskRun>(+ 'POST',+ `/maintenance_task_runs/${id}/cancellation`,+ options,+ ),+ }+// ============================================// Imports (CSV: products, customers, …)// ============================================diff --git a/packages/admin-sdk/src/types/generated/Enums.ts b/packages/admin-sdk/src/types/generated/Enums.tsindex 278a6c69df..076d0f6a10 100644--- a/packages/admin-sdk/src/types/generated/Enums.ts+++ b/packages/admin-sdk/src/types/generated/Enums.ts@@ -1,4 +1,4 @@-// Typelizer digest 771274d4f112bf2d088672d1632b082e+// Typelizer digest a291fde5935ffea3d03730e34c2f5e3a//// DO NOT MODIFY: This file was automatically generated by Typelizer.export type { ActorKind } from '@spree/sdk-core';@@ -37,6 +37,7 @@ export type { ImportRowStatus } from '@spree/sdk-core';export type { ImportStatus } from '@spree/sdk-core';export type { InvitationStatus } from '@spree/sdk-core';export type { LocaleCode } from '@spree/sdk-core';+export type { MaintenanceTaskRunStatus } from '@spree/sdk-core';export type { MatchPolicy } from '@spree/sdk-core';export type { MediaType } from '@spree/sdk-core';export type { OptionTypeKind } from '@spree/sdk-core';diff --git a/packages/admin-sdk/src/types/generated/MaintenanceTaskRun.ts b/packages/admin-sdk/src/types/generated/MaintenanceTaskRun.tsnew file mode 100644index 0000000000..6849bca6e7--- /dev/null+++ b/packages/admin-sdk/src/types/generated/MaintenanceTaskRun.ts@@ -0,0 +1,29 @@+// Typelizer digest de3af37a82edf3bf2aeaa5845b3b2d95+//+// DO NOT MODIFY: This file was automatically generated by Typelizer.+import type {AdminUser, MaintenanceTaskRunStatus} from '@/types'++interface MaintenanceTaskRun {+ id: string;+ status: MaintenanceTaskRunStatus;+ dry_run: boolean;+ initiated_via: string;+ tick_count: number;+ tick_total: number | null;+ error_class: string | null;+ error_message: string | null;+ started_at: string | null;+ ended_at: string | null;+ created_at: string;+ updated_at: string;+ task_name: string;+ duration: number | null;+ tallies: Record<string, number>;+ arguments: Record<string, unknown>;+ error_backtrace: string | null;+ active: boolean;+ admin_user_id: string | null;+ admin_user?: AdminUser;+}++export default MaintenanceTaskRun;diff --git a/packages/admin-sdk/src/types/generated/index.ts b/packages/admin-sdk/src/types/generated/index.tsindex 0eb044f5cd..b1790f4a1b 100644--- a/packages/admin-sdk/src/types/generated/index.ts+++ b/packages/admin-sdk/src/types/generated/index.ts@@ -1,7 +1,7 @@-// Typelizer digest 4a2758b46bf42f6eaba07f0103ccf757+// Typelizer digest e1f8ebdd912bdb148613bcc10ccf38e8//// DO NOT MODIFY: This file was automatically generated by Typelizer.-export type { ActorKind, AddressOwnerType, ApiKeyType, CaptureMethod, CatalogAssignableType, CatalogPriceSource, ClaimResolution, ClaimStatus, CollectionRuleMatchPolicy, CollectionSortOrder, CommissionKind, CompanyInvitationStatus, CompanyKind, ConsentSource, CountryCode, CurrencyCode, DataRequestKind, DataRequestStatus, DeliveryStatus, DeliveryZoneMemberType, DimensionUnit, DiscountKind, DocumentNumberFormat, EmailFont, EmailTemplateKind, ExchangeStatus, FeeKind, FileUploadVisibility, FulfillmentItemStatus, FulfillmentStatus, FulfillmentType, GiftCardStatus, ImportRowStatus, ImportStatus, InvitationStatus, LocaleCode, MatchPolicy, MediaType, OptionTypeKind, OrderFulfillmentStatus, OrderPaymentStatus, OrderStatus, PackageTypeKind, PaymentSourceType, PaymentStatus, PayoutScheduleInterval, PermissionKind, PickupStockPolicy, PriceListStatus, ProductStatus, ProductSubmissionStatus, ProviderFailurePolicy, PurchaseOrderStatus, PurchaseUnit, ReturnStatus, SellerPayoutStatus, SellerRequirementState, SellerRequirementSubmissionStatus, SellerStatus, SellerTransferKind, SellerTransferStatus, ShippingLabelFormat, ShippingLabelOwnerType, ShippingLabelSource, ShippingLabelStatus, StockLocationKind, StockMovementKind, StockReceiptLineType, StockReceiptReceivableType, StockReceiptRejectionReason, StockTransferStatus, StorefrontAccess, TaxExemptionCertificateStatus, TaxIdentifierSource, TaxIdentifierValidationStatus, TaxRemittance, TaxabilityReason, UnitSystem, WeightUnit } from './Enums'+export type { ActorKind, AddressOwnerType, ApiKeyType, CaptureMethod, CatalogAssignableType, CatalogPriceSource, ClaimResolution, ClaimStatus, CollectionRuleMatchPolicy, CollectionSortOrder, CommissionKind, CompanyInvitationStatus, CompanyKind, ConsentSource, CountryCode, CurrencyCode, DataRequestKind, DataRequestStatus, DeliveryStatus, DeliveryZoneMemberType, DimensionUnit, DiscountKind, DocumentNumberFormat, EmailFont, EmailTemplateKind, ExchangeStatus, FeeKind, FileUploadVisibility, FulfillmentItemStatus, FulfillmentStatus, FulfillmentType, GiftCardStatus, ImportRowStatus, ImportStatus, InvitationStatus, LocaleCode, MaintenanceTaskRunStatus, MatchPolicy, MediaType, OptionTypeKind, OrderFulfillmentStatus, OrderPaymentStatus, OrderStatus, PackageTypeKind, PaymentSourceType, PaymentStatus, PayoutScheduleInterval, PermissionKind, PickupStockPolicy, PriceListStatus, ProductStatus, ProductSubmissionStatus, ProviderFailurePolicy, PurchaseOrderStatus, PurchaseUnit, ReturnStatus, SellerPayoutStatus, SellerRequirementState, SellerRequirementSubmissionStatus, SellerStatus, SellerTransferKind, SellerTransferStatus, ShippingLabelFormat, ShippingLabelOwnerType, ShippingLabelSource, ShippingLabelStatus, StockLocationKind, StockMovementKind, StockReceiptLineType, StockReceiptReceivableType, StockReceiptRejectionReason, StockTransferStatus, StorefrontAccess, TaxExemptionCertificateStatus, TaxIdentifierSource, TaxIdentifierValidationStatus, TaxRemittance, TaxabilityReason, UnitSystem, WeightUnit } from './Enums'export type { default as Actor } from './Actor'export type { default as AddressOwner } from './AddressOwner'export type { default as Address } from './Address'@@ -78,6 +78,7 @@ export type { default as InvitationAcceptanceLink } from './InvitationAcceptanceexport type { default as Invitation } from './Invitation'export type { default as LineItem } from './LineItem'export type { default as Locale } from './Locale'+export type { default as MaintenanceTaskRun } from './MaintenanceTaskRun'export type { default as Market } from './Market'export type { default as Media } from './Media'export type { default as MembershipProduct } from './MembershipProduct'diff --git a/packages/admin-sdk/src/types/index.ts b/packages/admin-sdk/src/types/index.tsindex 10cfb036ca..4f33c08f61 100644--- a/packages/admin-sdk/src/types/index.ts+++ b/packages/admin-sdk/src/types/index.ts@@ -130,6 +130,7 @@ export type { default as Invitation } from './generated/Invitation'export type { default as InvitationAcceptanceLink } from './generated/InvitationAcceptanceLink'export type { default as LineItem } from './generated/LineItem'export type { default as Locale } from './generated/Locale'+export type { default as MaintenanceTaskRun } from './generated/MaintenanceTaskRun'export type { default as Market } from './generated/Market'export type { default as Media } from './generated/Media'export type { default as OauthAccessToken } from './generated/OauthAccessToken'@@ -219,3 +220,4 @@ export type {TranslationCoverageRow,TranslationsUpsertParams,} from './translations'+export type { UpgradeStep, UpgradeStepsMeta } from './upgrade-step'diff --git a/packages/admin-sdk/src/types/params/MaintenanceTaskRunCreateParams.ts b/packages/admin-sdk/src/types/params/MaintenanceTaskRunCreateParams.tsnew file mode 100644index 0000000000..cfce9bb9cf--- /dev/null+++ b/packages/admin-sdk/src/types/params/MaintenanceTaskRunCreateParams.ts@@ -0,0 +1,16 @@+// This file is auto-generated from the request schemas in docs/api-reference by `pnpm generate:params`. Do not edit directly.++export type MaintenanceTaskRunCreateParams = {+ /** The task to run, as `task_name` from `GET /upgrade_steps`. */+ task_name: string+ /**+ * Values for the task's declared parameters, keyed by parameter name. A key the task does not+ * declare is rejected.+ */+ arguments?: Record<string, unknown>+ /**+ * Report what would change without writing. Ignored by tasks that do not support a dry run, which+ * run for real.+ */+ dry_run?: boolean+}diff --git a/packages/admin-sdk/src/types/params/index.ts b/packages/admin-sdk/src/types/params/index.tsindex 5962dd2c28..5ab756e8bb 100644--- a/packages/admin-sdk/src/types/params/index.ts+++ b/packages/admin-sdk/src/types/params/index.ts@@ -101,6 +101,7 @@ export type { InvitationAcceptParams } from './InvitationAcceptParams'export type { InvitationCreateParams } from './InvitationCreateParams'export type { LineItemCreateParams } from './LineItemCreateParams'export type { LineItemUpdateParams } from './LineItemUpdateParams'+export type { MaintenanceTaskRunCreateParams } from './MaintenanceTaskRunCreateParams'export type { MarketCreateParams } from './MarketCreateParams'export type { MarketUpdateParams } from './MarketUpdateParams'export type { MeUpdateParams } from './MeUpdateParams'diff --git a/packages/admin-sdk/src/types/upgrade-step.ts b/packages/admin-sdk/src/types/upgrade-step.tsnew file mode 100644index 0000000000..e694f56520--- /dev/null+++ b/packages/admin-sdk/src/types/upgrade-step.ts@@ -0,0 +1,39 @@+import type { MaintenanceTaskRun } from './generated'++/**+ * One step of an upgrade manifest — the data work a release requires, in the+ * order it has to run (docs/plans/6.0-maintenance-tasks.md).+ *+ * Hand-written: the endpoint describes manifest entries rather than a+ * serialized record, so there is no serializer to derive it from.+ */+export interface UpgradeStep {+ /** Manifest step id, stable across releases and used with `STEP=` on the CLI. */+ id: string+ /**+ * True for a release this installation has already been through. Shown as+ * history and never runnable — re-running a completed conversion is how an+ * upgrade does damage.+ */+ superseded: boolean+ name: string+ /** Operator guidance from the manifest — ordering constraints, knobs, caveats. */+ notes: string | null+ /** Release boundary this step belongs to. */+ from: string+ to: string+ docs: string | null+ /** The maintenance task to start for this step. */+ task_name: string+ /**+ * Arguments to start it with. Empty for a step that is its own task; carries+ * `step_id` for a step that names a rake task, since those share one runner.+ */+ arguments: Record<string, unknown>+ last_run: MaintenanceTaskRun | null+}++export interface UpgradeStepsMeta {+ /** The boundary whose steps are already done, and where the list starts. */+ completed_version: string | null+}diff --git a/packages/admin-sdk/src/zod/generated/MaintenanceTaskRun.ts b/packages/admin-sdk/src/zod/generated/MaintenanceTaskRun.tsnew file mode 100644index 0000000000..1f149509a1--- /dev/null+++ b/packages/admin-sdk/src/zod/generated/MaintenanceTaskRun.ts@@ -0,0 +1,28 @@+// This file is auto-generated. Do not edit directly.+import { z } from 'zod';+import { AdminUserSchema } from './AdminUser';++export const MaintenanceTaskRunSchema = z.object({+ id: z.string(),+ status: z.string(),+ dry_run: z.boolean(),+ initiated_via: z.string(),+ tick_count: z.number(),+ tick_total: z.number().nullable(),+ error_class: z.string().nullable(),+ error_message: z.string().nullable(),+ started_at: z.string().nullable(),+ ended_at: z.string().nullable(),+ created_at: z.string(),+ updated_at: z.string(),+ task_name: z.string(),+ duration: z.number().nullable(),+ tallies: z.record(z.string(), z.number()),+ arguments: z.record(z.string(), z.unknown()),+ error_backtrace: z.string().nullable(),+ active: z.boolean(),+ admin_user_id: z.string().nullable(),+ admin_user: AdminUserSchema.optional(),+});++export type MaintenanceTaskRun = z.infer<typeof MaintenanceTaskRunSchema>;diff --git a/packages/admin-sdk/src/zod/generated/index.ts b/packages/admin-sdk/src/zod/generated/index.tsindex 5f43ff2bc8..3a2efeedaa 100644--- a/packages/admin-sdk/src/zod/generated/index.ts+++ b/packages/admin-sdk/src/zod/generated/index.ts@@ -75,6 +75,7 @@ export { InvitationSchema, type Invitation } from './Invitation';export { InvitationAcceptanceLinkSchema, type InvitationAcceptanceLink } from './InvitationAcceptanceLink';export { LineItemSchema, type LineItem } from './LineItem';export { LocaleSchema, type Locale } from './Locale';+export { MaintenanceTaskRunSchema, type MaintenanceTaskRun } from './MaintenanceTaskRun';export { MarketSchema, type Market } from './Market';export { MediaSchema, type Media } from './Media';export { MembershipProductSchema, type MembershipProduct } from './MembershipProduct';diff --git a/packages/core/src/enums.generated.ts b/packages/core/src/enums.generated.tsindex a1e39475df..40f4574d46 100644--- a/packages/core/src/enums.generated.ts+++ b/packages/core/src/enums.generated.ts@@ -204,6 +204,20 @@ export type ImportStatus = (typeof IMPORT_STATUSES)[number] | (string & {})export const INVITATION_STATUSES = ['pending', 'accepted'] as constexport type InvitationStatus = (typeof INVITATION_STATUSES)[number] | (string & {})+/** The built-in values of `MaintenanceTaskRunStatus`. Extensions may add more. */+export const MAINTENANCE_TASK_RUN_STATUSES = [+ 'enqueued',+ 'running',+ 'interrupted',+ 'cancelling',+ 'cancelled',+ 'succeeded',+ 'errored',+] as const+export type MaintenanceTaskRunStatus =+ | (typeof MAINTENANCE_TASK_RUN_STATUSES)[number]+ | (string & {})+/** Every value of `MatchPolicy`. */export const MATCH_POLICIES = ['all', 'any'] as constexport type MatchPolicy = (typeof MATCH_POLICIES)[number]@@ -530,6 +544,7 @@ export type BuiltInStatus =| (typeof IMPORT_ROW_STATUSES)[number]| (typeof IMPORT_STATUSES)[number]| (typeof INVITATION_STATUSES)[number]+ | (typeof MAINTENANCE_TASK_RUN_STATUSES)[number]| (typeof ORDER_FULFILLMENT_STATUSES)[number]| (typeof ORDER_PAYMENT_STATUSES)[number]| (typeof ORDER_STATUSES)[number]diff --git a/packages/dashboard-core/src/lib/permissions.ts b/packages/dashboard-core/src/lib/permissions.tsindex a37fbcc8d0..551147f10a 100644--- a/packages/dashboard-core/src/lib/permissions.ts+++ b/packages/dashboard-core/src/lib/permissions.ts@@ -86,6 +86,7 @@ export const Subject = {CommissionLine: 'commission_line',SellerPayout: 'seller_payout',SellerTransfer: 'seller_transfer',+ MaintenanceTaskRun: 'maintenance_task_run',} as constexport type SubjectName = (typeof Subject)[keyof typeof Subject] | stringdiff --git a/packages/dashboard-starter/src/routeTree.gen.ts b/packages/dashboard-starter/src/routeTree.gen.tsindex f226d49b88..51fc9ee663 100644--- a/packages/dashboard-starter/src/routeTree.gen.ts+++ b/packages/dashboard-starter/src/routeTree.gen.ts@@ -66,6 +66,7 @@ import { Route as SettingsChannelsRouteImport } from './../../dashboard/src/routimport { Route as SettingsCommissionRatesRouteImport } from './../../dashboard/src/routes/_authenticated/$storeId/settings/commission-rates'import { Route as SettingsCustomFieldDefinitionsRouteImport } from './../../dashboard/src/routes/_authenticated/$storeId/settings/custom-field-definitions'import { Route as SettingsIntegrationsRouteImport } from './../../dashboard/src/routes/_authenticated/$storeId/settings/integrations'+import { Route as SettingsMaintenanceTasksRouteImport } from './../../dashboard/src/routes/_authenticated/$storeId/settings/maintenance-tasks'import { Route as SettingsMarketplaceRouteImport } from './../../dashboard/src/routes/_authenticated/$storeId/settings/marketplace'import { Route as SettingsMarketsRouteImport } from './../../dashboard/src/routes/_authenticated/$storeId/settings/markets'import { Route as SettingsOauthClientsRouteImport } from './../../dashboard/src/routes/_authenticated/$storeId/settings/oauth-clients'@@ -403,6 +404,12 @@ const SettingsIntegrationsRoute = SettingsIntegrationsRouteImport.update({path: '/integrations',getParentRoute: () => SettingsRoute,} as any)+const SettingsMaintenanceTasksRoute =+ SettingsMaintenanceTasksRouteImport.update({+ id: '/maintenance-tasks',+ path: '/maintenance-tasks',+ getParentRoute: () => SettingsRoute,+ } as any)const SettingsMarketplaceRoute = SettingsMarketplaceRouteImport.update({id: '/marketplace',path: '/marketplace',@@ -717,6 +724,7 @@ export interface FileRoutesByFullPath {'/$storeId/settings/commission-rates': typeof SettingsCommissionRatesRoute'/$storeId/settings/custom-field-definitions': typeof SettingsCustomFieldDefinitionsRoute'/$storeId/settings/integrations': typeof SettingsIntegrationsRoute+ '/$storeId/settings/maintenance-tasks': typeof SettingsMaintenanceTasksRoute'/$storeId/settings/marketplace': typeof SettingsMarketplaceRoute'/$storeId/settings/markets': typeof SettingsMarketsRoute'/$storeId/settings/oauth-clients': typeof SettingsOauthClientsRoute@@ -823,6 +831,7 @@ export interface FileRoutesByTo {'/$storeId/settings/commission-rates': typeof SettingsCommissionRatesRoute'/$storeId/settings/custom-field-definitions': typeof SettingsCustomFieldDefinitionsRoute'/$storeId/settings/integrations': typeof SettingsIntegrationsRoute+ '/$storeId/settings/maintenance-tasks': typeof SettingsMaintenanceTasksRoute'/$storeId/settings/marketplace': typeof SettingsMarketplaceRoute'/$storeId/settings/markets': typeof SettingsMarketsRoute'/$storeId/settings/oauth-clients': typeof SettingsOauthClientsRoute@@ -932,6 +941,7 @@ export interface FileRoutesById {'/_authenticated/$storeId/settings/commission-rates': typeof SettingsCommissionRatesRoute'/_authenticated/$storeId/settings/custom-field-definitions': typeof SettingsCustomFieldDefinitionsRoute'/_authenticated/$storeId/settings/integrations': typeof SettingsIntegrationsRoute+ '/_authenticated/$storeId/settings/maintenance-tasks': typeof SettingsMaintenanceTasksRoute'/_authenticated/$storeId/settings/marketplace': typeof SettingsMarketplaceRoute'/_authenticated/$storeId/settings/markets': typeof SettingsMarketsRoute'/_authenticated/$storeId/settings/oauth-clients': typeof SettingsOauthClientsRoute@@ -1042,6 +1052,7 @@ export interface FileRouteTypes {| '/$storeId/settings/commission-rates'| '/$storeId/settings/custom-field-definitions'| '/$storeId/settings/integrations'+ | '/$storeId/settings/maintenance-tasks'| '/$storeId/settings/marketplace'| '/$storeId/settings/markets'| '/$storeId/settings/oauth-clients'@@ -1148,6 +1159,7 @@ export interface FileRouteTypes {| '/$storeId/settings/commission-rates'| '/$storeId/settings/custom-field-definitions'| '/$storeId/settings/integrations'+ | '/$storeId/settings/maintenance-tasks'| '/$storeId/settings/marketplace'| '/$storeId/settings/markets'| '/$storeId/settings/oauth-clients'@@ -1256,6 +1268,7 @@ export interface FileRouteTypes {| '/_authenticated/$storeId/settings/commission-rates'| '/_authenticated/$storeId/settings/custom-field-definitions'| '/_authenticated/$storeId/settings/integrations'+ | '/_authenticated/$storeId/settings/maintenance-tasks'| '/_authenticated/$storeId/settings/marketplace'| '/_authenticated/$storeId/settings/markets'| '/_authenticated/$storeId/settings/oauth-clients'@@ -1729,6 +1742,13 @@ declare module '@tanstack/react-router' {preLoaderRoute: typeof SettingsIntegrationsRouteImportparentRoute: typeof SettingsRoute}+ '/_authenticated/$storeId/settings/maintenance-tasks': {+ id: '/_authenticated/$storeId/settings/maintenance-tasks'+ path: '/maintenance-tasks'+ fullPath: '/$storeId/settings/maintenance-tasks'+ preLoaderRoute: typeof SettingsMaintenanceTasksRouteImport+ parentRoute: typeof SettingsRoute+ }'/_authenticated/$storeId/settings/marketplace': {id: '/_authenticated/$storeId/settings/marketplace'path: '/marketplace'@@ -2108,6 +2128,7 @@ interface SettingsRouteChildren {SettingsCommissionRatesRoute: typeof SettingsCommissionRatesRouteSettingsCustomFieldDefinitionsRoute: typeof SettingsCustomFieldDefinitionsRouteSettingsIntegrationsRoute: typeof SettingsIntegrationsRoute+ SettingsMaintenanceTasksRoute: typeof SettingsMaintenanceTasksRouteSettingsMarketplaceRoute: typeof SettingsMarketplaceRouteSettingsMarketsRoute: typeof SettingsMarketsRouteSettingsOauthClientsRoute: typeof SettingsOauthClientsRoute@@ -2144,6 +2165,7 @@ const SettingsRouteChildren: SettingsRouteChildren = {SettingsCommissionRatesRoute: SettingsCommissionRatesRoute,SettingsCustomFieldDefinitionsRoute: SettingsCustomFieldDefinitionsRoute,SettingsIntegrationsRoute: SettingsIntegrationsRoute,+ SettingsMaintenanceTasksRoute: SettingsMaintenanceTasksRoute,SettingsMarketplaceRoute: SettingsMarketplaceRoute,SettingsMarketsRoute: SettingsMarketsRoute,SettingsOauthClientsRoute: SettingsOauthClientsRoute,diff --git a/packages/dashboard-ui/src/spree/icons.ts b/packages/dashboard-ui/src/spree/icons.tsindex f6caea8214..a32e727915 100644--- a/packages/dashboard-ui/src/spree/icons.ts+++ b/packages/dashboard-ui/src/spree/icons.ts@@ -169,6 +169,7 @@ export {UsersRoundIcon,WarehouseIcon,WebhookIcon,+ WrenchIcon,X,XCircleIcon,XIcon,diff --git a/packages/dashboard-ui/src/ui/badge.tsx b/packages/dashboard-ui/src/ui/badge.tsxindex c31261d3b9..f2c4a8df02 100644--- a/packages/dashboard-ui/src/ui/badge.tsx+++ b/packages/dashboard-ui/src/ui/badge.tsx@@ -188,6 +188,15 @@ const statusToneMap: Record<string, StatusTone> = {// same green/red the rest of the app uses saves them parsing the word.true: 'success',false: 'destructive',+ // Maintenance task runs: amber while a worker holds or is about to release+ // the run, blue while it waits for one.+ enqueued: 'info',+ running: 'warning',+ interrupted: 'info',+ cancelling: 'warning',+ cancelled: 'destructive',+ succeeded: 'success',+ errored: 'destructive',} satisfies Record<BuiltInStatus, StatusTone> & Record<string, StatusTone>// Dot fills, by tone. These read the same `--status-*` ramps the tinted Badgediff --git a/packages/dashboard-ui/src/ui/tabs.tsx b/packages/dashboard-ui/src/ui/tabs.tsxindex f422abd305..fe209eed01 100644--- a/packages/dashboard-ui/src/ui/tabs.tsx+++ b/packages/dashboard-ui/src/ui/tabs.tsx@@ -41,7 +41,17 @@ function TabsList({)}-function TabsTrigger({ className, ...props }: React.ComponentProps<typeof TabsPrimitive.Tab>) {+/**+ * A tab. Pass `count` to append a tally — the number of steps outstanding, or+ * of records in the panel — which is what tells an operator whether a tab is+ * worth opening before they open it.+ */+function TabsTrigger({+ className,+ children,+ count,+ ...props+}: React.ComponentProps<typeof TabsPrimitive.Tab> & { count?: number }) {return (<TabsPrimitive.Tabdata-slot="tabs-trigger"@@ -67,7 +77,12 @@ function TabsTrigger({ className, ...props }: React.ComponentProps<typeof TabsPrclassName,)}{...props}- />+ >+ {children}+ {count !== undefined && (+ <span className="rounded-full bg-muted px-1.5 py-0.5 text-xs tabular-nums">{count}</span>+ )}+ </TabsPrimitive.Tab>)}diff --git a/packages/dashboard/src/components/spree/maintenance-tasks/run-detail-sheet.tsx b/packages/dashboard/src/components/spree/maintenance-tasks/run-detail-sheet.tsxnew file mode 100644index 0000000000..8142c7eab7--- /dev/null+++ b/packages/dashboard/src/components/spree/maintenance-tasks/run-detail-sheet.tsx@@ -0,0 +1,214 @@+import { Can, Subject } from '@spree/dashboard-core'+import {+ Badge,+ Button,+ Progress,+ ProgressLabel,+ ProgressValue,+ RelativeTime,+ Sheet,+ SheetContent,+ SheetDescription,+ SheetFooter,+ SheetHeader,+ SheetTitle,+ StatusBadge,+ useConfirm,+} from '@spree/dashboard-ui'+import { useTranslation } from 'react-i18next'+import {+ useCancelMaintenanceTaskRun,+ useMaintenanceTaskRun,+} from '../../../hooks/use-maintenance-tasks'+import { humanizeName, runProgress, runTitle } from '../../../lib/maintenance-tasks'++export function RunDetailSheet({+ runId,+ open,+ onOpenChange,+}: {+ runId: string | undefined+ open: boolean+ onOpenChange: (open: boolean) => void+}) {+ const { t } = useTranslation()+ const confirm = useConfirm()++ const { data: run, isLoading } = useMaintenanceTaskRun(open ? runId : undefined)+ const cancelMutation = useCancelMaintenanceTaskRun()++ async function handleCancel() {+ if (!run) return++ const confirmed = await confirm({+ title: t('admin.maintenance_tasks.cancel_confirm.title'),+ message: t('admin.maintenance_tasks.cancel_confirm.message'),+ variant: 'destructive',+ confirmLabel: t('admin.maintenance_tasks.actions.cancel_run'),+ })+ if (!confirmed) return++ await cancelMutation.mutateAsync(run.id).catch(() => undefined)+ }++ return (+ <Sheet open={open} onOpenChange={onOpenChange}>+ <SheetContent>+ <SheetHeader>+ <SheetTitle>{run ? runTitle(run) : t('admin.maintenance_tasks.run.loading')}</SheetTitle>+ <SheetDescription>+ {run && t(`admin.maintenance_tasks.initiated_via.${run.initiated_via}`)}+ </SheetDescription>+ </SheetHeader>++ <div className="flex min-h-0 flex-1 flex-col">+ <div className="flex flex-1 flex-col gap-6 overflow-y-auto p-4">+ {isLoading && !run && (+ <p className="text-muted-foreground text-sm">+ {t('admin.maintenance_tasks.run.loading')}+ </p>+ )}++ {run && (+ <>+ <div className="flex flex-wrap items-center gap-2">+ <StatusBadge+ status={run.status}+ label={t(`admin.maintenance_tasks.status.${run.status}`)}+ />+ {run.dry_run && (+ <Badge variant="secondary">{t('admin.maintenance_tasks.dry_run_badge')}</Badge>+ )}+ </div>++ <Progress {...runProgress(run)}>+ <ProgressLabel>{t('admin.maintenance_tasks.run.progress_label')}</ProgressLabel>+ <ProgressValue>+ {() =>+ run.tick_total == null+ ? t('admin.maintenance_tasks.run.processed_count', {+ count: run.tick_count,+ })+ : `${run.tick_count} / ${run.tick_total}`+ }+ </ProgressValue>+ </Progress>++ <DetailRows run={run} />++ {Object.keys(run.tallies).length > 0 && (+ <section className="flex flex-col gap-2">+ <h3 className="font-medium text-sm">+ {t('admin.maintenance_tasks.run.results')}+ </h3>+ <dl className="flex flex-col gap-1 text-sm">+ {Object.entries(run.tallies).map(([key, count]) => (+ <div key={key} className="flex justify-between gap-4">+ <dt className="text-muted-foreground">{humanizeName(key)}</dt>+ <dd className="tabular-nums">{count}</dd>+ </div>+ ))}+ </dl>+ </section>+ )}++ {run.error_message && (+ <section className="flex flex-col gap-2">+ <h3 className="font-medium text-destructive text-sm">+ {run.error_class ?? t('admin.maintenance_tasks.run.error')}+ </h3>+ <p className="text-sm">{run.error_message}</p>+ {run.error_backtrace && (+ <details className="text-muted-foreground text-xs">+ <summary className="cursor-pointer">+ {t('admin.maintenance_tasks.run.show_backtrace')}+ </summary>+ <pre className="mt-2 overflow-x-auto whitespace-pre-wrap">+ {run.error_backtrace}+ </pre>+ </details>+ )}+ </section>+ )}++ {Object.keys(run.arguments).length > 0 && (+ <section className="flex flex-col gap-2">+ <h3 className="font-medium text-sm">+ {t('admin.maintenance_tasks.run.arguments')}+ </h3>+ <dl className="flex flex-col gap-1 text-sm">+ {Object.entries(run.arguments).map(([key, value]) => (+ <div key={key} className="flex justify-between gap-4">+ <dt className="text-muted-foreground">{key}</dt>+ <dd className="break-all">{String(value)}</dd>+ </div>+ ))}+ </dl>+ </section>+ )}+ </>+ )}+ </div>+ </div>++ {run && (+ <SheetFooter>+ <Can I="update" a={Subject.MaintenanceTaskRun}>+ {run.active && (+ <Button+ type="button"+ variant="destructive"+ size="sm"+ onClick={handleCancel}+ disabled={cancelMutation.isPending}+ >+ {t('admin.maintenance_tasks.actions.cancel_run')}+ </Button>+ )}+ </Can>+ </SheetFooter>+ )}+ </SheetContent>+ </Sheet>+ )+}++function DetailRows({+ run,+}: {+ run: NonNullable<ReturnType<typeof useMaintenanceTaskRun>['data']>+}) {+ const { t } = useTranslation()++ return (+ <dl className="flex flex-col gap-1 text-sm">+ {run.admin_user && (+ <Row label={t('admin.maintenance_tasks.run.initiated_by')}>{run.admin_user.email}</Row>+ )}+ {run.started_at && (+ <Row label={t('admin.maintenance_tasks.run.started')}>+ <RelativeTime iso={run.started_at} />+ </Row>+ )}+ {run.ended_at && (+ <Row label={t('admin.maintenance_tasks.run.ended')}>+ <RelativeTime iso={run.ended_at} />+ </Row>+ )}+ {run.duration != null && (+ <Row label={t('admin.maintenance_tasks.run.duration')}>+ {t('admin.maintenance_tasks.run.seconds', { count: Math.round(run.duration) })}+ </Row>+ )}+ </dl>+ )+}++function Row({ label, children }: { label: string; children: React.ReactNode }) {+ return (+ <div className="flex justify-between gap-4">+ <dt className="text-muted-foreground">{label}</dt>+ <dd>{children}</dd>+ </div>+ )+}diff --git a/packages/dashboard/src/components/spree/maintenance-tasks/upgrade-panel.tsx b/packages/dashboard/src/components/spree/maintenance-tasks/upgrade-panel.tsxnew file mode 100644index 0000000000..dc2936cee6--- /dev/null+++ b/packages/dashboard/src/components/spree/maintenance-tasks/upgrade-panel.tsx@@ -0,0 +1,341 @@+import type { UpgradeStep } from '@spree/admin-sdk'+import { Can, Subject } from '@spree/dashboard-core'+import {+ Button,+ Card,+ CardContent,+ CardDescription,+ CardHeader,+ CardTitle,+ Empty,+ EmptyDescription,+ EmptyHeader,+ EmptyMedia,+ EmptyTitle,+ Progress,+ StatusBadge,+ useConfirm,+} from '@spree/dashboard-ui'+import {+ CheckIcon,+ ChevronRightIcon,+ CircleCheckIcon,+ ExternalLinkIcon,+ PlayIcon,+} from 'lucide-react'+import { useState } from 'react'+import { useTranslation } from 'react-i18next'+import { useStartMaintenanceTask, useUpgradeSteps } from '../../../hooks/use-maintenance-tasks'++interface Boundary {+ from: string+ to: string+ steps: UpgradeStep[]+ /** A release this installation has already been through. */+ superseded: boolean+ docs: string | null+}++/**+ * The upgrade manifests, one card per release.+ *+ * The release being upgraded to comes first, open, with its steps runnable.+ * Releases already crossed follow as collapsed history — a store should be+ * able to see which upgrades it has been through, but re-running a conversion+ * it already applied is how an upgrade does damage, so those are never+ * runnable.+ *+ * A store installed fresh at this release has no historical data to convert,+ * so it is told where the steps of a later upgrade will appear instead.+ */+export function UpgradePanel({ onOpenRun }: { onOpenRun: (runId: string) => void }) {+ const { data, isLoading } = useUpgradeSteps()++ const { t } = useTranslation()++ const allSteps = data?.data ?? []+ if (isLoading) return null++ if (allSteps.length === 0) {+ return (+ <Empty>+ <EmptyHeader>+ <EmptyMedia variant="icon">+ <CircleCheckIcon />+ </EmptyMedia>+ <EmptyTitle>{t('admin.maintenance_tasks.upgrade.up_to_date_title')}</EmptyTitle>+ <EmptyDescription>+ {t('admin.maintenance_tasks.upgrade.up_to_date_description')}+ </EmptyDescription>+ </EmptyHeader>+ </Empty>+ )+ }++ const boundaries = groupByBoundary(allSteps)+ const current = boundaries.filter((boundary) => !boundary.superseded)+ // Newest first: the most recently completed upgrade is the one an operator+ // is most likely to be checking.+ const history = boundaries.filter((boundary) => boundary.superseded).reverse()++ return (+ <div className="flex flex-col gap-4">+ {current.map((boundary) => (+ <BoundaryCard+ key={`${boundary.from}-${boundary.to}`}+ boundary={boundary}+ onOpenRun={onOpenRun}+ />+ ))}++ {history.map((boundary) => (+ <BoundaryCard+ key={`${boundary.from}-${boundary.to}`}+ boundary={boundary}+ onOpenRun={onOpenRun}+ />+ ))}+ </div>+ )+}++function BoundaryCard({+ boundary,+ onOpenRun,+}: {+ boundary: Boundary+ onOpenRun: (runId: string) => void+}) {+ const { t } = useTranslation()+ const confirm = useConfirm()+ const startMutation = useStartMaintenanceTask()++ // History starts collapsed — it is reference, not work.+ const [open, setOpen] = useState(!boundary.superseded)+ const [expandedStep, setExpandedStep] = useState<string | null>(null)++ const { steps, superseded } = boundary+ const done = superseded+ ? steps.length+ : steps.filter((step) => step.last_run?.status === 'succeeded').length+ const busy = steps.some((step) => step.last_run?.active)+ const nextStep = steps.find((step) => step.last_run?.status !== 'succeeded')++ async function runStep(step: UpgradeStep) {+ const confirmed = await confirm({+ title: t('admin.maintenance_tasks.upgrade.confirm.title', { name: step.name }),+ message: t('admin.maintenance_tasks.upgrade.confirm.message'),+ confirmLabel: t('admin.maintenance_tasks.upgrade.run_step'),+ })+ if (!confirmed) return++ const run = await startMutation+ .mutateAsync({ task_name: step.task_name, arguments: step.arguments })+ .catch(() => undefined)++ if (run) onOpenRun(run.id)+ }++ return (+ <Card className={superseded ? 'border-dashed' : undefined}>+ <CardHeader>+ <div className="flex flex-wrap items-start justify-between gap-3">+ <div className="flex flex-col gap-1">+ <CardTitle className={superseded ? 'text-base text-muted-foreground' : 'text-base'}>+ {superseded+ ? t('admin.maintenance_tasks.upgrade.boundary', {+ from: boundary.from,+ to: boundary.to,+ })+ : t('admin.maintenance_tasks.upgrade.title', { version: boundary.to })}+ </CardTitle>+ <CardDescription>+ {superseded+ ? t('admin.maintenance_tasks.upgrade.history_description')+ : t('admin.maintenance_tasks.upgrade.description')}+ </CardDescription>+ </div>++ <div className="flex items-center gap-3">+ <span className="text-muted-foreground text-sm tabular-nums">+ {superseded+ ? t('admin.maintenance_tasks.upgrade.already_completed')+ : t('admin.maintenance_tasks.upgrade.progress', { done, total: steps.length })}+ </span>++ {superseded ? (+ <Button type="button" size="sm" variant="ghost" onClick={() => setOpen(!open)}>+ {open+ ? t('admin.maintenance_tasks.upgrade.hide_steps')+ : t('admin.maintenance_tasks.upgrade.show_steps')}+ </Button>+ ) : (+ // Runs the next unfinished step rather than the whole manifest:+ // steps have ordering constraints, and a failure part way needs+ // the operator to look before the walk carries on.+ <Can I="update" a={Subject.MaintenanceTaskRun}>+ {nextStep && (+ <Button+ type="button"+ size="sm"+ onClick={() => runStep(nextStep)}+ disabled={busy || startMutation.isPending}+ >+ <PlayIcon className="size-4" />+ {t('admin.maintenance_tasks.upgrade.run_next')}+ </Button>+ )}+ </Can>+ )}+ </div>+ </div>++ {!superseded && <Progress value={done} max={steps.length} className="mt-2" />}+ </CardHeader>++ {open && (+ <CardContent className="flex flex-col gap-1">+ {steps.map((step, index) => (+ <StepRow+ key={`${step.to}-${step.id}`}+ step={step}+ position={index + 1}+ superseded={superseded}+ expanded={expandedStep === step.id}+ onToggle={() => setExpandedStep(expandedStep === step.id ? null : step.id)}+ onRun={() => runStep(step)}+ onOpenRun={onOpenRun}+ disabled={busy || startMutation.isPending}+ />+ ))}++ {boundary.docs && (+ <a+ href={boundary.docs}+ target="_blank"+ rel="noreferrer"+ className="mt-2 flex items-center gap-1 text-muted-foreground text-xs hover:underline"+ >+ <ExternalLinkIcon className="size-3" />+ {t('admin.maintenance_tasks.upgrade.read_guide')}+ </a>+ )}+ </CardContent>+ )}+ </Card>+ )+}++function StepRow({+ step,+ position,+ superseded,+ expanded,+ onToggle,+ onRun,+ onOpenRun,+ disabled,+}: {+ step: UpgradeStep+ position: number+ superseded: boolean+ expanded: boolean+ onToggle: () => void+ onRun: () => void+ onOpenRun: (runId: string) => void+ disabled: boolean+}) {+ const { t } = useTranslation()+ const run = step.last_run+ // A superseded step belongs to a release this store has already been+ // through, so it counts as done whether or not a run row exists for it —+ // most were run long before runs were recorded.+ const succeeded = superseded || run?.status === 'succeeded'+ const active = run?.active ?? false++ return (+ <div className="rounded-md border border-transparent hover:border-border">+ <div className="flex items-center gap-3 p-2">+ <span+ className={+ succeeded+ ? 'flex size-5 shrink-0 items-center justify-center rounded-full bg-green-500/15 text-green-600'+ : 'flex size-5 shrink-0 items-center justify-center rounded-full bg-muted text-muted-foreground text-xs tabular-nums'+ }+ >+ {succeeded ? <CheckIcon className="size-3" /> : position}+ </span>++ <button+ type="button"+ className="flex flex-1 items-center gap-2 text-left"+ onClick={onToggle}+ >+ <ChevronRightIcon+ className={+ expanded ? 'size-3 rotate-90 text-muted-foreground' : 'size-3 text-muted-foreground'+ }+ />+ <span className={succeeded ? 'text-muted-foreground text-sm' : 'text-sm'}>+ {step.name}+ </span>+ </button>++ {run && (+ <button type="button" onClick={() => onOpenRun(run.id)}>+ <StatusBadge+ status={run.status}+ label={t(`admin.maintenance_tasks.status.${run.status}`)}+ />+ </button>+ )}++ {!superseded && (+ <Can I="update" a={Subject.MaintenanceTaskRun}>+ <Button+ type="button"+ size="sm"+ variant="ghost"+ onClick={onRun}+ disabled={disabled || active}+ >+ {succeeded+ ? t('admin.maintenance_tasks.upgrade.run_again')+ : t('admin.maintenance_tasks.upgrade.run_step')}+ </Button>+ </Can>+ )}+ </div>++ {/* The manifest's own guidance: ordering constraints and caveats that+ decide whether a step is safe to run right now. */}+ {expanded && step.notes && (+ <p className="whitespace-pre-line px-10 pb-3 text-muted-foreground text-xs">{step.notes}</p>+ )}+ </div>+ )+}++function groupByBoundary(steps: UpgradeStep[]): Boundary[] {+ const boundaries: Boundary[] = []++ for (const step of steps) {+ const last = boundaries[boundaries.length - 1]++ if (last && last.from === step.from && last.to === step.to) {+ last.steps.push(step)+ // A boundary is history only when every one of its steps is.+ last.superseded = last.superseded && step.superseded+ } else {+ boundaries.push({+ from: step.from,+ to: step.to,+ steps: [step],+ superseded: step.superseded,+ docs: step.docs,+ })+ }+ }++ return boundaries+}diff --git a/packages/dashboard/src/hooks/use-maintenance-tasks.ts b/packages/dashboard/src/hooks/use-maintenance-tasks.tsnew file mode 100644index 0000000000..5dd65fbf57--- /dev/null+++ b/packages/dashboard/src/hooks/use-maintenance-tasks.ts@@ -0,0 +1,95 @@+import type { MaintenanceTaskRun, MaintenanceTaskRunCreateParams } from '@spree/admin-sdk'+import {+ adminClient,+ i18n,+ useResourceKey,+ useResourceKeyBuilder,+ useResourceMutation,+} from '@spree/dashboard-core'+import { useQuery, useQueryClient } from '@tanstack/react-query'+import { useEffect, useRef } from 'react'++const RUN_POLL_INTERVAL_MS = 2000++/**+ * One run, polled while the runner is working.+ *+ * When a run this hook watched finishes, the run history and the upgrade+ * steps are marked stale: a maintenance task writes records+ * outside any tracked mutation, so nothing else would. Done in an effect on+ * the run going inactive, never from `refetchInterval` — that runs again on every+ * fetch, and the run history key covers this query too, so invalidating from+ * there refetches this run and invalidates again without end.+ */+export function useMaintenanceTaskRun(id: string | undefined) {+ const queryClient = useQueryClient()+ const buildKey = useResourceKeyBuilder()++ const query = useQuery({+ queryKey: useResourceKey('maintenance-task-runs', id),+ queryFn: () => adminClient.maintenanceTaskRuns.get(id as string, { expand: ['admin_user'] }),+ enabled: !!id,+ refetchInterval: (query) => (query.state.data?.active ? RUN_POLL_INTERVAL_MS : false),+ })++ const active = query.data?.active+ const wasActive = useRef(active)++ useEffect(() => {+ const finished = wasActive.current === true && active === false+ wasActive.current = active+ if (!finished) return++ queryClient.invalidateQueries({ queryKey: buildKey('maintenance-task-runs') })+ queryClient.invalidateQueries({ queryKey: buildKey('upgrade-steps') })+ }, [active, queryClient, buildKey])++ return query+}++/**+ * The upgrade manifest as an ordered checklist. Polled while any step is+ * working, so the panel advances as the walk does.+ */+export function useUpgradeSteps() {+ return useQuery({+ queryKey: useResourceKey('upgrade-steps'),+ queryFn: () => adminClient.upgradeSteps.list(),+ refetchInterval: (query) =>+ query.state.data?.data.some((step) => step.last_run?.active) ? RUN_POLL_INTERVAL_MS : false,+ })+}++export function useStartMaintenanceTask() {+ return useResourceMutation<MaintenanceTaskRun, Error, MaintenanceTaskRunCreateParams>({+ mutationFn: (params) => adminClient.maintenanceTaskRuns.create(params),+ invalidate: [['maintenance-task-runs'], ['upgrade-steps']],+ successMessage: i18n.t('admin.maintenance_tasks.messages.started'),+ errorMessage: i18n.t('admin.maintenance_tasks.messages.start_failed'),+ })+}++/**+ * Writes the returned run straight into the cache so the sheet settles on the+ * new status without waiting for the next poll.+ */+export function useCancelMaintenanceTaskRun() {+ const queryClient = useQueryClient()+ const buildKey = useResourceKeyBuilder()++ return useResourceMutation<MaintenanceTaskRun, Error, string>({+ mutationFn: (id) => adminClient.maintenanceTaskRuns.cancel(id),+ invalidate: [['maintenance-task-runs'], ['upgrade-steps']],+ successMessage: i18n.t('admin.maintenance_tasks.messages.canceled'),+ errorMessage: i18n.t('admin.errors.generic'),+ // Merged rather than replaced: the cancellation endpoint returns the run+ // without the embedded admin user the detail query asked for.+ onSuccess: (run) => {+ queryClient.setQueryData<MaintenanceTaskRun>(+ buildKey('maintenance-task-runs', run.id),+ (cached) =>+ cached ? { ...cached, ...run, admin_user: run.admin_user ?? cached.admin_user } : run,+ )+ },+ })+}diff --git a/packages/dashboard/src/lib/maintenance-tasks.ts b/packages/dashboard/src/lib/maintenance-tasks.tsnew file mode 100644index 0000000000..33e2221220--- /dev/null+++ b/packages/dashboard/src/lib/maintenance-tasks.ts@@ -0,0 +1,37 @@+import type { MaintenanceTaskRun } from '@spree/admin-sdk'++/**+ * A snake_case name as a label — `backfill_order_markets` reads as+ * "Backfill order markets".+ */+export function humanizeName(taskName: string): string {+ return taskName.replaceAll('_', ' ').replace(/^./, (character) => character.toUpperCase())+}++/**+ * A run's label. A one-pass upgrade step runs through the shared+ * `upgrade_step` task, so its own step id is what tells the runs apart.+ */+export function runTitle(run: Pick<MaintenanceTaskRun, 'task_name' | 'arguments'>): string {+ const stepId = run.task_name === 'upgrade_step' ? run.arguments?.step_id : undefined+ return humanizeName(typeof stepId === 'string' && stepId !== '' ? stepId : run.task_name)+}++/**+ * The value and maximum for a run's progress bar.+ *+ * A task that could not count its collection gets an indeterminate bar while+ * it works, but once it has finished that bar would still read as running —+ * a succeeded run fills the bar, and a run that stopped early shows what it+ * reached, or nothing when there was no total to measure against.+ */+export function runProgress(+ run: Pick<MaintenanceTaskRun, 'active' | 'status' | 'tick_count' | 'tick_total'>,+): {+ value: number | null+ max: number | undefined+} {+ if (run.status === 'succeeded') return { value: 1, max: 1 }+ if (run.tick_total != null) return { value: run.tick_count, max: run.tick_total }+ return run.active ? { value: null, max: undefined } : { value: 0, max: 1 }+}diff --git a/packages/dashboard/src/locales/ar.json b/packages/dashboard/src/locales/ar.jsonindex cc1632adf6..be20604ef0 100644--- a/packages/dashboard/src/locales/ar.json+++ b/packages/dashboard/src/locales/ar.json@@ -2830,6 +2830,87 @@"title": "مستخدم في"}},+ "maintenance_tasks": {+ "actions": {+ "cancel_run": "إلغاء التشغيل"+ },+ "cancel_confirm": {+ "message": "تتوقف المهمة عند نقطة التحقق التالية. العمل المنجز يبقى كما هو — الإلغاء لا يتراجع عنه.",+ "title": "إلغاء هذا التشغيل؟"+ },+ "description": "شغّل خطوات البيانات في ترقية Spree وتابع تقدّمها. يُسجَّل كل تشغيل.",+ "dry_run_badge": "معاينة",+ "history": {+ "empty_title": "لا توجد عمليات تشغيل",+ "search_placeholder": "ابحث باسم المهمة…",+ "table": {+ "initiated_by": "بدأها",+ "processed": "تمت معالجتها",+ "status": "الحالة",+ "task": "المهمة"+ },+ "title": "سجل التشغيل"+ },+ "initiated_via": {+ "api": "بدأت عبر واجهة البرمجة",+ "cli": "بدأت من سطر الأوامر",+ "dashboard": "بدأت من لوحة التحكم"+ },+ "messages": {+ "canceled": "جارٍ إلغاء التشغيل",+ "start_failed": "تعذّر بدء المهمة",+ "started": "بدأت المهمة"+ },+ "run": {+ "arguments": "المعاملات",+ "duration": "المدة",+ "ended": "انتهت",+ "error": "خطأ",+ "initiated_by": "بدأها",+ "loading": "جارٍ تحميل التشغيل…",+ "processed_count": "تمت معالجة {{count}}",+ "progress_label": "التقدّم",+ "results": "النتائج",+ "seconds": "{{count}} ث",+ "show_backtrace": "عرض التفاصيل التقنية",+ "started": "بدأت"+ },+ "status": {+ "cancelled": "أُلغيت",+ "cancelling": "جارٍ الإلغاء…",+ "enqueued": "في الانتظار",+ "errored": "فشلت",+ "interrupted": "جارٍ الاستئناف…",+ "running": "قيد التشغيل",+ "succeeded": "اكتملت"+ },+ "tabs": {+ "history": "السجل",+ "upgrade": "الترقية"+ },+ "title": "مهام الصيانة",+ "unavailable": "مهام الصيانة غير متاحة لك. في بعض التثبيتات تكون معطّلة، ويشغّل مسؤول التثبيت خطوات الترقية من سطر الأوامر.",+ "upgrade": {+ "already_completed": "مكتمل",+ "boundary": "Spree {{from}} ← {{to}}",+ "confirm": {+ "title": "تشغيل «{{name}}»؟",+ "message": "للخطوات ترتيب — شغّل ما قبلها أولًا. هذا يكتب في بياناتك ولا يمكن التراجع عنه."+ },+ "description": "خطوات البيانات التي يحتاجها هذا الإصدار، بالترتيب الذي يجب تنفيذها به.",+ "hide_steps": "إخفاء الخطوات",+ "history_description": "اكتمل بالفعل في هذا المتجر.",+ "progress": "اكتمل {{done}} من {{total}}",+ "read_guide": "اقرأ دليل الترقية",+ "run_again": "إعادة التشغيل",+ "run_next": "تشغيل الخطوة التالية",+ "run_step": "تشغيل",+ "show_steps": "عرض الخطوات",+ "title": "الترقية إلى Spree {{version}}",+ "up_to_date_description": "عند ترقية Spree إلى إصدار جديد، ستظهر هنا خطوات البيانات التي يحتاجها ذلك الإصدار، جاهزة للتشغيل بالترتيب.",+ "up_to_date_title": "متجرك محدّث"+ }+ },"nav": {"account": "الحساب","catalogs": "الكتالوجات",@@ -4274,6 +4355,7 @@"import_row": "صف استيراد","invitation": "دعوة","line_item": "Line item",+ "maintenance_task_run": "تشغيل مهمة صيانة","media": "وسائط","newsletter_subscriber": "Newsletter subscriber","order": "طلب",@@ -5467,6 +5549,7 @@"emails": "عناوين المُرسِل وإعدادات رسائل المعاملات","imports": "سجل عمليات استيراد CSV ونتائجها","integrations": "اربط مزوّدي الشحن والضرائب وغيرهم",+ "maintenance_tasks": "عمليات التعبئة وإعادة الفهرسة وخطوات الترقية، مع سجل لكل تشغيل","markets": "البلدان التي تبيع إليها وعملاتها","payment_methods": "بوابات الدفع وطريقة تحصيل المدفوعات","policies": "الشروط والخصوصية والإرجاع والشحن",@@ -5505,6 +5588,7 @@"emails": "البريد الإلكتروني","imports": "عمليات الاستيراد","integrations": "التكاملات",+ "maintenance_tasks": "مهام الصيانة","markets": "الأسواق","payment_methods": "طرق الدفع","policies": "السياسات",diff --git a/packages/dashboard/src/locales/de.json b/packages/dashboard/src/locales/de.jsonindex 79e0793816..b1eb4f9da4 100644--- a/packages/dashboard/src/locales/de.json+++ b/packages/dashboard/src/locales/de.json@@ -2728,6 +2728,87 @@"jurisdiction": {"everywhere": "Überall"},+ "maintenance_tasks": {+ "actions": {+ "cancel_run": "Lauf abbrechen"+ },+ "cancel_confirm": {+ "message": "Die Aufgabe stoppt am nächsten Prüfpunkt. Bereits erledigte Arbeit bleibt bestehen — ein Abbruch macht sie nicht rückgängig.",+ "title": "Diesen Lauf abbrechen?"+ },+ "description": "Führen Sie die Datenschritte eines Spree-Upgrades aus und verfolgen Sie ihren Fortschritt. Jeder Lauf wird aufgezeichnet.",+ "dry_run_badge": "Vorschau",+ "history": {+ "empty_title": "Noch keine Läufe",+ "search_placeholder": "Nach Aufgabenname suchen…",+ "table": {+ "initiated_by": "Gestartet von",+ "processed": "Verarbeitet",+ "status": "Status",+ "task": "Aufgabe"+ },+ "title": "Laufverlauf"+ },+ "initiated_via": {+ "api": "Über die API gestartet",+ "cli": "Über die Kommandozeile gestartet",+ "dashboard": "Über das Dashboard gestartet"+ },+ "messages": {+ "canceled": "Lauf wird abgebrochen",+ "start_failed": "Aufgabe konnte nicht gestartet werden",+ "started": "Aufgabe gestartet"+ },+ "run": {+ "arguments": "Parameter",+ "duration": "Dauer",+ "ended": "Beendet",+ "error": "Fehler",+ "initiated_by": "Gestartet von",+ "loading": "Lauf wird geladen…",+ "processed_count": "{{count}} verarbeitet",+ "progress_label": "Fortschritt",+ "results": "Ergebnisse",+ "seconds": "{{count}} s",+ "show_backtrace": "Technische Details anzeigen",+ "started": "Gestartet"+ },+ "status": {+ "cancelled": "Abgebrochen",+ "cancelling": "Wird abgebrochen…",+ "enqueued": "In Warteschlange",+ "errored": "Fehlgeschlagen",+ "interrupted": "Wird fortgesetzt…",+ "running": "Läuft",+ "succeeded": "Abgeschlossen"+ },+ "tabs": {+ "history": "Verlauf",+ "upgrade": "Upgrade"+ },+ "title": "Wartungsaufgaben",+ "unavailable": "Wartungsaufgaben stehen Ihnen nicht zur Verfügung. Auf manchen Installationen sind sie abgeschaltet, und Upgrade-Schritte werden von den Betreibern der Installation über die Kommandozeile ausgeführt.",+ "upgrade": {+ "already_completed": "Abgeschlossen",+ "boundary": "Spree {{from}} → {{to}}",+ "confirm": {+ "title": "„{{name}}“ ausführen?",+ "message": "Die Schritte haben eine Reihenfolge — führen Sie zuerst die vorhergehenden aus. Dies schreibt in Ihre Daten und kann nicht rückgängig gemacht werden."+ },+ "description": "Datenschritte, die dieses Release benötigt, in der Reihenfolge ihrer Ausführung.",+ "hide_steps": "Schritte ausblenden",+ "history_description": "In diesem Shop bereits abgeschlossen.",+ "progress": "{{done}} von {{total}} erledigt",+ "read_guide": "Upgrade-Anleitung lesen",+ "run_again": "Erneut ausführen",+ "run_next": "Nächsten Schritt ausführen",+ "run_step": "Ausführen",+ "show_steps": "Schritte anzeigen",+ "title": "Upgrade auf Spree {{version}}",+ "up_to_date_description": "Wenn Sie Spree auf eine neue Version aktualisieren, erscheinen hier die Datenschritte, die dieses Release benötigt, bereit zur Ausführung in der richtigen Reihenfolge.",+ "up_to_date_title": "Ihr Shop ist auf dem neuesten Stand"+ }+ },"markets": {"add_cta": "Markt hinzufügen","columns": {@@ -4242,6 +4323,7 @@"import_row": "Importzeile","invitation": "Einladung","line_item": "Position",+ "maintenance_task_run": "Wartungsaufgaben-Lauf","media": "Medien","newsletter_subscriber": "Newsletter-Abonnent","order": "Bestellung",@@ -5430,6 +5512,7 @@"emails": "Absenderadressen und Einstellungen für Transaktions-E-Mails","imports": "Verlauf der CSV-Importe und ihre Ergebnisse","integrations": "Versand-, Steuer- und andere Anbieter verbinden",+ "maintenance_tasks": "Nachbefüllungen, Neuindizierungen und Upgrade-Schritte samt Protokoll jedes Laufs","markets": "Länder, in die Sie verkaufen, und ihre Währungen","payment_methods": "Zahlungsanbieter und wie Zahlungen eingezogen werden","policies": "AGB, Datenschutz, Rückgabe und Versand",@@ -5468,6 +5551,7 @@"emails": "E-Mails","imports": "Importe","integrations": "Integrationen",+ "maintenance_tasks": "Wartungsaufgaben","markets": "Märkte","payment_methods": "Zahlungsmethoden","policies": "Richtlinien",diff --git a/packages/dashboard/src/locales/en.json b/packages/dashboard/src/locales/en.jsonindex 09ccef4e9c..129c8a9156 100644--- a/packages/dashboard/src/locales/en.json+++ b/packages/dashboard/src/locales/en.json@@ -2728,6 +2728,87 @@"jurisdiction": {"everywhere": "Everywhere"},+ "maintenance_tasks": {+ "actions": {+ "cancel_run": "Cancel run"+ },+ "cancel_confirm": {+ "message": "The task stops at its next checkpoint. Work already done stays done — cancelling does not undo it.",+ "title": "Cancel this run?"+ },+ "description": "Run the data steps of a Spree upgrade and follow their progress. Every run is recorded.",+ "dry_run_badge": "Preview",+ "history": {+ "empty_title": "No runs yet",+ "search_placeholder": "Search by task name…",+ "table": {+ "initiated_by": "Started by",+ "processed": "Processed",+ "status": "Status",+ "task": "Task"+ },+ "title": "Run history"+ },+ "initiated_via": {+ "api": "Started through the API",+ "cli": "Started from the command line",+ "dashboard": "Started from the dashboard"+ },+ "messages": {+ "canceled": "Cancelling the run",+ "start_failed": "Could not start the task",+ "started": "Task started"+ },+ "run": {+ "arguments": "Arguments",+ "duration": "Duration",+ "ended": "Ended",+ "error": "Error",+ "initiated_by": "Started by",+ "loading": "Loading run…",+ "processed_count": "{{count}} processed",+ "progress_label": "Progress",+ "results": "Results",+ "seconds": "{{count}}s",+ "show_backtrace": "Show technical detail",+ "started": "Started"+ },+ "status": {+ "cancelled": "Cancelled",+ "cancelling": "Cancelling…",+ "enqueued": "Queued",+ "errored": "Failed",+ "interrupted": "Resuming…",+ "running": "Running",+ "succeeded": "Completed"+ },+ "tabs": {+ "history": "History",+ "upgrade": "Upgrade"+ },+ "title": "Maintenance tasks",+ "unavailable": "Maintenance tasks are not available to you. On some installations they are turned off, and upgrade steps are run from the command line by whoever operates the installation.",+ "upgrade": {+ "already_completed": "Completed",+ "boundary": "Spree {{from}} → {{to}}",+ "confirm": {+ "title": "Run “{{name}}”?",+ "message": "Steps have an order — run the ones before it first. This writes to your data and cannot be undone."+ },+ "description": "Data steps this release needs, in the order they must run.",+ "hide_steps": "Hide steps",+ "history_description": "Already completed on this store.",+ "progress": "{{done}} of {{total}} done",+ "read_guide": "Read the upgrade guide",+ "run_again": "Run again",+ "run_next": "Run next step",+ "run_step": "Run",+ "show_steps": "Show steps",+ "title": "Upgrade to Spree {{version}}",+ "up_to_date_description": "When you upgrade Spree to a new version, the data steps that release needs will appear here, ready to run in order.",+ "up_to_date_title": "Your store is up to date"+ }+ },"markets": {"add_cta": "Add market","columns": {@@ -4242,6 +4323,7 @@"import_row": "Import row","invitation": "Invitation","line_item": "Line item",+ "maintenance_task_run": "Maintenance task run","media": "Media","newsletter_subscriber": "Newsletter subscriber","order": "Order",@@ -5430,6 +5512,7 @@"emails": "Sender addresses and transactional email settings","imports": "History of CSV imports and their results","integrations": "Connect shipping, tax and other providers",+ "maintenance_tasks": "Backfills, reindexes and upgrade steps, with a record of every run","markets": "Countries you sell to and their currencies","payment_methods": "Payment gateways and how payments are captured","policies": "Terms, privacy, returns and shipping documents",@@ -5468,6 +5551,7 @@"emails": "Emails","imports": "Imports","integrations": "Integrations",+ "maintenance_tasks": "Maintenance tasks","markets": "Markets","payment_methods": "Payment methods","policies": "Policies",diff --git a/packages/dashboard/src/locales/es.json b/packages/dashboard/src/locales/es.jsonindex c63e0a7647..b509f8cff5 100644--- a/packages/dashboard/src/locales/es.json+++ b/packages/dashboard/src/locales/es.json@@ -1,5 +1,86 @@{"admin": {+ "maintenance_tasks": {+ "actions": {+ "cancel_run": "Cancelar ejecución"+ },+ "cancel_confirm": {+ "message": "La tarea se detiene en su próximo punto de control. El trabajo ya hecho se conserva: cancelar no lo deshace.",+ "title": "¿Cancelar esta ejecución?"+ },+ "description": "Ejecuta los pasos de datos de una actualización de Spree y sigue su progreso. Cada ejecución queda registrada.",+ "dry_run_badge": "Vista previa",+ "history": {+ "empty_title": "Todavía no hay ejecuciones",+ "search_placeholder": "Buscar por nombre de tarea…",+ "table": {+ "initiated_by": "Iniciada por",+ "processed": "Procesados",+ "status": "Estado",+ "task": "Tarea"+ },+ "title": "Historial de ejecuciones"+ },+ "initiated_via": {+ "api": "Iniciada a través de la API",+ "cli": "Iniciada desde la línea de comandos",+ "dashboard": "Iniciada desde el panel"+ },+ "messages": {+ "canceled": "Cancelando la ejecución",+ "start_failed": "No se pudo iniciar la tarea",+ "started": "Tarea iniciada"+ },+ "run": {+ "arguments": "Argumentos",+ "duration": "Duración",+ "ended": "Finalizada",+ "error": "Error",+ "initiated_by": "Iniciada por",+ "loading": "Cargando ejecución…",+ "processed_count": "{{count}} procesados",+ "progress_label": "Progreso",+ "results": "Resultados",+ "seconds": "{{count}} s",+ "show_backtrace": "Mostrar detalle técnico",+ "started": "Iniciada"+ },+ "status": {+ "cancelled": "Cancelada",+ "cancelling": "Cancelando…",+ "enqueued": "En cola",+ "errored": "Fallida",+ "interrupted": "Reanudando…",+ "running": "En ejecución",+ "succeeded": "Completada"+ },+ "tabs": {+ "history": "Historial",+ "upgrade": "Actualización"+ },+ "title": "Tareas de mantenimiento",+ "unavailable": "Las tareas de mantenimiento no están disponibles para ti. En algunas instalaciones están desactivadas, y quien opera la instalación ejecuta los pasos de actualización desde la línea de comandos.",+ "upgrade": {+ "already_completed": "Completada",+ "boundary": "Spree {{from}} → {{to}}",+ "confirm": {+ "message": "Los pasos tienen un orden: ejecuta primero los anteriores. Esto escribe en tus datos y no se puede deshacer.",+ "title": "¿Ejecutar «{{name}}»?"+ },+ "description": "Pasos de datos que necesita esta versión, en el orden en que deben ejecutarse.",+ "hide_steps": "Ocultar pasos",+ "history_description": "Ya completado en esta tienda.",+ "progress": "{{done}} de {{total}} hechos",+ "read_guide": "Leer la guía de actualización",+ "run_again": "Ejecutar de nuevo",+ "run_next": "Ejecutar el siguiente paso",+ "run_step": "Ejecutar",+ "show_steps": "Mostrar pasos",+ "title": "Actualizar a Spree {{version}}",+ "up_to_date_description": "Cuando actualices Spree a una nueva versión, aquí aparecerán los pasos de datos que necesita esa versión, listos para ejecutarse en orden.",+ "up_to_date_title": "Tu tienda está al día"+ }+ },"pages": {"channels": {"add_cta": "Nuevo canal de venta",@@ -640,6 +721,7 @@"import_row": "Fila de importación","invitation": "Invitación","line_item": "Línea de pedido",+ "maintenance_task_run": "Ejecución de tarea de mantenimiento","media": "Medios","newsletter_subscriber": "Suscriptor de newsletter","order": "Pedido",@@ -4322,6 +4404,7 @@"emails": "Direcciones de remitente y configuración de emails transaccionales","imports": "Historial de importaciones CSV y sus resultados","integrations": "Conectá proveedores de envío, impuestos y otros",+ "maintenance_tasks": "Rellenos, reindexaciones y pasos de actualización, con un registro de cada ejecución","markets": "Los países a los que vendés y sus monedas","payment_methods": "Pasarelas de pago y cómo se capturan los pagos","policies": "Documentos de términos, privacidad, devoluciones y envíos",@@ -4360,6 +4443,7 @@"emails": "Emails","imports": "Importaciones","integrations": "Integraciones",+ "maintenance_tasks": "Tareas de mantenimiento","markets": "Mercados","payment_methods": "Métodos de pago","policies": "Políticas",diff --git a/packages/dashboard/src/locales/fr.json b/packages/dashboard/src/locales/fr.jsonindex 3fe167aaf7..0052231db6 100644--- a/packages/dashboard/src/locales/fr.json+++ b/packages/dashboard/src/locales/fr.json@@ -2728,6 +2728,87 @@"jurisdiction": {"everywhere": "Partout"},+ "maintenance_tasks": {+ "actions": {+ "cancel_run": "Annuler l'exécution"+ },+ "cancel_confirm": {+ "message": "La tâche s'arrête au prochain point de contrôle. Le travail déjà effectué est conservé — l'annulation ne le défait pas.",+ "title": "Annuler cette exécution ?"+ },+ "description": "Exécutez les étapes de données d'une mise à jour de Spree et suivez leur progression. Chaque exécution est enregistrée.",+ "dry_run_badge": "Aperçu",+ "history": {+ "empty_title": "Aucune exécution",+ "search_placeholder": "Rechercher par nom de tâche…",+ "table": {+ "initiated_by": "Lancée par",+ "processed": "Traités",+ "status": "Statut",+ "task": "Tâche"+ },+ "title": "Historique des exécutions"+ },+ "initiated_via": {+ "api": "Lancée via l'API",+ "cli": "Lancée en ligne de commande",+ "dashboard": "Lancée depuis le tableau de bord"+ },+ "messages": {+ "canceled": "Annulation de l'exécution",+ "start_failed": "Impossible de démarrer la tâche",+ "started": "Tâche démarrée"+ },+ "run": {+ "arguments": "Paramètres",+ "duration": "Durée",+ "ended": "Terminée",+ "error": "Erreur",+ "initiated_by": "Lancée par",+ "loading": "Chargement de l'exécution…",+ "processed_count": "{{count}} traités",+ "progress_label": "Progression",+ "results": "Résultats",+ "seconds": "{{count}} s",+ "show_backtrace": "Afficher le détail technique",+ "started": "Démarrée"+ },+ "status": {+ "cancelled": "Annulée",+ "cancelling": "Annulation…",+ "enqueued": "En file d'attente",+ "errored": "Échouée",+ "interrupted": "Reprise…",+ "running": "En cours",+ "succeeded": "Terminée"+ },+ "tabs": {+ "history": "Historique",+ "upgrade": "Mise à niveau"+ },+ "title": "Tâches de maintenance",+ "unavailable": "Les tâches de maintenance ne vous sont pas accessibles. Sur certaines installations, elles sont désactivées et les étapes de mise à niveau sont lancées en ligne de commande par l'équipe qui exploite l'installation.",+ "upgrade": {+ "already_completed": "Terminé",+ "boundary": "Spree {{from}} → {{to}}",+ "confirm": {+ "title": "Exécuter « {{name}} » ?",+ "message": "Les étapes ont un ordre — exécutez d'abord celles qui précèdent. Cette action écrit dans vos données et est irréversible."+ },+ "description": "Étapes de données requises par cette version, dans l'ordre où elles doivent s'exécuter.",+ "hide_steps": "Masquer les étapes",+ "history_description": "Déjà effectué sur cette boutique.",+ "progress": "{{done}} sur {{total}} terminées",+ "read_guide": "Lire le guide de mise à niveau",+ "run_again": "Réexécuter",+ "run_next": "Exécuter l'étape suivante",+ "run_step": "Exécuter",+ "show_steps": "Afficher les étapes",+ "title": "Mise à niveau vers Spree {{version}}",+ "up_to_date_description": "Lorsque vous mettrez Spree à niveau vers une nouvelle version, les étapes de données dont elle a besoin apparaîtront ici, prêtes à être lancées dans l'ordre.",+ "up_to_date_title": "Votre boutique est à jour"+ }+ },"markets": {"add_cta": "Ajouter un marché","columns": {@@ -4243,6 +4324,7 @@"import_row": "Ligne d'import","invitation": "Invitation","line_item": "Ligne d'article",+ "maintenance_task_run": "Exécution de tâche de maintenance","media": "Médias","newsletter_subscriber": "Abonné à la newsletter","order": "Commande",@@ -5431,6 +5513,7 @@"emails": "Adresses d'expéditeur et paramètres des e-mails transactionnels","imports": "Historique des imports CSV et leurs résultats","integrations": "Connecter des prestataires d'expédition, de taxe et autres",+ "maintenance_tasks": "Remplissages, réindexations et étapes de mise à niveau, avec le journal de chaque exécution","markets": "Pays où vous vendez et leurs devises","payment_methods": "Passerelles de paiement et mode de capture","policies": "Conditions, confidentialité, retours et livraison",@@ -5469,6 +5552,7 @@"emails": "E-mails","imports": "Imports","integrations": "Intégrations",+ "maintenance_tasks": "Tâches de maintenance","markets": "Marchés","payment_methods": "Modes de paiement","policies": "Politiques",diff --git a/packages/dashboard/src/locales/pl.json b/packages/dashboard/src/locales/pl.jsonindex b9158cfc4c..6ce6c22916 100644--- a/packages/dashboard/src/locales/pl.json+++ b/packages/dashboard/src/locales/pl.json@@ -2746,6 +2746,87 @@"jurisdiction": {"everywhere": "Wszędzie"},+ "maintenance_tasks": {+ "actions": {+ "cancel_run": "Anuluj uruchomienie"+ },+ "cancel_confirm": {+ "message": "Zadanie zatrzyma się w najbliższym punkcie kontrolnym. Wykonana już praca pozostaje — anulowanie jej nie cofa.",+ "title": "Anulować to uruchomienie?"+ },+ "description": "Uruchamiaj kroki danych aktualizacji Spree i śledź ich postęp. Każde uruchomienie jest zapisywane.",+ "dry_run_badge": "Podgląd",+ "history": {+ "empty_title": "Brak uruchomień",+ "search_placeholder": "Szukaj po nazwie zadania…",+ "table": {+ "initiated_by": "Uruchomił",+ "processed": "Przetworzono",+ "status": "Status",+ "task": "Zadanie"+ },+ "title": "Historia uruchomień"+ },+ "initiated_via": {+ "api": "Uruchomione przez API",+ "cli": "Uruchomione z wiersza poleceń",+ "dashboard": "Uruchomione z panelu"+ },+ "messages": {+ "canceled": "Anulowanie uruchomienia",+ "start_failed": "Nie udało się uruchomić zadania",+ "started": "Zadanie uruchomione"+ },+ "run": {+ "arguments": "Parametry",+ "duration": "Czas trwania",+ "ended": "Zakończono",+ "error": "Błąd",+ "initiated_by": "Uruchomił",+ "loading": "Wczytywanie uruchomienia…",+ "processed_count": "przetworzono: {{count}}",+ "progress_label": "Postęp",+ "results": "Wyniki",+ "seconds": "{{count}} s",+ "show_backtrace": "Pokaż szczegóły techniczne",+ "started": "Rozpoczęto"+ },+ "status": {+ "cancelled": "Anulowane",+ "cancelling": "Anulowanie…",+ "enqueued": "W kolejce",+ "errored": "Nieudane",+ "interrupted": "Wznawianie…",+ "running": "W trakcie",+ "succeeded": "Zakończone"+ },+ "tabs": {+ "history": "Historia",+ "upgrade": "Aktualizacja"+ },+ "title": "Zadania konserwacyjne",+ "unavailable": "Zadania konserwacyjne nie są dla Ciebie dostępne. W niektórych instalacjach są wyłączone, a kroki aktualizacji uruchamia z wiersza poleceń osoba zarządzająca instalacją.",+ "upgrade": {+ "already_completed": "Ukończone",+ "boundary": "Spree {{from}} → {{to}}",+ "confirm": {+ "title": "Uruchomić „{{name}}”?",+ "message": "Kroki mają kolejność — najpierw uruchom te wcześniejsze. Ta operacja zapisuje dane i nie można jej cofnąć."+ },+ "description": "Kroki na danych wymagane przez to wydanie, w kolejności ich wykonania.",+ "hide_steps": "Ukryj kroki",+ "history_description": "Już ukończone w tym sklepie.",+ "progress": "ukończono {{done}} z {{total}}",+ "read_guide": "Przeczytaj przewodnik aktualizacji",+ "run_again": "Uruchom ponownie",+ "run_next": "Uruchom następny krok",+ "run_step": "Uruchom",+ "show_steps": "Pokaż kroki",+ "title": "Aktualizacja do Spree {{version}}",+ "up_to_date_description": "Gdy zaktualizujesz Spree do nowej wersji, pojawią się tutaj kroki danych wymagane przez to wydanie, gotowe do uruchomienia po kolei.",+ "up_to_date_title": "Twój sklep jest aktualny"+ }+ },"markets": {"add_cta": "Dodaj rynek","columns": {@@ -4292,6 +4373,7 @@"import_row": "Wiersz importu","invitation": "Zaproszenie","line_item": "Pozycja zamówienia",+ "maintenance_task_run": "Uruchomienie zadania konserwacyjnego","media": "Multimedia","newsletter_subscriber": "Subskrybent newslettera","order": "Zamówienie",@@ -5496,6 +5578,7 @@"emails": "Adresy nadawcy i ustawienia e-maili transakcyjnych","imports": "Historia importów CSV i ich wyniki","integrations": "Podłącz dostawców wysyłki, podatków i innych usług",+ "maintenance_tasks": "Uzupełnienia, przebudowy indeksów i kroki aktualizacji wraz z zapisem każdego uruchomienia","markets": "Kraje, do których sprzedajesz, i ich waluty","payment_methods": "Bramki płatnicze i sposób pobierania płatności","policies": "Regulamin, prywatność, zwroty i wysyłka",@@ -5534,6 +5617,7 @@"emails": "Wiadomości e-mail","imports": "Importy","integrations": "Integracje",+ "maintenance_tasks": "Zadania konserwacyjne","markets": "Rynki","payment_methods": "Metody płatności","policies": "Polityki",diff --git a/packages/dashboard/src/locales/zh-CN.json b/packages/dashboard/src/locales/zh-CN.jsonindex 9fe92114e4..adb685707e 100644--- a/packages/dashboard/src/locales/zh-CN.json+++ b/packages/dashboard/src/locales/zh-CN.json@@ -2723,6 +2723,87 @@"jurisdiction": {"everywhere": "所有地区"},+ "maintenance_tasks": {+ "actions": {+ "cancel_run": "取消运行"+ },+ "cancel_confirm": {+ "message": "任务会在下一个检查点停止。已完成的工作会保留——取消不会撤销它。",+ "title": "取消这次运行?"+ },+ "description": "运行 Spree 升级中的数据步骤并跟踪其进度。每次运行都会被记录。",+ "dry_run_badge": "预览",+ "history": {+ "empty_title": "暂无运行记录",+ "search_placeholder": "按任务名称搜索…",+ "table": {+ "initiated_by": "启动人",+ "processed": "已处理",+ "status": "状态",+ "task": "任务"+ },+ "title": "运行历史"+ },+ "initiated_via": {+ "api": "通过 API 启动",+ "cli": "从命令行启动",+ "dashboard": "从仪表板启动"+ },+ "messages": {+ "canceled": "正在取消运行",+ "start_failed": "无法启动任务",+ "started": "任务已启动"+ },+ "run": {+ "arguments": "参数",+ "duration": "耗时",+ "ended": "结束时间",+ "error": "错误",+ "initiated_by": "启动人",+ "loading": "正在加载运行记录…",+ "processed_count": "已处理 {{count}} 条",+ "progress_label": "进度",+ "results": "结果",+ "seconds": "{{count}} 秒",+ "show_backtrace": "显示技术详情",+ "started": "开始时间"+ },+ "status": {+ "cancelled": "已取消",+ "cancelling": "正在取消…",+ "enqueued": "排队中",+ "errored": "已失败",+ "interrupted": "正在恢复…",+ "running": "运行中",+ "succeeded": "已完成"+ },+ "tabs": {+ "history": "历史",+ "upgrade": "升级"+ },+ "title": "维护任务",+ "unavailable": "你无法使用维护任务。在某些安装中维护任务已关闭,升级步骤由安装的运维人员通过命令行运行。",+ "upgrade": {+ "already_completed": "已完成",+ "boundary": "Spree {{from}} → {{to}}",+ "confirm": {+ "title": "运行“{{name}}”?",+ "message": "步骤有先后顺序——请先运行前面的步骤。此操作会写入数据且无法撤销。"+ },+ "description": "此版本所需的数据步骤,按必须执行的顺序排列。",+ "hide_steps": "隐藏步骤",+ "history_description": "此店铺已完成。",+ "progress": "已完成 {{done}} / {{total}}",+ "read_guide": "阅读升级指南",+ "run_again": "重新运行",+ "run_next": "运行下一步",+ "run_step": "运行",+ "show_steps": "显示步骤",+ "title": "升级到 Spree {{version}}",+ "up_to_date_description": "将 Spree 升级到新版本后,该版本所需的数据步骤会显示在这里,可按顺序运行。",+ "up_to_date_title": "你的店铺已是最新"+ }+ },"markets": {"add_cta": "添加市场","columns": {@@ -4231,6 +4312,7 @@"import_row": "导入行","invitation": "邀请","line_item": "订单项",+ "maintenance_task_run": "维护任务运行","media": "媒体","newsletter_subscriber": "邮件订阅者","order": "订单",@@ -5418,6 +5500,7 @@"emails": "发件地址与交易邮件设置","imports": "CSV 导入历史与结果","integrations": "连接物流、税务及其他服务商",+ "maintenance_tasks": "回填、重建索引与升级步骤,并记录每次运行","markets": "销售的国家/地区及其货币","payment_methods": "支付网关与收款方式","policies": "条款、隐私、退货与配送文件",@@ -5456,6 +5539,7 @@"emails": "邮件","imports": "导入","integrations": "集成",+ "maintenance_tasks": "维护任务","markets": "市场","payment_methods": "支付方式","policies": "政策",diff --git a/packages/dashboard/src/nav/settings.ts b/packages/dashboard/src/nav/settings.tsindex 879ab6c1fb..245063bddc 100644--- a/packages/dashboard/src/nav/settings.ts+++ b/packages/dashboard/src/nav/settings.ts@@ -23,6 +23,7 @@ import {UsersIcon,WarehouseIcon,WebhookIcon,+ WrenchIcon,} from '@spree/dashboard-ui/icons'// Built-in entries use `labelKey` so labels re-render on language change —@@ -413,3 +414,17 @@ settingsNav.add({subject: Subject.Product,action: 'update',})++// Running a task can rewrite any data in the install, so the entry follows the+// same grant the API enforces rather than a proxy permission.+settingsNav.add({+ key: 'settings.maintenance-tasks',+ labelKey: 'admin.settings_nav.items.maintenance_tasks',+ descriptionKey: 'admin.settings_nav.descriptions.maintenance_tasks',+ keywords: ['backfill', 'reindex', 'upgrade', 'migration', 'data'],+ path: '/maintenance-tasks',+ icon: WrenchIcon,+ group: 'developer',+ position: 500,+ subject: Subject.MaintenanceTaskRun,+})diff --git a/packages/dashboard/src/routeTree.gen.ts b/packages/dashboard/src/routeTree.gen.tsindex 4ce601e5d0..c8bcef2c68 100644--- a/packages/dashboard/src/routeTree.gen.ts+++ b/packages/dashboard/src/routeTree.gen.ts@@ -64,6 +64,7 @@ import { Route as SettingsChannelsRouteImport } from './routes/_authenticated/$simport { Route as SettingsCommissionRatesRouteImport } from './routes/_authenticated/$storeId/settings/commission-rates'import { Route as SettingsCustomFieldDefinitionsRouteImport } from './routes/_authenticated/$storeId/settings/custom-field-definitions'import { Route as SettingsIntegrationsRouteImport } from './routes/_authenticated/$storeId/settings/integrations'+import { Route as SettingsMaintenanceTasksRouteImport } from './routes/_authenticated/$storeId/settings/maintenance-tasks'import { Route as SettingsMarketplaceRouteImport } from './routes/_authenticated/$storeId/settings/marketplace'import { Route as SettingsMarketsRouteImport } from './routes/_authenticated/$storeId/settings/markets'import { Route as SettingsOauthClientsRouteImport } from './routes/_authenticated/$storeId/settings/oauth-clients'@@ -391,6 +392,12 @@ const SettingsIntegrationsRoute = SettingsIntegrationsRouteImport.update({path: '/integrations',getParentRoute: () => SettingsRoute,} as any)+const SettingsMaintenanceTasksRoute =+ SettingsMaintenanceTasksRouteImport.update({+ id: '/maintenance-tasks',+ path: '/maintenance-tasks',+ getParentRoute: () => SettingsRoute,+ } as any)const SettingsMarketplaceRoute = SettingsMarketplaceRouteImport.update({id: '/marketplace',path: '/marketplace',@@ -704,6 +711,7 @@ export interface FileRoutesByFullPath {'/$storeId/settings/commission-rates': typeof SettingsCommissionRatesRoute'/$storeId/settings/custom-field-definitions': typeof SettingsCustomFieldDefinitionsRoute'/$storeId/settings/integrations': typeof SettingsIntegrationsRoute+ '/$storeId/settings/maintenance-tasks': typeof SettingsMaintenanceTasksRoute'/$storeId/settings/marketplace': typeof SettingsMarketplaceRoute'/$storeId/settings/markets': typeof SettingsMarketsRoute'/$storeId/settings/oauth-clients': typeof SettingsOauthClientsRoute@@ -808,6 +816,7 @@ export interface FileRoutesByTo {'/$storeId/settings/commission-rates': typeof SettingsCommissionRatesRoute'/$storeId/settings/custom-field-definitions': typeof SettingsCustomFieldDefinitionsRoute'/$storeId/settings/integrations': typeof SettingsIntegrationsRoute+ '/$storeId/settings/maintenance-tasks': typeof SettingsMaintenanceTasksRoute'/$storeId/settings/marketplace': typeof SettingsMarketplaceRoute'/$storeId/settings/markets': typeof SettingsMarketsRoute'/$storeId/settings/oauth-clients': typeof SettingsOauthClientsRoute@@ -915,6 +924,7 @@ export interface FileRoutesById {'/_authenticated/$storeId/settings/commission-rates': typeof SettingsCommissionRatesRoute'/_authenticated/$storeId/settings/custom-field-definitions': typeof SettingsCustomFieldDefinitionsRoute'/_authenticated/$storeId/settings/integrations': typeof SettingsIntegrationsRoute+ '/_authenticated/$storeId/settings/maintenance-tasks': typeof SettingsMaintenanceTasksRoute'/_authenticated/$storeId/settings/marketplace': typeof SettingsMarketplaceRoute'/_authenticated/$storeId/settings/markets': typeof SettingsMarketsRoute'/_authenticated/$storeId/settings/oauth-clients': typeof SettingsOauthClientsRoute@@ -1023,6 +1033,7 @@ export interface FileRouteTypes {| '/$storeId/settings/commission-rates'| '/$storeId/settings/custom-field-definitions'| '/$storeId/settings/integrations'+ | '/$storeId/settings/maintenance-tasks'| '/$storeId/settings/marketplace'| '/$storeId/settings/markets'| '/$storeId/settings/oauth-clients'@@ -1127,6 +1138,7 @@ export interface FileRouteTypes {| '/$storeId/settings/commission-rates'| '/$storeId/settings/custom-field-definitions'| '/$storeId/settings/integrations'+ | '/$storeId/settings/maintenance-tasks'| '/$storeId/settings/marketplace'| '/$storeId/settings/markets'| '/$storeId/settings/oauth-clients'@@ -1233,6 +1245,7 @@ export interface FileRouteTypes {| '/_authenticated/$storeId/settings/commission-rates'| '/_authenticated/$storeId/settings/custom-field-definitions'| '/_authenticated/$storeId/settings/integrations'+ | '/_authenticated/$storeId/settings/maintenance-tasks'| '/_authenticated/$storeId/settings/marketplace'| '/_authenticated/$storeId/settings/markets'| '/_authenticated/$storeId/settings/oauth-clients'@@ -1691,6 +1704,13 @@ declare module '@tanstack/react-router' {preLoaderRoute: typeof SettingsIntegrationsRouteImportparentRoute: typeof SettingsRoute}+ '/_authenticated/$storeId/settings/maintenance-tasks': {+ id: '/_authenticated/$storeId/settings/maintenance-tasks'+ path: '/maintenance-tasks'+ fullPath: '/$storeId/settings/maintenance-tasks'+ preLoaderRoute: typeof SettingsMaintenanceTasksRouteImport+ parentRoute: typeof SettingsRoute+ }'/_authenticated/$storeId/settings/marketplace': {id: '/_authenticated/$storeId/settings/marketplace'path: '/marketplace'@@ -2070,6 +2090,7 @@ interface SettingsRouteChildren {SettingsCommissionRatesRoute: typeof SettingsCommissionRatesRouteSettingsCustomFieldDefinitionsRoute: typeof SettingsCustomFieldDefinitionsRouteSettingsIntegrationsRoute: typeof SettingsIntegrationsRoute+ SettingsMaintenanceTasksRoute: typeof SettingsMaintenanceTasksRouteSettingsMarketplaceRoute: typeof SettingsMarketplaceRouteSettingsMarketsRoute: typeof SettingsMarketsRouteSettingsOauthClientsRoute: typeof SettingsOauthClientsRoute@@ -2106,6 +2127,7 @@ const SettingsRouteChildren: SettingsRouteChildren = {SettingsCommissionRatesRoute: SettingsCommissionRatesRoute,SettingsCustomFieldDefinitionsRoute: SettingsCustomFieldDefinitionsRoute,SettingsIntegrationsRoute: SettingsIntegrationsRoute,+ SettingsMaintenanceTasksRoute: SettingsMaintenanceTasksRoute,SettingsMarketplaceRoute: SettingsMarketplaceRoute,SettingsMarketsRoute: SettingsMarketsRoute,SettingsOauthClientsRoute: SettingsOauthClientsRoute,diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/settings/maintenance-tasks.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/settings/maintenance-tasks.tsxnew file mode 100644index 0000000000..b680ec2dad--- /dev/null+++ b/packages/dashboard/src/routes/_authenticated/$storeId/settings/maintenance-tasks.tsx@@ -0,0 +1,140 @@+import {+ adminClient,+ ResourceTable,+ resourceSearchSchema,+ Subject,+ usePermissions,+} from '@spree/dashboard-core'+import {+ Empty,+ Tabs,+ TabsContent,+ TabsList,+ TabsTrigger,+ useRowClickBridge,+} from '@spree/dashboard-ui'+import { createFileRoute, useNavigate } from '@tanstack/react-router'+import { useCallback } from 'react'+import { useTranslation } from 'react-i18next'+import { z } from 'zod'+import { RunDetailSheet } from '../../../../components/spree/maintenance-tasks/run-detail-sheet'+import { UpgradePanel } from '../../../../components/spree/maintenance-tasks/upgrade-panel'+import { useUpgradeSteps } from '../../../../hooks/use-maintenance-tasks'+import '../../../../tables/maintenance-task-runs'++// The page shares its URL with the run-history `<ResourceTable>`; `run` is the+// prefixed ID of the run whose detail sheet is open, so a run in progress can+// be linked to and survives a reload.+const searchSchema = resourceSearchSchema.extend({+ run: z.string().optional(),+ tab: z.enum(['upgrade', 'history']).optional(),+})++export const Route = createFileRoute('/_authenticated/$storeId/settings/maintenance-tasks')({+ validateSearch: searchSchema,+ component: MaintenanceTasksRoute,+})++// The settings entry is hidden without access, but a bookmark still lands+// here — including on an installation that turned maintenance tasks off,+// where every request would be refused.+function MaintenanceTasksRoute() {+ const { t } = useTranslation()+ const { permissions } = usePermissions()++ if (permissions.can('read', Subject.MaintenanceTaskRun)) return <MaintenanceTasksPage />++ return (+ <div className="flex flex-col gap-6">+ <PageHeader />+ <Empty>{t('admin.maintenance_tasks.unavailable')}</Empty>+ </div>+ )+}++function PageHeader() {+ const { t } = useTranslation()++ return (+ <header className="flex flex-col gap-1">+ <h1 className="font-semibold text-2xl">{t('admin.maintenance_tasks.title')}</h1>+ <p className="text-muted-foreground text-sm">{t('admin.maintenance_tasks.description')}</p>+ </header>+ )+}++function MaintenanceTasksPage() {+ const { t } = useTranslation()+ const navigate = useNavigate({ from: Route.fullPath })+ const search = Route.useSearch()+ const openRunId = search.run++ const { data: upgradeData } = useUpgradeSteps()++ const openRun = useCallback(+ (runId: string | undefined) => {+ navigate({+ search: (previous: Record<string, unknown>) => ({ ...previous, run: runId }),+ replace: true,+ })+ },+ [navigate],+ )++ // The history table's task cell carries the run id; clicking a row opens the+ // run sheet.+ useRowClickBridge('data-maintenance-task-run-id', openRun)++ // Steps still outstanding — what the Upgrade tab is counting.+ const pendingUpgradeSteps = (upgradeData?.data ?? []).filter((step) => !step.superseded)++ return (+ <div className="flex flex-col gap-6">+ <PageHeader />++ <Tabs+ value={search.tab ?? 'upgrade'}+ onValueChange={(value) =>+ navigate({+ search: (previous: Record<string, unknown>) => ({ ...previous, tab: value }),+ replace: true,+ })+ }+ >+ <TabsList>+ <TabsTrigger value="upgrade" count={pendingUpgradeSteps.length || undefined}>+ {t('admin.maintenance_tasks.tabs.upgrade')}+ </TabsTrigger>+ <TabsTrigger value="history">{t('admin.maintenance_tasks.tabs.history')}</TabsTrigger>+ </TabsList>++ <TabsContent value="upgrade">+ <UpgradePanel onOpenRun={openRun} />+ </TabsContent>++ {/* Kept mounted so the run table's loaded page, scroll position and+ polling survive a tab switch. */}+ <TabsContent value="history" keepMounted>+ <ResourceTable+ tableKey="maintenance-task-runs"+ queryKey="maintenance-task-runs"+ queryFn={(params) =>+ adminClient.maintenanceTaskRuns.list({+ ...(params as Record<string, unknown>),+ expand: ['admin_user'],+ })+ }+ searchParams={search}+ hideHeader+ />+ </TabsContent>+ </Tabs>++ <RunDetailSheet+ runId={openRunId}+ open={!!openRunId}+ onOpenChange={(open) => !open && openRun(undefined)}+ />+ </div>+ )+}diff --git a/packages/dashboard/src/tables/maintenance-task-runs.tsx b/packages/dashboard/src/tables/maintenance-task-runs.tsxnew file mode 100644index 0000000000..d45b99f1e9--- /dev/null+++ b/packages/dashboard/src/tables/maintenance-task-runs.tsx@@ -0,0 +1,86 @@+import type { MaintenanceTaskRun } from '@spree/admin-sdk'+import { defineTable } from '@spree/dashboard-core'+import { RelativeTime, ResourceNameCell, StatusBadge } from '@spree/dashboard-ui'+import i18n from 'i18next'+import { HistoryIcon } from 'lucide-react'+import { runTitle } from '../lib/maintenance-tasks'++defineTable<MaintenanceTaskRun>('maintenance-task-runs', {+ title: i18n.t('admin.maintenance_tasks.history.title'),+ searchParam: 'task_name_cont',+ searchPlaceholder: i18n.t('admin.maintenance_tasks.history.search_placeholder'),+ defaultSort: { field: 'created_at', direction: 'desc' },+ emptyIcon: <HistoryIcon className="size-8 text-muted-foreground" />,+ emptyMessage: i18n.t('admin.maintenance_tasks.history.empty_title'),+ columns: [+ {+ key: 'task_name',+ label: i18n.t('admin.maintenance_tasks.history.table.task'),+ sortable: true,+ filterable: true,+ default: true,+ render: (run) => (+ <ResourceNameCell+ id={run.id}+ dataAttr="data-maintenance-task-run-id"+ name={runTitle(run)}+ />+ ),+ },+ {+ key: 'status',+ label: i18n.t('admin.maintenance_tasks.history.table.status'),+ sortable: true,+ filterable: true,+ default: true,+ render: (run) => (+ <div className="flex items-center gap-2">+ <StatusBadge+ status={run.status}+ label={i18n.t(`admin.maintenance_tasks.status.${run.status}`)}+ />+ {run.dry_run && (+ <span className="text-muted-foreground text-xs">+ {i18n.t('admin.maintenance_tasks.dry_run_badge')}+ </span>+ )}+ </div>+ ),+ },+ {+ key: 'progress',+ label: i18n.t('admin.maintenance_tasks.history.table.processed'),+ default: true,+ // A task that could not count its collection reports ticks alone —+ // showing "12 / null" would read as a bug rather than an unknown total.+ render: (run) =>+ run.tick_total == null ? (+ <span>{run.tick_count}</span>+ ) : (+ <span>+ {run.tick_count} / {run.tick_total}+ </span>+ ),+ },+ {+ key: 'initiated_by',+ label: i18n.t('admin.maintenance_tasks.history.table.initiated_by'),+ default: true,+ render: (run) =>+ run.admin_user ? (+ <span>{run.admin_user.email}</span>+ ) : (+ <span className="text-muted-foreground">+ {i18n.t(`admin.maintenance_tasks.initiated_via.${run.initiated_via}`)}+ </span>+ ),+ },+ {+ key: 'created_at',+ label: i18n.t('admin.fields.created_at.label'),+ sortable: true,+ default: true,+ render: (run) => <RelativeTime iso={run.created_at} />,+ },+ ],+})diff --git a/packages/sdk/src/webhooks/generated/events.ts b/packages/sdk/src/webhooks/generated/events.tsindex f041a02e86..bb55327f09 100644--- a/packages/sdk/src/webhooks/generated/events.ts+++ b/packages/sdk/src/webhooks/generated/events.ts@@ -154,6 +154,14 @@ export interface WebhookEventMap {'line_item.created': LineItem'line_item.deleted': LineItem'line_item.updated': LineItem+ 'maintenance_task_run.cancelled': WebhookRecordReference+ 'maintenance_task_run.created': WebhookRecordReference+ 'maintenance_task_run.deleted': WebhookRecordReference+ 'maintenance_task_run.errored': WebhookRecordReference+ 'maintenance_task_run.interrupted': WebhookRecordReference+ 'maintenance_task_run.started': WebhookRecordReference+ 'maintenance_task_run.succeeded': WebhookRecordReference+ 'maintenance_task_run.updated': WebhookRecordReference'media.created': MediaEvent'media.deleted': MediaEvent'media.updated': MediaEventdiff --git a/packages/sdk/src/webhooks/generated/schemas.ts b/packages/sdk/src/webhooks/generated/schemas.tsindex bb3c830c67..4320377ca9 100644--- a/packages/sdk/src/webhooks/generated/schemas.ts+++ b/packages/sdk/src/webhooks/generated/schemas.ts@@ -144,6 +144,14 @@ type WebhookEventName =| 'line_item.created'| 'line_item.deleted'| 'line_item.updated'+ | 'maintenance_task_run.cancelled'+ | 'maintenance_task_run.created'+ | 'maintenance_task_run.deleted'+ | 'maintenance_task_run.errored'+ | 'maintenance_task_run.interrupted'+ | 'maintenance_task_run.started'+ | 'maintenance_task_run.succeeded'+ | 'maintenance_task_run.updated'| 'media.created'| 'media.deleted'| 'media.updated'@@ -399,6 +407,14 @@ export const webhookEventSchemas: Readonly<Record<WebhookEventName, z.ZodType>>'line_item.created': LineItemSchema,'line_item.deleted': LineItemSchema,'line_item.updated': LineItemSchema,+ 'maintenance_task_run.cancelled': WebhookRecordReferenceSchema,+ 'maintenance_task_run.created': WebhookRecordReferenceSchema,+ 'maintenance_task_run.deleted': WebhookRecordReferenceSchema,+ 'maintenance_task_run.errored': WebhookRecordReferenceSchema,+ 'maintenance_task_run.interrupted': WebhookRecordReferenceSchema,+ 'maintenance_task_run.started': WebhookRecordReferenceSchema,+ 'maintenance_task_run.succeeded': WebhookRecordReferenceSchema,+ 'maintenance_task_run.updated': WebhookRecordReferenceSchema,'media.created': MediaEventSchema,'media.deleted': MediaEventSchema,'media.updated': MediaEventSchema,diff --git a/spree/api/app/controllers/concerns/spree/api/v3/admin/maintenance_tasks_switch.rb b/spree/api/app/controllers/concerns/spree/api/v3/admin/maintenance_tasks_switch.rbnew file mode 100644index 0000000000..a36c05df20--- /dev/null+++ b/spree/api/app/controllers/concerns/spree/api/v3/admin/maintenance_tasks_switch.rb@@ -0,0 +1,35 @@+module Spree+ module Api+ module V3+ module Admin+ # Refuses every maintenance task endpoint when the installation has+ # turned them off (Spree::Config.maintenance_tasks_dashboard_enabled).+ # The ability already withholds them from signed-in staff; this also+ # covers secret API keys, which are authorized by scope instead.+ #+ # Runs ahead of every other callback, so the caller learns the feature+ # is off rather than a lookup or permission failure that no grant could+ # fix — whether the caller is signed in does not change that answer.+ module MaintenanceTasksSwitch+ extend ActiveSupport::Concern++ included do+ before_action :ensure_maintenance_tasks_enabled, prepend: true+ end++ private++ def ensure_maintenance_tasks_enabled+ return if Spree::Config.maintenance_tasks_dashboard_enabled++ render_error(+ code: ErrorHandler::ERROR_CODES[:access_denied],+ message: I18n.t('spree.maintenance_tasks_turned_off'),+ status: :forbidden+ )+ end+ end+ end+ end+ end+enddiff --git a/spree/api/app/controllers/spree/api/v3/admin/maintenance_task_runs/cancellations_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/maintenance_task_runs/cancellations_controller.rbnew file mode 100644index 0000000000..2c2cda3b68--- /dev/null+++ b/spree/api/app/controllers/spree/api/v3/admin/maintenance_task_runs/cancellations_controller.rb@@ -0,0 +1,42 @@+module Spree+ module Api+ module V3+ module Admin+ module MaintenanceTaskRuns+ # POST /api/v3/admin/maintenance_task_runs/:maintenance_task_run_id/cancellation+ #+ # Stops a run for good. Work already committed stays committed; the+ # runner records the outcome (docs/plans/6.0-maintenance-tasks.md).+ class CancellationsController < Admin::BaseController+ include MaintenanceTasksSwitch++ scoped_resource :maintenance_tasks++ def create+ run = Spree::MaintenanceTaskRun.find_by_prefix_id!(params[:maintenance_task_run_id])+ authorize! :update, run++ result = Spree::MaintenanceTasks::Cancel.call(run: run)++ if result.success?+ render json: serialize_resource(result.value)+ else+ render_validation_error(result.error)+ end+ end++ protected++ def serializer_class+ Spree.api.admin_maintenance_task_run_serializer+ end++ def serializer_params+ super.merge(show_backtrace: true)+ end+ end+ end+ end+ end+ end+enddiff --git a/spree/api/app/controllers/spree/api/v3/admin/maintenance_task_runs_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/maintenance_task_runs_controller.rbnew file mode 100644index 0000000000..2914228012--- /dev/null+++ b/spree/api/app/controllers/spree/api/v3/admin/maintenance_task_runs_controller.rb@@ -0,0 +1,92 @@+module Spree+ module Api+ module V3+ module Admin+ # Firing a maintenance task and steering the run it creates+ # (docs/plans/6.0-maintenance-tasks.md).+ #+ # No destroy: a run is the audit record of work that touched merchant+ # data, so it is never removed through the API. Stopping one is a+ # cancellation (MaintenanceTaskRuns::CancellationsController).+ class MaintenanceTaskRunsController < ResourceController+ include ActiveStorage::SetCurrent++ include MaintenanceTasksSwitch++ scoped_resource :maintenance_tasks++ request_params :maintenance_task_run do |body|+ body.attribute :task_name, :string,+ required: true, on: :create,+ example: 'capture_methods',+ description: 'The task to run, as `task_name` from `GET /upgrade_steps`.'+ body.attribute :arguments, :hash,+ description: "Values for the task's declared parameters, keyed by parameter name. " \+ 'A key the task does not declare is rejected.'+ body.attribute :dry_run, :boolean,+ description: 'Report what would change without writing. Ignored by tasks that do not support a dry run, which run for real.'+ end++ # POST /api/v3/admin/maintenance_task_runs+ def create+ authorize! :create, Spree::MaintenanceTaskRun++ # Not normalized: a task argument holding a prefixed id is the+ # task's to resolve, and decoding it here would hand it a raw key.+ body = params.permit(*declared_permitted_attributes)++ result = Spree::MaintenanceTasks::Start.call(+ api_type: body[:task_name].to_s,+ arguments: body[:arguments]&.to_h || {},+ dry_run: ActiveModel::Type::Boolean.new.cast(body[:dry_run]) || false,+ admin_user: try_spree_current_user,+ api_key: current_api_key,+ initiated_via: initiated_via+ )++ if result.success?+ render json: serialize_resource(result.value), status: :created+ else+ render_validation_error(result.error)+ end+ end++ protected++ def model_class+ Spree::MaintenanceTaskRun+ end++ def serializer_class+ Spree.api.admin_maintenance_task_run_serializer+ end++ # Runs are installation-wide: an upgrade step converts every store's+ # data, so a run belongs to no store.+ def scope+ model_class.all+ end++ def collection_includes+ [{ admin_user: [{ spree_roles: :resource }, { avatar_attachment: :blob }] }]+ end++ # A backtrace names internal paths and class names, so it rides with+ # the permission to act on runs rather than the one to read them.+ def serializer_params+ super.merge(show_backtrace: holds_permission?('write_maintenance_tasks'))+ end++ private++ # A secret key belongs to an integration rather than a person, so the+ # two are recorded distinctly — "who ran this" has a different answer+ # for each.+ def initiated_via+ try_spree_current_user ? 'dashboard' : 'api'+ end+ end+ end+ end+ end+enddiff --git a/spree/api/app/controllers/spree/api/v3/admin/upgrade_steps_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/upgrade_steps_controller.rbnew file mode 100644index 0000000000..a453d4d48d--- /dev/null+++ b/spree/api/app/controllers/spree/api/v3/admin/upgrade_steps_controller.rb@@ -0,0 +1,114 @@+module Spree+ module Api+ module V3+ module Admin+ # The upgrade manifest as an ordered checklist, so the dashboard can+ # show what a release still needs and how far an operator has got+ # (docs/plans/6.0-maintenance-tasks.md).+ #+ # Read-only: running a step is starting the maintenance task it names,+ # which is what the runs endpoint already does. This exists to supply+ # the order and the operator notes, neither of which a task knows about+ # itself — a step's position in the manifest is a property of the+ # upgrade, not of the class.+ class UpgradeStepsController < BaseController+ include MaintenanceTasksSwitch++ scoped_resource :maintenance_tasks++ # GET /api/v3/admin/upgrade_steps+ #+ # Every step of every manifest this installation has reached, from+ # the first release whose runs are recorded, each marked pending or+ # superseded. Superseded steps are the releases it has already been+ # through: shown as history rather than hidden, but never runnable,+ # since re-running a completed conversion is how an upgrade does+ # damage. Earlier releases are left to the command line.+ def index+ authorize! :read, :maintenance_task++ # A store installed fresh at this release has no upgrade to show —+ # not the outstanding steps, and not the history of releases it was+ # never on.+ return render json: { data: [], meta: meta } unless Spree::Upgrade.relevant?++ render json: {+ data: steps.map { |step| present(step) },+ meta: meta+ }+ end++ private++ def meta+ { completed_version: Spree::Upgrade.completed_boundary }+ end++ # Superseded first: they are the earlier releases, so listing them+ # above what is outstanding keeps the whole thing in release order.+ def steps+ @steps ||= (superseded_steps + Spree::Upgrade.pending_steps).select { |step| Spree::Upgrade.tracked?(step) }+ end++ def superseded_steps+ @superseded_steps ||= Spree::Upgrade.superseded_steps+ end++ def superseded_ids+ @superseded_ids ||= superseded_steps.map { |step| step['id'] }.to_set+ end++ def present(step)+ task_name = Spree::Upgrade.task_class_name(step)+ run = latest_runs[run_key(step, task_name)]++ {+ # A boundary this installation has already crossed. The dashboard+ # shows these as done and refuses to run them.+ superseded: superseded_ids.include?(step['id']),+ id: step['id'],+ name: step['name'],+ notes: step['notes'],+ from: step['from'],+ to: step['to'],+ docs: step['docs'],+ task_name: Spree::MaintenanceTask.api_type_for(task_name),+ # A rake-backed step runs inside the shared runner, so the id it+ # was invoked with is what distinguishes one run from another.+ arguments: Spree::Upgrade.task_arguments(step),+ last_run: run && Spree.api.admin_maintenance_task_run_serializer.new(+ run, params: { show_backtrace: holds_permission?('write_maintenance_tasks') }+ ).to_h+ }+ end++ # The most recent run per step. Reduced in Ruby rather than grouped+ # in SQL: rake-backed runs are told apart by the step id inside their+ # `arguments` JSON, and grouping on a JSON column is not portable+ # across the adapters Spree supports. Only the three columns that+ # pick the latest run are read for the whole history; the runs kept+ # are then loaded in full.+ def latest_runs+ @latest_runs ||= begin+ latest_ids = Spree::MaintenanceTaskRun.where(task_name: manifest_task_names).order(:id).+ pluck(:id, :task_name, :arguments).+ each_with_object({}) do |(id, task_name, arguments), result|+ result[[task_name, arguments&.dig('step_id')]] = id+ end+ runs = Spree::MaintenanceTaskRun.includes(:admin_user).where(id: latest_ids.values).index_by(&:id)+ latest_ids.transform_values { |id| runs[id] }+ end+ end++ def manifest_task_names+ steps.map { |step| Spree::Upgrade.task_class_name(step) }.uniq+ end++ def run_key(step, task_name)+ [task_name, step['task_class'] ? nil : step['id']]+ end+ end+ end+ end+ end+enddiff --git a/spree/api/app/serializers/spree/api/v3/admin/maintenance_task_run_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/maintenance_task_run_serializer.rbnew file mode 100644index 0000000000..46bb5f29ac--- /dev/null+++ b/spree/api/app/serializers/spree/api/v3/admin/maintenance_task_run_serializer.rb@@ -0,0 +1,72 @@+module Spree+ module Api+ module V3+ module Admin+ # Admin API serializer for {Spree::MaintenanceTaskRun} — the progress+ # the dashboard polls while a task runs, and the audit trail it shows+ # afterwards (docs/plans/6.0-maintenance-tasks.md).+ #+ # Admin-only by design: there is no store counterpart, because nothing+ # about operator-run data work is customer-facing.+ class MaintenanceTaskRunSerializer < BaseSerializer+ typelize task_name: :string,+ status: [:string, enum: Spree::MaintenanceTaskRun.statuses, enum_type_name: 'MaintenanceTaskRunStatus'],+ dry_run: :boolean,+ initiated_via: :string,+ tick_count: :number,+ tick_total: [:number, nullable: true],+ duration: [:number, nullable: true],+ tallies: 'Record<string, number>',+ arguments: 'Record<string, unknown>',+ error_class: [:string, nullable: true],+ error_message: [:string, nullable: true],+ error_backtrace: [:string, nullable: true],+ active: :boolean,+ admin_user_id: [:string, nullable: true],+ started_at: [:string, nullable: true],+ ended_at: [:string, nullable: true]++ attributes :status, :dry_run, :initiated_via,+ :tick_count, :tick_total, :error_class, :error_message,+ :started_at, :ended_at, :created_at, :updated_at++ # The task's short name, as `GET /upgrade_steps` gives it.+ attribute :task_name, &:task_api_type++ # to_f before rounding: the column is a decimal, and a BigDecimal+ # serializes as a quoted string — a client reading `duration` wants a+ # number, and the schema says it gets one.+ attribute :duration do |run|+ run.duration&.to_f&.round(3)+ end++ attribute :tallies do |run|+ run.tallies || {}+ end++ attribute :arguments do |run|+ run.arguments || {}+ end++ # The failure detail an operator needs to fix the cause. Held back+ # from read-only callers — a backtrace names internal paths and+ # class names that a read scope has no business seeing.+ attribute :error_backtrace do |run|+ run.error_backtrace if params[:show_backtrace]+ end++ attribute :active, &:active?++ attribute :admin_user_id do |run|+ run.admin_user&.prefixed_id+ end++ # Who fired it. Pass `expand=admin_user` for the record itself.+ one :admin_user,+ resource: proc { Spree.api.admin_admin_user_serializer },+ if: proc { expand?('admin_user') }+ end+ end+ end+ end+enddiff --git a/spree/api/config/routes.rb b/spree/api/config/routes.rbindex 416a4e8a8f..a885f27c2e 100644--- a/spree/api/config/routes.rb+++ b/spree/api/config/routes.rb@@ -509,6 +509,15 @@ Spree::Core::Engine.add_routes dopost :test, on: :memberend+ # Maintenance tasks — see docs/plans/6.0-maintenance-tasks.md.+ # A run names its task by the short name the upgrade steps give.+ resources :upgrade_steps, only: [:index]+ resources :maintenance_task_runs, only: [:index, :show, :create] do+ scope module: :maintenance_task_runs do+ resource :cancellation, only: [:create]+ end+ end+# Promotions, with nested actions/rules/coupon codes.resources :promotions, concerns: :custom_fieldable doresources :promotion_actions, only: [:index, :show, :create, :update, :destroy]diff --git a/spree/api/lib/spree/api/dependencies.rb b/spree/api/lib/spree/api/dependencies.rbindex c1e56bc063..8e7e4133ab 100644--- a/spree/api/lib/spree/api/dependencies.rb+++ b/spree/api/lib/spree/api/dependencies.rb@@ -41,6 +41,7 @@ module Spreestore setup_task update_status api_key oauth_application oauth_access_token oauth_consent_request oauth_redirectoauth_protected_resource allowed_origin webhook_endpoint webhook_event webhook_delivery invitationinvitation_acceptance_link role permission export saved_report import import_row import_mapping promotion+ maintenance_task_runpromotion_action promotion_rule coupon_code price_adjustment_tier price_list price_ruleresource_translations email_template email_template_draft email_template_revision email_template_previewemail_template_sample_record file_upload file_upload_target].freezediff --git a/spree/api/spec/controllers/spree/api/v3/admin/maintenance_task_runs/cancellations_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/maintenance_task_runs/cancellations_controller_spec.rbnew file mode 100644index 0000000000..13c0ba1948--- /dev/null+++ b/spree/api/spec/controllers/spree/api/v3/admin/maintenance_task_runs/cancellations_controller_spec.rb@@ -0,0 +1,67 @@+require 'spec_helper'++RSpec.describe Spree::Api::V3::Admin::MaintenanceTaskRuns::CancellationsController, type: :controller do+ render_views++ include_context 'API v3 Admin authenticated'++ before { request.headers.merge!(headers) }++ let(:run) { create(:maintenance_task_run, task_name: 'Spree::MaintenanceTasks::UpgradeStep', status: 'running') }++ describe 'POST #create' do+ it 'asks the runner to stop for good' do+ post :create, params: { maintenance_task_run_id: run.prefixed_id }++ expect(response).to have_http_status(:ok)+ expect(run.reload).to be_cancelling+ end++ it '404s for a run that does not exist' do+ post :create, params: { maintenance_task_run_id: 'mtr_nonexistent' }++ expect(response).to have_http_status(:not_found)+ end+ end++ # Checked before anything else, so an admin is told the feature is off+ # rather than which permission they lack — no grant would help.+ context 'when the installation turns maintenance tasks off' do+ before { allow(Spree::Config).to receive(:maintenance_tasks_dashboard_enabled).and_return(false) }++ it 'refuses a signed-in admin and says why' do+ post :create, params: { maintenance_task_run_id: run.prefixed_id }++ expect(response).to have_http_status(:forbidden)+ expect(json_response['error']['message']).to include('spree upgrade')+ expect(json_response['error']).not_to have_key('details')+ expect(run.reload).to be_running+ end+ end++ context 'without maintenance task access' do+ include_context 'API v3 Admin with custom permissions'++ let(:custom_permissions) { %w[read_orders write_products] }++ it 'cannot cancel a run' do+ post :create, params: { maintenance_task_run_id: run.prefixed_id }++ expect(response).to have_http_status(:forbidden)+ expect(run.reload).to be_running+ end+ end++ context 'with write access' do+ include_context 'API v3 Admin with custom permissions'++ let(:custom_permissions) { %w[write_maintenance_tasks] }++ it 'can cancel a run' do+ post :create, params: { maintenance_task_run_id: run.prefixed_id }++ expect(response).to have_http_status(:ok)+ expect(run.reload).to be_cancelling+ end+ end+enddiff --git a/spree/api/spec/controllers/spree/api/v3/admin/maintenance_task_runs_authorization_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/maintenance_task_runs_authorization_spec.rbnew file mode 100644index 0000000000..d0f2df38c0--- /dev/null+++ b/spree/api/spec/controllers/spree/api/v3/admin/maintenance_task_runs_authorization_spec.rb@@ -0,0 +1,140 @@+require 'spec_helper'++# Maintenance tasks can rewrite any data in the install, so the grant sits with+# the other sensitive access keys rather than under settings: out of the box+# only the admin role holds it (docs/plans/6.0-maintenance-tasks.md).+RSpec.describe Spree::Api::V3::Admin::MaintenanceTaskRunsController, type: :controller do+ render_views++ include_context 'API v3 Admin with custom permissions'++ before { request.headers.merge!(headers) }++ let(:task_class) do+ Class.new(Spree::MaintenanceTask) do+ def self.name = 'TestMaintenance::Authorized'+ def collection = Spree::Product.order(:id)+ def process(product) = nil+ end+ end++ let!(:run) { create(:maintenance_task_run, task_name: 'TestMaintenance::Authorized', status: 'running') }++ before do+ stub_const('TestMaintenance::Authorized', task_class)+ Spree.maintenance_tasks << 'TestMaintenance::Authorized'+ end++ after { Spree.maintenance_tasks.delete('TestMaintenance::Authorized') }++ context 'a role with no maintenance-task permission' do+ let(:custom_permissions) { %w[read_orders write_products] }++ it 'cannot list runs' do+ get :index++ expect(response).to have_http_status(:forbidden)+ end++ # The point of the separate key: broad data permissions elsewhere must not+ # add up to permission to run bulk rewrites.+ it 'cannot start a run' do+ post :create, params: { task_name: 'authorized' }++ expect(response).to have_http_status(:forbidden)+ expect(Spree::MaintenanceTaskRun.where(status: 'enqueued')).to be_empty+ end+ end++ context 'a role granted read access only' do+ let(:custom_permissions) { %w[read_maintenance_tasks] }++ it 'can review the run history' do+ get :index++ expect(response).to have_http_status(:ok)+ end++ it 'cannot start a run' do+ post :create, params: { task_name: 'authorized' }++ expect(response).to have_http_status(:forbidden)+ end++ # A backtrace names internal paths and class names — detail that belongs+ # to whoever may act on the run, not to everyone who may read it.+ it 'does not see error backtraces' do+ run.update!(status: 'errored', error_class: 'ArgumentError',+ error_message: 'boom', error_backtrace: "app/models/secret.rb:42")++ get :show, params: { id: run.prefixed_id }++ expect(json_response['error_message']).to eq('boom')+ expect(json_response['error_backtrace']).to be_nil+ end+ end++ # A secret key passes every CanCanCan check by design, so whether it may see+ # a backtrace has to be read from its scopes.+ context 'a secret key with read scope only' do+ let(:secret_api_key) { create(:api_key, :secret, store: store, scopes: %w[read_maintenance_tasks]) }+ let(:headers) { api_key_headers }++ it 'does not see error backtraces' do+ run.update!(status: 'errored', error_class: 'ArgumentError',+ error_message: 'boom', error_backtrace: "app/models/secret.rb:42")++ get :show, params: { id: run.prefixed_id }++ expect(json_response['error_message']).to eq('boom')+ expect(json_response['error_backtrace']).to be_nil+ end+ end++ # A secret key is authorized by its scopes rather than by the ability, so+ # the switch has to refuse it in the controller.+ context 'a secret key with write scope when the installation turns tasks off' do+ let(:secret_api_key) { create(:api_key, :secret, store: store, scopes: %w[write_maintenance_tasks]) }+ let(:headers) { api_key_headers }++ before { allow(Spree::Config).to receive(:maintenance_tasks_dashboard_enabled).and_return(false) }++ it 'cannot list runs' do+ get :index++ expect(response).to have_http_status(:forbidden)+ expect(json_response['error']['message']).to include('spree upgrade')+ end++ it 'cannot start a run' do+ run.update!(status: 'succeeded')++ post :create, params: { task_name: 'authorized' }++ expect(response).to have_http_status(:forbidden)+ expect(Spree::MaintenanceTaskRun.where(status: 'enqueued')).to be_empty+ end+ end++ context 'a role granted write access' do+ let(:custom_permissions) { %w[write_maintenance_tasks] }++ it 'can start a run' do+ # Nothing may be in flight: one run per task is the rule.+ run.update!(status: 'succeeded')++ post :create, params: { task_name: 'authorized' }++ expect(response).to have_http_status(:created)+ end++ it 'sees error backtraces' do+ run.update!(status: 'errored', error_class: 'ArgumentError',+ error_message: 'boom', error_backtrace: "app/models/secret.rb:42")++ get :show, params: { id: run.prefixed_id }++ expect(json_response['error_backtrace']).to include('secret.rb')+ end+ end+enddiff --git a/spree/api/spec/controllers/spree/api/v3/admin/maintenance_task_runs_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/maintenance_task_runs_controller_spec.rbnew file mode 100644index 0000000000..1daed636b9--- /dev/null+++ b/spree/api/spec/controllers/spree/api/v3/admin/maintenance_task_runs_controller_spec.rb@@ -0,0 +1,162 @@+require 'spec_helper'++RSpec.describe Spree::Api::V3::Admin::MaintenanceTaskRunsController, type: :controller do+ render_views++ include_context 'API v3 Admin authenticated'++ before { request.headers.merge!(headers) }++ let(:task_class) do+ Class.new(Spree::MaintenanceTask) do+ def self.name = 'TestMaintenance::Runs'+ supports_dry_run+ attribute :label, :string+ attribute :product_id, :string+ validates :label, presence: true+ def collection = Spree::Product.order(:id)+ def process(product) = nil+ end+ end++ before do+ stub_const('TestMaintenance::Runs', task_class)+ Spree.maintenance_tasks << 'TestMaintenance::Runs'+ end++ after { Spree.maintenance_tasks.delete('TestMaintenance::Runs') }++ describe 'POST #create' do+ let(:valid_params) { { task_name: 'runs', arguments: { label: 'nightly' } } }++ it 'starts a run and enqueues the runner' do+ expect { post :create, params: valid_params }.to have_enqueued_job(Spree::MaintenanceTasks::RunJob)++ expect(response).to have_http_status(:created)+ expect(json_response['status']).to eq('enqueued')+ expect(json_response['task_name']).to eq('runs')+ end++ it 'records who fired it' do+ post :create, params: valid_params++ run = Spree::MaintenanceTaskRun.last+ expect(run.admin_user).to eq(admin_user)+ expect(run.initiated_via).to eq('dashboard')+ end++ it 'carries the dry-run flag through' do+ post :create, params: valid_params.merge(dry_run: true)++ expect(json_response['dry_run']).to be(true)+ end++ it 'rejects arguments the task refuses' do+ post :create, params: { task_name: 'runs', arguments: {} }++ expect(response).to have_http_status(:unprocessable_content)+ end++ it 'passes an argument holding a prefixed id through as given' do+ product = create(:product, store: store)++ post :create, params: { task_name: 'runs', arguments: { label: 'x', product_id: product.prefixed_id } }++ expect(Spree::MaintenanceTaskRun.last.arguments['product_id']).to eq(product.prefixed_id)+ end++ it 'rejects an argument the task does not declare' do+ post :create, params: { task_name: 'runs', arguments: { label: 'x', nope: '1' } }++ expect(response).to have_http_status(:unprocessable_content)+ end++ it 'rejects a task that is not registered' do+ post :create, params: { task_name: 'nope' }++ expect(response).to have_http_status(:unprocessable_content)+ end++ # A class name never crosses the API, in either direction.+ it 'rejects a task named by its class name' do+ post :create, params: valid_params.merge(task_name: 'TestMaintenance::Runs')++ expect(response).to have_http_status(:unprocessable_content)+ expect(Spree::MaintenanceTaskRun.count).to eq(0)+ end++ it 'refuses a second run while one is in flight' do+ create(:maintenance_task_run, task_name: 'TestMaintenance::Runs', status: 'running')++ post :create, params: valid_params++ expect(response).to have_http_status(:unprocessable_content)+ end+ end++ describe 'GET #index' do+ let!(:run) { create(:maintenance_task_run, task_name: 'TestMaintenance::Runs', status: 'succeeded') }++ it_behaves_like 'a list without N+1 queries' do+ subject { get :index, params: { expand: 'admin_user' } }++ let!(:started_runs) do+ create_list(:admin_user, 2).map do |user|+ create(:maintenance_task_run, task_name: 'TestMaintenance::Runs', status: 'succeeded', admin_user: user)+ end+ end+ end++ it 'lists runs' do+ get :index++ expect(response).to have_http_status(:ok)+ expect(json_response['data'].map { |entry| entry['id'] }).to include(run.prefixed_id)+ end++ it 'filters by task name' do+ create(:maintenance_task_run, task_name: 'Other::Task', status: 'succeeded')++ get :index, params: { q: { task_name_eq: 'runs' } }++ expect(json_response['data'].map { |entry| entry['task_name'] }.uniq).to eq(['runs'])+ end++ it 'finds runs by part of the task name' do+ get :index, params: { q: { task_name_cont: 'run' } }++ expect(json_response['data'].map { |entry| entry['id'] }).to include(run.prefixed_id)+ end++ it 'embeds who started a run when asked to' do+ run.update!(admin_user: admin_user)++ get :index, params: { expand: 'admin_user' }++ entry = json_response['data'].find { |candidate| candidate['id'] == run.prefixed_id }+ expect(entry['admin_user_id']).to eq(admin_user.prefixed_id)+ expect(entry['admin_user']['email']).to eq(admin_user.email)+ end+ end++ describe 'GET #show' do+ let(:run) do+ create(:maintenance_task_run, task_name: 'TestMaintenance::Runs', status: 'running',+ tick_count: 5, tick_total: 20)+ end++ it 'reports progress the dashboard can draw a bar from' do+ get :show, params: { id: run.prefixed_id }++ expect(json_response['tick_count']).to eq(5)+ expect(json_response['tick_total']).to eq(20)+ expect(json_response['active']).to be(true)+ end+ end++ describe 'runs are never deleted through the API' do+ it 'has no destroy route' do+ expect { delete :destroy, params: { id: 1 } }.to raise_error(ActionController::UrlGenerationError)+ end+ end+enddiff --git a/spree/api/spec/controllers/spree/api/v3/admin/upgrade_steps_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/upgrade_steps_controller_spec.rbnew file mode 100644index 0000000000..0d0b671721--- /dev/null+++ b/spree/api/spec/controllers/spree/api/v3/admin/upgrade_steps_controller_spec.rb@@ -0,0 +1,211 @@+require 'spec_helper'++RSpec.describe Spree::Api::V3::Admin::UpgradeStepsController, type: :controller do+ render_views++ include_context 'API v3 Admin authenticated'++ before { request.headers.merge!(headers) }++ describe 'GET #index' do+ context 'when the installation turns maintenance tasks off' do+ let(:secret_api_key) { create(:api_key, :secret, store: store, scopes: %w[read_maintenance_tasks]) }+ let(:headers) { api_key_headers }++ before { allow(Spree::Config).to receive(:maintenance_tasks_dashboard_enabled).and_return(false) }++ it 'refuses a secret key that holds the scope' do+ get :index++ expect(response).to have_http_status(:forbidden)+ expect(json_response['error']['message']).to include('spree upgrade')+ end+ end++ it_behaves_like 'a list without N+1 queries' do+ subject { get :index }++ # Runs of a class-backed step and of rake-backed steps, each started by+ # someone different, so a per-step lookup would repeat.+ let!(:runs) do+ [+ ['Spree::MaintenanceTasks::Upgrade::CaptureMethods', {}],+ ['Spree::MaintenanceTasks::UpgradeStep', { 'step_id' => 'migrate_tax_zones' }],+ ['Spree::MaintenanceTasks::UpgradeStep', { 'step_id' => 'backfill_tax_store_ids' }]+ ].map do |task_name, arguments|+ create(:maintenance_task_run, task_name: task_name, arguments: arguments, status: 'succeeded',+ admin_user: create(:admin_user))+ end+ end+ end++ it 'lists the manifest steps in the order they must run' do+ get :index++ expect(response).to have_http_status(:ok)+ ids = json_response['data'].map { |step| step['id'] }++ expect(ids).to include('migrate_capture_methods')+ # Rich text is copied onto rows the customer migration creates, so the+ # order the endpoint returns is the order they have to run in.+ expect(ids.index('migrate_rich_text_to_columns')).to be > ids.index('migrate_users_to_customers')+ end++ it 'names the task each step runs' do+ get :index++ step = json_response['data'].find { |entry| entry['id'] == 'migrate_capture_methods' }++ expect(step['task_name']).to eq('capture_methods')+ expect(step['arguments']).to eq({})+ end++ # A rake-backed step of a released manifest runs inside the generic+ # wrapper, so the step id has to travel as an argument.+ it 'carries the step id for wrapper-backed steps' do+ # Reachable only from a store still below the released boundary.+ Spree::UpgradeRecord.stamp!('5.5', source: 'manual')++ get :index++ wrapper = json_response['data'].find do |entry|+ entry['task_name'] == 'upgrade_step' && !entry['superseded']+ end++ expect(wrapper['arguments']['step_id']).to eq(wrapper['id'])+ end++ it 'includes the operator notes the manifest carries' do+ get :index++ step = json_response['data'].find { |entry| entry['id'] == 'migrate_capture_methods' }++ expect(step['notes']).to be_present+ end++ it 'reports how each step last went' do+ run = create(:maintenance_task_run,+ task_name: 'Spree::MaintenanceTasks::Upgrade::CaptureMethods',+ status: 'succeeded')++ get :index++ step = json_response['data'].find { |entry| entry['id'] == 'migrate_capture_methods' }++ expect(step['last_run']['id']).to eq(run.prefixed_id)+ expect(step['last_run']['status']).to eq('succeeded')+ end++ it 'reports no run for a step that has never been run' do+ get :index++ step = json_response['data'].find { |entry| entry['id'] == 'migrate_capture_methods' }++ expect(step['last_run']).to be_nil+ end++ # Wrapper runs all share one task name, so the step id is what tells one+ # step's history from another's.+ it 'matches a wrapper run to the step it ran' do+ create(:maintenance_task_run,+ task_name: 'Spree::MaintenanceTasks::UpgradeStep',+ arguments: { 'step_id' => 'migrate_tax_zones' },+ status: 'succeeded')++ get :index++ tax_zones_step = json_response['data'].find { |entry| entry['id'] == 'migrate_tax_zones' }+ other_step = json_response['data'].find do |entry|+ entry['task_name'] == 'upgrade_step' && entry['id'] != 'migrate_tax_zones'+ end++ expect(tax_zones_step['last_run']).to be_present+ expect(other_step['last_run']).to be_nil+ end+ end++ describe 'which steps an installation is shown' do+ # The list would otherwise grow with every release Spree ships, and a+ # store that upgraded last release would be offered steps it must never+ # run again.+ # Earlier releases stay visible as history — a store should be able to see+ # which upgrades it has been through — but are never runnable.+ it 'marks the boundaries it has already crossed as superseded' do+ Spree::UpgradeRecord.stamp!('6.0', source: 'walk')++ get :index++ expect(json_response['data']).not_to be_empty+ expect(json_response['data']).to all(include('superseded' => true, 'to' => '6.0'))+ end++ # Nothing recorded the runs of releases before 6.0, so a checklist of them+ # could only ever show steps as done on an assumption.+ it 'leaves releases before the first recorded one to the command line' do+ Spree::UpgradeRecord.stamp!('5.6', source: 'walk')++ get :index++ expect(json_response['data'].map { |step| step['to'] }.uniq).to eq(['6.0'])+ expect(json_response['data']).to all(include('superseded' => false))+ end++ it 'reports the boundary it is counting from' do+ Spree::UpgradeRecord.stamp!('5.6', source: 'walk')++ get :index++ expect(json_response['meta']['completed_version']).to eq('5.6')+ end++ # A store installed fresh at this release has no upgrade at all — not the+ # outstanding steps, and not a history of releases it was never on.+ it 'shows a freshly installed store no upgrade whatsoever' do+ Spree::Upgrade.manifests.each { |m| Spree::UpgradeRecord.stamp!(m['to'], source: 'install') }++ get :index++ expect(json_response['data']).to be_empty+ end++ # An upgraded store keeps its history, so it can see which releases it has+ # been through even once nothing is outstanding.+ it 'keeps the history of a store that was upgraded' do+ Spree::Upgrade.manifests.each { |m| Spree::UpgradeRecord.stamp!(m['to'], source: 'walk') }++ get :index++ expect(json_response['data']).not_to be_empty+ expect(json_response['data']).to all(include('superseded' => true))+ end++ # Without a stamp the store is assumed to come from the release below.+ it 'counts from the release below the installed one when nothing is recorded' do+ get :index++ expect(json_response['meta']['completed_version']).to eq('5.6')+ end++ it 'still bounds outstanding work at the installed version' do+ get :index++ outstanding = json_response['data'].reject { |step| step['superseded'] }++ expect(outstanding.map { |step| step['to'] }.uniq).to eq(['6.0'])+ end+ end++ describe 'authorization' do+ include_context 'API v3 Admin with custom permissions'++ let(:custom_permissions) { %w[read_orders] }++ it 'refuses a caller without the maintenance tasks grant' do+ request.headers.merge!(headers)++ get :index++ expect(response).to have_http_status(:forbidden)+ end+ end+enddiff --git a/spree/api/spec/integration/spree/api/v3/admin/maintenance_tasks_spec.rb b/spree/api/spec/integration/spree/api/v3/admin/maintenance_tasks_spec.rbnew file mode 100644index 0000000000..37b8533ec4--- /dev/null+++ b/spree/api/spec/integration/spree/api/v3/admin/maintenance_tasks_spec.rb@@ -0,0 +1,221 @@+# frozen_string_literal: true++require 'swagger_helper'++RSpec.describe 'Admin Maintenance Tasks API', type: :request, swagger_doc: 'api-reference/admin.yaml' do+ include_context 'API v3 Admin'++ let(:Authorization) { "Bearer #{admin_jwt_token}" }++ path '/api/v3/admin/maintenance_task_runs' do+ get 'List maintenance task runs' do+ tags 'Maintenance Tasks'+ produces 'application/json'+ security [api_key: [], bearer_auth: []]+ description <<~DESC+ The record of every maintenance task run: who started it, with which+ arguments, how far it got and how it ended.++ Runs are installation-wide rather than per store — an upgrade step+ converts every store's data — so this list is not filtered by the+ store the request is made against.+ DESC+ admin_scope :read, :maintenance_tasks++ admin_sdk_example 'maintenance-task-runs/list'++ parameter name: 'x-spree-api-key', in: :header, type: :string, required: true+ parameter name: :Authorization, in: :header, type: :string, required: true,+ description: 'Bearer token for admin authentication'+ parameter name: :page, in: :query, type: :integer, required: false, description: 'Page number'+ parameter name: :limit, in: :query, type: :integer, required: false, description: 'Number of records per page'+ parameter name: :'q[task_name_cont]', in: :query, type: :string, required: false,+ description: 'Filter by task name (contains), e.g. `capture`'+ parameter name: :'q[status_eq]', in: :query, type: :string, required: false,+ description: 'Filter by status (enqueued, running, succeeded, errored, cancelled, …)'+ parameter name: :sort, in: :query, type: :string, required: false,+ description: 'Sort by field. Prefix with `-` for descending (e.g., `-created_at`).'++ response '200', 'maintenance task runs found' do+ let(:'x-spree-api-key') { secret_api_key.plaintext_token }+ let!(:maintenance_task_run) do+ create(:maintenance_task_run, task_name: 'Spree::MaintenanceTasks::Upgrade::CaptureMethods',+ status: 'succeeded', initiated_via: 'dashboard')+ end++ schema SwaggerSchemaHelpers.paginated('MaintenanceTaskRun')++ run_test! do |response|+ data = JSON.parse(response.body)+ expect(data['data'].map { |run| run['id'] }).to include(maintenance_task_run.prefixed_id)+ end+ end++ response '401', 'unauthorized' do+ let(:'x-spree-api-key') { 'invalid' }+ let(:Authorization) { 'Bearer invalid' }++ schema '$ref' => '#/components/schemas/ErrorResponse'++ run_test!+ end+ end++ post 'Start a maintenance task' do+ tags 'Maintenance Tasks'+ consumes 'application/json'+ produces 'application/json'+ security [api_key: [], bearer_auth: []]+ description <<~DESC+ Starts a run of a registered maintenance task and returns it. The run+ is enqueued, so poll it while `active` is true.++ `arguments` are validated by the task's own Active Model validations,+ so a bad value is rejected here rather than failing on the first+ record. `dry_run` is honored only by tasks whose `supports_dry_run` is+ true — recording a run as a preview that would in fact have written+ would misrepresent what happened.++ Only one run of a task can be in flight at a time: two would race over+ the same records and their cursors would leapfrog.+ DESC+ admin_scope :write, :maintenance_tasks++ admin_sdk_example 'maintenance-task-runs/create'++ parameter name: 'x-spree-api-key', in: :header, type: :string, required: true+ parameter name: :Authorization, in: :header, type: :string, required: true,+ description: 'Bearer token for admin authentication'+ request_body_for++ response '201', 'maintenance task started' do+ let(:'x-spree-api-key') { secret_api_key.plaintext_token }+ let(:body) do+ { task_name: 'capture_methods', dry_run: true }+ end++ schema '$ref' => '#/components/schemas/MaintenanceTaskRun'++ run_test! do |response|+ data = JSON.parse(response.body)+ expect(data['status']).to eq('enqueued')+ expect(data['dry_run']).to be(true)+ end+ end++ response '422', 'task is not registered' do+ let(:'x-spree-api-key') { secret_api_key.plaintext_token }+ let(:body) { { task_name: 'nope' } }++ schema '$ref' => '#/components/schemas/ErrorResponse'++ run_test!+ end+ end+ end++ path '/api/v3/admin/maintenance_task_runs/{id}' do+ parameter name: :id, in: :path, type: :string, description: 'Maintenance task run ID'++ get 'Retrieve a maintenance task run' do+ tags 'Maintenance Tasks'+ produces 'application/json'+ security [api_key: [], bearer_auth: []]+ description <<~DESC+ A single run, with the progress a dashboard polls while it works.++ `progress` is `0..1` when the task could count its collection and+ `null` when it could not, in which case `tick_count` alone reports what+ has been processed. `arguments` are rendered through the task's masking+ rules, so a secret passed as a parameter is stored for reproducibility+ but never echoed back.+ DESC+ admin_scope :read, :maintenance_tasks++ admin_sdk_example 'maintenance-task-runs/get'++ parameter name: 'x-spree-api-key', in: :header, type: :string, required: true+ parameter name: :Authorization, in: :header, type: :string, required: true,+ description: 'Bearer token for admin authentication'++ response '200', 'maintenance task run found' do+ let(:'x-spree-api-key') { secret_api_key.plaintext_token }+ let(:maintenance_task_run) do+ create(:maintenance_task_run, task_name: 'Spree::MaintenanceTasks::Upgrade::CaptureMethods',+ status: 'running', tick_count: 5, tick_total: 20)+ end+ let(:id) { maintenance_task_run.prefixed_id }++ schema '$ref' => '#/components/schemas/MaintenanceTaskRun'++ run_test! do |response|+ data = JSON.parse(response.body)+ expect(data['tick_total']).to eq(20)+ expect(data['active']).to be(true)+ end+ end++ response '404', 'maintenance task run not found' do+ let(:'x-spree-api-key') { secret_api_key.plaintext_token }+ let(:id) { 'mtr_nonexistent' }++ schema '$ref' => '#/components/schemas/ErrorResponse'++ run_test!+ end+ end+ end++ path '/api/v3/admin/maintenance_task_runs/{maintenance_task_run_id}/cancellation' do+ parameter name: :maintenance_task_run_id, in: :path, type: :string, description: 'Maintenance task run ID'++ post 'Cancel a maintenance task run' do+ tags 'Maintenance Tasks'+ produces 'application/json'+ security [api_key: [], bearer_auth: []]+ description <<~DESC+ Asks the runner to stop for good at its next checkpoint.++ Cancelling is not a rollback — work already committed stays committed.+ What a cancelled run keeps is its cursor, so an operator can see how+ far it got. A run that is still `cancelling` because its worker has+ gone is cancelled outright by a second request.+ DESC+ admin_scope :write, :maintenance_tasks++ admin_sdk_example 'maintenance-task-runs/cancel'++ parameter name: 'x-spree-api-key', in: :header, type: :string, required: true+ parameter name: :Authorization, in: :header, type: :string, required: true,+ description: 'Bearer token for admin authentication'++ response '200', 'maintenance task run cancelling' do+ let(:'x-spree-api-key') { secret_api_key.plaintext_token }+ let(:maintenance_task_run) do+ create(:maintenance_task_run, task_name: 'Spree::MaintenanceTasks::Upgrade::CaptureMethods',+ status: 'running')+ end+ let(:maintenance_task_run_id) { maintenance_task_run.prefixed_id }++ schema '$ref' => '#/components/schemas/MaintenanceTaskRun'++ run_test! do |response|+ expect(JSON.parse(response.body)['status']).to eq('cancelling')+ end+ end++ response '422', 'maintenance task run cannot be cancelled' do+ let(:'x-spree-api-key') { secret_api_key.plaintext_token }+ let(:maintenance_task_run) do+ create(:maintenance_task_run, task_name: 'Spree::MaintenanceTasks::Upgrade::CaptureMethods',+ status: 'succeeded')+ end+ let(:maintenance_task_run_id) { maintenance_task_run.prefixed_id }++ schema '$ref' => '#/components/schemas/ErrorResponse'++ run_test!+ end+ end+ end+enddiff --git a/spree/api/spec/swagger_helper.rb b/spree/api/spec/swagger_helper.rbindex f65439af57..9c9ec5b967 100644--- a/spree/api/spec/swagger_helper.rb+++ b/spree/api/spec/swagger_helper.rb@@ -173,6 +173,7 @@ RSpec.configure do |config|{ name: 'Fulfillments', description: 'Order fulfillments — shipments, fulfill, cancel, resume, split' },{ name: 'Gift Cards', description: 'Gift cards and gift card batches' },{ name: 'Imports', description: 'Async CSV imports of admin resources, with per-row status and failed-row retry' },+ { name: 'Maintenance Tasks', description: 'Operator-run data work — backfills, reindexes and upgrade steps — and the record of every run' },{ name: 'Markets', description: 'Markets — geographic groupings of countries used for pricing, tax, and fulfillment rules' },{ name: 'Option Types', description: 'Option types and option values used to build product variants (e.g. Size, Color)' },{ name: 'Orders', description: 'Orders, order items, applied gift cards, and applied store credits' },diff --git a/spree/core/app/jobs/spree/maintenance_tasks/run_job.rb b/spree/core/app/jobs/spree/maintenance_tasks/run_job.rbnew file mode 100644index 0000000000..891d9c070b--- /dev/null+++ b/spree/core/app/jobs/spree/maintenance_tasks/run_job.rb@@ -0,0 +1,321 @@+module Spree+ module MaintenanceTasks+ # Executes one Spree::MaintenanceTaskRun on Active Job Continuations+ # (docs/plans/6.0-maintenance-tasks.md).+ #+ # Three things can stop a run mid-collection, and all three resolve to the+ # same checkpoint: the worker is shutting down (Continuations re-queue the+ # job), the execution has used its time slice (the runner re-queues+ # itself so no single task holds a worker), or an operator asked to+ # cancel (the Cancel service writes the request, the runner observes it+ # here). The run row's cursor is written before each checkpoint, so+ # whichever path fires, the next execution restarts from the same record.+ class RunJob < ::Spree::BaseJob+ include ActiveJob::Continuable++ queue_as Spree.queues.maintenance_tasks++ # A run that fails is recorded as failed; it must not be replayed by the+ # backend behind the operator's back. Running it again is an explicit+ # action.+ #+ # `inline` is a run executing in the caller's own process — the+ # upgrade walk and the command line. It holds no worker, so it is not+ # sliced: handing the remainder to a worker would let the caller report+ # a step done that has not finished, on a deploy where no worker runs.+ def perform(run_id, inline: false)+ # Outside the steps on purpose — runs on every execution, resumes+ # included.+ @run = Spree::MaintenanceTaskRun.find_by(id: run_id)+ return if @run.nil?+ # `cancelling` counts as active: a job re-queued after its worker+ # stopped is the only execution that will ever answer it.+ return unless @run.active?++ @task_class = @run.task_class+ return unfindable_task if @task_class.nil?++ @inline = inline+ @execution_started_at = Time.current+ @time_running_before = @run.time_running.to_f+ prepare+ return if @halted++ check_operator_request+ return if @halted+ return refuse_duplicate if duplicate_run?++ step :start+ # Seeded from the row rather than from the continuation: the row+ # survives a dropped job, which a re-queued execution then picks up+ # with no continuation at all.+ step :process_collection, start: @run.cursor+ step :finish+ rescue SignalException => e+ # Ctrl-C or a deploy stopping an inline run. No job was queued for it,+ # so nothing would ever come back to a run left `running`, and it+ # would block every later run of its task.+ record_error(e) if @inline && run&.reload&.active?+ raise+ end++ private++ attr_reader :run, :task++ def start+ return if run.running?++ started = write_status('running', from: %w[enqueued interrupted],+ started_at: run.started_at || Time.current,+ job_id: job_id,+ tick_total: run.tick_total || safe_count)+ # An operator cancelled the run after the check above.+ return check_operator_request unless started++ publish('started')+ rescue StandardError => e+ record_error(e)+ end++ # Outside the steps, so an error here would never reach the rescues+ # below: a run whose arguments no longer fit its task (a deploy removed+ # a parameter) would stay queued forever, or be resumed by Continuations+ # without end. Recorded as a failure instead.+ def prepare+ @task = @task_class.new(@run.arguments.presence || {})+ @task.run = @run+ resume_after_time_slice+ rescue StandardError => e+ record_error(e)+ end++ # One run per task is checked when a run is created, but two requests+ # can both pass that check before either is saved. The older run wins,+ # so the outcome does not depend on which worker picks a job up first.+ def duplicate_run?+ return false unless run.enqueued?++ run.class.active.where(task_name: run.task_name).where(run.class.arel_table[:id].lt(run.id)).exists?+ end++ def refuse_duplicate+ close_run('cancelled', 'Spree::MaintenanceTasks::AlreadyRunning',+ "#{run.task_api_type} was already running, so this run did not start")+ publish('cancelled')+ end++ # Continuations skip `start` once it has completed, so an execution+ # picking up after its time slice would otherwise keep reporting+ # `interrupted` while it works — and the Cancel service would treat it as+ # idle. Conditional, so a cancel written while the job sat+ # in the queue is not overwritten.+ def resume_after_time_slice+ return unless run.interrupted?++ run.class.where(id: run.id, status: 'interrupted').update_all(status: 'running', updated_at: Time.current)+ run.reload+ end++ # The collection walk. Batches are fetched by cursor rather than by+ # offset so a resumed execution reads nothing it has already processed.+ def process_collection(step)+ return if @halted++ if task.no_collection?+ process_single+ return+ end++ loop do+ break if @halted++ items = next_batch(step.cursor)+ break if items.empty?++ process_batch(items)+ break if @halted++ # One cursor value, the last id seen, written to the row and to the+ # continuation. Persisted before the checkpoint — an interruption+ # between these two lines must not lose the batch already applied.+ cursor = items.last.id.to_s+ persist_progress(cursor: cursor, count: items.size)+ step.set!(cursor)++ check_operator_request+ check_time_slice(step)+ end+ rescue StandardError => e+ # Not discard_on: Continuations resume errors raised after progress,+ # so a discard handler would never see them and the run would loop.+ record_error(e)+ end++ # The callback runs before the row is written so a task can summarise in+ # `after_complete` — tallying there and persisting first would silently+ # drop whatever it recorded.+ def finish+ return if @halted++ task.after_complete+ return check_operator_request unless write_status('succeeded', from: 'running',+ ended_at: Time.current,+ tallies: merged_tallies)++ publish('succeeded')+ rescue StandardError => e+ record_error(e)+ end++ # A no_collection task is one unit of work: no cursor, no partial+ # progress, and an error fails the whole run.+ def process_single+ task.process+ persist_progress(cursor: nil, count: 1)+ rescue StandardError => e+ record_error(e)+ end++ def process_batch(items)+ items.each { |item| task.process(item) }+ end++ # Cursor-paged rather than find_each: the cursor has to survive between+ # executions, which an in-memory batch enumerator cannot do.+ def next_batch(cursor)+ scope = task.collection+ scope = scope.where(scope.arel_table[scope.primary_key].gt(cursor)) if cursor.present?+ scope.limit(task.class.batch_size).to_a+ end++ # update_columns rather than update!: progress is written on every batch+ # and carries no validation of its own.+ def persist_progress(cursor:, count:)+ run.update_columns(+ cursor: cursor,+ tick_count: run.tick_count + count,+ tallies: merged_tallies,+ time_running: accumulated_time,+ updated_at: Time.current+ )+ end++ # Cancel is a request written to the row by the Cancel service; the+ # runner is the only writer of the resulting state, so a killed worker+ # can never leave `cancelled` on a run that is still moving.+ #+ # Read once per batch rather than on a timer: a primary-key read costs+ # nothing beside the batch of writes it follows, and a time-based+ # throttle would make a fast task ignore a cancel altogether — the+ # batches would all land inside one interval.+ def check_operator_request+ requested = run.class.where(id: run.id).pick(:status)+ return unless requested.in?(%w[cancelling cancelled])++ write_status('cancelled', from: requested, ended_at: Time.current, time_running: accumulated_time)+ publish('cancelled')+ @halted = true+ end++ # The control services write to the same row this job holds in memory,+ # so the write only lands while the row is still in the status the+ # runner expects. Otherwise an operator's cancel, written+ # between the runner's read and its write, would be overwritten.+ #+ # @return [Boolean] whether the row was in an expected status+ def write_status(status, from:, **attributes)+ written = run.class.where(id: run.id, status: from).+ update_all(status: status, updated_at: Time.current, **attributes)+ run.reload+ written.positive?+ end++ def check_time_slice(step)+ return if @inline+ return if Time.current - @execution_started_at < Spree::MaintenanceTask::MAX_RUN_TIME++ return check_operator_request unless write_status('interrupted', from: 'running',+ time_running: accumulated_time)++ publish('interrupted')+ # Raises Continuation::Interrupt, which inherits Exception and is+ # never caught by the rescues above.+ interrupt!(reason: :run_time_limit)+ end++ # Recording a failure must never fail. This is the last thing standing+ # between a crashed task and a run stuck in `running` forever, so it+ # writes columns directly rather than going through validations that+ # could reject the very state that describes the problem.+ def record_error(error)+ run.reload+ run.update_columns(+ status: 'errored',+ ended_at: Time.current,+ time_running: accumulated_time,+ tallies: merged_tallies,+ error_class: error.class.name,+ error_message: error.message.to_s.truncate(1000),+ error_backtrace: cleaned_backtrace(error),+ updated_at: Time.current+ )+ publish('errored')+ Rails.error.report(error, handled: true)+ @halted = true+ end++ def cleaned_backtrace(error)+ return nil if error.backtrace.blank?++ Rails.backtrace_cleaner.clean(error.backtrace).first(50).join("\n")+ end++ # The task was removed from the registry between enqueue and execution —+ # a deploy that dropped it. Recorded rather than raised: retrying cannot+ # bring the class back.+ def unfindable_task+ close_run('errored', 'Spree::MaintenanceTasks::TaskNotRegistered',+ "#{run.task_name} is not a registered maintenance task")+ end++ # Ends a run that never started work, so there is nothing to tally.+ def close_run(status, error_class, error_message)+ run.update_columns(status: status, ended_at: Time.current, error_class: error_class,+ error_message: error_message, updated_at: Time.current)+ end++ # Summed, not replaced: a task instance counts only what the current+ # execution did, so an interrupted run that merged would report its last+ # slice as the whole total. Baselined at the first checkpoint of each+ # execution so repeated writes within one execution stay accurate.+ def merged_tallies+ @tally_baseline ||= (run.tallies || {}).dup+ return @tally_baseline.dup if task.nil?++ task.tallies.each_with_object(@tally_baseline.dup) do |(key, value), result|+ result[key] = result.fetch(key, 0) + value+ end+ end++ # From the total this execution started with, never the row's current+ # value: progress rewrites the row every batch, so adding elapsed time+ # to it would count the same seconds again on each write.+ def accumulated_time+ return run.time_running if @execution_started_at.nil?++ @time_running_before + (Time.current - @execution_started_at)+ end++ def safe_count+ task.count+ rescue StandardError+ nil+ end++ def publish(event)+ run.publish_event("maintenance_task_run.#{event}")+ end+ end+ end+enddiff --git a/spree/core/app/maintenance_tasks/spree/maintenance_tasks/upgrade/backfill_order_markets.rb b/spree/core/app/maintenance_tasks/spree/maintenance_tasks/upgrade/backfill_order_markets.rbnew file mode 100644index 0000000000..86905dc19f--- /dev/null+++ b/spree/core/app/maintenance_tasks/spree/maintenance_tasks/upgrade/backfill_order_markets.rb@@ -0,0 +1,48 @@+module Spree+ module MaintenanceTasks+ module Upgrade+ # 5.6 → 6.0: market is mandatory on orders in Spree 6, and orders placed+ # before markets existed carry NULLs. Each order takes its own store's+ # default market, so the walk is per order rather than one UPDATE per+ # store — that is what gives the run a cursor to resume from and a+ # progress bar to watch on a catalog-sized table.+ #+ # Orders whose store has no default market are counted and left alone;+ # there is nothing to assign, and failing the run would strand every+ # other store's orders behind them.+ class BackfillOrderMarkets < Spree::MaintenanceTask+ supports_dry_run+ collection_batch_size 500++ def collection+ Spree::Order.unscoped.where(market_id: nil).order(:id)+ end++ def process(order)+ market_id = default_market_id_for(order.store_id)++ if market_id.nil?+ tally(:skipped_no_default_market)+ return+ end++ return tally(:would_update) if dry_run?++ order.update_columns(market_id: market_id, updated_at: Time.current)+ tally(:updated)+ end++ private++ # One lookup per store rather than per order: a backfill of this size+ # walks the same handful of stores over and over.+ def default_market_id_for(store_id)+ @default_market_ids ||= {}+ return @default_market_ids[store_id] if @default_market_ids.key?(store_id)++ @default_market_ids[store_id] = Spree::Store.find_by(id: store_id)&.default_market&.id+ end+ end+ end+ end+enddiff --git a/spree/core/app/maintenance_tasks/spree/maintenance_tasks/upgrade/capture_methods.rb b/spree/core/app/maintenance_tasks/spree/maintenance_tasks/upgrade/capture_methods.rbnew file mode 100644index 0000000000..2cdeeb1296--- /dev/null+++ b/spree/core/app/maintenance_tasks/spree/maintenance_tasks/upgrade/capture_methods.rb@@ -0,0 +1,40 @@+module Spree+ module MaintenanceTasks+ module Upgrade+ # 5.6 → 6.0 conversion of the per-payment-method auto_capture boolean onto+ # the capture_method vocabulary (docs/plans/6.0-store-scoped-configuration.md).+ #+ # A method that captured on authorization charges at checkout. One that+ # did not only recorded "not at checkout" — the old column could not say+ # whether dispatch or staff was meant to take the money, and the store's+ # own setting is what decided. Leaving those rows empty is what makes them+ # keep inheriting it, so only the true case is written here, and the+ # collection is the true case alone: any other scope would never reach+ # zero remaining.+ class CaptureMethods < Spree::MaintenanceTask+ supports_dry_run+ collection_batch_size 5_000++ def collection+ Spree::PaymentMethod.unscoped.where(capture_method: nil, auto_capture: true).order(:id)+ end++ def process(payment_method)+ return tally(:would_convert) if dry_run?++ payment_method.update_columns(capture_method: 'checkout', updated_at: Time.current)+ tally(:converted)+ end++ # Rows the conversion deliberately leaves alone, reported once so an+ # operator can see they were considered rather than missed.+ def after_complete+ return if dry_run?++ inheriting = Spree::PaymentMethod.unscoped.where(capture_method: nil, auto_capture: false).count+ tally(:left_inheriting_store_setting, inheriting) if inheriting.positive?+ end+ end+ end+ end+enddiff --git a/spree/core/app/maintenance_tasks/spree/maintenance_tasks/upgrade/deliveries.rb b/spree/core/app/maintenance_tasks/spree/maintenance_tasks/upgrade/deliveries.rbnew file mode 100644index 0000000000..823fe22d85--- /dev/null+++ b/spree/core/app/maintenance_tasks/spree/maintenance_tasks/upgrade/deliveries.rb@@ -0,0 +1,15 @@+module Spree+ module MaintenanceTasks+ module Upgrade+ # Creates a delivery for every fulfillment that carries a 5.6 tracking+ # number, moving carrier tracking onto its own record.+ class Deliveries < RakeStep+ runs_rake_task 'spree:migrate_deliveries'++ attribute :batch_size, :integer, default: 1_000++ passes_to_environment :batch_size, as: 'BATCH_SIZE'+ end+ end+ end+enddiff --git a/spree/core/app/maintenance_tasks/spree/maintenance_tasks/upgrade/order_coupon_codes.rb b/spree/core/app/maintenance_tasks/spree/maintenance_tasks/upgrade/order_coupon_codes.rbnew file mode 100644index 0000000000..1596848d88--- /dev/null+++ b/spree/core/app/maintenance_tasks/spree/maintenance_tasks/upgrade/order_coupon_codes.rb@@ -0,0 +1,15 @@+module Spree+ module MaintenanceTasks+ module Upgrade+ # Copies the coupon code a placed order was bought with onto the order+ # itself.+ class OrderCouponCodes < RakeStep+ runs_rake_task 'spree:backfill_order_coupon_codes'++ attribute :batch_size, :integer, default: 500++ passes_to_environment :batch_size, as: 'BATCH_SIZE'+ end+ end+ end+enddiff --git a/spree/core/app/maintenance_tasks/spree/maintenance_tasks/upgrade/promotion_option_value_rules.rb b/spree/core/app/maintenance_tasks/spree/maintenance_tasks/upgrade/promotion_option_value_rules.rbnew file mode 100644index 0000000000..79f3484b7a--- /dev/null+++ b/spree/core/app/maintenance_tasks/spree/maintenance_tasks/upgrade/promotion_option_value_rules.rb@@ -0,0 +1,15 @@+module Spree+ module MaintenanceTasks+ module Upgrade+ # Rewrites Option Value promotion rules so they reference option values+ # directly rather than the join rows they used to point at.+ class PromotionOptionValueRules < RakeStep+ runs_rake_task 'spree:upgrade:migrate_promotion_option_value_rules'++ attribute :skip_failed_rows, :boolean, default: false++ passes_to_environment :skip_failed_rows, as: 'SKIP_FAILED_ROWS'+ end+ end+ end+enddiff --git a/spree/core/app/maintenance_tasks/spree/maintenance_tasks/upgrade/rake_step.rb b/spree/core/app/maintenance_tasks/spree/maintenance_tasks/upgrade/rake_step.rbnew file mode 100644index 0000000000..95195199c9--- /dev/null+++ b/spree/core/app/maintenance_tasks/spree/maintenance_tasks/upgrade/rake_step.rb@@ -0,0 +1,83 @@+module Spree+ module MaintenanceTasks+ module Upgrade+ # Base for the one-pass upgrade steps that ask the operator for parameters+ # (docs/plans/6.0-maintenance-tasks.md). The rake body stays the+ # implementation; this class only maps its parameters onto the environment+ # variables the body reads. A step without parameters runs through+ # `UpgradeStep` and needs no class at all.+ class RakeStep < Spree::MaintenanceTask+ ENVIRONMENT_LOCK = Mutex.new++ no_collection++ class_attribute :rake_task_name, instance_writer: false+ class_attribute :environment_parameters, instance_writer: false, default: {}.freeze++ # @param name [String] the rake task this step runs+ def self.runs_rake_task(name)+ self.rake_task_name = name+ end++ # Declares a parameter the rake body reads from the environment.+ #+ # These bodies were written for a shell, so their answers arrive as+ # environment variables. Mapping them to attributes records the answer+ # on the run, and lets `ARGS` supply it when the step is run on its own.+ #+ # @param attribute_name [Symbol]+ # @param as [String] the environment variable the body reads+ def self.passes_to_environment(attribute_name, as:)+ self.environment_parameters = environment_parameters.merge(attribute_name.to_sym => as).freeze+ end++ # The declared parameters an operator exported before running the+ # upgrade walk, so the walk passes them on rather than letting each+ # attribute's default overwrite them.+ #+ # @return [Hash{String => String}]+ def self.arguments_from_environment+ environment_parameters.each_with_object({}) do |(attribute_name, variable), arguments|+ arguments[attribute_name.to_s] = ENV[variable] if ENV.key?(variable)+ end+ end++ def process+ with_environment { invoke_rake_task(self.class.rake_task_name) }+ end++ private++ # Restored afterwards so one run never leaks its answers into the next.+ # ENV is shared by the whole process, so two steps running at once in a+ # threaded worker take turns rather than reading each other's answers.+ def with_environment(&block)+ return yield if self.class.environment_parameters.empty?++ ENVIRONMENT_LOCK.synchronize { with_variables_set(&block) }+ end++ def with_variables_set+ keys = self.class.environment_parameters.values+ previous = ENV.to_h.slice(*keys)++ self.class.environment_parameters.each do |attribute_name, variable|+ ENV[variable] = environment_value(public_send(attribute_name))+ end++ yield+ ensure+ keys&.each { |key| ENV[key] = previous[key] }+ end++ def environment_value(value)+ case value+ when true then 'true'+ when false, nil then nil+ else value.to_s.presence+ end+ end+ end+ end+ end+enddiff --git a/spree/core/app/maintenance_tasks/spree/maintenance_tasks/upgrade/returns.rb b/spree/core/app/maintenance_tasks/spree/maintenance_tasks/upgrade/returns.rbnew file mode 100644index 0000000000..728284170d--- /dev/null+++ b/spree/core/app/maintenance_tasks/spree/maintenance_tasks/upgrade/returns.rb@@ -0,0 +1,20 @@+module Spree+ module MaintenanceTasks+ module Upgrade+ # Moves return authorizations onto the 6.0 Return and Exchange models.+ #+ # Resumable by construction: the legacy number is copied onto the new+ # record and uniquely indexed there, so what is still outstanding is a+ # query rather than tracked state.+ class Returns < RakeStep+ runs_rake_task 'spree:upgrade:migrate_returns'++ attribute :skip_failed_rows, :boolean, default: false+ attribute :batch_size, :integer, default: 500++ passes_to_environment :skip_failed_rows, as: 'SKIP_FAILED_ROWS'+ passes_to_environment :batch_size, as: 'BATCH_SIZE'+ end+ end+ end+enddiff --git a/spree/core/app/maintenance_tasks/spree/maintenance_tasks/upgrade/users_to_customers.rb b/spree/core/app/maintenance_tasks/spree/maintenance_tasks/upgrade/users_to_customers.rbnew file mode 100644index 0000000000..f97feb2056--- /dev/null+++ b/spree/core/app/maintenance_tasks/spree/maintenance_tasks/upgrade/users_to_customers.rb@@ -0,0 +1,28 @@+module Spree+ module MaintenanceTasks+ module Upgrade+ # Copies the legacy Devise user table onto the gem-owned customer model+ # and re-points every polymorphic reference that named the old class.+ #+ # Two of its parameters are questions only an operator can answer: whether+ # a Devise pepper was ever configured (an encrypted password cannot be+ # read without knowing, and Devise is gone by the time this runs), and+ # what to do with source rows that cannot be copied.+ class UsersToCustomers < RakeStep+ runs_rake_task 'spree:upgrade:migrate_users_to_customers'++ attribute :confirm_no_pepper, :boolean, default: false+ attribute :skip_invalid_rows, :boolean, default: false+ attribute :source_user_table, :string+ attribute :source_user_type, :string+ attribute :batch_size, :integer, default: 1_000++ passes_to_environment :confirm_no_pepper, as: 'CONFIRM_NO_PEPPER'+ passes_to_environment :skip_invalid_rows, as: 'SKIP_INVALID_ROWS'+ passes_to_environment :source_user_table, as: 'SOURCE_USER_TABLE'+ passes_to_environment :source_user_type, as: 'SOURCE_USER_TYPE'+ passes_to_environment :batch_size, as: 'BATCH_SIZE'+ end+ end+ end+enddiff --git a/spree/core/app/maintenance_tasks/spree/maintenance_tasks/upgrade_step.rb b/spree/core/app/maintenance_tasks/spree/maintenance_tasks/upgrade_step.rbnew file mode 100644index 0000000000..ffa8b8c0a9--- /dev/null+++ b/spree/core/app/maintenance_tasks/spree/maintenance_tasks/upgrade_step.rb@@ -0,0 +1,44 @@+module Spree+ module MaintenanceTasks+ # Runs one rake-backed step of an upgrade manifest, so a shell walk and a+ # dashboard run leave the same audit record+ # (docs/plans/6.0-maintenance-tasks.md).+ #+ # Every one-pass step names its rake task in the manifest and runs here, so+ # the rake body stays the only implementation. A step gets a task class of+ # its own only when it walks rows (progress, resume, dry run) or asks the+ # operator for parameters.+ class UpgradeStep < Spree::MaintenanceTask+ no_collection++ attribute :step_id, :string+ validates :step_id, presence: true++ validate :step_must_exist++ def process+ invoke_rake_task(manifest_step.fetch('task'))+ end++ # The manifest entry this run is executing, resolved across every+ # manifest rather than a fixed one — the walker may be part way through a+ # multi-release upgrade.+ #+ # @return [Hash, nil]+ def manifest_step+ @manifest_step ||= Spree::Upgrade.find_step(step_id)+ end++ private++ # A step with a task class of its own runs as that class, so only a+ # step that names a rake task can be run here.+ def step_must_exist+ return if step_id.blank?+ return if manifest_step&.dig('task').present?++ errors.add(:step_id, "no upgrade step with id #{step_id} runs a rake task")+ end+ end+ end+enddiff --git a/spree/core/app/models/spree/ability.rb b/spree/core/app/models/spree/ability.rbindex 457252cabe..f333ab5d04 100644--- a/spree/core/app/models/spree/ability.rb+++ b/spree/core/app/models/spree/ability.rb@@ -95,6 +95,15 @@ module Spreeapply_staff_baselinegrantable_keys_for(roles).each { |key| activate_permission(key) }end++ withhold_maintenance_tasks unless Spree::Config.maintenance_tasks_dashboard_enabled+ end++ # Applied last so it overrides the full-access grant, and travels to the+ # dashboard with the other rules, which then hides the page.+ def withhold_maintenance_tasks+ cannot :manage, [Spree::MaintenanceTaskRun, :maintenance_task]+ @permission_keys -= %w[read_maintenance_tasks write_maintenance_tasks]end# Every key the roles ask for, bounded at activation by what each role'sdiff --git a/spree/core/app/models/spree/maintenance_task.rb b/spree/core/app/models/spree/maintenance_task.rbnew file mode 100644index 0000000000..f36cc2bc0b--- /dev/null+++ b/spree/core/app/models/spree/maintenance_task.rb@@ -0,0 +1,221 @@+module Spree+ # Base class for the data work an upgrade runs: one step of an upgrade+ # manifest (docs/plans/6.0-maintenance-tasks.md).+ #+ # A task walks a stable-ordered collection and processes one record at a+ # time. The runner (Spree::MaintenanceTasks::RunJob) supplies batching,+ # checkpointing, cancelling and the audit row, so a task body says+ # only what it does.+ #+ # class Spree::MaintenanceTasks::Upgrade::BackfillOrderMarkets < Spree::MaintenanceTask+ # supports_dry_run+ #+ # def collection+ # Spree::Order.where(market_id: nil).order(:id)+ # end+ #+ # def process(order)+ # return tally(:would_update) if dry_run?+ #+ # order.update_columns(market_id: order.store.default_market.id)+ # tally(:updated)+ # end+ # end+ #+ # A manifest step names its task class, which registers it in+ # `Spree.maintenance_tasks`; nothing else is runnable.+ class MaintenanceTask+ include ActiveModel::Model+ include ActiveModel::Attributes+ extend Spree::ApiTyped++ # A rake body that stopped itself with `abort`.+ class RakeTaskAborted < StandardError; end++ # Two threads of one worker must not both find a task undefined and both+ # load its file — the second load would make the task run twice.+ RAKE_LOAD_LOCK = Mutex.new++ DEFAULT_BATCH_SIZE = 100++ # How long one execution may run before the runner checkpoints and+ # re-enqueues itself, so a long step cannot hold a worker indefinitely.+ MAX_RUN_TIME = 5.minutes++ class_attribute :dry_run_supported, instance_writer: false, default: false+ class_attribute :collection_kind, instance_writer: false, default: :relation+ class_attribute :batch_size, instance_writer: false, default: DEFAULT_BATCH_SIZE++ attr_accessor :run++ class << self+ # Declares that `process` honors `dry_run?`. The runner never fakes a+ # dry run by rolling a transaction back, which would silently lie about+ # external calls, enqueued jobs and cache writes.+ def supports_dry_run+ self.dry_run_supported = true+ end++ # The task performs a single operation instead of iterating; `process`+ # is called once with no argument.+ def no_collection+ self.collection_kind = :none+ end++ def collection_batch_size(size)+ self.batch_size = size+ end++ # @return [Array<Class>] registered task classes, sorted by name+ def registered_classes+ Spree.maintenance_tasks.filter_map do |entry|+ entry.is_a?(Class) ? entry : entry.to_s.safe_constantize+ end.uniq.sort_by(&:name)+ end++ # @param name [String] a task class name+ # @return [Class, nil] nil when the name is not registered — an+ # unregistered task is never runnable, so the runner and the API can+ # treat nil as "no such task" without a second check+ def find_registered(name)+ return nil if name.blank?++ registered_classes.find { |klass| klass.name == name.to_s }+ end++ # A task class name as the API shows it. A task that is no longer+ # registered is shortened the same way rather than loaded by name.+ #+ # @param class_name [String]+ # @return [String]+ def api_type_for(class_name)+ find_registered(class_name)&.api_type || class_name.to_s.demodulize.underscore+ end++ # The registered task an API caller names. Matches the short name only,+ # so a Ruby class name arriving over the API is an unknown task.+ #+ # @param api_type [String] e.g. "capture_methods"+ # @return [Class, nil]+ def find_by_api_type(api_type)+ Spree::ApiTyped.find(Spree.maintenance_tasks, api_type)+ end+ end++ # The records to walk, ordered by primary key — the cursor is the last id+ # processed, so any other order would resume in the wrong place.+ #+ # @return [ActiveRecord::Relation]+ def collection+ raise NotImplementedError, "#{self.class.name} must implement #collection or declare `no_collection`"+ end++ # @param item [Object] one record from the collection; omitted for+ # `no_collection` tasks+ def process(item = nil)+ raise NotImplementedError, "#{self.class.name} must implement #process"+ end++ # Total records, for the progress bar. Return nil when counting is more+ # expensive than the work itself — the run then reports ticks only.+ #+ # @return [Integer, nil]+ def count+ collection.count unless no_collection?+ end++ def no_collection?+ self.class.collection_kind == :none+ end++ def dry_run?+ run&.dry_run? || false+ end++ # Records a counter shown on the run page: what was updated, skipped, or+ # would have changed in a dry run.+ def tally(key, by = 1)+ @tallies ||= Hash.new(0)+ @tallies[key.to_s] += by+ end++ def tallies+ @tallies ||= Hash.new(0)+ end++ # Runs an engine rake task as part of this task.+ #+ # Rake bodies stop themselves with `abort`, which raises SystemExit — not+ # an error the runner records. Left alone it would end the whole process+ # from the command line and, in a worker, leave the run marked running+ # with nothing to finish it.+ #+ # @param task_name [String]+ # @raise [RakeTaskAborted] carrying the body's own message+ def invoke_rake_task(task_name)+ load_engine_rake_tasks(task_name)++ task = ::Rake::Task[task_name]+ task.reenable+ task.invoke+ rescue SystemExit => e+ raise RakeTaskAborted, e.message+ end++ # Finds the file that defines a task by reading the files rather than+ # loading them: loading a .rake file to discover whether it is the right+ # one would append its blocks to every task it defines, which is the very+ # duplication this avoids.+ #+ # Searches every engine and the host application, since a step may ship in+ # an extension gem. When two files define the same task name, the one+ # that also declares the task's namespaces wins.+ #+ # @return [String, nil]+ def rake_file_defining(task_name)+ *namespaces, leaf = task_name.split(':')+ candidates = rake_files.select do |path|+ File.read(path).match?(/^\s*(?:desc\s.*\n\s*)?task\s+:?["']?#{Regexp.escape(leaf)}["']?\b/)+ end++ candidates.find do |path|+ source = File.read(path)+ namespaces.all? { |name| source.match?(/namespace\s+:?["']?#{Regexp.escape(name)}["']?\b/) }+ end || candidates.first+ end++ # Called once the last record has been processed, before the run is+ # marked succeeded — for a summary tally of what the walk left alone.+ def after_complete; end++ private++ # Rake tasks are defined by the Rakefile, which a web process never loads —+ # a task fired from the dashboard has to load the engine's tasks itself.+ #+ # Loads the one file that defines the task, and only when it is not already+ # defined. Both halves matter: re-loading a .rake file APPENDS its block to+ # a task that already exists, so a second load makes that task run twice,+ # and loading every file would do that to every task in the engine. The+ # symptom is invisible until something counts what it did.+ #+ # @param task_name [String] the rake task about to be invoked+ def load_engine_rake_tasks(task_name)+ require 'rake'++ RAKE_LOAD_LOCK.synchronize do+ next if ::Rake::Task.task_defined?(task_name)++ ::Rake::Task.define_task(:environment) unless ::Rake::Task.task_defined?(:environment)++ path = rake_file_defining(task_name)+ load(path) if path+ end+ end++ def rake_files+ roots = Rails.application.railties.grep(Rails::Engine).map(&:root) + [Rails.root]+ roots.uniq.flat_map { |root| Dir.glob(File.join(root, 'lib/tasks/**/*.rake')).sort }+ end+ end+enddiff --git a/spree/core/app/models/spree/maintenance_task_run.rb b/spree/core/app/models/spree/maintenance_task_run.rbnew file mode 100644index 0000000000..8b7b7b9d0a--- /dev/null+++ b/spree/core/app/models/spree/maintenance_task_run.rb@@ -0,0 +1,78 @@+module Spree+ # One execution of a Spree::MaintenanceTask — the durable record of what was+ # run, by whom, with which arguments, and how far it got+ # (docs/plans/6.0-maintenance-tasks.md).+ #+ # The row is both the checkpoint and the audit trail. Its `cursor` is the+ # authoritative resume point: Active Job serializes its own continuation+ # into the job data, but that copy is lost whenever the job is dropped by+ # the backend, so the runner writes both in the same checkpoint and always+ # seeds from this column.+ #+ # Runs are installation-wide: an upgrade step converts every store's data,+ # so a run belongs to no store.+ class MaintenanceTaskRun < Spree.base_class+ has_prefix_id :mtr++ include Spree::HasStatus++ publishes_lifecycle_events+ publishes_events :started, :succeeded, :cancelled, :interrupted, :errored++ # Terminal statuses end a run for good; a failed run is started again+ # rather than resumed. `cancelling` is the operator's request, written by+ # the Cancel service and observed by the runner at its next checkpoint —+ # the runner alone moves a running run into `cancelled`, so a stopped+ # worker can never leave a lie in the column.+ has_status :enqueued, :running, :interrupted, :cancelling, :cancelled,+ :succeeded, :errored,+ default: :enqueued++ ACTIVE_STATUSES = %w[enqueued running interrupted cancelling].freeze+ INITIATED_VIA = %w[dashboard api cli].freeze++ belongs_to :admin_user, class_name: Spree.admin_user_class.to_s, optional: true+ belongs_to :api_key, class_name: 'Spree::ApiKey', optional: true++ validates :task_name, presence: true+ validates :initiated_via, presence: true, inclusion: { in: INITIATED_VIA }++ scope :active, -> { where(status: ACTIVE_STATUSES) }++ self.whitelisted_ransackable_attributes = %w[task_name status created_at]++ # Filtered by the task's short name, which is what responses carry; the+ # column holds its class name. A partial value (`task_name_cont=capture`)+ # is camelized so a search still matches part of the stored name.+ ransacker :task_name, formatter: ->(value) {+ Spree::MaintenanceTask.find_by_api_type(value)&.name || value.to_s.camelize+ } do |parent|+ parent.table[:task_name]+ end++ # @return [Class, nil] the registered task class, or nil when the task has+ # been removed from the registry since the run was created+ def task_class+ Spree::MaintenanceTask.find_registered(task_name)+ end++ # The task's short name, as the API and the dashboard identify it.+ #+ # @return [String]+ def task_api_type+ Spree::MaintenanceTask.api_type_for(task_name)+ end++ def active?+ ACTIVE_STATUSES.include?(status)+ end++ # Seconds of work. Time since the last checkpoint counts only while a+ # worker holds the run — a queued run is not working.+ def duration+ return time_running unless status.in?(%w[running cancelling]) && started_at.present?++ time_running + (Time.current - (updated_at || started_at))+ end+ end+enddiff --git a/spree/core/app/models/spree/upgrade_record.rb b/spree/core/app/models/spree/upgrade_record.rbnew file mode 100644index 0000000000..72b0750a89--- /dev/null+++ b/spree/core/app/models/spree/upgrade_record.rb@@ -0,0 +1,62 @@+module Spree+ # A release boundary whose data steps this installation has completed+ # (docs/plans/6.0-maintenance-tasks.md).+ #+ # This exists because nothing else in the schema records where an+ # installation upgraded *from*. `Spree.version` is only ever the gem that is+ # installed now, so without a stamp the dashboard cannot tell a store that+ # has been on 5.6 for months from one jumping straight from 5.4 — and would+ # have to show both every step of every manifest, which grows with each+ # release.+ #+ # Written from three places, none of which guesses:+ #+ # - a successful `spree:upgrade` walk stamps the boundary it reached+ # - a fresh install stamps the current version, because a database created+ # by today's schema has no historical data to convert+ # - an operator can stamp one by hand, for a store upgraded before this+ # record existed+ class UpgradeRecord < Spree.base_class+ has_prefix_id :upg++ SOURCES = %w[walk install manual].freeze++ validates :version, presence: true, uniqueness: true+ validates :source, presence: true, inclusion: { in: SOURCES }+ validates :completed_at, presence: true++ # Whether this installation has ever been upgraded, as opposed to having+ # been installed at its current version.+ #+ # A store installed fresh at 6.0 has no historical data to convert and no+ # upgrade to perform — showing it a manifest of steps, current or past,+ # describes work that does not exist for it.+ #+ # @return [Boolean]+ def self.upgraded?+ where.not(source: 'install').exists?+ end++ # The highest boundary recorded, or nil when this installation has never+ # stamped one.+ #+ # @return [String, nil]+ def self.current_version+ all.map(&:version).max_by { |version| Spree::Upgrade.version_parts(version) }+ end++ # Records a completed boundary. Idempotent — re-running a walk that has+ # already been stamped updates when it happened rather than failing.+ #+ # @param version [String] two-segment release, e.g. "6.0"+ # @param source [String] one of SOURCES+ # @return [Spree::UpgradeRecord]+ def self.stamp!(version, source: 'walk')+ record = find_or_initialize_by(version: version.to_s)+ record.source = source.to_s+ record.completed_at = Time.current+ record.save!+ record+ end+ end+enddiff --git a/spree/core/app/services/spree/maintenance_tasks/argument_parser.rb b/spree/core/app/services/spree/maintenance_tasks/argument_parser.rbnew file mode 100644index 0000000000..7d71edf6ad--- /dev/null+++ b/spree/core/app/services/spree/maintenance_tasks/argument_parser.rb@@ -0,0 +1,23 @@+module Spree+ module MaintenanceTasks+ # Turns the CLI's `ARGS='market_id=mkt_1 batch_size=200'` into the hash the+ # task's ActiveModel attributes expect.+ #+ # Values stay strings: attribute types cast them, so the parser never has+ # to guess whether `200` is a number or a label.+ module ArgumentParser+ # Quoted values may contain spaces: ARGS='label="two words" limit=5'.+ TOKEN = /(\w+)=("[^"]*"|'[^']*'|\S+)/++ # @param raw [String, nil]+ # @return [Hash{String => String}]+ def self.parse(raw)+ return {} if raw.blank?++ raw.scan(TOKEN).to_h do |key, value|+ [key, value.gsub(/\A["']|["']\z/, '')]+ end+ end+ end+ end+enddiff --git a/spree/core/app/services/spree/maintenance_tasks/cancel.rb b/spree/core/app/services/spree/maintenance_tasks/cancel.rbnew file mode 100644index 0000000000..1fcd29abb0--- /dev/null+++ b/spree/core/app/services/spree/maintenance_tasks/cancel.rb@@ -0,0 +1,51 @@+module Spree+ module MaintenanceTasks+ # Stops a run for good. The service records the request and the runner+ # records the outcome; a run that has not started yet is cancelled+ # outright, since no execution will ever observe the request.+ #+ # Cancelling a run that is already `cancelling` also cancels it outright.+ # That is the way out when the worker that should have observed the first+ # request is gone: a run the runner never comes back to would otherwise+ # stay active and block every new run of its task.+ #+ # Cancelling is not a rollback — work already committed stays committed.+ # What a cancelled run keeps is its cursor, so an operator can see exactly+ # how far it got.+ class Cancel+ prepend ::Spree::ServiceModule::Base++ # @param run [Spree::MaintenanceTaskRun]+ # @return [Spree::ServiceModule::Base::Result] the run+ def call(run:)+ # Locked so the status read here is still the status when it is+ # written: the runner may finish the run in between, and a finished+ # run overwritten with `cancelling` would stay active for good.+ run.with_lock do+ return failure(run, not_cancelable_error(run)) unless run.active?++ # A running run has a worker mid-batch, so it, not this service,+ # records that the run stopped.+ if run.running?+ run.update!(status: 'cancelling')+ else+ run.update!(status: 'cancelled', ended_at: Time.current)+ run.publish_event('maintenance_task_run.cancelled')+ end+ end++ success(run.reload)+ end++ private++ def not_cancelable_error(run)+ build_error("a run with status #{run.status} cannot be cancelled")+ end++ def build_error(message)+ ActiveModel::Errors.new(Spree::MaintenanceTaskRun.new).tap { |errors| errors.add(:base, message) }+ end+ end+ end+enddiff --git a/spree/core/app/services/spree/maintenance_tasks/start.rb b/spree/core/app/services/spree/maintenance_tasks/start.rbnew file mode 100644index 0000000000..6086f8626a--- /dev/null+++ b/spree/core/app/services/spree/maintenance_tasks/start.rb@@ -0,0 +1,127 @@+module Spree+ module MaintenanceTasks+ # Creates a run for a registered task and hands it to the runner+ # (docs/plans/6.0-maintenance-tasks.md).+ #+ # Everything that can be known before any work happens is checked here —+ # the task exists, its parameters validate, and no run of the same task+ # is already in flight — so an operator sees a 422+ # rather than a run that dies on its first record.+ class Start+ prepend ::Spree::ServiceModule::Base++ # @param task_name [String] a registered Spree::MaintenanceTask subclass name+ # @param api_type [String] the task's short name, in place of `task_name`+ # — how an API caller names it, so a class name never has to cross+ # the API+ # @param arguments [Hash] task parameters+ # @param dry_run [Boolean] preview mode; only honored by tasks that declare+ # `supports_dry_run`+ # @param initiated_via [String] dashboard / api / cli+ # @param inline [Boolean] run synchronously (seeds, the CLI, the upgrade walk)+ # @return [Spree::ServiceModule::Base::Result] the run+ def call(task_name: nil, api_type: nil, arguments: {}, dry_run: false, admin_user: nil,+ api_key: nil, initiated_via: 'api', inline: false)+ task_class = if api_type.nil?+ Spree::MaintenanceTask.find_registered(task_name)+ else+ Spree::MaintenanceTask.find_by_api_type(api_type)+ end+ return failure(nil, unknown_task_error(api_type || task_name)) if task_class.nil?++ task_name = task_class.name++ arguments = (arguments || {}).stringify_keys+ unknown = arguments.keys - task_class.attribute_names+ return failure(nil, unknown_arguments_error(unknown)) if unknown.any?++ if initiated_via.to_s.in?(%w[api dashboard]) && superseded_step?(task_class, arguments)+ return failure(nil, superseded_error(task_class))+ end++ task = task_class.new(arguments)+ return failure(task, task.errors) unless task.valid?++ active = active_run_for(task_name)+ return failure(active, already_running_error(task_class)) if active++ run = build_run(task_class, arguments, dry_run, admin_user, api_key, initiated_via)+ return failure(run, run.errors) unless run.save++ dispatch(run, inline)++ success(run)+ end++ private++ def build_run(task_class, arguments, dry_run, admin_user, api_key, initiated_via)+ Spree::MaintenanceTaskRun.new(+ task_name: task_class.name,+ status: Spree::MaintenanceTaskRun.default_status,+ arguments: arguments,+ # A task that does not declare dry-run support would ignore the flag+ # and write for real; recording it as a preview would be a lie.+ dry_run: dry_run && task_class.dry_run_supported,+ admin_user: admin_user,+ api_key: api_key,+ initiated_via: initiated_via.to_s+ )+ end++ # The enqueue waits for the transaction so the worker cannot pick the+ # job up before the row it names is visible.+ def dispatch(run, inline)+ if inline+ ActiveRecord.after_all_transactions_commit { Spree::MaintenanceTasks::RunJob.perform_now(run.id, inline: true) }+ else+ Spree::MaintenanceTasks::RunJob.perform_later(run.id)+ end+ end++ # Upgrade steps of a release this installation already completed. The+ # dashboard never offers them; the command line still runs them, since+ # that is where an operator deliberately repeats a step.+ #+ # Refused even when the completed release was assumed rather than+ # recorded. The assumption is right for nearly every store, and for+ # those a repeated conversion damages data; a store that really skipped+ # a release is told to run its steps from the command line.+ def superseded_step?(task_class, arguments)+ Spree::Upgrade.superseded_steps.any? do |step|+ step['task_class'] == task_class.name ||+ (task_class <= Spree::MaintenanceTasks::UpgradeStep && step['id'] == arguments['step_id'])+ end+ end++ # One run per task at a time. Checked rather than locked: two requests+ # can both pass this check, and the runner then cancels the newer run+ # before it does any work (RunJob#duplicate_run?).+ def active_run_for(task_name)+ Spree::MaintenanceTaskRun.active.find_by(task_name: task_name)+ end++ def unknown_task_error(task_name)+ errors_for(:task_name, "#{task_name} is not a registered maintenance task")+ end++ def unknown_arguments_error(names)+ errors_for(:arguments, "the task takes no parameter named #{names.to_sentence}")+ end++ def superseded_error(task_class)+ errors_for(:base, "#{task_class.api_type} belongs to a release this store has already completed")+ end++ def already_running_error(task_class)+ errors_for(:base, "#{task_class.api_type} is already running")+ end++ def errors_for(attribute, message)+ ActiveModel::Errors.new(Spree::MaintenanceTaskRun.new).tap do |errors|+ errors.add(attribute, message)+ end+ end+ end+ end+enddiff --git a/spree/core/app/services/spree/seeds/all.rb b/spree/core/app/services/spree/seeds/all.rbindex 47cf21021d..3a9c251ede 100644--- a/spree/core/app/services/spree/seeds/all.rb+++ b/spree/core/app/services/spree/seeds/all.rb@@ -10,6 +10,8 @@ module Spree# countries gem, and zones are migration-only, so none of them# are seeded.+ fresh_database = Spree::Store.none?+Stores.callSpree::Store.find_each { |store| StoreResources.call(store: store) }# The warehouse, delivery zones and pickup are not seeded: their@@ -18,6 +20,26 @@ module Spree# them from the merchant's answer — at first-run setup, or here# when ADMIN_EMAIL/ADMIN_PASSWORD name an install that skips it.AdminUser.call++ # A database created by today's schema has no historical data to+ # convert, so every upgrade boundary up to this release is already+ # satisfied. Recording that is what keeps a fresh install from+ # being shown a backlog of steps it must never run. Only a database+ # seeded for the first time qualifies: seeding is also a deploy+ # step, and an upgraded store seeded before its upgrade ran still+ # has every step to do.+ stamp_upgrade_boundaries if fresh_database+ end+ end+ end++ private++ def stamp_upgrade_boundaries+ Spree::Upgrade.manifests.each do |manifest|+ Spree::UpgradeRecord.find_or_create_by!(version: manifest['to']) do |record|+ record.source = 'install'+ record.completed_at = Time.currentendendenddiff --git a/spree/core/config/locales/en.yml b/spree/core/config/locales/en.ymlindex deb70a45f9..573ac17521 100644--- a/spree/core/config/locales/en.yml+++ b/spree/core/config/locales/en.yml@@ -1032,6 +1032,7 @@ en:locale_not_supported_by_market: is not offered by the chosen marketlocale_not_supported_by_store: is not supported by this storelocales_not_listed: 'includes locales Spree does not support: %{codes}'+ maintenance_tasks_turned_off: Maintenance tasks are turned off for this installation. Run upgrade steps from the command line with `spree upgrade` (or `bin/rake spree:upgrade`).manual: Manualmarket: Marketme_no_current_user: No admin user authenticated this requestdiff --git a/spree/core/db/migrate/20260813130001_add_capture_method_to_payment_methods.rb b/spree/core/db/migrate/20260813130001_add_capture_method_to_payment_methods.rbindex fff9cfd0fe..4a176486f9 100644--- a/spree/core/db/migrate/20260813130001_add_capture_method_to_payment_methods.rb+++ b/spree/core/db/migrate/20260813130001_add_capture_method_to_payment_methods.rb@@ -10,7 +10,7 @@ class AddCaptureMethodToPaymentMethods < ActiveRecord::Migration[8.1]# from the provider configuration form.## Existing auto_capture values are carried over by- # spree:migrate_capture_methods, never here.+ # the capture_methods maintenance task, never here.def changeadd_column :spree_payment_methods, :capture_method, :stringenddiff --git a/spree/core/db/migrate/20260815000001_create_spree_maintenance_task_runs.rb b/spree/core/db/migrate/20260815000001_create_spree_maintenance_task_runs.rbnew file mode 100644index 0000000000..2955236ec9--- /dev/null+++ b/spree/core/db/migrate/20260815000001_create_spree_maintenance_task_runs.rb@@ -0,0 +1,40 @@+class CreateSpreeMaintenanceTaskRuns < ActiveRecord::Migration[8.1]+ def change+ create_table :spree_maintenance_task_runs do |t|+ t.string :task_name, null: false+ t.string :status, null: false+ t.boolean :dry_run, null: false, default: false++ t.string :cursor+ t.integer :tick_count, null: false, default: 0+ t.integer :tick_total++ t.decimal :time_running, null: false, default: 0.0, precision: 12, scale: 3+ t.datetime :started_at+ t.datetime :ended_at++ t.string :error_class+ t.text :error_message+ t.text :error_backtrace++ t.string :job_id+ t.string :initiated_via, null: false++ t.references :admin_user, null: true+ t.references :api_key, null: true++ if t.respond_to?(:jsonb)+ t.jsonb :arguments+ t.jsonb :tallies+ else+ t.json :arguments+ t.json :tallies+ end++ t.timestamps+ end++ add_index :spree_maintenance_task_runs, [:task_name, :status]+ add_index :spree_maintenance_task_runs, :created_at+ end+enddiff --git a/spree/core/db/migrate/20260816000001_create_spree_upgrade_records.rb b/spree/core/db/migrate/20260816000001_create_spree_upgrade_records.rbnew file mode 100644index 0000000000..8ad1019ff7--- /dev/null+++ b/spree/core/db/migrate/20260816000001_create_spree_upgrade_records.rb@@ -0,0 +1,17 @@+class CreateSpreeUpgradeRecords < ActiveRecord::Migration[8.1]+ def change+ create_table :spree_upgrade_records do |t|+ # The release boundary this installation has completed the data steps+ # for — "5.6" means every manifest up to and including 5.5 → 5.6 is done.+ t.string :version, null: false+ # How we know: `walk` (a successful upgrade walk), `install` (a fresh+ # install, which needs no historical steps) or `manual`.+ t.string :source, null: false+ t.datetime :completed_at, null: false++ t.timestamps+ end++ add_index :spree_upgrade_records, :version, unique: true+ end+enddiff --git a/spree/core/lib/spree/core.rb b/spree/core/lib/spree/core.rbindex 4057b2d7a9..8d5a2a6d20 100644--- a/spree/core/lib/spree/core.rb+++ b/spree/core/lib/spree/core.rb@@ -135,7 +135,8 @@ module Spreestock_reservations: :default,tax_identifiers: :default,data_requests: :default,- payouts: :default+ payouts: :default,+ maintenance_tasks: :default).tap do |queues|# @deprecated The taxons queue was renamed to categories in 6.0; removed in 6.1.queues.define_singleton_method(:taxons) do@@ -455,6 +456,19 @@ module Spreecustom_fieldsend+ # Registered maintenance task class names — the tasks an operator can run+ # from the dashboard, the Admin API or the CLI+ # (docs/plans/6.0-maintenance-tasks.md). Extensions append their own from an+ # initializer:+ #+ # Spree.maintenance_tasks << 'SpreeReviews::MaintenanceTasks::RecountRatings'+ #+ # Class names rather than classes, so registration is safe at initializer+ # time and survives code reloading in development.+ #+ # @return [Array<String, Class>]+ singleton_class.delegate :maintenance_tasks, :maintenance_tasks=, to: :spree_config+# Registry mapping a numbered resource to the generator that produces its# document numbers. With no entry, the store's `document_number_format`# preference picks between the sequential and random strategies.@@ -644,6 +658,7 @@ require 'spree/core/version'require 'spree/core/number_generator'require 'spree/number_generators/registry'require 'spree/migrations'+require 'spree/upgrade'require 'spree/validators'require 'spree/core/engine'diff --git a/spree/core/lib/spree/core/configuration.rb b/spree/core/lib/spree/core/configuration.rbindex 0ecf17c583..7e388a1adf 100644--- a/spree/core/lib/spree/core/configuration.rb+++ b/spree/core/lib/spree/core/configuration.rb@@ -195,6 +195,12 @@ module Spree# importspreference :large_import_threshold, :integer, default: 500, env: 'SPREE_LARGE_IMPORT_THRESHOLD' # imports with more rows than this skip per-row UI broadcasts and use bulk processing+ # maintenance tasks+ # Turn off to run upgrade steps only from the command line: the dashboard+ # page and its Admin API endpoints are refused. For hosts where the people+ # holding a store's admin role are not the ones operating the installation,+ # such as a platform serving many merchants from one database.+ preference :maintenance_tasks_dashboard_enabled, :boolean, default: true, env: 'SPREE_MAINTENANCE_TASKS_DASHBOARD_ENABLED'endendenddiff --git a/spree/core/lib/spree/core/engine.rb b/spree/core/lib/spree/core/engine.rbindex 7199d5c9e2..c3eb88a33b 100644--- a/spree/core/lib/spree/core/engine.rb+++ b/spree/core/lib/spree/core/engine.rb@@ -46,6 +46,7 @@ module Spree:admin_agent_tools,:store_agent_tools,:integrations,+ :maintenance_tasks,:number_generators,:subscribers,:store_authentication_strategies,@@ -77,7 +78,8 @@ module Spree# Core's defaults are concatenated in after_initialize below.%i[subscribers actor_classes commission_rules delivery_method_rules seller_requirementsdelivery_rate_providers tax_providers pricing_providers inventory_providers- payout_providers digital_asset_providers delivery_profile_types pickup_point_providers].each do |registry|+ payout_providers digital_asset_providers delivery_profile_types pickup_point_providers+ maintenance_tasks].each do |registry|app.config.spree[registry] = []endapp.config.spree.line_item_comparison_hooks = Set.new@@ -540,6 +542,13 @@ module SpreeRails.application.config.spree.integrations = []+ # Upgrade steps backed by a task class are registered from the manifests+ # that name them, so adding a step never means editing a second list.+ Rails.application.config.spree.maintenance_tasks.concat [+ 'Spree::MaintenanceTasks::UpgradeStep',+ *Spree::Upgrade.steps.filter_map { |step| step['task_class'] }+ ]+Rails.application.config.spree.validators.addresses = [Spree::Addresses::PhoneValidator]diff --git a/spree/core/lib/spree/core/permissions/default_catalog.rb b/spree/core/lib/spree/core/permissions/default_catalog.rbindex 5694feae97..420339f5e3 100644--- a/spree/core/lib/spree/core/permissions/default_catalog.rb+++ b/spree/core/lib/spree/core/permissions/default_catalog.rb@@ -201,6 +201,13 @@ module Spree})catalog.register_scope(:integrations, group: :settings, resources: -> { [Spree::Integration] })+ # Sits with the other sensitive access grants rather than under+ # settings: a task can rewrite any data in the install, so out of the+ # box only the admin role holds it (docs/plans/6.0-maintenance-tasks.md).+ catalog.register_scope(:maintenance_tasks, group: :access, resources: -> {+ [Spree::MaintenanceTaskRun, :maintenance_task]+ })+# The CORS allowlist is a credential as much as a key is: an origin on# it may call the cookie-authenticated refresh endpoint from a browser# and read back any signed-in admin's access token. So it sits withdiff --git a/spree/core/lib/spree/testing_support/factories/maintenance_task_run_factory.rb b/spree/core/lib/spree/testing_support/factories/maintenance_task_run_factory.rbnew file mode 100644index 0000000000..dd883c6293--- /dev/null+++ b/spree/core/lib/spree/testing_support/factories/maintenance_task_run_factory.rb@@ -0,0 +1,7 @@+FactoryBot.define do+ factory :maintenance_task_run, class: 'Spree::MaintenanceTaskRun' do+ task_name { 'Spree::MaintenanceTasks::BackfillOrderMarkets' }+ status { 'enqueued' }+ initiated_via { 'api' }+ end+enddiff --git a/spree/core/lib/spree/upgrade.rb b/spree/core/lib/spree/upgrade.rbnew file mode 100644index 0000000000..079dd6674d--- /dev/null+++ b/spree/core/lib/spree/upgrade.rb@@ -0,0 +1,189 @@+module Spree+ # Reads the upgrade manifests shipped inside spree_core — the list of data+ # steps an installation must run after `db:migrate` for a given release+ # boundary (docs/plans/6.0-maintenance-tasks.md).+ #+ # Extracted from lib/tasks/upgrade.rake so the dashboard and the maintenance+ # task runner can read the same manifests the rake walk does; the rake file+ # keeps the walking and printing.+ module Upgrade+ # The first release whose upgrade steps run as maintenance tasks. Nothing+ # recorded the steps of earlier releases, so the dashboard starts here; the+ # command line still walks every manifest.+ FIRST_TRACKED_RELEASE = '6.0'.freeze++ # Two-segment "5.5" form of the installed Spree version.+ #+ # @return [String]+ def self.installed_minor_version+ Spree.version.split('.').first(2).join('.')+ end++ # Root directory containing N_M_to_O_P/manifest.yml files inside the+ # spree_core gem.+ #+ # @return [String]+ def self.manifests_root+ File.expand_path('upgrades', __dir__)+ end++ # All available manifest directories, parsed into { from:, to:, dir: }.+ # Sorted by `to` ascending, with `from` as a tiebreaker (smallest first)+ # for the rare case where two manifests share a `to` boundary.+ #+ # @return [Array<Hash>]+ def self.available_manifests+ Dir.glob(File.join(manifests_root, '*_to_*')).filter_map do |dir|+ name = File.basename(dir)+ match = name.match(/\A([\d_]+)_to_([\d_]+)\z/)+ next unless match++ { from: match[1].tr('_', '.'), to: match[2].tr('_', '.'), dir: dir }+ end.sort_by { |manifest| version_parts(manifest[:to]) + version_parts(manifest[:from]) }+ end++ # Every manifest with its steps loaded, in walk order. Read once per+ # process: the files ship inside the gem and change only with a deploy.+ #+ # @return [Array<Hash>]+ def self.manifests+ @manifests ||= available_manifests.map do |entry|+ YAML.safe_load_file(File.join(entry[:dir], 'manifest.yml')).freeze+ end.freeze+ end++ # Every step of every manifest, in walk order, each carrying the manifest+ # boundary it belongs to so callers can group without re-reading the files.+ #+ # @return [Array<Hash>]+ def self.steps+ @steps ||= manifests.flat_map do |manifest|+ manifest['steps'].map do |step|+ step.merge('from' => manifest['from'], 'to' => manifest['to'], 'docs' => manifest['docs'])+ end+ end.freeze+ end++ # Whether a step belongs to a release whose runs are recorded, and so has a+ # place in the dashboard's checklist.+ #+ # @param step [Hash] a manifest step+ # @return [Boolean]+ def self.tracked?(step)+ compare(step['to'], FIRST_TRACKED_RELEASE) >= 0+ end++ # The task a step runs: its own class, or the shared runner for a step+ # that names a rake task.+ #+ # @param step [Hash] a manifest step+ # @return [String] a task class name+ def self.task_class_name(step)+ step['task_class'] || 'Spree::MaintenanceTasks::UpgradeStep'+ end++ # The arguments that start a step's task: a rake-backed step is named by+ # its id, so the shared runner knows which rake task to invoke.+ #+ # @param step [Hash] a manifest step+ # @return [Hash]+ def self.task_arguments(step)+ step['task_class'] ? {} : { 'step_id' => step['id'] }+ end++ # @param step_id [String]+ # @return [Hash, nil]+ def self.find_step(step_id)+ return nil if step_id.blank?++ steps.find { |step| step['id'] == step_id.to_s }+ end++ # The boundary this installation has already completed, and therefore the+ # point a pending list starts from.+ #+ # Falls back to the release before the installed one when nothing has been+ # stamped: an installation running 6.0 has, by far most often, come from+ # 5.6, and showing every step of every manifest ever written is worse than+ # showing the one boundary that is almost certainly right. A store that+ # skipped releases runs the earlier steps from the command line, which+ # walks every manifest whatever the boundary.+ #+ # @return [String, nil]+ def self.completed_boundary+ Spree::UpgradeRecord.current_version || previous_boundary+ end++ # The `to` of the manifest immediately below the installed version.+ #+ # @return [String, nil]+ def self.previous_boundary+ boundaries = manifests.map { |manifest| manifest['from'] }.uniq+ boundaries.select { |version| compare(version, installed_minor_version) < 0 }.+ max_by { |version| version_parts(version) }+ end++ # Whether an upgrade applies to this installation at all.+ #+ # False for a store installed fresh at its current version: it has no+ # historical data to convert, so neither the outstanding steps nor the+ # history of past releases describes anything real for it. True again+ # once a later release ships steps it has not run.+ #+ # @return [Boolean]+ def self.relevant?+ !Spree::UpgradeRecord.exists? || Spree::UpgradeRecord.upgraded? || pending_steps.any?+ end++ # Whether a step can run here. An optional step belongs to a gem that may+ # not be installed — a payment gateway, for instance — and is skipped+ # where it is absent rather than offered as work that cannot start.+ #+ # @param step [Hash] a manifest step+ # @return [Boolean]+ def self.available?(step)+ return true unless step['optional']+ return Spree::MaintenanceTask.find_registered(step['task_class']).present? if step['task_class']++ Spree::MaintenanceTask.new.rake_file_defining(step['task']).present?+ end++ # Steps this installation still has to run: every manifest above the+ # boundary it has completed, up to and including the installed version.+ #+ # @return [Array<Hash>]+ def self.pending_steps+ boundary = completed_boundary++ steps.select do |step|+ next false if compare(step['to'], installed_minor_version) > 0+ next false unless available?(step)+ next true if boundary.nil?++ compare(step['from'], boundary) >= 0+ end+ end++ # Steps of manifests below the completed boundary — the ones a fresh or+ # already-upgraded installation does not need. When the boundary was+ # assumed rather than recorded the dashboard says so, and points a store+ # that skipped a release at the command line, which still runs them.+ #+ # @return [Array<Hash>]+ def self.superseded_steps+ boundary = completed_boundary+ return [] if boundary.nil?++ steps.select { |step| compare(step['from'], boundary) < 0 }+ end++ def self.version_parts(version)+ version.split('.').map { |segment| Integer(segment, 10) rescue 0 }+ end++ # Compare two dotted-version strings (returns -1, 0, +1).+ def self.compare(first, second)+ version_parts(first) <=> version_parts(second)+ end+ end+enddiff --git a/spree/core/lib/spree/upgrades/5_6_to_6_0/manifest.yml b/spree/core/lib/spree/upgrades/5_6_to_6_0/manifest.ymlindex 0eb71c543e..8e92077f95 100644--- a/spree/core/lib/spree/upgrades/5_6_to_6_0/manifest.yml+++ b/spree/core/lib/spree/upgrades/5_6_to_6_0/manifest.yml@@ -12,8 +12,15 @@# live in the upgrade doc at docs/developer/upgrades/5.6-to-6.0.mdx.## This manifest is the machine-runnable shape — what `bin/rake spree:upgrade`-# (in production) and `spree upgrade` (in dev) execute. Every step must be a-# rake task and must be idempotent. Re-running the full manifest is safe.+# (in production) and `spree upgrade` (in dev) execute. Every step must be+# idempotent; re-running the full manifest is safe.+#+# Steps name a `task_class` — a Spree::MaintenanceTask that the walk runs+# through the maintenance task runner, so a shell walk and a dashboard run+# leave the same audit record and the same resume behaviour+# (docs/plans/6.0-maintenance-tasks.md). Released manifests keep their `task`+# rake names, which have shipped and may be scripted; the walker runs both+# kinds.---from: "5.6"to: "6.0"@@ -151,7 +158,7 @@ steps:- id: migrate_users_to_customersname: "Move users onto the gem-owned Customer/AdminUser models"- task: "spree:upgrade:migrate_users_to_customers"+ task_class: "Spree::MaintenanceTasks::Upgrade::UsersToCustomers"notes: |Copies the legacy Devise user table (default spree_users) intospree_customers, preserving ids so the renamed customer_id foreign keys@@ -261,7 +268,7 @@ steps:- id: migrate_deliveriesname: "Move tracking numbers onto deliveries"- task: "spree:migrate_deliveries"+ task_class: "Spree::MaintenanceTasks::Upgrade::Deliveries"notes: |Every fulfillment carrying a 5.6 tracking number gets one delivery rowwith that number: the carrier axis (tracking number, carrier, carrier@@ -322,7 +329,7 @@ steps:- id: migrate_promotion_option_value_rulesname: "Rewrite Option Value promotion rules to stable option value ids"- task: "spree:upgrade:migrate_promotion_option_value_rules"+ task_class: "Spree::MaintenanceTasks::Upgrade::PromotionOptionValueRules"notes: |Spree 6.0 stores Option Value promotion rules against Spree::OptionValueids. Upgrades from 5.6 may still carry join-row ids from@@ -365,7 +372,7 @@ steps:- id: migrate_returnsname: "Move returns onto the new returns models"- task: "spree:upgrade:migrate_returns"+ task_class: "Spree::MaintenanceTasks::Upgrade::Returns"notes: |Converts each ReturnAuthorization into a Spree::Return, or aSpree::Exchange when any of its return items named an exchange variant,@@ -494,7 +501,7 @@ steps:- id: backfill_order_coupon_codesname: "Backfill coupon codes on placed orders"- task: "spree:backfill_order_coupon_codes"+ task_class: "Spree::MaintenanceTasks::Upgrade::OrderCouponCodes"notes: |spree_orders gains a coupon_code column in Spree 6, matching carts.Historical placed orders applied coupons only through the promotion@@ -510,7 +517,7 @@ steps:- id: backfill_order_marketsname: "Backfill order markets"- task: "spree:backfill_order_markets"+ task_class: "Spree::MaintenanceTasks::Upgrade::BackfillOrderMarkets"notes: |Market is mandatory in Spree 6. Assigns the store's default market toorders that predate markets. Channel needs no step here — the 5.4→5.5@@ -573,7 +580,7 @@ steps:- id: migrate_capture_methodsname: "Convert payment method auto_capture into capture_method"- task: "spree:migrate_capture_methods"+ task_class: "Spree::MaintenanceTasks::Upgrade::CaptureMethods"notes: |Payment methods say when they charge with a capture_method string(checkout, on_dispatch or manual) rather than an auto_capture boolean,@@ -625,7 +632,7 @@ steps:- id: migrate_stripe_webhook_keysname: "Move Stripe webhook signing secrets onto the gateway"- task: "spree:upgrade:migrate_stripe_webhook_keys"+ task_class: "SpreeStripe::MaintenanceTasks::MigrateWebhookKeys"optional: truenotes: |Only runs when spree_stripe is installed; skipped otherwise.diff --git a/spree/core/lib/tasks/capture_methods_migration.rake b/spree/core/lib/tasks/capture_methods_migration.rakedeleted file mode 100644index 0ecb48874f..0000000000--- a/spree/core/lib/tasks/capture_methods_migration.rake+++ /dev/null@@ -1,30 +0,0 @@-# frozen_string_literal: true--# 5.6 → 6.0 conversion of the per-payment-method auto_capture boolean onto the-# capture_method vocabulary (docs/plans/6.0-store-scoped-configuration.md).-# Idempotent — it only writes rows whose capture_method is still empty, so a-# second run finds nothing to do and an interrupted run resumes for free.-namespace :spree do- desc 'Convert payment method auto_capture booleans into capture_method values'- task migrate_capture_methods: :environment do- batch_size = ENV.fetch('BATCH_SIZE', 5_000).to_i- say = ->(message) { puts message }-- payment_methods = Spree::PaymentMethod.unscoped.where(capture_method: nil)-- # A method that captured on authorization charges at checkout. One that did- # not only recorded "not at checkout" — the old column could not say- # whether dispatch or staff was meant to take the money, and the store's- # own setting is what decided. Leaving those rows empty is what makes them- # keep inheriting it, so only the true case is written here.- count = payment_methods.where(auto_capture: true).- in_batches(of: batch_size).- update_all(capture_method: 'checkout')- say.call "spree_payment_methods.capture_method: #{count} rows auto_capture → checkout"-- remaining = Spree::PaymentMethod.unscoped.where(capture_method: nil, auto_capture: false).count- say.call "spree_payment_methods.capture_method: #{remaining} rows left inheriting the store setting"-- say.call 'migrate_capture_methods done.'- end-enddiff --git a/spree/core/lib/tasks/maintenance_tasks.rake b/spree/core/lib/tasks/maintenance_tasks.rakenew file mode 100644index 0000000000..e54609bbfc--- /dev/null+++ b/spree/core/lib/tasks/maintenance_tasks.rake@@ -0,0 +1,42 @@+# frozen_string_literal: true++# Command-line entry to the same runner the dashboard drives, so a shell run+# is audited exactly like an operator's (docs/plans/6.0-maintenance-tasks.md).+#+# bin/rake "spree:maintenance_tasks:perform[backfill_order_markets]"+# DRY_RUN=1 bin/rake "spree:maintenance_tasks:perform[capture_methods]"+# ARGS='batch_size=200' bin/rake "spree:maintenance_tasks:perform[deliveries]"+namespace :spree do+ namespace :maintenance_tasks do+ desc 'Run a maintenance task synchronously'+ task :perform, [:task_name] => :environment do |_task, args|+ task_name = args[:task_name] || ENV['TASK']+ abort ' Pass a task name: rake "spree:maintenance_tasks:perform[Your::Task]"' if task_name.blank?++ # Either the class name or the short name the dashboard shows.+ lookup = Spree::MaintenanceTask.find_registered(task_name) ? { task_name: task_name } : { api_type: task_name }++ result = Spree::MaintenanceTasks::Start.call(+ **lookup,+ arguments: Spree::MaintenanceTasks::ArgumentParser.parse(ENV['ARGS']),+ dry_run: ENV['DRY_RUN'] == '1',+ initiated_via: 'cli',+ inline: true+ )++ abort " #{result.error}" if result.failure?++ run = result.value.reload+ puts " #{run.task_name}: #{run.status} — #{run.tick_count} processed#{run.dry_run? ? ' (dry run)' : ''}"+ (run.tallies || {}).each { |key, value| puts " #{key}: #{value}" }++ if run.errored?+ puts " #{run.error_class}: #{run.error_message}"+ abort ' The run failed. Fix the cause, then re-run this task.'+ end++ # A refused duplicate or a cancellation did not do the work either.+ abort " The run did not finish (#{run.status})." unless run.succeeded?+ end+ end+enddiff --git a/spree/core/lib/tasks/order_market_backfill.rake b/spree/core/lib/tasks/order_market_backfill.rakedeleted file mode 100644index 3fefcba0d9..0000000000--- a/spree/core/lib/tasks/order_market_backfill.rake+++ /dev/null@@ -1,27 +0,0 @@-# frozen_string_literal: true--# 5.6 → 6.0: market is mandatory on orders in Spree 6. Orders created before-# markets existed carry NULLs — backfill from the store's default market so-# the 6.1 NOT NULL constraint can land. (channel_id has no equivalent task-# here: the 5.4→5.5 manifest's spree:channels:backfill_order_channel_ids-# already covers it on every upgrade path.)-namespace :spree do- desc 'Backfill missing market on orders from the store default market'- task backfill_order_markets: :environment do- batch_size = ENV.fetch('BATCH_SIZE', 5_000).to_i-- Spree::Store.all.find_each do |store|- market_id = store.default_market&.id-- if market_id- count = Spree::Order.unscoped.where(store_id: store.id, market_id: nil).- in_batches(of: batch_size).update_all(market_id: market_id)- puts "store #{store.code}: #{count} orders assigned market #{market_id}" if count.positive?- else- puts "store #{store.code}: no default market — orders left as-is"- end- end-- puts 'backfill_order_markets done. The NOT NULL constraint lands in 6.1.'- end-enddiff --git a/spree/core/lib/tasks/upgrade.rake b/spree/core/lib/tasks/upgrade.rakeindex e29bb96841..12a06dca09 100644--- a/spree/core/lib/tasks/upgrade.rake+++ b/spree/core/lib/tasks/upgrade.rake@@ -33,41 +33,10 @@ namespace :spree doendend+require 'spree/upgrade'+module Spreemodule Upgrade- # Two-segment "5.5" form of the installed Spree version.- def self.installed_minor_version- Spree.version.split('.').first(2).join('.')- end-- # Root directory containing N_M_to_O_P/manifest.yml files inside- # the spree_core gem.- def self.manifests_root- File.expand_path('../spree/upgrades', __dir__)- end-- # All available manifest directories, parsed into { from:, to:, dir: }.- # Sorted by `to` ascending, with `from` as a tiebreaker (smallest first)- # for the rare case where two manifests share a `to` boundary.- def self.available_manifests- Dir.glob(File.join(manifests_root, '*_to_*')).filter_map do |dir|- name = File.basename(dir)- match = name.match(/\A([\d_]+)_to_([\d_]+)\z/)- next unless match-- { from: match[1].tr('_', '.'), to: match[2].tr('_', '.'), dir: dir }- end.sort_by { |m| version_parts(m[:to]) + version_parts(m[:from]) }- end-- def self.version_parts(v)- v.split('.').map { |s| Integer(s, 10) rescue 0 }- end-- # Compare two dotted-version strings (returns -1, 0, +1).- def self.compare(a, b)- version_parts(a) <=> version_parts(b)- end-# The runner is a class (not a method) so individual concerns (selection,# rendering, invocation) stay separable and the plan can be inspected# without execution.@@ -100,13 +69,7 @@ module Spree# Plan mode selects exactly what a real run executes, so a dry run after# bumping the gem lists every backfill the upgrade is about to perform.def eligible_manifests- Spree::Upgrade.available_manifests- .select { |manifest| Spree::Upgrade.compare(manifest[:to], target_version) <= 0 }- .map { |entry| load_manifest_yaml(entry) }- end-- def load_manifest_yaml(entry)- YAML.safe_load_file(File.join(entry[:dir], 'manifest.yml'))+ Spree::Upgrade.manifests.select { |manifest| Spree::Upgrade.compare(manifest['to'], target_version) <= 0 }enddef run_full_walk(manifests)@@ -122,10 +85,22 @@ module Spreeendend+ stamp_completed_boundaries(manifests) unless dry_run+putsputs dry_run ? ' (dry run — nothing executed)' : ' Upgrade tasks complete.'end+ # Records the boundaries this walk finished, so a later dashboard visit+ # shows only what is still outstanding rather than every step of every+ # manifest ever written. A partial walk stamps nothing — `invoke` aborts+ # on a failed step, so reaching here means every step succeeded.+ def stamp_completed_boundaries(manifests)+ manifests.each do |manifest|+ Spree::UpgradeRecord.stamp!(manifest['to'], source: 'walk')+ end+ end+# STEP=<id> looks across every eligible manifest; we need exactly one# match. Multiple matches are likely a manifest bug (two manifests# referencing the same step id) but we surface it rather than picking@@ -162,38 +137,84 @@ module Spreeputsputs " Step #{index}/#{total} [#{step['id']}]"puts " #{step['name']}"- puts " > bin/rake #{step['task']}"+ puts " > #{step_command(step)}"return unless step['notes']step['notes'].each_line { |line| puts " #{line.chomp}" }enddef print_step_complete(step)- puts " ✓ #{step['task']} done."+ puts " ✓ #{step_label(step)} done."end+ def step_label(step)+ step['task_class'] || step['task']+ end++ def step_command(step)+ if step['task_class']+ "bin/rake \"spree:maintenance_tasks:perform[#{step['task_class']}]\""+ else+ "bin/rake #{step['task']}"+ end+ end++ # Both step kinds run through the maintenance task runner, so a shell+ # walk records the same audit rows a dashboard run does: a class-backed+ # step runs its own task, a rake-backed step runs inside UpgradeStep.+ #+ # Returns false when the step was skipped, so the caller can leave the+ # "done" line off a step that never ran.def invoke(step)- task = step.fetch('task')-- # Steps contributed by optional gems (payment gateways, for instance)- # are absent unless that gem is installed. Skipping keeps the upgrade- # runnable on installs that never had the gem, while an install that- # does have it still gets the backfill.- if step['optional'] && !Rake::Task.task_defined?(task)- puts " Skipping #{task} — not installed."- return false+ return false if skip_uninstalled?(step)++ puts " Running #{step_label(step)}..."++ result = Spree::MaintenanceTasks::Start.call(+ task_name: Spree::Upgrade.task_class_name(step),+ arguments: step_arguments(step),+ initiated_via: 'cli',+ inline: true+ )++ abort " #{result.error}" if result.failure?++ run = result.value.reload+ (run.tallies || {}).each { |key, value| puts " #{key}: #{value}" }++ if run.errored?+ puts " #{run.error_class}: #{run.error_message}"+ abort ' Step failed. Fix the cause, then re-run this step.'+ end++ # Anything short of success — cancelled or still running — means+ # the step's data is not converted, and the steps after it depend on it.+ unless run.succeeded?+ puts " The step did not finish (#{run.status})."+ abort ' Re-run this step once it can finish.'end- puts " Running #{task}..."+ true+ end++ # A rake-backed step is named by id; a class-backed step that reads+ # environment variables gets the ones the operator exported, so+ # `CONFIRM_NO_PEPPER=true bin/rake spree:upgrade` reaches it.+ def step_arguments(step)+ return Spree::Upgrade.task_arguments(step) unless step['task_class']++ task_class = Spree::MaintenanceTask.find_registered(step['task_class'])+ task_class.respond_to?(:arguments_from_environment) ? task_class.arguments_from_environment : {}+ end++ # Steps contributed by optional gems (payment gateways, for instance)+ # are absent unless that gem is installed. Skipping keeps the upgrade+ # runnable on installs that never had the gem, while an install that+ # does have it still gets the backfill.+ def skip_uninstalled?(step)+ return false if Spree::Upgrade.available?(step)- # Rake caches invoked tasks in-process; explicit reenable lets a- # single `rake spree:upgrade` run re-invoke aggregators that share- # subtasks across multiple manifests (e.g. two manifests both- # depending on `spree:install:migrations` would otherwise only- # invoke it once).- rake_task = Rake::Task[task]- rake_task.reenable- rake_task.invoke+ puts " Skipping #{step_label(step)} — not installed."trueendenddiff --git a/spree/core/spec/jobs/spree/maintenance_tasks/run_job_spec.rb b/spree/core/spec/jobs/spree/maintenance_tasks/run_job_spec.rbnew file mode 100644index 0000000000..37899699a8--- /dev/null+++ b/spree/core/spec/jobs/spree/maintenance_tasks/run_job_spec.rb@@ -0,0 +1,388 @@+require 'spec_helper'+require 'active_job/continuation/test_helper'++RSpec.describe Spree::MaintenanceTasks::RunJob, type: :job do+ let(:store) { @default_store }++ # A task with no dependencies on the rest of the catalog, so the runner's+ # own behavior is what these examples measure.+ before do+ stub_const('SpecMaintenanceTask', Class.new(Spree::MaintenanceTask) do+ cattr_accessor :processed, default: []+ cattr_accessor :raise_on, default: nil+ # Writes a pause/cancel request onto the row after N records, standing+ # in for an operator clicking the button mid-run.+ cattr_accessor :request_after, default: nil+ cattr_accessor :request_status, default: nil+ cattr_accessor :seconds_per_item, default: nil+ cattr_accessor :statuses_seen, default: []+ cattr_accessor :fail_in, default: nil++ supports_dry_run+ collection_batch_size 2++ attribute :label, :string+ validates :label, presence: true++ def self.name = 'SpecMaintenanceTask'++ def collection = Spree::Product.order(:id)++ def after_complete+ raise ArgumentError, 'complete failed' if self.class.fail_in == :after_complete+ end++ def process(product)+ raise ArgumentError, 'boom' if self.class.raise_on == product.id++ self.class.statuses_seen << run.class.where(id: run.id).pick(:status)+ Timecop.travel(self.class.seconds_per_item.seconds) if self.class.seconds_per_item++ return tally(:would_update) if dry_run?++ self.class.processed << product.id+ tally(:updated)++ if self.class.request_after && self.class.processed.size == self.class.request_after+ run.class.where(id: run.id).update_all(status: self.class.request_status)+ end+ end+ end)++ SpecMaintenanceTask.processed = []+ SpecMaintenanceTask.raise_on = nil+ SpecMaintenanceTask.request_after = nil+ SpecMaintenanceTask.request_status = nil+ SpecMaintenanceTask.seconds_per_item = nil+ SpecMaintenanceTask.statuses_seen = []+ SpecMaintenanceTask.fail_in = nil+ Spree.maintenance_tasks << 'SpecMaintenanceTask'+ end++ after { Spree.maintenance_tasks.delete('SpecMaintenanceTask') }++ def start_run(**overrides)+ Spree::MaintenanceTasks::Start.call(+ task_name: 'SpecMaintenanceTask',+ arguments: { 'label' => 'x' },+ initiated_via: 'api',+ **overrides+ ).value+ end++ describe 'a successful run' do+ let!(:products) { create_list(:product, 3, store: store) }++ it 'processes every record and succeeds' do+ run = start_run+ described_class.perform_now(run.id)++ expect(SpecMaintenanceTask.processed).to match_array(products.map(&:id))+ expect(run.reload).to be_succeeded+ end++ it 'records progress and the task tallies' do+ run = start_run+ described_class.perform_now(run.id)++ expect(run.reload.tick_count).to eq(3)+ expect(run.tick_total).to eq(3)+ expect(run.tallies['updated']).to eq(3)+ end++ it 'stamps the cursor so a resume would not repeat work' do+ run = start_run+ described_class.perform_now(run.id)++ expect(run.reload.cursor).to eq(products.max_by(&:id).id.to_s)+ end++ it 'records when it started and ended' do+ run = start_run+ described_class.perform_now(run.id)++ expect(run.reload.started_at).to be_present+ expect(run.ended_at).to be_present+ end+ end++ describe 'dry run' do+ let!(:products) { create_list(:product, 2, store: store) }++ it 'reports what it would do without doing it' do+ run = start_run(dry_run: true)+ described_class.perform_now(run.id)++ expect(SpecMaintenanceTask.processed).to be_empty+ expect(run.reload.tallies['would_update']).to eq(2)+ expect(run).to be_succeeded+ end+ end++ describe 'failure' do+ let!(:products) { create_list(:product, 2, store: store) }++ before { SpecMaintenanceTask.raise_on = Spree::Product.order(:id).first.id }++ it 'records the error on the run instead of raising' do+ run = start_run++ expect { described_class.perform_now(run.id) }.not_to raise_error++ expect(run.reload).to be_errored+ expect(run.error_class).to eq('ArgumentError')+ expect(run.error_message).to eq('boom')+ end+ end++ # The Cancel service writes the request onto the row and the runner+ # observes it at its next checkpoint. This example writes the same column+ # the service does, from inside the task, so the request lands mid-walk+ # exactly as an operator's would.+ describe 'operator cancel' do+ let!(:products) { create_list(:product, 4, store: store) }++ before { SpecMaintenanceTask.request_after = 2 }++ it 'stops for good' do+ run = start_run+ SpecMaintenanceTask.request_status = 'cancelling'++ described_class.perform_now(run.id)++ expect(run.reload).to be_cancelled+ expect(run.ended_at).to be_present+ expect(SpecMaintenanceTask.processed.size).to eq(2)+ end+ end++ # A worker that stops mid-run leaves the run `running` and its job back in+ # the queue. An operator who clicks Cancel in that gap writes the request,+ # and the re-queued job is the only thing left to answer it.+ describe 'a request written while the job waited in the queue' do+ let!(:products) { create_list(:product, 2, store: store) }++ it 'settles cancelling as cancelled without doing more work' do+ run = create(:maintenance_task_run, task_name: 'SpecMaintenanceTask', arguments: { 'label' => 'x' },+ status: 'cancelling', started_at: 1.minute.ago)++ described_class.perform_now(run.id)++ expect(run.reload).to be_cancelled+ expect(SpecMaintenanceTask.processed).to be_empty+ end+ end++ # A deploy can remove a parameter while a run waits; the run must fail+ # where an operator sees it rather than stay queued and block the task.+ describe 'arguments the task no longer accepts' do+ it 'fails the run instead of leaving it queued' do+ run = create(:maintenance_task_run, task_name: 'SpecMaintenanceTask',+ arguments: { 'label' => 'x', 'removed' => '1' })++ expect { described_class.perform_now(run.id) }.not_to raise_error++ expect(run.reload).to be_errored+ expect(run.error_class).to eq('ActiveModel::UnknownAttributeError')+ expect(run).not_to be_active+ end+ end++ # Two requests can both pass Start's one-run-per-task check before either+ # row is saved.+ describe 'two runs of one task created together' do+ let!(:products) { create_list(:product, 2, store: store) }++ it 'cancels the newer one before it does any work' do+ older = create(:maintenance_task_run, task_name: 'SpecMaintenanceTask', arguments: { 'label' => 'x' })+ newer = create(:maintenance_task_run, task_name: 'SpecMaintenanceTask', arguments: { 'label' => 'x' })++ described_class.perform_now(newer.id)+ described_class.perform_now(older.id)++ expect(newer.reload).to be_cancelled+ expect(newer.error_class).to eq('Spree::MaintenanceTasks::AlreadyRunning')+ expect(older.reload).to be_succeeded+ expect(SpecMaintenanceTask.processed).to match_array(products.map(&:id))+ end+ end++ # Ctrl-C or a deploy stopping a command-line upgrade: no job was queued,+ # so a run left `running` would block every later run of its task.+ describe 'an inline run stopped by a signal' do+ let!(:products) { create_list(:product, 2, store: store) }++ it 'is recorded as failed before the signal carries on' do+ run = start_run+ allow_any_instance_of(SpecMaintenanceTask).to receive(:process).and_raise(Interrupt)++ expect { described_class.perform_now(run.id, inline: true) }.to raise_error(Interrupt)++ expect(run.reload).to be_errored+ expect(run).not_to be_active+ end+ end++ describe 'a task removed from the registry' do+ it 'fails the run rather than retrying forever' do+ run = start_run+ Spree.maintenance_tasks.delete('SpecMaintenanceTask')++ described_class.perform_now(run.id)++ expect(run.reload).to be_errored+ expect(run.error_class).to eq('Spree::MaintenanceTasks::TaskNotRegistered')+ end+ end++ describe 'running time' do+ let!(:products) { create_list(:product, 6, store: store) }++ after { Timecop.return }++ it 'adds each batch once rather than compounding the total' do+ Timecop.freeze+ SpecMaintenanceTask.seconds_per_item = 5+ run = start_run++ described_class.perform_now(run.id)++ expect(run.reload.time_running.to_f).to be_within(1).of(30)+ end+ end++ describe 'batch fetching' do+ let!(:products) { create_list(:product, 3, store: store) }++ it 'never loads the whole collection to see whether it is empty' do+ unbounded = []+ callback = lambda do |*, payload|+ sql = payload[:sql]+ unbounded << sql if sql.include?(Spree::Product.table_name) && sql.start_with?('SELECT') && !sql.include?('LIMIT') && !sql.include?('COUNT')+ end++ run = start_run+ ActiveSupport::Notifications.subscribed(callback, 'sql.active_record') { described_class.perform_now(run.id) }++ expect(unbounded).to be_empty+ end+ end++ describe 'a callback that fails' do+ let!(:products) { create_list(:product, 2, store: store) }++ %i[after_complete].each do |callback|+ it "records a failing #{callback} as an error instead of retrying" do+ SpecMaintenanceTask.fail_in = callback+ run = start_run++ expect { described_class.perform_now(run.id) }.not_to raise_error++ expect(run.reload).to be_errored+ expect(run.error_message).to end_with('failed')+ end+ end+ end++ describe 'a run marked cancelled while it works' do+ let!(:products) { create_list(:product, 4, store: store) }++ it 'stops instead of carrying on and overwriting the cancellation' do+ SpecMaintenanceTask.request_after = 2+ SpecMaintenanceTask.request_status = 'cancelled'+ run = start_run++ described_class.perform_now(run.id)++ expect(run.reload).to be_cancelled+ expect(SpecMaintenanceTask.processed.size).to eq(2)+ end++ # The last checkpoint has passed, so only the final status write can+ # still see the request.+ it 'keeps a cancellation that arrives while the run finishes' do+ run = start_run+ allow_any_instance_of(SpecMaintenanceTask).to receive(:after_complete) do+ Spree::MaintenanceTaskRun.where(id: run.id).update_all(status: 'cancelling')+ end++ described_class.perform_now(run.id)++ expect(run.reload).to be_cancelled+ end+ end++ describe 'an inline run' do+ let!(:products) { create_list(:product, 4, store: store) }++ it 'finishes in one go instead of handing the rest to a worker' do+ stub_const('Spree::MaintenanceTask::MAX_RUN_TIME', 0.seconds)+ run = start_run(inline: true)++ expect(run.reload).to be_succeeded+ expect(SpecMaintenanceTask.processed.size).to eq(4)+ end+ end++ describe 'interruption and resume' do+ include ActiveJob::Continuation::TestHelper++ let!(:products) { create_list(:product, 4, store: store) }++ around do |example|+ original = ActiveJob::Base.queue_adapter+ ActiveJob::Base.queue_adapter = :test+ example.run+ ensure+ ActiveJob::Base.queue_adapter = original+ end++ it 'resumes from the cursor instead of restarting the walk' do+ run = start_run+ all_ids = Spree::Product.order(:id).pluck(:id)+ first_batch_cursor = all_ids.first(2).last.to_s++ described_class.perform_later(run.id)++ # Interrupted at the checkpoint after the first batch. The test adapter+ # drains the retry inside the same call, so what this proves is not that+ # the run stopped — it is that the second execution picked up from the+ # cursor rather than from the beginning.+ interrupt_job_during_step(described_class, :process_collection, cursor: first_batch_cursor) do+ perform_enqueued_jobs+ end++ expect(SpecMaintenanceTask.processed).to eq(all_ids)+ expect(run.reload).to be_succeeded+ expect(run.tick_count).to eq(4)+ end++ it 'reports itself running again once it resumes after its time slice' do+ stub_const('Spree::MaintenanceTask::MAX_RUN_TIME', 0.seconds)+ run = start_run++ described_class.perform_later(run.id)+ # Each execution processes one batch and re-queues the next.+ 5.times { perform_enqueued_jobs if enqueued_jobs.any? }++ expect(run.reload).to be_succeeded+ expect(SpecMaintenanceTask.statuses_seen.uniq).to eq(['running'])+ end++ it 'does not reprocess records that were already applied' do+ run = start_run+ all_ids = Spree::Product.order(:id).pluck(:id)++ described_class.perform_later(run.id)++ interrupt_job_during_step(described_class, :process_collection, cursor: all_ids.first(2).last.to_s) do+ perform_enqueued_jobs+ end++ # Each id appears exactly once: the resumed execution re-read nothing the+ # interrupted one had finished.+ expect(SpecMaintenanceTask.processed).to eq(SpecMaintenanceTask.processed.uniq)+ expect(SpecMaintenanceTask.processed.size).to eq(all_ids.size)+ end+ end+enddiff --git a/spree/core/spec/lib/tasks/maintenance_tasks_spec.rb b/spree/core/spec/lib/tasks/maintenance_tasks_spec.rbnew file mode 100644index 0000000000..a8641f0153--- /dev/null+++ b/spree/core/spec/lib/tasks/maintenance_tasks_spec.rb@@ -0,0 +1,50 @@+require 'spec_helper'+require 'rake'++RSpec.describe 'spree:maintenance_tasks rake tasks' do+ let(:store) { @default_store }++ before(:all) do+ Rake.application.rake_require('tasks/maintenance_tasks', [Spree::Core::Engine.root.join('lib').to_s])+ Rake::Task.define_task(:environment)+ end++ def run_task(name, *args)+ task = Rake::Task[name]+ task.reenable+ silence_stream($stdout) { task.invoke(*args) }+ end++ describe 'perform' do+ it 'runs the task and records a CLI-initiated run' do+ order = create(:order, store: store)+ order.update_columns(market_id: nil)++ run_task('spree:maintenance_tasks:perform', 'Spree::MaintenanceTasks::Upgrade::BackfillOrderMarkets')++ run = Spree::MaintenanceTaskRun.last+ expect(run.initiated_via).to eq('cli')+ expect(run).to be_succeeded+ expect(order.reload.market_id).to eq(store.default_market.id)+ end++ it 'honors DRY_RUN' do+ order = create(:order, store: store)+ order.update_columns(market_id: nil)+ ENV['DRY_RUN'] = '1'++ run_task('spree:maintenance_tasks:perform', 'Spree::MaintenanceTasks::Upgrade::BackfillOrderMarkets')++ expect(Spree::MaintenanceTaskRun.last).to be_dry_run+ expect(order.reload.market_id).to be_nil+ ensure+ ENV.delete('DRY_RUN')+ end++ it 'aborts on an unknown task rather than failing silently' do+ expect {+ run_task('spree:maintenance_tasks:perform', 'Nope::Task')+ }.to raise_error(SystemExit)+ end+ end+enddiff --git a/spree/core/spec/lib/tasks/six_zero_data_migrations_spec.rb b/spree/core/spec/lib/tasks/six_zero_data_migrations_spec.rbindex e5a5a9cc7e..0e51ea603c 100644--- a/spree/core/spec/lib/tasks/six_zero_data_migrations_spec.rb+++ b/spree/core/spec/lib/tasks/six_zero_data_migrations_spec.rb@@ -9,13 +9,11 @@ describe '6.0 data migration tasks' doload Spree::Core::Engine.root.join('lib', 'tasks', 'typed_adjustments_migration.rake')load Spree::Core::Engine.root.join('lib', 'tasks', 'carts_migration.rake')load Spree::Core::Engine.root.join('lib', 'tasks', 'products.rake')- load Spree::Core::Engine.root.join('lib', 'tasks', 'order_market_backfill.rake')load Spree::Core::Engine.root.join('lib', 'tasks', 'store_binding_migration.rake')load Spree::Core::Engine.root.join('lib', 'tasks', 'fulfillment_statuses_migration.rake')load Spree::Core::Engine.root.join('lib', 'tasks', 'deliveries_migration.rake')load Spree::Core::Engine.root.join('lib', 'tasks', 'tax_zones_migration.rake')load Spree::Core::Engine.root.join('lib', 'tasks', 'markets.rake')- load Spree::Core::Engine.root.join('lib', 'tasks', 'capture_methods_migration.rake')load Spree::Core::Engine.root.join('lib', 'tasks', 'typed_stock_movements_migration.rake')end@@ -631,17 +629,6 @@ describe '6.0 data migration tasks' doendend- describe 'spree:backfill_order_markets' do- it 'assigns the store default market to orders missing one' do- order = create(:order, store: store)- order.update_columns(market_id: nil)-- run_task('spree:backfill_order_markets')-- expect(order.reload.market_id).to eq(store.default_market.id)- end- end-describe 'spree:product_types:backfill' doit 'assigns store-less product types to the default store' doproduct_type = Spree::ProductType.create!(name: "Orphan #{Time.current.to_f}")@@ -778,37 +765,6 @@ describe '6.0 data migration tasks' doendend- describe 'spree:migrate_capture_methods' do- it 'converts capture-on-authorization into charging at checkout' do- payment_method = create(:payment_method, store: store)- payment_method.update_columns(auto_capture: true, capture_method: nil)-- run_task('spree:migrate_capture_methods')-- expect(payment_method.reload.capture_method).to eq('checkout')- end-- # The boolean only recorded "not at checkout"; it could not say whether- # dispatch or staff was meant to charge, so the store keeps deciding.- it 'leaves a method that did not capture on authorization inheriting' do- payment_method = create(:payment_method, store: store)- payment_method.update_columns(auto_capture: false, capture_method: nil)-- run_task('spree:migrate_capture_methods')-- expect(payment_method.reload.capture_method).to be_nil- end-- it 'never overwrites a method that already has a capture method' do- payment_method = create(:payment_method, store: store)- payment_method.update_columns(auto_capture: true, capture_method: 'manual')-- run_task('spree:migrate_capture_methods')-- expect(payment_method.reload.capture_method).to eq('manual')- end- end-describe 'spree:migrate_stock_movements_to_typed_rows' dolet(:stock_location) { create(:stock_location) }let(:variant) { create(:variant) }diff --git a/spree/core/spec/lib/tasks/upgrade_manifest_spec.rb b/spree/core/spec/lib/tasks/upgrade_manifest_spec.rbnew file mode 100644index 0000000000..e5022866d8--- /dev/null+++ b/spree/core/spec/lib/tasks/upgrade_manifest_spec.rb@@ -0,0 +1,276 @@+require 'spec_helper'+require 'rake'+require 'spree/upgrade'++RSpec.describe 'the upgrade manifest' do+ let(:store) { @default_store }++ describe Spree::Upgrade do+ it 'reads every shipped manifest' do+ expect(described_class.manifests).to be_present+ end++ it 'carries the release boundary onto each step' do+ step = described_class.steps.first++ expect(step['from']).to be_present+ expect(step['to']).to be_present+ end++ it 'finds a step by id across manifests' do+ expect(described_class.find_step('migrate_capture_methods')).to be_present+ end++ it 'returns nothing for an unknown id' do+ expect(described_class.find_step('no_such_step')).to be_nil+ end+ end++ describe 'the 5.6 to 6.0 manifest' do+ let(:manifest) do+ Spree::Upgrade.manifests.find { |candidate| candidate['to'] == '6.0' }+ end++ # A one-pass step is a rake task run through UpgradeStep; a step that walks+ # rows is a task class of its own. Never both, so its logic lives in one+ # place.+ it 'names either a rake task or a task class for every step' do+ manifest['steps'].each do |step|+ expect([step['task'], step['task_class']].compact.size).to eq(1), "#{step['id']} must name exactly one"+ end+ end++ it 'names rake tasks the engine defines, except the optional ones' do+ manifest['steps'].select { |step| step['task'] && !step['optional'] }.each do |step|+ expect(Spree::MaintenanceTask.new.rake_file_defining(step['task'])).+ to be_present, "#{step['id']} names #{step['task']}, which no rake file defines"+ end+ end++ # An optional step's task class ships in the gem that owns it, so it is+ # absent here by design — that absence is exactly what makes the walk skip+ # the step instead of failing on an installation without the gem.+ it 'registers every task class it names, except the optional ones' do+ manifest['steps'].select { |step| step['task_class'] && !step['optional'] }.each do |step|+ expect(Spree::MaintenanceTask.find_registered(step['task_class'])).+ to be_present, "#{step['id']} names #{step['task_class']}, which is not registered"+ end+ end++ it 'leaves an optional step to the gem that owns it' do+ optional = manifest['steps'].select { |step| step['optional'] }++ expect(optional).not_to be_empty+ optional.each do |step|+ expect(Spree::MaintenanceTask.find_registered(step['task_class'])).to be_nil+ end+ end++ it 'keeps its steps in dependency order' do+ ids = manifest['steps'].map { |step| step['id'] }++ # Rich text is copied onto rows the customer migration creates, and+ # retyped by the taxon migration — it has to follow both.+ expect(ids.index('migrate_rich_text_to_columns')).+ to be > ids.index('migrate_users_to_customers')+ expect(ids.index('migrate_rich_text_to_columns')).+ to be > ids.index('migrate_taxons_to_categories_and_collections')+ end+ end++ describe 'released manifests' do+ # These names have shipped, so an operator may have scripted them; the+ # walker keeps running rake-backed steps for exactly that reason.+ it 'still name rake tasks' do+ released = Spree::Upgrade.manifests.reject { |manifest| manifest['to'] == '6.0' }++ expect(released).to be_present+ released.each do |manifest|+ expect(manifest['steps'].map { |step| step['task'] }).to all(be_present)+ end+ end+ end++ describe Spree::MaintenanceTasks::UpgradeStep do+ it 'refuses an id no manifest defines' do+ result = Spree::MaintenanceTasks::Start.call(+ task_name: described_class.name,+ arguments: { 'step_id' => 'no_such_step' },+ initiated_via: 'cli'+ )++ expect(result).to be_failure+ expect(result.error.to_s).to include('no upgrade step')+ end++ # Such a step runs as its own class; accepting it here would fail the+ # run at work time instead of refusing it up front.+ it 'refuses the id of a step that has a task class of its own' do+ result = Spree::MaintenanceTasks::Start.call(+ task_name: described_class.name,+ arguments: { 'step_id' => 'migrate_capture_methods' },+ initiated_via: 'cli'+ )++ expect(result).to be_failure+ expect(Spree::MaintenanceTaskRun.count).to be_zero+ end++ it 'runs the rake task the step names' do+ run = Spree::MaintenanceTasks::Start.call(+ task_name: described_class.name,+ arguments: { 'step_id' => 'product_tag_tenants' },+ initiated_via: 'cli',+ inline: true+ )++ expect(run).to be_success+ expect(run.value.reload).to be_succeeded+ end+ end++ describe Spree::MaintenanceTasks::Upgrade::CaptureMethods do+ let!(:payment_method) do+ create(:payment_method, store: store).tap do |method|+ method.update_columns(capture_method: nil, auto_capture: true)+ end+ end++ def run_task(dry_run: false)+ result = Spree::MaintenanceTasks::Start.call(+ task_name: described_class.name, dry_run: dry_run, initiated_via: 'cli', inline: true+ )+ result.value.reload+ end++ it 'converts methods that captured at authorization' do+ run = run_task++ expect(payment_method.reload.capture_method).to eq('checkout')+ expect(run.tallies['converted']).to eq(1)+ end++ it 'reports without writing in a preview' do+ run = run_task(dry_run: true)++ expect(payment_method.reload.capture_method).to be_nil+ expect(run.tallies['would_convert']).to eq(1)+ end++ # The old column could not say whether dispatch or staff was meant to take+ # the money, so those rows keep inheriting the store's setting.+ it 'leaves methods that did not capture at authorization inheriting' do+ other = create(:payment_method, store: store)+ other.update_columns(capture_method: nil, auto_capture: false)++ run = run_task++ expect(other.reload.capture_method).to be_nil+ expect(run.tallies['left_inheriting_store_setting']).to eq(1)+ end++ it 'is idempotent' do+ run_task+ Spree::MaintenanceTaskRun.update_all(status: 'succeeded')++ second = run_task++ expect(second.tick_count).to be_zero+ expect(payment_method.reload.capture_method).to eq('checkout')+ end+ end++ describe Spree::MaintenanceTasks::Upgrade::RakeStep do+ before do+ require 'rake'+ Rake::Task.define_task('spec:aborting_step') { abort 'Set the pepper first.' }+ stub_const('SpecAbortingStep', Class.new(described_class) do+ def self.name = 'SpecAbortingStep'++ runs_rake_task 'spec:aborting_step'+ end)+ Spree.maintenance_tasks << 'SpecAbortingStep'+ end++ after do+ Spree.maintenance_tasks.delete('SpecAbortingStep')+ Rake::Task['spec:aborting_step'].clear+ end++ # Rake bodies stop with `abort`, which is not an ordinary error; left+ # alone it would leave the run marked running for good and the task+ # impossible to start again.+ it 'records a rake body that aborts as a failure' do+ run = nil++ expect do+ run = Spree::MaintenanceTasks::Start.call(task_name: 'SpecAbortingStep', initiated_via: 'cli', inline: true).value+ end.to output.to_stderr++ expect(run.reload).to be_errored+ expect(run.error_message).to eq('Set the pepper first.')+ end+ end++ describe 'the walk' do+ before(:all) do+ require 'rake'+ Rake::Task.define_task(:environment) unless Rake::Task.task_defined?(:environment)+ load Spree::Core::Engine.root.join('lib', 'tasks', 'upgrade.rake')+ end++ # The documented way to re-run one step after fixing the data that stopped+ # it, rather than walking the whole manifest again.+ it 'runs a single step by id and records it' do+ runner = Spree::Upgrade::Runner.new(target_version: '6.0', step_id: 'migrate_capture_methods')++ expect { runner.call }.to change(Spree::MaintenanceTaskRun, :count).by(1)++ expect(Spree::MaintenanceTaskRun.last.task_name).+ to eq('Spree::MaintenanceTasks::Upgrade::CaptureMethods')+ end++ # The gem that owns an optional step is absent here, so the walk has to+ # skip it — an installation that never had the gem would otherwise fail on+ # a step that does not apply to it.+ it 'skips an optional step whose gem is not installed' do+ runner = Spree::Upgrade::Runner.new(target_version: '6.0', step_id: 'migrate_stripe_webhook_keys')++ expect { runner.call }.to output(/Skipping/).to_stdout+ expect(Spree::MaintenanceTaskRun.where(task_name: 'SpreeStripe::MaintenanceTasks::MigrateWebhookKeys')).to be_empty+ end++ # An inline run never slices itself, so anything short of success means+ # the step did not finish; the walk must stop rather than record the+ # release complete on top of it.+ it 'stops when a step did not succeed' do+ allow(Spree::MaintenanceTasks::RunJob).to receive(:perform_now)+ runner = Spree::Upgrade::Runner.new(target_version: '6.0', step_id: 'migrate_capture_methods')++ expect { runner.call }.to raise_error(SystemExit).and output(/did not finish/).to_stdout+ end++ # The manifest notes tell operators to export these; a step's attribute+ # defaults must not overwrite what they exported.+ it 'passes exported variables on to a step that reads them' do+ step = Spree::Upgrade.find_step('migrate_users_to_customers')+ runner = Spree::Upgrade::Runner.new(target_version: '6.0')+ original = ENV.fetch('CONFIRM_NO_PEPPER', nil)+ ENV['CONFIRM_NO_PEPPER'] = 'true'++ expect(runner.send(:step_arguments, step)).to eq('confirm_no_pepper' => 'true')+ ensure+ ENV['CONFIRM_NO_PEPPER'] = original+ end++ it 'records a run for a rake-backed step of a released manifest' do+ runner = Spree::Upgrade::Runner.new(target_version: '5.6', step_id: 'taxon_store_id')++ expect { runner.call }.to change(Spree::MaintenanceTaskRun, :count).by(1)++ run = Spree::MaintenanceTaskRun.last+ expect(run.task_name).to eq('Spree::MaintenanceTasks::UpgradeStep')+ expect(run.arguments['step_id']).to eq('taxon_store_id')+ end+ end+enddiff --git a/spree/core/spec/lib/tasks/upgrade_manifests_spec.rb b/spree/core/spec/lib/tasks/upgrade_manifests_spec.rbindex b6daec846f..6859301f7e 100644--- a/spree/core/spec/lib/tasks/upgrade_manifests_spec.rb+++ b/spree/core/spec/lib/tasks/upgrade_manifests_spec.rb@@ -2,8 +2,8 @@ require 'spec_helper'require 'rake'# Guards the contract `rake spree:upgrade` relies on: every manifest step is-# well-formed, ids are unique, and each required step names a rake task that-# spree_core actually defines. A task added without a manifest entry is caught+# well-formed, ids are unique, and each required step's rake task — named+# directly or wrapped by its task class — is one spree_core actually defines. A task added without a manifest entry is caught# by review; an entry pointing at a renamed or missing task is caught here.describe 'spree:upgrade manifests' domanifests = Dir[Spree::Core::Engine.root.join('lib', 'spree', 'upgrades', '*', 'manifest.yml')].sort@@ -30,11 +30,14 @@ describe 'spree:upgrade manifests' docontext File.basename(File.dirname(path)) dolet(:manifest) { YAML.safe_load_file(path) }- it 'gives every step an id, name and task' do+ it 'gives every step an id, a name and either a task or a task class' domanifest['steps'].each do |step|- expect(step).to include('id', 'name', 'task'), "malformed step: #{step.inspect}"- expect(step.values_at('id', 'name', 'task')).to all(be_a(String).and(match(/\S/))),- "manifest fields must be non-empty strings: #{step.inspect}"+ runner = step.slice('task', 'task_class')++ expect(step).to include('id', 'name'), "malformed step: #{step.inspect}"+ expect(runner.size).to eq(1), "a step names a task or a task class, not both: #{step.inspect}"+ expect(step.values_at('id', 'name', *runner.keys)).to all(be_a(String).and(match(/\S/))),+ "manifest fields must be non-empty strings: #{step.inspect}"endend@@ -44,8 +47,10 @@ describe 'spree:upgrade manifests' doendit 'names a defined rake task for every required step' do+ # A task class wrapping a rake body names that body, which can be+ # renamed out from under it just as a manifest entry can.missing = manifest['steps'].reject { |step| step['optional'] }.- map { |step| step['task'] }.+ filter_map { |step| step['task'] || step['task_class'].constantize.try(:rake_task_name) }.reject { |task| @rake_app.lookup(task) }expect(missing).to be_empty, "manifest references undefined rake tasks: #{missing.join(', ')}"diff --git a/spree/core/spec/lib/tasks/upgrade_spec.rb b/spree/core/spec/lib/tasks/upgrade_spec.rbindex 1b23cfc9f7..ce3467b868 100644--- a/spree/core/spec/lib/tasks/upgrade_spec.rb+++ b/spree/core/spec/lib/tasks/upgrade_spec.rb@@ -65,11 +65,21 @@ describe 'spree:upgrade' doendend- run_upgrade+ # A failing step aborts the walk, and an abort must fail this example+ # rather than end it quietly.+ expect { run_upgrade }.not_to raise_error+ # The rake task each step runs: named by a released manifest, or wrapped+ # by its task class. Collection tasks run no rake task, and an optional+ # step whose gem is absent is skipped.expected_tasks = manifests.select { |manifest| Spree::Upgrade.compare(manifest['to'], '6.0') <= 0 }- .flat_map { |manifest| manifest['steps'].map { |step| step['task'] } }+ .flat_map { |manifest| manifest['steps'] }+ .filter_map do |step|+ next step['task'] if step['task']++ Spree::MaintenanceTask.find_registered(step['task_class'])&.try(:rake_task_name)+ endexpect(invoked_tasks).to eq(expected_tasks)endenddiff --git a/spree/core/spec/maintenance_tasks/spree/maintenance_tasks/upgrade/backfill_order_markets_spec.rb b/spree/core/spec/maintenance_tasks/spree/maintenance_tasks/upgrade/backfill_order_markets_spec.rbnew file mode 100644index 0000000000..ccf7519334--- /dev/null+++ b/spree/core/spec/maintenance_tasks/spree/maintenance_tasks/upgrade/backfill_order_markets_spec.rb@@ -0,0 +1,74 @@+require 'spec_helper'++RSpec.describe Spree::MaintenanceTasks::Upgrade::BackfillOrderMarkets do+ let(:store) { @default_store }++ def run_task(dry_run: false)+ result = Spree::MaintenanceTasks::Start.call(task_name: described_class.name,+ dry_run: dry_run, initiated_via: 'cli')+ Spree::MaintenanceTasks::RunJob.perform_now(result.value.id)+ result.value.reload+ end++ it 'assigns each order its own store default market' do+ order = create(:order, store: store)+ order.update_columns(market_id: nil)++ run = run_task++ expect(order.reload.market_id).to eq(store.default_market.id)+ expect(run).to be_succeeded+ expect(run.tallies['updated']).to eq(1)+ end++ it 'leaves orders that already have a market alone' do+ order = create(:order, store: store)+ original_market_id = order.market_id++ run_task++ expect(order.reload.market_id).to eq(original_market_id)+ end++ # Re-running the manifest step is expected: the second pass has nothing left+ # to find, because assigned orders drop out of the collection.+ it 'is idempotent' do+ order = create(:order, store: store)+ order.update_columns(market_id: nil)+ run_task++ Spree::MaintenanceTaskRun.last.update!(status: 'succeeded')+ second = run_task++ expect(second.tick_count).to be_zero+ expect(order.reload.market_id).to eq(store.default_market.id)+ end++ describe 'dry run' do+ it 'reports what it would change without writing' do+ order = create(:order, store: store)+ order.update_columns(market_id: nil)++ run = run_task(dry_run: true)++ expect(order.reload.market_id).to be_nil+ expect(run.tallies['would_update']).to eq(1)+ end+ end++ describe 'a store with no default market' do+ # Failing the run would strand every other store's orders behind a store+ # that has nothing to assign.+ it 'counts the orders it skipped and finishes' do+ order = create(:order, store: store)+ order.update_columns(market_id: nil)+ allow_any_instance_of(Spree::Store).to receive(:default_market).and_return(nil)++ run = run_task++ expect(run).to be_succeeded+ expect(run.tallies['skipped_no_default_market']).to eq(1)+ expect(order.reload.market_id).to be_nil+ end+ end+enddiff --git a/spree/core/spec/maintenance_tasks/spree/maintenance_tasks/upgrade/capture_methods_spec.rb b/spree/core/spec/maintenance_tasks/spree/maintenance_tasks/upgrade/capture_methods_spec.rbnew file mode 100644index 0000000000..08a5535875--- /dev/null+++ b/spree/core/spec/maintenance_tasks/spree/maintenance_tasks/upgrade/capture_methods_spec.rb@@ -0,0 +1,42 @@+require 'spec_helper'++RSpec.describe Spree::MaintenanceTasks::Upgrade::CaptureMethods do+ let(:store) { @default_store }++ def run_task+ result = Spree::MaintenanceTasks::Start.call(task_name: described_class.name, initiated_via: 'cli')+ Spree::MaintenanceTasks::RunJob.perform_now(result.value.id)+ result.value.reload+ end++ it 'converts capture-on-authorization into charging at checkout' do+ payment_method = create(:payment_method, store: store)+ payment_method.update_columns(auto_capture: true, capture_method: nil)++ run = run_task++ expect(payment_method.reload.capture_method).to eq('checkout')+ expect(run.tallies['converted']).to eq(1)+ end++ # The boolean only recorded "not at checkout"; it could not say whether+ # dispatch or staff was meant to charge, so the store keeps deciding.+ it 'leaves a method that did not capture on authorization inheriting' do+ payment_method = create(:payment_method, store: store)+ payment_method.update_columns(auto_capture: false, capture_method: nil)++ run = run_task++ expect(payment_method.reload.capture_method).to be_nil+ expect(run.tallies['left_inheriting_store_setting']).to eq(1)+ end++ it 'never overwrites a method that already has a capture method' do+ payment_method = create(:payment_method, store: store)+ payment_method.update_columns(auto_capture: true, capture_method: 'manual')++ run_task++ expect(payment_method.reload.capture_method).to eq('manual')+ end+enddiff --git a/spree/core/spec/models/spree/ability_spec.rb b/spree/core/spec/models/spree/ability_spec.rbindex 4ceac77b0f..9c94624c75 100644--- a/spree/core/spec/models/spree/ability_spec.rb+++ b/spree/core/spec/models/spree/ability_spec.rb@@ -159,6 +159,17 @@ describe Spree::Ability, type: :model doit 'leaves out the keys only another audience may hold' doexpect(staff_ability.permission_keys).not_to include('read_seller_profile', 'read_seller_earnings')end++ # A host whose store admins do not operate the installation runs upgrade+ # steps from the command line only.+ it 'withholds maintenance tasks when the installation turns them off' do+ allow(Spree::Config).to receive(:maintenance_tasks_dashboard_enabled).and_return(false)++ expect(staff_ability).not_to be_able_to :read, Spree::MaintenanceTaskRun+ expect(staff_ability).not_to be_able_to :read, :maintenance_task+ expect(staff_ability.permission_keys).not_to include('read_maintenance_tasks', 'write_maintenance_tasks')+ expect(staff_ability).to be_able_to :manage, Spree::Order+ endendcontext 'with overlapping keys across roles' dodiff --git a/spree/core/spec/models/spree/maintenance_task_run_spec.rb b/spree/core/spec/models/spree/maintenance_task_run_spec.rbnew file mode 100644index 0000000000..0dcabc24ea--- /dev/null+++ b/spree/core/spec/models/spree/maintenance_task_run_spec.rb@@ -0,0 +1,66 @@+require 'spec_helper'++RSpec.describe Spree::MaintenanceTaskRun do+ it 'starts enqueued' do+ expect(create(:maintenance_task_run)).to be_enqueued+ end++ it 'requires a way to tell where it was fired from' do+ run = build(:maintenance_task_run, initiated_via: 'telepathy')++ expect(run).not_to be_valid+ expect(run.errors[:initiated_via]).to be_present+ end++ describe 'lifecycle' do+ it 'counts every non-terminal status as active' do+ described_class::ACTIVE_STATUSES.each do |status|+ expect(build(:maintenance_task_run, status: status)).to be_active+ end+ end++ it 'counts succeeded, errored and cancelled as finished' do+ %w[succeeded errored cancelled].each do |status|+ expect(build(:maintenance_task_run, status: status)).not_to be_active+ end+ end+ end++ describe '#duration' do+ let(:started_at) { 2.hours.ago }++ it 'counts the time since the last checkpoint while a worker holds the run' do+ run = build(:maintenance_task_run, status: 'running', time_running: 30, started_at: started_at,+ updated_at: 10.seconds.ago)++ expect(run.duration).to be_within(1).of(40)+ end++ # A run that waited an hour in the queue after its time slice did 30+ # seconds of work, not an hour and a half.+ it 'stops counting while the run waits in the queue' do+ run = build(:maintenance_task_run, status: 'interrupted', time_running: 30, started_at: started_at,+ updated_at: 1.hour.ago)++ expect(run.duration).to eq(30)+ end+ end++ describe '#task_api_type' do+ it 'is the short name the API identifies the task by' do+ run = build(:maintenance_task_run, task_name: 'Spree::MaintenanceTasks::Upgrade::CaptureMethods')++ expect(run.task_api_type).to eq('capture_methods')+ end++ it 'is shortened the same way for a task that is no longer registered' do+ expect(build(:maintenance_task_run, task_name: 'Gone::OldTask').task_api_type).to eq('old_task')+ end+ end++ describe '#task_class' do+ it 'is nil when the task is no longer registered' do+ expect(build(:maintenance_task_run, task_name: 'Gone::Task').task_class).to be_nil+ end+ end+enddiff --git a/spree/core/spec/models/spree/maintenance_task_spec.rb b/spree/core/spec/models/spree/maintenance_task_spec.rbnew file mode 100644index 0000000000..055d06e6a0--- /dev/null+++ b/spree/core/spec/models/spree/maintenance_task_spec.rb@@ -0,0 +1,86 @@+require 'spec_helper'++RSpec.describe Spree::MaintenanceTask do+ describe 'the registry' do+ after { Spree.maintenance_tasks.delete('RegistrySpecTask') }++ it 'lists the tasks core ships' do+ expect(described_class.registered_classes).to include(Spree::MaintenanceTasks::Upgrade::BackfillOrderMarkets)+ end++ it 'resolves class names registered by an extension' do+ stub_const('RegistrySpecTask', Class.new(described_class) { def self.name = 'RegistrySpecTask' })+ Spree.maintenance_tasks << 'RegistrySpecTask'++ expect(described_class.find_registered('RegistrySpecTask')).to eq(RegistrySpecTask)+ end++ # A class that merely exists is not an operator-runnable task; only+ # registration makes it one.+ it 'does not resolve an unregistered class' do+ stub_const('UnregisteredTask', Class.new(described_class) { def self.name = 'UnregisteredTask' })++ expect(described_class.find_registered('UnregisteredTask')).to be_nil+ end++ it 'ignores a registered name whose class has gone away' do+ Spree.maintenance_tasks << 'RegistrySpecTask'++ expect { described_class.registered_classes }.not_to raise_error+ expect(described_class.find_registered('RegistrySpecTask')).to be_nil+ end+ end++ describe 'short names' do+ it 'names a task by its demodulized, underscored class' do+ expect(Spree::MaintenanceTasks::Upgrade::CaptureMethods.api_type).to eq('capture_methods')+ end++ it 'finds a registered task by its short name but not by its class name' do+ expect(described_class.find_by_api_type('capture_methods')).to eq(Spree::MaintenanceTasks::Upgrade::CaptureMethods)+ expect(described_class.find_by_api_type('Spree::MaintenanceTasks::Upgrade::CaptureMethods')).to be_nil+ end++ # The short name is the only identifier the API has, so two registered+ # tasks sharing one would make one of them unreachable.+ it 'is unique across the tasks core ships' do+ names = described_class.registered_classes.map(&:api_type)++ expect(names.size).to eq(names.uniq.size)+ end+ end++ describe 'declarations' do+ it 'defaults to a batch size' do+ expect(described_class.batch_size).to eq(described_class::DEFAULT_BATCH_SIZE)+ end++ it 'does not support dry run unless the task says so' do+ plain = Class.new(described_class) { def self.name = 'PlainTask' }+ previewable = Class.new(described_class) do+ def self.name = 'PreviewableTask'+ supports_dry_run+ end++ expect(plain.dry_run_supported).to be(false)+ expect(previewable.dry_run_supported).to be(true)+ end++ end++ describe 'the default instance surface' do+ it 'refuses to run without a collection' do+ task = Class.new(described_class) { def self.name = 'NoCollectionDefined' }.new++ expect { task.collection }.to raise_error(NotImplementedError)+ end++ it 'accumulates tallies' do+ task = Class.new(described_class) { def self.name = 'TallyTask' }.new+ task.tally(:updated)+ task.tally(:updated, 3)++ expect(task.tallies['updated']).to eq(4)+ end+ end+enddiff --git a/spree/core/spec/models/spree/upgrade_record_spec.rb b/spree/core/spec/models/spree/upgrade_record_spec.rbnew file mode 100644index 0000000000..86590f072f--- /dev/null+++ b/spree/core/spec/models/spree/upgrade_record_spec.rb@@ -0,0 +1,115 @@+require 'spec_helper'++RSpec.describe Spree::UpgradeRecord do+ it 'records a completed boundary' do+ record = described_class.stamp!('5.6', source: 'walk')++ expect(record.version).to eq('5.6')+ expect(record.completed_at).to be_present+ end++ # A walk that runs twice must not fail on the second pass.+ it 'is idempotent for the same boundary' do+ described_class.stamp!('5.6', source: 'walk')++ expect { described_class.stamp!('5.6', source: 'walk') }.not_to change(described_class, :count)+ end++ it 'refuses a source it does not recognise' do+ record = described_class.new(version: '5.6', source: 'guessing', completed_at: Time.current)++ expect(record).not_to be_valid+ end++ describe '.current_version' do+ it 'is nil before anything is recorded' do+ expect(described_class.current_version).to be_nil+ end++ # Compared as versions, not strings: "5.10" is above "5.9".+ it 'is the highest boundary recorded' do+ described_class.stamp!('5.6', source: 'walk')+ described_class.stamp!('5.10', source: 'walk')+ described_class.stamp!('5.9', source: 'walk')++ expect(described_class.current_version).to eq('5.10')+ end+ end+end++RSpec.describe Spree::Upgrade do+ describe '.pending_steps' do+ # The list would otherwise grow with every release Spree ships, and a store+ # that upgraded last release would be offered steps it must never re-run.+ it 'starts from the boundary already completed' do+ Spree::UpgradeRecord.stamp!('5.6', source: 'walk')++ boundaries = described_class.pending_steps.map { |step| step['from'] }.uniq++ expect(boundaries).to eq(['5.6'])+ end++ it 'offers every manifest to a store far enough behind' do+ Spree::UpgradeRecord.stamp!('5.4', source: 'manual')++ boundaries = described_class.pending_steps.map { |step| step['from'] }.uniq++ expect(boundaries.size).to be > 1+ end++ # A database created by today's schema has no historical data to convert.+ it 'has nothing left for a freshly seeded installation' do+ described_class.manifests.each { |m| Spree::UpgradeRecord.stamp!(m['to'], source: 'install') }++ expect(described_class.pending_steps).to be_empty+ end++ # The Stripe step ships in spree_stripe, which this suite does not load;+ # offered here it could never start, and the checklist never finishes.+ it 'leaves out an optional step whose gem is not installed' do+ Spree::UpgradeRecord.stamp!('5.6', source: 'walk')++ expect(described_class.pending_steps.map { |step| step['id'] }).not_to include('migrate_stripe_webhook_keys')+ end++ it 'never offers steps of a release beyond the installed one' do+ versions = described_class.pending_steps.map { |step| step['to'] }.uniq++ expect(versions).to all(satisfy { |v| described_class.compare(v, described_class.installed_minor_version) <= 0 })+ end+ end++ describe '.relevant?' do+ it 'is false for a store installed fresh with nothing to run' do+ described_class.manifests.each { |m| Spree::UpgradeRecord.stamp!(m['to'], source: 'install') }++ expect(described_class).not_to be_relevant+ end++ # A later release ships steps a store installed fresh still has to run.+ it 'is true for a store installed fresh once a later release has steps' do+ described_class.manifests.each { |m| Spree::UpgradeRecord.stamp!(m['to'], source: 'install') }+ allow(described_class).to receive(:pending_steps).and_return([{ 'id' => 'later_step' }])++ expect(described_class).to be_relevant+ end+ end++ describe 'the assumed boundary' do+ # Without a stamp the starting point is a guess. Showing the single most+ # likely boundary beats showing every step ever written.+ it 'falls back to the release below the installed one' do+ expect(described_class.completed_boundary).to eq('5.6')+ end++ it 'follows what something records' do+ Spree::UpgradeRecord.stamp!('5.6', source: 'walk')++ expect(described_class.completed_boundary).to eq('5.6')+ end++ it 'counts the steps it is leaving out' do+ expect(described_class.superseded_steps).not_to be_empty+ end+ end+enddiff --git a/spree/core/spec/services/spree/maintenance_tasks/cancel_spec.rb b/spree/core/spec/services/spree/maintenance_tasks/cancel_spec.rbnew file mode 100644index 0000000000..76f6895e3f--- /dev/null+++ b/spree/core/spec/services/spree/maintenance_tasks/cancel_spec.rb@@ -0,0 +1,81 @@+require 'spec_helper'++# The service records what the operator asked for, and the runner records+# what actually happened.+RSpec.describe Spree::MaintenanceTasks::Cancel do+ before do+ stub_const('CancelSpecTask', Class.new(Spree::MaintenanceTask) do+ def self.name = 'CancelSpecTask'+ def collection = Spree::Product.order(:id)+ def process(product) = nil+ end)+ Spree.maintenance_tasks << 'CancelSpecTask'+ end++ after { Spree.maintenance_tasks.delete('CancelSpecTask') }++ let(:run) { create(:maintenance_task_run, task_name: 'CancelSpecTask', status: status) }++ context 'while the runner is working' do+ let(:status) { 'running' }++ it 'asks the runner to stop for good' do+ expect(described_class.call(run: run).value).to be_cancelling+ end+ end++ context 'before the runner has picked it up' do+ let(:status) { 'enqueued' }++ it 'cancels outright, since no execution will observe the request' do+ result = described_class.call(run: run).value++ expect(result).to be_cancelled+ expect(result.ended_at).to be_present+ end++ it 'publishes the cancellation, since the runner never will' do+ expect(run).to receive(:publish_event).with('maintenance_task_run.cancelled')++ described_class.call(run: run)+ end+ end++ # The runner can finish the run between the caller loading it and the+ # service writing; a finished run marked `cancelling` would stay active.+ context 'when the run finished after it was loaded' do+ let(:status) { 'running' }++ it 'is refused and leaves the outcome alone' do+ run+ Spree::MaintenanceTaskRun.where(id: run.id).update_all(status: 'succeeded')++ expect(described_class.call(run: run)).to be_failure+ expect(run.reload).to be_succeeded+ end+ end++ # The way out when the worker that should answer the first request is+ # gone: the run would otherwise stay active and block its task.+ context 'when already cancelling' do+ let(:status) { 'cancelling' }++ it 'cancels outright' do+ result = described_class.call(run: run).value++ expect(result).to be_cancelled+ expect(result).not_to be_active+ end+ end++ context 'once the run has finished' do+ let(:status) { 'succeeded' }++ it 'is refused' do+ result = described_class.call(run: run)++ expect(result).to be_failure+ expect(result.error.to_s).to include('cannot be cancelled')+ end+ end+enddiff --git a/spree/core/spec/services/spree/maintenance_tasks/start_spec.rb b/spree/core/spec/services/spree/maintenance_tasks/start_spec.rbnew file mode 100644index 0000000000..3d696a58b0--- /dev/null+++ b/spree/core/spec/services/spree/maintenance_tasks/start_spec.rb@@ -0,0 +1,145 @@+require 'spec_helper'++RSpec.describe Spree::MaintenanceTasks::Start do+ let(:store) { @default_store }++ before do+ stub_const('StartSpecTask', Class.new(Spree::MaintenanceTask) do+ supports_dry_run+ def self.name = 'StartSpecTask'+ attribute :label, :string+ validates :label, presence: true+ def collection = Spree::Product.order(:id)+ def process(product) = nil+ end)+ Spree.maintenance_tasks << 'StartSpecTask'+ end++ after { Spree.maintenance_tasks.delete('StartSpecTask') }++ def start(**overrides)+ described_class.call(task_name: 'StartSpecTask', arguments: { 'label' => 'x' }, **overrides)+ end++ it 'creates a run and enqueues the runner' do+ expect { start }.to have_enqueued_job(Spree::MaintenanceTasks::RunJob)++ expect(Spree::MaintenanceTaskRun.last).to be_enqueued+ end++ it 'records who fired it and from where' do+ admin = create(:admin_user)++ run = start(admin_user: admin, initiated_via: 'dashboard').value++ expect(run.admin_user).to eq(admin)+ expect(run.initiated_via).to eq('dashboard')+ end++ it 'finds a task by its short name' do+ run = described_class.call(api_type: 'start_spec_task', arguments: { 'label' => 'x' }).value++ expect(run.task_name).to eq('StartSpecTask')+ end++ it 'does not take a class name as a short name' do+ result = described_class.call(api_type: 'StartSpecTask', arguments: { 'label' => 'x' })++ expect(result).to be_failure+ end++ it 'refuses a task that is not registered' do+ result = described_class.call(task_name: 'Nope::Task')++ expect(result).to be_failure+ expect(result.error.to_s).to include('not a registered maintenance task')+ end++ it 'refuses arguments the task rejects' do+ result = described_class.call(task_name: 'StartSpecTask', arguments: {})++ expect(result).to be_failure+ expect(result.error.to_h[:label]).to be_present+ end++ # Two runs of one task would race each other over the same records, and+ # their cursors would leapfrog.+ # A typo or a stale client must get told which parameter is wrong, and a+ # key naming one of the task's own internals must never reach it.+ it 'refuses an argument the task does not declare' do+ result = described_class.call(task_name: 'StartSpecTask', arguments: { 'label' => 'x', 'run' => 'x' })++ expect(result).to be_failure+ expect(result.error.to_s).to include('no parameter named run')+ expect(Spree::MaintenanceTaskRun.count).to eq(0)+ end++ describe 'an upgrade step from a release already completed' do+ before { Spree::UpgradeRecord.stamp!('6.0', source: 'walk') }++ let(:step) { Spree::Upgrade.find_step('migrate_capture_methods') }++ # Re-running a completed conversion is how an upgrade damages data; the+ # dashboard hides these steps, and the API has to refuse them too.+ it 'is refused from the API and the dashboard' do+ %w[api dashboard].each do |initiated_via|+ result = described_class.call(task_name: step['task_class'], initiated_via: initiated_via)++ expect(result).to be_failure, "#{initiated_via} was allowed"+ end+ end++ it 'is refused through the generic step runner too' do+ released = Spree::Upgrade.superseded_steps.find { |candidate| candidate['task'] }+ result = described_class.call(task_name: 'Spree::MaintenanceTasks::UpgradeStep',+ arguments: { 'step_id' => released['id'] }, initiated_via: 'api')++ expect(result).to be_failure+ end++ # The command line is where an operator deliberately re-runs a step.+ it 'stays available from the command line' do+ result = described_class.call(task_name: step['task_class'], initiated_via: 'cli')++ expect(result).to be_success+ end+ end++ it 'refuses a second run while one is in flight' do+ start++ result = start++ expect(result).to be_failure+ expect(result.error.to_s).to include('already running')+ end++ it 'allows a new run once the previous one finished' do+ start+ Spree::MaintenanceTaskRun.last.update!(status: 'succeeded')++ expect(start).to be_success+ end++ describe 'dry run' do+ it 'is recorded when the task supports it' do+ expect(start(dry_run: true).value).to be_dry_run+ end++ # A task that ignores dry_run? writes for real; recording the run as a+ # preview would misrepresent what happened.+ it 'is refused for a task that does not support it' do+ stub_const('NoDryRunTask', Class.new(Spree::MaintenanceTask) do+ def self.name = 'NoDryRunTask'+ def collection = Spree::Product.order(:id)+ def process(product) = nil+ end)+ Spree.maintenance_tasks << 'NoDryRunTask'++ run = described_class.call(task_name: 'NoDryRunTask', dry_run: true).value++ expect(run).not_to be_dry_run+ Spree.maintenance_tasks.delete('NoDryRunTask')+ end+ end+enddiff --git a/spree/core/spec/services/spree/seeds/all_spec.rb b/spree/core/spec/services/spree/seeds/all_spec.rbindex f4651b1038..953c3fab70 100644--- a/spree/core/spec/services/spree/seeds/all_spec.rb+++ b/spree/core/spec/services/spree/seeds/all_spec.rb@@ -7,6 +7,36 @@ RSpec.describe Spree::Seeds::All doexpect { subject }.not_to raise_errorend+ describe 'upgrade records' do+ # A database seeded for the first time was created by today's schema, so+ # no past release has data to convert.+ it 'marks every release complete on a brand new database' do+ allow(Spree::Store).to receive(:none?).and_return(true)++ subject++ expect(Spree::UpgradeRecord.pluck(:source).uniq).to eq(['install'])+ expect(Spree::UpgradeRecord.pluck(:version)).to match_array(Spree::Upgrade.manifests.map { |manifest| manifest['to'] })+ end++ # Seeding is a common deploy step, and an upgraded store seeded before its+ # upgrade steps ran still has every one of them to do.+ it 'leaves an existing database to the upgrade walk' do+ subject++ expect(Spree::UpgradeRecord).not_to exist+ end++ it 'never rewrites a release the upgrade walk recorded' do+ allow(Spree::Store).to receive(:none?).and_return(true)+ walked = Spree::UpgradeRecord.stamp!(Spree::Upgrade.manifests.first['to'], source: 'walk')++ subject++ expect(walked.reload.source).to eq('walk')+ end+ end+it 'seeds every store' doother_store = create(:store)diff --git a/spree/providers/stripe/app/maintenance_tasks/spree_stripe/maintenance_tasks/migrate_webhook_keys.rb b/spree/providers/stripe/app/maintenance_tasks/spree_stripe/maintenance_tasks/migrate_webhook_keys.rbnew file mode 100644index 0000000000..9c8d04d045--- /dev/null+++ b/spree/providers/stripe/app/maintenance_tasks/spree_stripe/maintenance_tasks/migrate_webhook_keys.rb@@ -0,0 +1,13 @@+module SpreeStripe+ module MaintenanceTasks+ # Moves Stripe webhook signing secrets onto the gateway that uses them.+ #+ # Ships with this gem rather than core, which is what makes the manifest+ # step optional: an installation without spree_stripe has neither the rake+ # task nor this class, and the upgrade walk skips the step rather than+ # failing on it.+ class MigrateWebhookKeys < Spree::MaintenanceTasks::Upgrade::RakeStep+ runs_rake_task 'spree:upgrade:migrate_stripe_webhook_keys'+ end+ end+enddiff --git a/spree/providers/stripe/spec/registers_upgrade_task_spec.rb b/spree/providers/stripe/spec/registers_upgrade_task_spec.rbnew file mode 100644index 0000000000..6d4d8ad7da--- /dev/null+++ b/spree/providers/stripe/spec/registers_upgrade_task_spec.rb@@ -0,0 +1,22 @@+require 'spec_helper'++RSpec.describe 'the Stripe upgrade step' do+ # The manifest marks this step optional because the class ships here rather+ # than in core; an installation with the gem must therefore find it.+ it 'is registered when this gem is loaded' do+ expect(Spree::MaintenanceTask.find_registered('SpreeStripe::MaintenanceTasks::MigrateWebhookKeys')).to be_present+ end++ it 'runs the rake task the manifest names' do+ expect(SpreeStripe::MaintenanceTasks::MigrateWebhookKeys.rake_task_name).+ to eq('spree:upgrade:migrate_stripe_webhook_keys')+ end++ # A web or worker process never loads the Rakefile, so a run started from+ # the dashboard has to find the task in this gem, not only in core.+ it 'finds the rake task outside the command line' do+ path = SpreeStripe::MaintenanceTasks::MigrateWebhookKeys.new.rake_file_defining('spree:upgrade:migrate_stripe_webhook_keys')++ expect(path).to start_with(SpreeStripe::Engine.root.to_s)+ end+end