From 2061d040badd9fbc495c58fa822dd25b6fb9bf16 Mon Sep 17 00:00:00 2001 From: Dmitriy Krainiy Date: Fri, 6 Nov 2026 13:58:33 +0100 Subject: [PATCH 01/18] Added capability map tools and reuse-gate skills searchSprykerCapabilities and getSprykerCapability read the published Spryker capability map (S3 index.json, 24h cache, stale fallback) and add the project's install status from composer.lock. New skills find-existing-capability and spryker-feature-install, wired into the PRD, customization, feature-expert and demo-intake flows. Plugin version 0.9.0. --- .claude-plugin/marketplace.json | 2 +- .../.claude-plugin/plugin.json | 2 +- .../agents/spryker-feature-expert.agent.md | 4 +- .../skills/demo-intake/SKILL.md | 2 + .../skills/find-existing-capability/README.md | 48 +++++ .../skills/find-existing-capability/SKILL.md | 118 ++++++++++++ .../product-requirement-document/SKILL.md | 5 +- .../product-requirement-document/workflow.md | 3 +- .../skills/spryker-customization/README.md | 2 + .../skills/spryker-customization/SKILL.md | 2 + .../references/delegation.md | 2 + .../skills/spryker-feature-install/README.md | 43 +++++ .../skills/spryker-feature-install/SKILL.md | 137 ++++++++++++++ .../Shared/AiDev/AiDevConstants.php | 9 + src/SprykerSdk/Zed/AiDev/AiDevConfig.php | 50 +++++ .../Zed/AiDev/AiDevDependencyProvider.php | 4 + .../AiDev/Business/AiDevBusinessFactory.php | 54 ++++++ .../CapabilityInstallStatusResolver.php | 176 ++++++++++++++++++ ...pabilityInstallStatusResolverInterface.php | 25 +++ .../CapabilityMap/CapabilityMapFinder.php | 165 ++++++++++++++++ .../CapabilityMapFinderInterface.php | 30 +++ .../CapabilityMap/CapabilityMapReader.php | 163 ++++++++++++++++ .../CapabilityMapReaderInterface.php | 31 +++ .../CapabilityMap/CapabilitySearcher.php | 167 +++++++++++++++++ .../CapabilitySearcherInterface.php | 32 ++++ .../CapabilityMap/ComposerLockReader.php | 52 ++++++ .../ComposerLockReaderInterface.php | 20 ++ .../CapabilityMapUnavailableException.php | 16 ++ ...GetSprykerCapabilityAiDevMcpToolPlugin.php | 44 +++++ ...hSprykerCapabilitiesAiDevMcpToolPlugin.php | 45 +++++ .../CapabilityInstallStatusResolverTest.php | 140 ++++++++++++++ .../CapabilityMap/CapabilityMapReaderTest.php | 155 +++++++++++++++ .../CapabilityMapTestDataTrait.php | 85 +++++++++ .../CapabilityMap/CapabilitySearcherTest.php | 126 +++++++++++++ .../CapabilityMap/ComposerLockReaderTest.php | 86 +++++++++ 35 files changed, 2039 insertions(+), 6 deletions(-) create mode 100644 plugins/spryker-ai-dev-sdk/skills/find-existing-capability/README.md create mode 100644 plugins/spryker-ai-dev-sdk/skills/find-existing-capability/SKILL.md create mode 100644 plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/README.md create mode 100644 plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/SKILL.md create mode 100644 src/SprykerSdk/Zed/AiDev/Business/CapabilityMap/CapabilityInstallStatusResolver.php create mode 100644 src/SprykerSdk/Zed/AiDev/Business/CapabilityMap/CapabilityInstallStatusResolverInterface.php create mode 100644 src/SprykerSdk/Zed/AiDev/Business/CapabilityMap/CapabilityMapFinder.php create mode 100644 src/SprykerSdk/Zed/AiDev/Business/CapabilityMap/CapabilityMapFinderInterface.php create mode 100644 src/SprykerSdk/Zed/AiDev/Business/CapabilityMap/CapabilityMapReader.php create mode 100644 src/SprykerSdk/Zed/AiDev/Business/CapabilityMap/CapabilityMapReaderInterface.php create mode 100644 src/SprykerSdk/Zed/AiDev/Business/CapabilityMap/CapabilitySearcher.php create mode 100644 src/SprykerSdk/Zed/AiDev/Business/CapabilityMap/CapabilitySearcherInterface.php create mode 100644 src/SprykerSdk/Zed/AiDev/Business/CapabilityMap/ComposerLockReader.php create mode 100644 src/SprykerSdk/Zed/AiDev/Business/CapabilityMap/ComposerLockReaderInterface.php create mode 100644 src/SprykerSdk/Zed/AiDev/Business/CapabilityMap/Exception/CapabilityMapUnavailableException.php create mode 100644 src/SprykerSdk/Zed/AiDev/Communication/Plugins/AiDevMcpTools/GetSprykerCapabilityAiDevMcpToolPlugin.php create mode 100644 src/SprykerSdk/Zed/AiDev/Communication/Plugins/AiDevMcpTools/SearchSprykerCapabilitiesAiDevMcpToolPlugin.php create mode 100644 tests/SprykerSdkTest/Zed/AiDev/Business/CapabilityMap/CapabilityInstallStatusResolverTest.php create mode 100644 tests/SprykerSdkTest/Zed/AiDev/Business/CapabilityMap/CapabilityMapReaderTest.php create mode 100644 tests/SprykerSdkTest/Zed/AiDev/Business/CapabilityMap/CapabilityMapTestDataTrait.php create mode 100644 tests/SprykerSdkTest/Zed/AiDev/Business/CapabilityMap/CapabilitySearcherTest.php create mode 100644 tests/SprykerSdkTest/Zed/AiDev/Business/CapabilityMap/ComposerLockReaderTest.php diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index d2d9b8d..0f4165b 100644 --- a/.claude-plugin/marketplace.json +++ b/.claude-plugin/marketplace.json @@ -10,7 +10,7 @@ { "name": "spryker-ai-dev-sdk", "description": "Set of setup tools, skills and agents for Spryker project development.", - "version": "0.8.0", + "version": "0.9.0", "author": { "name": "Spryker Systems GmbH", "email": "support@spryker.com" diff --git a/plugins/spryker-ai-dev-sdk/.claude-plugin/plugin.json b/plugins/spryker-ai-dev-sdk/.claude-plugin/plugin.json index e236365..a846f44 100644 --- a/plugins/spryker-ai-dev-sdk/.claude-plugin/plugin.json +++ b/plugins/spryker-ai-dev-sdk/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "spryker-ai-dev-sdk", - "version": "0.8.0", + "version": "0.9.0", "description": "Set of setup tools, skills and agents for Spryker project development. Works with Claude Code and GitHub Copilot.", "author": { "name": "Spryker Systems GmbH", diff --git a/plugins/spryker-ai-dev-sdk/agents/spryker-feature-expert.agent.md b/plugins/spryker-ai-dev-sdk/agents/spryker-feature-expert.agent.md index e6f7862..c1cbcb0 100644 --- a/plugins/spryker-ai-dev-sdk/agents/spryker-feature-expert.agent.md +++ b/plugins/spryker-ai-dev-sdk/agents/spryker-feature-expert.agent.md @@ -56,6 +56,8 @@ When a structured Spryker MCP tool can answer a question, **use it — do not** | Tool | Use For | |------|---------| +| `searchSprykerCapabilities` | **First call for "which module / feature does X?" questions.** Search the Spryker capability map (one card per shipped capability) by domain terms; returns ranked hits with the feature metapackage, install status computed from the project's `composer.lock`, and the card's "Extend, don't duplicate" line. Run several short queries (noun plus synonyms). | +| `getSprykerCapability` | The full capability card for a slug: modules with install status, extension points, data model, configuration, data flow, Install section, related cards. Open the top hits of the search. | | `getSprykerModules` | Discover which modules belong to a feature | | `getSprykerModuleMap` | Module structure: facades, plugins, factories, key classes | | `getTransferStructureByName` | Transfer objects the feature uses | @@ -90,7 +92,7 @@ Spryker transfer XMLs, schema XMLs, and config PHP files are small enough that ` ## Approach 1. **Run the mandatory checklist** above. State its key outputs (applicable primitives, reinvention flags, scope confirmation) at the top of your answer. -2. **Identify the feature / problem class.** Use the `spryker-docs-research` skill to confirm the concept and scope. **For enumerating the modules involved, use `getSprykerModules` (reads project + vendor directly) — not docs.** Docs may list modules that aren't installed in this project. If MCP is unavailable, fall back to `composer.json` / `composer.lock` and direct inspection of `vendor/spryker/` and each project-namespace directory under `src/`. Docs are for *concepts*; project + vendor are for *what's actually here*. +2. **Identify the feature / problem class.** For "which module / feature does X", "does Spryker already do X" and "how do I build X" questions, **start with `searchSprykerCapabilities`** (then `getSprykerCapability` on the top hits) and follow the `find-existing-capability` skill's verdicts: a capability that ships is extended or installed (`spryker-feature-install`), and a hit counts toward the reinvention flags in the checklist above. A miss is not proof of absence; cross-check with docs and `getSprykerModules` before saying Spryker has no X. If the tools are not connected, `find-existing-capability` describes the web fallback. Then use the `spryker-docs-research` skill to confirm the concept and scope. **For enumerating the modules involved, use `getSprykerModules` (reads project + vendor directly) — not docs.** Docs may list modules that aren't installed in this project. If MCP is unavailable, fall back to `composer.json` / `composer.lock` and direct inspection of `vendor/spryker/` and each project-namespace directory under `src/`. Docs are for *concepts*; project + vendor are for *what's actually here*. 3. **Build the explanation at the depth the question requires.** Cover: - What the feature does — capabilities, types, behaviour. - Key concepts and terminology. diff --git a/plugins/spryker-ai-dev-sdk/skills/demo-intake/SKILL.md b/plugins/spryker-ai-dev-sdk/skills/demo-intake/SKILL.md index f63118c..808c570 100644 --- a/plugins/spryker-ai-dev-sdk/skills/demo-intake/SKILL.md +++ b/plugins/spryker-ai-dev-sdk/skills/demo-intake/SKILL.md @@ -101,6 +101,8 @@ work and add customization files that were not requested. A brief that spans cla before anything starts; the adjacent class is never done silently (work-classes.md, "when one request spans several classes"). +When unsure whether the platform already offers a briefing item (*already works* versus customization), the capability map answers it: `find-existing-capability` maps a requirement to what Spryker ships and what the project has installed. Intake itself stays read-only; name the item as a question for the owner skill rather than running that search here. + ## 3. Source fidelity — a gap is reported, never closed Attributes, prices, copy and imagery come from the **source** (the supplied export, the customer's site). diff --git a/plugins/spryker-ai-dev-sdk/skills/find-existing-capability/README.md b/plugins/spryker-ai-dev-sdk/skills/find-existing-capability/README.md new file mode 100644 index 0000000..e82aede --- /dev/null +++ b/plugins/spryker-ai-dev-sdk/skills/find-existing-capability/README.md @@ -0,0 +1,48 @@ +# find-existing-capability + +The **reuse gate** for Spryker feature work: before anything new is designed or built, find out whether Spryker already ships it, and whether the project already has it. + +Agents in Spryker projects tend to build a new module for something a package already provides. Searching `vendor/` only finds what is installed and what you already suspect. This skill searches the **capability map** instead - 590 cards, one per shipped Spryker capability - and reads the project's `composer.lock` to say what is installed, partly installed or missing. + +It is report-only. It recommends; it never installs or edits anything. + +## When it triggers + +At the start of any feature work in a Spryker project: "build / add / implement X", "we need a system for X", "new module for X", scoping a PRD, "is there something in Spryker for X", "extend X", and when a customer requirement list or briefing has to be mapped to what Spryker offers. It is not for changing one already-identified behaviour (that is `spryker-customization` or `spryker-bugfix`). + +## Flow schema + +```mermaid +flowchart TD + A([Feature request / requirement list]) --> B["1 - Capability nouns + synonyms
3-6 short queries per requirement"] + B --> C["2 - searchSprykerCapabilities
one call per query, merge by slug"] + C --> T{"Tool available?"} + T -- "no" --> T1["Start server, ask for /mcp reload
after two failures: web fallback
INDEX.md + card, compare composer.lock
(weaker ranking, say so)"] --> D + T -- "yes" --> D["3 - getSprykerCapability
on the top hits
read What it does, Extend don't duplicate,
Extension points, Install, Related cards"] + D --> V{"4 - Verdict per hit"} + V -- "installed" --> V1["Extend it
extension points + getSprykerModuleMap
then spryker-customization"] + V -- "partially_installed" --> V2["Install the missing part
API packages only if that API is exposed
then spryker-feature-install"] + V -- "not_installed" --> V3["Install the feature, then extend
name + docs guide + composer line
then spryker-feature-install"] + V -- "card status partial" --> V4["Build only the gap
the card says what is missing"] + V -- "no relevant hit" --> V5["Cross-check: docs search,
getSprykerModules, project grep
then building new is allowed"] + V1 --> R + V2 --> R + V3 --> R + V4 --> R + V5 --> R(["5 - Verdict table + Reuse decision block
user decides"]) +``` + +## Tools + +Matched by tool name (server names are install-specific): `searchSprykerCapabilities`, `getSprykerCapability`, `getSprykerModuleMap`, `getSprykerModules`, `searchAlgoliaDocumentation`. Without the MCP server the skill falls back to fetching `INDEX.md` and `.md` from `https://spryker-capability-map.s3.eu-central-1.amazonaws.com/` and comparing the card's packages to `composer.lock` by hand. + +## Output + +A verdict table (requirement, capability and card, verdict, next step) and one **Reuse decision** block per capability: capability, verdict, evidence, next step, and the card link `https://spryker-capability-map.s3.eu-central-1.amazonaws.com/.md`. + +## Design decisions baked in + +- **Reuse before build.** A shipped capability is extended or installed, not rebuilt; a PRD for it reads "configure / extend / install X". +- **A miss is not proof of absence.** A map miss triggers a docs search, a module check and a project grep; "Spryker has no X" is never claimed from the map alone. +- **Cards describe the latest release.** On an older project, the installed code is checked before a card detail is relied on, and `spryker-upgrade` is suggested when the project is behind. +- **Report-only.** Installing is `spryker-feature-install`, building is `spryker-customization`, and the user chooses. diff --git a/plugins/spryker-ai-dev-sdk/skills/find-existing-capability/SKILL.md b/plugins/spryker-ai-dev-sdk/skills/find-existing-capability/SKILL.md new file mode 100644 index 0000000..e0b433c --- /dev/null +++ b/plugins/spryker-ai-dev-sdk/skills/find-existing-capability/SKILL.md @@ -0,0 +1,118 @@ +--- +name: find-existing-capability +description: > + The reuse gate for Spryker feature work. Use at the start of any feature work in a Spryker + project, BEFORE designing or building a new module: "build / add / implement X", "we need a + system for X", "create a new module for X", scoping a PRD, "is there something in Spryker for + X", "does Spryker already have X", "extend X", and when a customer requirement list or briefing + has to be mapped to what Spryker already offers. Searches the Spryker capability map (one card + per shipped capability, with its modules, feature metapackage, extension points and install + guide) with the searchSprykerCapabilities and getSprykerCapability tools, checks what the + project's composer.lock already has, and returns a per-capability verdict: extend it (installed), + install the missing part, install the feature first, build only the gap (partial card), or build + new (no relevant hit). Report-only: it never installs or edits anything; the user decides. +--- + +# Find Existing Capability - the reuse gate + +Before anything new is designed, find out whether Spryker already ships it. Agents in Spryker projects keep building modules for things a package already provides (a project built "budgets" while `PurchasingControl` ships them). Searching `vendor/` only finds what is installed and only what you already suspect; the **capability map** covers every shipped capability, installed or not. + +The map is 590 cards, one per capability: what it does, its modules, its feature metapackage (`spryker-feature/`), public surface, extension points, data model, configuration, data flow, storefront surface, related cards, an "Extend, don't duplicate" line and an Install section. It describes the **latest Spryker release line**. Planned (unreleased) capabilities are not in it; `partial` cards are, and say what is missing. + +**This skill reports and recommends. It never installs, edits or builds anything.** The user decides what happens next. + +## When to run, when to skip + +Run when the work **adds a capability** (a new module, feature, integration or behaviour area) or when the question is "does Spryker already do X". Skip when the request changes one specific, already-identified existing behaviour (fix this plugin, change that label, tweak this price rule) - that is `spryker-customization` or `spryker-bugfix` directly. + +## Required tools + +Match tools by **tool name** (server names vary by install; some clients namespace them as `mcp____`). Both ship with the Spryker tooling MCP server. + +| Tool | Purpose | +|---|---| +| `searchSprykerCapabilities(query, limit = 10)` | Ranked capability search. `query` is space-separated domain terms, 3+ characters each (short terms such as `sso` or `oms` match whole words only). Returns hits with `slug`, `capability`, `status`, `matched`, `installStatus` (`installed`, `partially_installed`, `not_installed`, or `unknown` without `composer.lock`), `features`, `missingPackages`, `missingOptionalPackages` (API packages), `composerRequire`, `extend`, `url`, plus `source` (`stale` flag) and a `note`. | +| `getSprykerCapability(slug)` | The full card: `synonyms`, `features[]`, `modules[]` (package, path, installed, version), `composerRequire` and `sections` ("What it does", "Public surface (entry points)", "Extension points", "Data model", "Extend, don't duplicate", "Install", "Configuration", "Data flow", "Storefront surface", "Related cards"). | +| `getSprykerModuleMap` | Exact classes, facades and plugin interfaces of an installed module. | +| `getSprykerModules` | Which modules the project has, and the exact module names. | +| `searchAlgoliaDocumentation` | Official docs search, for the "no relevant hit" cross-check. | + +A tool result of `{"error": "..."}` is a failure, not an empty result: report it and use the fallback below. + +**If the capability tools are not available** (the Spryker tooling MCP server is not connected): try to start the server the way `product-requirement-document` does - the underlying server backs the local app, so `script -q /dev/null docker/sdk run` (or `up`) brings it up - then ask the user to reload the MCP connection (for example `/mcp`) and wait for confirmation. After a second failed reconnect, use the **web fallback**: + +1. Fetch `https://spryker-capability-map.s3.eu-central-1.amazonaws.com/INDEX.md` with the harness's web fetch tool, or `curl -s`. It has one entry per card with its modules, features and synonyms. +2. Search it for each term and its synonyms yourself; note the candidate slugs. +3. Fetch each candidate card from `https://spryker-capability-map.s3.eu-central-1.amazonaws.com/.md`. +4. Compare the card's `vendor/spryker/` modules and its `spryker-feature/` against the project's `composer.lock` by hand (the built-in file read/search tools). + +Say plainly in the report that you used the fallback and that **ranking is weaker** in that mode (no scoring, no computed install status), so a miss means less. + +## Step 1 - Extract the capability nouns + +From the request, pull the **capability nouns** (what the business calls the thing) and add the **synonyms** a Spryker doc or module would use. Examples: "budgets" also reads "spending limit", "cost center", "purchasing control"; "wishlist" also "shopping list"; "approval" also "workflow", "order confirmation"; "SSO" also "identity provider", "OAuth", "login". + +Several short queries beat one long one. Build 3-6 queries of 1-3 terms each: the main noun, each synonym cluster, and the surface when it matters (`budget`, `spending limit cost center`, `approval company`, `glue checkout`). Skip filler words and terms under 3 characters except well-known acronyms. + +For a requirement list or briefing, do this **per requirement row**, not once for the whole document. + +## Step 2 - Search + +Call `searchSprykerCapabilities` once per query. Merge the hits by `slug` and keep, per slug, which queries hit it and what `matched` says: a hit on `capability` (the title or synonyms) is strong, a hit on `modules` is good, a hit only on `body` is weak and must be judged by reading the card. Matching is stem- and substring-based, so check that the matched term means what you meant: "loyalty points" also hits `service-point` through `point`. Drop such hits instead of reporting them. + +Relay the response's `note` and check `source.stale`: when `true`, the map was served from a stale cache; say so. A search with no hits on the first query is not the end - try the synonyms before moving on. + +## Step 3 - Open the top hits + +Call `getSprykerCapability` for each plausible hit (usually the top 1-3 per requirement). Read, in this order: "What it does" (does it really cover the need), "Extend, don't duplicate", "Extension points", "Install", and "Related cards" (a `[[slug]]` link may be the real match; open it). Check `status`: `shipped` or `partial`. + +## Step 4 - Decide per hit + +One verdict per capability, driven by the card's `status` and the computed `installStatus` (read from the project's `composer.lock`; "installed" means the packages are present, not that the project wired them in - confirm the registered plugins in the project layer before promising a behaviour works today). + +| Condition | Verdict | What to report and propose | +|---|---|---| +| `installed` | **Extend it** | Name the card's extension points and plugin interfaces and its "Extend, don't duplicate" line. Call `getSprykerModuleMap` for the module(s) to get the exact classes. Grep the project namespace for what the project already built on it. Hand the implementation to `spryker-customization` as configure / extend work. | +| `partially_installed` | **Install the missing part** | List `missingPackages` and say whether they matter. API packages (`*-rest-api`, `*-storefront-api`, `*-backend-api`) are listed separately in `missingOptionalPackages` and are needed only when the project exposes that API. If a package that matters is missing, propose installing it through `spryker-feature-install`. | +| `not_installed` | **Install the feature, then extend it** | Propose the feature (name, the docs install guide URL from the card's Install section, the card's `composerRequire` line) via `spryker-feature-install`, then extending it. Do not propose building from scratch. When the card lists **several features**, they are alternatives (each ships some of the card's modules, e.g. `wishlist` and `marketplace-wishlist`) and `composerRequire` names the missing module packages instead: pick the feature that matches the project (marketplace or not, B2B or B2C) from the Install section. | +| `unknown` | **Check by hand** | The project has no readable `composer.lock`. Say so, and compare the card's packages with `composer.json` and `vendor/` yourself. | +| card `status` is `partial` | **Build only the gap** | Show what the card says is missing. Reuse the shipped part (install or extend per the rows above) and scope the new build to the gap only. | +| no relevant hit | **Building new is allowed - after the cross-check** | See below. | + +**A miss is not proof of absence.** Before concluding that Spryker has nothing: run `searchAlgoliaDocumentation` (or the `spryker-docs-research` skill) with the synonyms, check `getSprykerModules` for a module the project already has under a different name, and grep the project namespace. Report "no capability-map hit, no docs hit, no project module" as what you found. **Never claim "Spryker has no X" from the map alone.** + +**One request, several hits.** When two cards cover parts of the request, give each its own verdict and say how they combine. When a hit only partly matches (it does half of what was asked), say which half. + +## Version drift + +The map describes the latest release line. The project may be older. When a capability matters and a module's installed `version` (from the card's `modules[]`) looks old for the feature, read the module's code in `vendor/spryker/` or call `getSprykerModuleMap` before relying on a card detail (an extension point, a Glue resource, a config key). When the project is clearly behind, say so and suggest the `spryker-upgrade` skill instead of working around the gap. + +## Step 5 - Report + +End with a verdict table and one **Reuse decision** block per capability that matters. + +```markdown +| Requirement | Capability (card) | Verdict | Next step | +|---|---|---|---| +| Per-department spending limits | Budgets and cost centers (`purchasing-control`) | not installed - install, then extend | /spryker-feature-install spryker-feature/purchasing-control | +``` + +```markdown +## Reuse decision + +- Capability: +- Verdict: extend (installed) | install missing part | install feature then extend | build only the gap | build new (no relevant hit) +- Evidence: +- Next step: +- Card: https://spryker-capability-map.s3.eu-central-1.amazonaws.com/.md +``` + +State what you did not verify (a version-drift check you skipped, a fallback search, an API package you assumed is not needed). Then stop and let the user choose. A PRD for something that ships is framed as "configure / extend / install X", not "build X". + +## What you do not do + +- Do not install, `composer require`, edit config or write code. Proposals go to `spryker-feature-install` or `spryker-customization` after the user agrees. +- Do not conclude "not shipped" from the map alone, and do not skip the cross-check on a miss. +- Do not trust a card's detail over the installed code when the project's version is old. +- Do not search once with one long sentence; run several short queries. +- Do not treat a `body`-only match as a verdict - open the card and judge it. diff --git a/plugins/spryker-ai-dev-sdk/skills/product-requirement-document/SKILL.md b/plugins/spryker-ai-dev-sdk/skills/product-requirement-document/SKILL.md index 5f09398..18bd61b 100644 --- a/plugins/spryker-ai-dev-sdk/skills/product-requirement-document/SKILL.md +++ b/plugins/spryker-ai-dev-sdk/skills/product-requirement-document/SKILL.md @@ -50,6 +50,7 @@ Default to **narrow and sharp**; expand only where the user asks for detail. Cut **Before any requirement, story, or design, investigate.** Requirements written from memory drift from how Spryker actually works. Do this in three layers — **code first, then docs, then (for existing flows) the running app**: the codebase facts are cheap inline calls that settle most questions outright and tell you exactly what the expensive docs research should target. **Two of the three layers are opt-in — ASK the user before running them** (steps 2 and 3 below). Step 1 (codebase facts) is always done. 1. **Codebase facts — inline, first, using the Spryker tooling MCP server.** Establish against the real install what exists and pin down exact names — this is where the decisive findings usually come from. Match tools by **tool name** (server names vary by install; some clients namespace as `mcp____`): + - `searchSprykerCapabilities` - **the FIRST call, before the module tools below.** Search the Spryker capability map with the feature's nouns and their synonyms (several short queries) to learn whether Spryker already ships this capability, and whether the project has it installed. Open the top hits with `getSprykerCapability`. Follow the `find-existing-capability` skill for the queries, the per-hit verdicts and the fallback when the tool is unavailable. **A PRD for something that ships is framed as "configure / extend / install X", not "build X"**: installed means extend, partially or not installed means install the feature first (`spryker-feature-install`), and only a `partial` card's gap or a miss that survives the docs and module cross-check is "build". - `getSprykerModules` — confirm the module exists and get its exact name. - `getSprykerModuleMap` — the module's API surface: find the **controller + action** behind the feature, the **plugins / extension points** it hooks into, and whether the capability already ships. (For Yves, routes come from `RouteProviderPlugin`s; for Glue, the resource name from a `ResourceRoutePlugin`.) - `getTransferStructureByName` — real field names/types for any transfer a story touches. Never invent transfer fields. @@ -127,7 +128,7 @@ Run the **scenario lint pass** (see the checklist in [gherkin-guide.md](gherkin- ## Critical Requirements ### 1. Research before requirements — code first -Codebase facts (step 1) are not optional and come **first** — module names, transfer fields, controller/actions, and endpoint paths trace to the inline codebase tools (`getSprykerModules`/`getSprykerModuleMap`/`getTransferStructureByName` + `deploy.dev.yml`), never guessed, and they target the docs research that follows. Docs research (step 2) and running-app validation (step 3) are **opt-in — ask the user first**. Docs research, when run, is dispatched to **`spryker-docs-research` subagent(s) with your harness's subagent tool** (parallel subagents with explicit non-overlap boundaries when the feature spans multiple concepts) so documented behavior/actors trace to the merged subagent briefs — with the stated harness fallback (consent, else inline) when subagent dispatch isn't permitted; existing-flow behavior traces to what `spryker-runtime` observed. If the tooling MCP server is down, start it and ask the user to reload the MCP connection before falling back to the built-in file read/search tools. +Codebase facts (step 1) are not optional and come **first** - whether Spryker already ships the capability comes from `searchSprykerCapabilities` (the first call), and module names, transfer fields, controller/actions, and endpoint paths trace to the inline codebase tools (`getSprykerModules`/`getSprykerModuleMap`/`getTransferStructureByName` + `deploy.dev.yml`), never guessed, and they target the docs research that follows. Docs research (step 2) and running-app validation (step 3) are **opt-in — ask the user first**. Docs research, when run, is dispatched to **`spryker-docs-research` subagent(s) with your harness's subagent tool** (parallel subagents with explicit non-overlap boundaries when the feature spans multiple concepts) so documented behavior/actors trace to the merged subagent briefs — with the stated harness fallback (consent, else inline) when subagent dispatch isn't permitted; existing-flow behavior traces to what `spryker-runtime` observed. If the tooling MCP server is down, start it and ask the user to reload the MCP connection before falling back to the built-in file read/search tools. ### 2. Strict actor assignment Every story names one canonical actor from [actors.md](actors.md). One actor per story — if two actors are involved, split the story. @@ -202,7 +203,7 @@ Ask the user at Phase 8 which location: ## Interactive Workflow Checklist -- [ ] Phase 0: Gathered codebase facts inline **first** (`getSprykerModules`/`getSprykerModuleMap`/`getTransferStructureByName`, vendor paths from the module map — never guessed) and formed a hypothesis — started the server + asked the user to reload MCP if the tooling server was down; asked the user whether docs research is needed (and, only if yes, dispatched `spryker-docs-research` as **subagent(s) with your harness's subagent tool**, targeted by the hypothesis, non-overlapping scopes — or used the stated harness fallback: consent, else inline; merged their briefs); asked the user whether to validate existing endpoints/flows against the running app (and ran `spryker-runtime` only if yes); flagged any missing tools +- [ ] Phase 0: Gathered codebase facts inline **first** (`searchSprykerCapabilities` as the very first call - reuse verdict per `find-existing-capability`, PRD framed as configure / extend / install when the capability ships - then `getSprykerModules`/`getSprykerModuleMap`/`getTransferStructureByName`, vendor paths from the module map — never guessed) and formed a hypothesis — started the server + asked the user to reload MCP if the tooling server was down; asked the user whether docs research is needed (and, only if yes, dispatched `spryker-docs-research` as **subagent(s) with your harness's subagent tool**, targeted by the hypothesis, non-overlapping scopes — or used the stated harness fallback: consent, else inline; merged their briefs); asked the user whether to validate existing endpoints/flows against the running app (and ran `spryker-runtime` only if yes); flagged any missing tools - [ ] Phase 3 (start): Asked the pacing question once (per-criterion / per-story / draft-then-review) and honoured it through Phases 3–4 - [ ] Phase 2: Background & Goals approved - [ ] Phase 3: Each story approved at the chosen pacing — every checkpoint that occurred presented the **actor** and the **affected endpoint (URL path, or "no endpoint")** alongside the story, and the user confirmed both diff --git a/plugins/spryker-ai-dev-sdk/skills/product-requirement-document/workflow.md b/plugins/spryker-ai-dev-sdk/skills/product-requirement-document/workflow.md index 885b65e..734b436 100644 --- a/plugins/spryker-ai-dev-sdk/skills/product-requirement-document/workflow.md +++ b/plugins/spryker-ai-dev-sdk/skills/product-requirement-document/workflow.md @@ -15,6 +15,7 @@ Ground everything in real Spryker before drafting — **code first, then docs**: **Step 0.1 — Codebase facts (inline, first, Spryker tooling MCP server)** Establish against the real install what exists and pin exact names — match tools by tool name (server names vary by install): +- `searchSprykerCapabilities` - **first call, before the module tools.** Search the Spryker capability map with the feature's nouns and synonyms (several short queries), then open the top hits with `getSprykerCapability`, to learn whether Spryker already ships the capability and whether the project has it installed. See the `find-existing-capability` skill for queries, per-hit verdicts and the no-MCP fallback. **A PRD for something that ships is framed as "configure / extend / install X", not "build X"** (installed: extend; partially or not installed: install the feature first via `spryker-feature-install`; a `partial` card: only the gap is built). - `getSprykerModules` — exact module name(s). - `getSprykerModuleMap` — controller+action behind the feature, plugins/extension points, whether it already ships. (Yves routes from `RouteProviderPlugin`s; Glue resource from a `ResourceRoutePlugin`.) **Take vendor paths from the map's output — never guess `Business/...` sub-paths.** - `getTransferStructureByName` — real transfer field names/types. Never invent fields. @@ -32,7 +33,7 @@ If the feature modifies or extends an existing flow, ask the user: *"This extend **Step 0.4 — Hold the findings** Keep what you gathered: real module/transfer names always; documented behavior (if researched) and observed behavior (if validated) when applicable. They feed Phases 3–5 directly. Do not invent any of these later. -**CHECKPOINT:** Do not draft requirements until codebase facts (incl. the project-overlap sweep) are gathered, the opt-in questions (docs / running-app validation) have been asked, and any tool gaps are surfaced to the user. +**CHECKPOINT:** Do not draft requirements until codebase facts (incl. the capability-map search and the project-overlap sweep) are gathered, the opt-in questions (docs / running-app validation) have been asked, and any tool gaps are surfaced to the user. ### Phase 1: Initial Requirements Gathering 🔄 INTERACTIVE diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-customization/README.md b/plugins/spryker-ai-dev-sdk/skills/spryker-customization/README.md index dbf85a4..3f09f41 100644 --- a/plugins/spryker-ai-dev-sdk/skills/spryker-customization/README.md +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-customization/README.md @@ -9,6 +9,8 @@ focused work to the `spryker-*` subagents and skills at the points the workflow are fixed up front — a quality bar (PoC or MVP) and which phases run — and user-facing interaction is deliberately compressed into two gates: one consolidated planning round, and the commit. +Work that adds a new capability passes the reuse gate first (`find-existing-capability`): a capability Spryker already ships is extended, and a feature that is not installed is installed through `spryker-feature-install` before any custom code is written. + It **never auto-commits**, never pushes, and never works on the user's current branch. ## When it triggers diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-customization/SKILL.md b/plugins/spryker-ai-dev-sdk/skills/spryker-customization/SKILL.md index d89e7c7..1d2bb19 100644 --- a/plugins/spryker-ai-dev-sdk/skills/spryker-customization/SKILL.md +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-customization/SKILL.md @@ -168,6 +168,8 @@ A short ask ("hide this label") still gets a one-line intake before any edit — ## Step 3: Plan +**Reuse gate - before the solution design, when the work adds a new capability rather than changing an existing one** (a new module, feature or integration area; not a tweak to a behaviour you can already name): run the `find-existing-capability` skill (`/find-existing-capability`, or `/spryker-ai-dev-sdk:find-existing-capability` on a plugin install) on the PRD's capabilities, or reuse its Reuse decision if the PRD step already produced one. A shipped capability is extended, not rebuilt: **installed** means the plan extends it through the card's extension points; **partial** means the plan builds only the gap; **not installed** or **partially installed** means the plan starts with installing the feature through `spryker-feature-install` (after the user agrees), and custom code comes after the feature is in. Only "no relevant hit" after the cross-check lets the plan build from scratch, and the plan says that the check ran. Record the verdict in `decisions.md`. + **Before planning, always invoke `spryker-feature-expert`** for every Spryker domain the PRD touches. The division of labour is **discovery vs confirmation**: - **Discovery is the expert's, never yours.** *Which* mechanism, *which* extension point, *how does feature X work*, *which fields does this transfer have*, *which modules exist* — sweeping questions where the expert's synthesis beats raw grepping (`getTransferStructureByName`, `getInterfaceMethodsByNamespace`, `getSprykerModules`, docs). If the expert's first answer isn't enough, ask a more specific follow-up — don't fall back to exploratory grep of `vendor/spryker/`. diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-customization/references/delegation.md b/plugins/spryker-ai-dev-sdk/skills/spryker-customization/references/delegation.md index c677348..16dd14a 100644 --- a/plugins/spryker-ai-dev-sdk/skills/spryker-customization/references/delegation.md +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-customization/references/delegation.md @@ -29,6 +29,8 @@ These are **skills** (loaded into the main session), not subagents. Invoke each | Skill | When to invoke | |---|---| +| `find-existing-capability` | Step 3, before the solution design - when the work adds a new capability rather than changing an existing one. Searches the Spryker capability map and returns a reuse verdict (extend / install / build the gap / build new). Report-only. | +| `spryker-feature-install` | Step 3 - when the reuse gate says a shipped feature is `not_installed` or `partially_installed` and the user agrees to install it, before any custom code. Installs the feature per its official guide. | | `product-requirement-document` | Step 0c — when the user has no PRD (or wants to create/refresh one) before intake. Creates the business-facing PRD that Step 1 reads. | | `spryker-refresher` | Step 5 — post-change commands (composer dumpautoload, codegen, schema, cache clears, frontend builds, cache warmups). Mandatory; the orchestrator must not run `docker/sdk console` / `docker/sdk cli composer` inline during Step 5. | | `spryker-qa-coverage` | Step 6 (when the QA-thorough phase is on) — expand the AC list + scale envelope into a 5-bucket test plan before invoking the verifier. | diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/README.md b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/README.md new file mode 100644 index 0000000..a95d974 --- /dev/null +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/README.md @@ -0,0 +1,43 @@ +# spryker-feature-install + +Install a Spryker feature into a project **end to end**, from a capability card or a feature name: resolve the feature and its required features, confirm scope, fetch the official install guide, `composer require`, apply the guide's integration steps in the project layer, run codegen and setup, verify, and report what was done and skipped. + +Where `find-existing-capability` decides "install it instead of building it", this skill does the install - always after the user confirms the feature, packages, version constraint and optional integrations. + +## When it triggers + +"Install the X feature", "add `spryker-feature/x`", "integrate feature X", "install the X Glue API", or after `find-existing-capability` proposed an install (`not_installed` / `partially_installed`). + +## Flow schema + +```mermaid +flowchart TD + A([Feature name or capability card]) --> B["1 - Resolve
getSprykerCapability: Install section
feature, requires features, docs guides,
Glue API, Storefront API"] + B --> RQ{"Required features
installed?"} + RQ -- "no" --> RQ1["Offer to install them first
(recursively)"] --> C + RQ -- "yes" --> C + C{"2 - Confirm with the user
feature, packages, version constraint,
optional APIs and demo data, branch"} + C -- "no / change" --> C + C -- "yes" --> D["3 - Fetch the install guide
spryker-docs-research or docs markdown
match the project's release line
build the step checklist"] + D --> E["4 - composer require
docker/sdk cli composer require
conflict: stop and report"] + E --> F["5 - Integration steps, project layer only
config - plugin wiring - transfers - schema
navigation - routes - glossary - data import"] + F --> G["6 - spryker-refresher
codegen, caches, setup commands
+ the guide's own setup commands"] + G --> H["7 - Verify
guide's verify steps - boot-and-verify
spryker-verifier agent"] + H --> R(["8 - Report
installed - done / skipped checklist
follow-ups - unstaged changes"]) +``` + +## Tools + +Matched by tool name: `searchSprykerCapabilities`, `getSprykerCapability`, `searchAlgoliaDocumentation`, `getSprykerModules`, `getSprykerModuleMap`, `getTransferStructureByName`. Skills it hands to: `spryker-docs-research`, `spryker-refresher`, `boot-and-verify`, `project-data` / `data-import`; agents: `spryker-verifier`, `spryker-issue-diagnoser`. + +## Output + +A feature install report: what was installed (packages, versions, required features), the guide followed, the step checklist with `done` / `skipped (reason)`, verification evidence, follow-ups (for example the Glue API integration not done) and the changed files, left unstaged. + +## Design decisions baked in + +- **Confirm before changing.** Nothing is required or edited before the user agrees to the feature, constraint and optional integrations. +- **The guide is the source of truth for steps; the installed code is the source of truth for names.** Identifier spellings are confirmed against `vendor/` (read-only) before they are written. +- **Project layer only.** Never `vendor/`, `src/Generated/` or `src/Orm/`; existing plugin stacks keep their order. +- **No silent gaps.** Every guide step ends done or skipped with a reason; a failing step is diagnosed, not dropped. +- **No destructive commands, no auto-commit.** A rebuild (`docker/sdk up`) or `reset` is reported, not run. diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/SKILL.md b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/SKILL.md new file mode 100644 index 0000000..1e96d04 --- /dev/null +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/SKILL.md @@ -0,0 +1,137 @@ +--- +name: spryker-feature-install +description: > + Install a Spryker feature into the project end to end, from a capability card or a feature name: + resolve the feature metapackage and its required features, confirm scope with the user, fetch the + official install guide, `composer require`, apply the guide's integration steps in the project layer + only (config, dependency-provider plugin wiring, transfers, schema, navigation, routes, glossary, + data import), run codegen and setup, verify, and report done / skipped steps. Use when the user says + "install the X feature", "add spryker-feature/x", "integrate feature X", "install the X Glue API", + or after `find-existing-capability` proposed installing a feature instead of building one. Always + confirms before changing anything; never edits vendor/ or generated code; never auto-commits. +--- + +# Spryker Feature Install + +Take a Spryker feature from "not in the project" to "installed, wired and verified", following the **official install guide** for that feature. The goal is the documented integration, not a lookalike: a feature that ships should be installed, then extended, not rebuilt. + +Typical entry: `find-existing-capability` returned `not_installed` or `partially_installed` for a capability and the user agreed to install it. Also used standalone ("install the Cart feature", "add `spryker-feature/wishlist`"). + +Delegate with your harness's subagent tool; invoke skills by slash command (`/spryker-refresher`, or `/spryker-ai-dev-sdk:spryker-refresher` on a plugin install). **Agent names carry the plugin prefix on a plugin install and the separator differs by harness** (`spryker-ai-dev-sdk:spryker-verifier` or `spryker-ai-dev-sdk/spryker-verifier`); try the bare name only on a setup install, and if it does not resolve retry with your harness's prefixed form (see `../spryker-customization/references/delegation.md`). + +## Tools + +Match tools by **tool name** (server names vary by install; some clients namespace them `mcp____`). + +| Tool | Use | +|---|---| +| `searchSprykerCapabilities`, `getSprykerCapability` | Resolve the feature and read the card's Install section, modules and `installStatus` (computed from `composer.lock`). | +| `searchAlgoliaDocumentation` | Find the install guide pages; returns `github_api_url`s for the markdown. | +| `getSprykerModules`, `getSprykerModuleMap` | What the project has now; exact plugin interfaces and stack positions. | +| `getTransferStructureByName` | Check transfer fields before editing a transfer XML. | + +If the capability tools are not connected, start the MCP server and ask for a reload the way `find-existing-capability` describes; after two failed reconnects take the feature name and guide URL from the user, or fetch `https://spryker-capability-map.s3.eu-central-1.amazonaws.com/.md` with the web fetch tool and compare its packages with `composer.lock` by hand, and say that the install status is then unverified. + +## Step 1 - Resolve the feature + +1. From a card: `getSprykerCapability(slug)`. From a name: `searchSprykerCapabilities` with the name and its synonyms, then open the best card. Read the **Install** section; it lists: + - `Feature:` the metapackage (`spryker-feature/`) and its docs install guide URL, or "no install guide found" - then search the docs with `searchAlgoliaDocumentation` ("install the feature") and, without a guide, tell the user the integration steps come from the module code and the feature's other guides, not from an official guide; + - `Requires features:` other features that must be installed first; + - `Glue API:` the guide for the Glue API integration, when one exists; + - `Storefront API (when the project exposes it):` the `*-rest-api` / `*-storefront-api` packages. +2. Read `installStatus`, `features[]` and `missingPackages`. `installed` means there is nothing to install: say so and hand back to `find-existing-capability` (extend it). `partially_installed` means install only what is missing. +3. **Required features first.** Check each feature in `Requires features:` against `composer.lock` / `getSprykerModules`. For each one that is missing, resolve its card the same way and offer to install it first (recursively). Spryker Core and other base features are usually present already; verify, do not assume. + +## Step 2 - Confirm before changing anything + +Present one confirmation block and wait for the user's answer. It carries: + +- the feature, the packages `composer require` will add, and any required features that would be installed first; +- the **version constraint**: match the project's other `spryker-feature/*` constraints and release line in `composer.json` (for example the same `^202xxx.x` style); do not introduce a different style; +- the **optional integrations** the user wants: Glue API, Storefront API, Back Office, data import with demo data. Default to the project's existing surfaces (an API the project does not expose is not installed); +- which guide will be followed and its version line; +- the branch: work on a dedicated branch (`ai-feature/` from `HEAD`, as `spryker-customization` does with `ai-customize/`) when `git status` is clean; if it is not, ask first. + +No `composer require` and no edit before this answer. + +## Step 3 - Fetch the install guide + +The Install section gives a docs URL (usually `/latest/` or a versioned path). Read the page by: + +- the `spryker-docs-research` skill, or +- `searchAlgoliaDocumentation` and the markdown at its `github_api_url` (the docs markdown lives in `github.com/spryker/spryker-docs`), or +- the web fetch tool on the page itself. + +**Version match.** When the URL is `/latest/` and the project's release line (from `composer.json` and the installed `spryker/*` versions) is older than the docs' current one, prefer the guide for the project's line if the docs site offers it; if you cannot tell which line a step belongs to, say so and ask rather than apply a step that may not exist in the project's modules. Treat the guide as the source of truth for **steps and order**, but docs are not trusted for exact identifier spellings: confirm class, constant and transfer names against the installed packages in `vendor/` (read-only) or `getSprykerModuleMap` before writing them. + +Turn the guide into a **checklist** of its steps (install, integrate, verify), grouped as the guide groups them. This checklist is the run's state: every step ends `done` or `skipped (reason)`. + +## Step 4 - `composer require` + +Run inside the project's PHP environment. On Docker SDK that is `docker/sdk cli composer require :`, the form `spryker-refresher` and `spryker-upgrade` use (wrap in `script -q /dev/null` where the command needs a TTY). Without Docker SDK, run `composer require` in the project root. + +- Require the feature metapackage agreed in Step 2, with the agreed constraint. The card's `composerRequire` names the feature only when the card has exactly one; for a card with several features (alternatives such as `wishlist` and `marketplace-wishlist`) it names the missing module packages, so take the feature the user chose from the Install section instead. Require bare module packages only when the capability has no feature metapackage. +- Add the API packages only if the user chose that integration. +- On a resolution conflict, do not loosen constraints or add `--ignore-platform-reqs` on your own. Report the conflict (which package, which constraint) and stop; the cause is often a project behind the feature's release line, which is `spryker-upgrade` territory. +- Never edit `vendor/`; never hand-edit `composer.lock`. + +## Step 5 - Apply the guide's integration steps + +Apply the guide's steps in order, **in the project layer only**: under the project's namespace directories in `src/` (find them via `composer.json` `autoload.psr-4`; when there is a custom namespace ahead of `Pyz` in `KernelConstants::PROJECT_NAMESPACES`, new and overriding code goes there, extending the `Pyz` counterpart when one exists), plus `config/` and `data/import/`. Never `vendor/`, never `src/Generated/`, never `src/Orm/`. The `spryker-customization` project-layer rules apply; its `rules/` files (plugins, dependency providers, transfers) define the conventions. + +Typical step kinds, and the care each needs: + +| Guide step | Care | +|---|---| +| Config (`config/Shared/config_default.php`, module config, env overrides) | Read the existing file first; add keys in the surrounding style; no real secrets. | +| Dependency-provider plugin wiring | **Read the current plugin stack first** and insert at the guide's position; respect the existing order. Follow the project's own pattern for stack overrides (`parent::` plus a positional insert anchored on a named neighbour class, never a numeric index). Skip a plugin the project has already registered. | +| Transfer definitions (`*.transfer.xml`) | Project layer; check fields with `getTransferStructureByName`. | +| Propel schema (`*.schema.xml`) | Project layer; follow `propel-schema` conventions. | +| Navigation (`navigation.xml`), routes, route providers, widgets, module configs | Add the entry; do not reorder existing ones. | +| Glossary and translations | Add the keys for every configured locale. | +| Data import (import config, `data/import/**`, demo data) | Set up the importer wiring when the guide requires it. Load **demo data only if the user asked**; otherwise skip and record "demo data skipped". Use `project-data` and the `data-import` skill for CSV and importer work. | +| Publish and sync, queues, event wiring | Wire as the guide says; queue-worker restarts are project specific, report them. | +| New service in `deploy.dev.yml` (search, key-value, broker) | Do not change the deploy file silently; this usually needs a `docker/sdk up`, which is a rebuild. Ask the user. Never run `docker/sdk reset` or `clean-data`. | + +Where a step conflicts with something the project already built (a plugin already registered, a field already present), stop on that step, show the conflict and let the user choose; do not overwrite. Where a step is for an integration the user declined, mark it `skipped (not requested)`. + +## Step 6 - Codegen and setup + +Invoke `spryker-refresher` with the list of files you changed; it owns the file-pattern to command mapping (`transfer:generate`, `propel:install`, `cache:class-resolver:build`, router cache warm-up, `navigation:build-cache`, glossary and data import, search setup, cache clears, frontend builds). Do not improvise the command chain, and run Yves/Zed frontend builds only when the guide touches the frontend. Then run the **feature-specific setup commands the guide lists** that the refresher mapping does not cover (for example a search setup or a feature importer), verifying each command exists first with `docker/sdk console list`. + +A new `*.schema.xml` triggers `propel:install`, which changes the database schema: say so before it runs. If a command fails, show its output and diagnose before retrying (`spryker-issue-diagnoser`); do not skip a failing guide step to look green. + +## Step 7 - Verify + +- Run the guide's own **verify** steps (the pages, console commands or API calls it names) and record the evidence. +- Use `boot-and-verify` for standalone verification of what the feature touches (storefront, Back Office, search, queues); this is a running stack, not a first boot. +- Hand per-behaviour checks to the `spryker-verifier` agent with the guide's verification steps as acceptance criteria; it only asserts and reports. Weigh a FAIL as a hypothesis before acting (browser reasons look like feature failures). +- Confirm the feature's modules are now reported as installed (`getSprykerCapability(slug)` should show `installed`, or `partially_installed` when you skipped API packages on purpose). + +## Step 8 - Report + +Leave the changes **unstaged for review**; never commit or push without the user's explicit confirmation, and stage only the files you changed, by path. + +```markdown +## Feature install report: + +- Installed: +- Guide followed: +- Checklist: + - [done] - + - [skipped - ] +- Verification: +- Follow-ups: +- Files changed: +``` + +## What you do not do + +- Do not change anything (composer, files) before the Step 2 confirmation. +- Do not edit `vendor/`, `src/Generated/`, `src/Orm/` or `composer.lock` by hand. +- Do not loosen version constraints or ignore platform requirements to make a `composer require` pass. +- Do not install an optional integration (Glue API, Storefront API, demo data) the user did not choose. +- Do not reorder or overwrite existing plugin stacks, navigation or config; insert at the guide's position. +- Do not run `docker/sdk reset`, `clean-data` or any environment-destructive command; report when one is needed. +- Do not mark a guide step done without evidence, and do not drop a failing step silently. +- Do not commit or push without confirmation. diff --git a/src/SprykerSdk/Shared/AiDev/AiDevConstants.php b/src/SprykerSdk/Shared/AiDev/AiDevConstants.php index b24cb08..876c20d 100644 --- a/src/SprykerSdk/Shared/AiDev/AiDevConstants.php +++ b/src/SprykerSdk/Shared/AiDev/AiDevConstants.php @@ -12,4 +12,13 @@ */ interface AiDevConstants { + /** + * Specification: + * - URL of the capability map `index.json` the capability tools read, for example a mirror of the public bucket. + * + * @api + * + * @var string + */ + public const CAPABILITY_MAP_INDEX_URL = 'AI_DEV:CAPABILITY_MAP_INDEX_URL'; } diff --git a/src/SprykerSdk/Zed/AiDev/AiDevConfig.php b/src/SprykerSdk/Zed/AiDev/AiDevConfig.php index b2ff856..569514c 100644 --- a/src/SprykerSdk/Zed/AiDev/AiDevConfig.php +++ b/src/SprykerSdk/Zed/AiDev/AiDevConfig.php @@ -8,9 +8,14 @@ namespace SprykerSdk\Zed\AiDev; use Spryker\Zed\Kernel\AbstractBundleConfig; +use SprykerSdk\Shared\AiDev\AiDevConstants; class AiDevConfig extends AbstractBundleConfig { + protected const string CAPABILITY_MAP_INDEX_URL = 'https://spryker-capability-map.s3.eu-central-1.amazonaws.com/index.json'; + + protected const int CAPABILITY_MAP_CACHE_TTL = 86400; + /** * @var array */ @@ -327,4 +332,49 @@ public function getAgentsCompatibleTools(): array static fn (array $config): bool => ($config['agents_dir'] ?? null) !== null, ))); } + + /** + * Specification: + * - Returns the URL of the published capability map index. + * - Defaults to the public bucket the Spryker suite publishes on every change to the capability cards. + * + * @api + */ + public function getCapabilityMapIndexUrl(): string + { + return $this->get(AiDevConstants::CAPABILITY_MAP_INDEX_URL, static::CAPABILITY_MAP_INDEX_URL); + } + + /** + * Specification: + * - Returns the file the downloaded capability map index is cached in. + * + * @api + */ + public function getCapabilityMapCacheFilePath(): string + { + return APPLICATION_ROOT_DIR . '/data/tmp/ai-dev/capability-map/index.json'; + } + + /** + * Specification: + * - Returns how long, in seconds, the cached capability map index is used before it is downloaded again. + * + * @api + */ + public function getCapabilityMapCacheTtl(): int + { + return static::CAPABILITY_MAP_CACHE_TTL; + } + + /** + * Specification: + * - Returns the project's `composer.lock`, which tells the capability tools what is installed. + * + * @api + */ + public function getComposerLockFilePath(): string + { + return APPLICATION_ROOT_DIR . '/composer.lock'; + } } diff --git a/src/SprykerSdk/Zed/AiDev/AiDevDependencyProvider.php b/src/SprykerSdk/Zed/AiDev/AiDevDependencyProvider.php index 7761c04..0261155 100644 --- a/src/SprykerSdk/Zed/AiDev/AiDevDependencyProvider.php +++ b/src/SprykerSdk/Zed/AiDev/AiDevDependencyProvider.php @@ -17,10 +17,12 @@ use SprykerSdk\Zed\AiDev\Communication\Plugins\AiDevMcpTools\GetInterfaceMethodsAiDevMcpToolPlugin; use SprykerSdk\Zed\AiDev\Communication\Plugins\AiDevMcpTools\GetOmsTransitionsByOrderAiDevMcpToolPlugin; use SprykerSdk\Zed\AiDev\Communication\Plugins\AiDevMcpTools\GetOmsTransitionsByStateAiDevMcpToolPlugin; +use SprykerSdk\Zed\AiDev\Communication\Plugins\AiDevMcpTools\GetSprykerCapabilityAiDevMcpToolPlugin; use SprykerSdk\Zed\AiDev\Communication\Plugins\AiDevMcpTools\GetSprykerModuleMapAiDevMcpToolPlugin; use SprykerSdk\Zed\AiDev\Communication\Plugins\AiDevMcpTools\GetSprykerModulesAiDevMcpToolPlugin; use SprykerSdk\Zed\AiDev\Communication\Plugins\AiDevMcpTools\GetTransferStructureByNameAiDevMcpToolPlugin; use SprykerSdk\Zed\AiDev\Communication\Plugins\AiDevMcpTools\SearchAlgoliaDocumentationAiDevMcpToolPlugin; +use SprykerSdk\Zed\AiDev\Communication\Plugins\AiDevMcpTools\SearchSprykerCapabilitiesAiDevMcpToolPlugin; use SprykerSdk\Zed\AiDev\Communication\Plugins\AiDevMcpTools\SplitOdsToCsvAiDevMcpToolPlugin; use SprykerSdk\Zed\AiDev\Communication\Plugins\AiDevMcpTools\TransformCsvAiDevMcpToolPlugin; @@ -113,6 +115,8 @@ protected function getMcpToolPlugins(): array new SearchAlgoliaDocumentationAiDevMcpToolPlugin(), new GetSprykerModulesAiDevMcpToolPlugin(), new GetSprykerModuleMapAiDevMcpToolPlugin(), + new SearchSprykerCapabilitiesAiDevMcpToolPlugin(), + new GetSprykerCapabilityAiDevMcpToolPlugin(), new AnalyzeCsvFileAiDevMcpToolPlugin(), new DeleteCsvRowsAiDevMcpToolPlugin(), new TransformCsvAiDevMcpToolPlugin(), diff --git a/src/SprykerSdk/Zed/AiDev/Business/AiDevBusinessFactory.php b/src/SprykerSdk/Zed/AiDev/Business/AiDevBusinessFactory.php index b94b881..9ac6d66 100644 --- a/src/SprykerSdk/Zed/AiDev/Business/AiDevBusinessFactory.php +++ b/src/SprykerSdk/Zed/AiDev/Business/AiDevBusinessFactory.php @@ -9,9 +9,21 @@ namespace SprykerSdk\Zed\AiDev\Business; +use GuzzleHttp\Client; +use GuzzleHttp\ClientInterface; use Spryker\Zed\Kernel\Business\AbstractBusinessFactory; use Spryker\Zed\Oms\Business\OmsFacadeInterface; use SprykerSdk\Zed\AiDev\AiDevDependencyProvider; +use SprykerSdk\Zed\AiDev\Business\CapabilityMap\CapabilityInstallStatusResolver; +use SprykerSdk\Zed\AiDev\Business\CapabilityMap\CapabilityInstallStatusResolverInterface; +use SprykerSdk\Zed\AiDev\Business\CapabilityMap\CapabilityMapFinder; +use SprykerSdk\Zed\AiDev\Business\CapabilityMap\CapabilityMapFinderInterface; +use SprykerSdk\Zed\AiDev\Business\CapabilityMap\CapabilityMapReader; +use SprykerSdk\Zed\AiDev\Business\CapabilityMap\CapabilityMapReaderInterface; +use SprykerSdk\Zed\AiDev\Business\CapabilityMap\CapabilitySearcher; +use SprykerSdk\Zed\AiDev\Business\CapabilityMap\CapabilitySearcherInterface; +use SprykerSdk\Zed\AiDev\Business\CapabilityMap\ComposerLockReader; +use SprykerSdk\Zed\AiDev\Business\CapabilityMap\ComposerLockReaderInterface; use SprykerSdk\Zed\AiDev\Business\Database\Reader\DatabaseQueryReader; use SprykerSdk\Zed\AiDev\Business\Database\Reader\DatabaseQueryReaderInterface; use SprykerSdk\Zed\AiDev\Business\DataImport\CsvAnalyzer; @@ -301,4 +313,46 @@ public function createColumnRemovalValidator(): ValidatorInterface { return new ColumnRemovalValidator(); } + + public function createCapabilityMapFinder(): CapabilityMapFinderInterface + { + return new CapabilityMapFinder( + $this->createCapabilityMapReader(), + $this->createCapabilitySearcher(), + $this->createCapabilityInstallStatusResolver(), + $this->createComposerLockReader(), + ); + } + + public function createCapabilityMapReader(): CapabilityMapReaderInterface + { + return new CapabilityMapReader( + $this->createHttpClient(), + $this->getConfig()->getCapabilityMapIndexUrl(), + $this->getConfig()->getCapabilityMapCacheFilePath(), + $this->getConfig()->getCapabilityMapCacheTtl(), + ); + } + + public function createCapabilitySearcher(): CapabilitySearcherInterface + { + return new CapabilitySearcher(); + } + + public function createCapabilityInstallStatusResolver(): CapabilityInstallStatusResolverInterface + { + return new CapabilityInstallStatusResolver(); + } + + public function createComposerLockReader(): ComposerLockReaderInterface + { + return new ComposerLockReader( + $this->getConfig()->getComposerLockFilePath(), + ); + } + + public function createHttpClient(): ClientInterface + { + return new Client(); + } } diff --git a/src/SprykerSdk/Zed/AiDev/Business/CapabilityMap/CapabilityInstallStatusResolver.php b/src/SprykerSdk/Zed/AiDev/Business/CapabilityMap/CapabilityInstallStatusResolver.php new file mode 100644 index 0000000..4643da8 --- /dev/null +++ b/src/SprykerSdk/Zed/AiDev/Business/CapabilityMap/CapabilityInstallStatusResolver.php @@ -0,0 +1,176 @@ + $card + * @param array|null $installedPackages + * + * @return array + */ + public function resolve(array $card, ?array $installedPackages): array + { + $features = $this->resolveFeatures($card[static::KEY_FEATURES] ?? [], $installedPackages); + $modules = $this->resolveModules($card[static::KEY_MODULES] ?? [], $installedPackages); + + $missingFeatures = $this->collectMissing($features, 'name'); + $missingPackages = $this->collectMissing(array_filter($modules, fn (array $module): bool => !$module['optional']), 'package'); + $missingOptionalPackages = $this->collectMissing(array_filter($modules, fn (array $module): bool => $module['optional']), 'package'); + + $installStatus = $this->resolveInstallStatus($features, $modules, $installedPackages); + + return [ + 'installStatus' => $installStatus, + 'features' => $features, + 'modules' => $modules, + 'missingPackages' => $missingPackages, + 'missingOptionalPackages' => $missingOptionalPackages, + 'composerRequire' => $installStatus === static::STATUS_INSTALLED ? null : $this->buildComposerRequire($features, $missingFeatures, $missingPackages), + ]; + } + + /** + * @param array $featureNames + * @param array|null $installedPackages + * + * @return array + */ + protected function resolveFeatures(array $featureNames, ?array $installedPackages): array + { + $features = []; + foreach ($featureNames as $featureName) { + $features[] = [ + 'name' => $featureName, + 'installed' => $installedPackages === null ? null : isset($installedPackages[strtolower($featureName)]), + 'version' => $installedPackages[strtolower($featureName)] ?? null, + ]; + } + + return $features; + } + + /** + * @param array $modulePaths + * @param array|null $installedPackages + * + * @return array + */ + protected function resolveModules(array $modulePaths, ?array $installedPackages): array + { + $modules = []; + foreach ($modulePaths as $modulePath) { + if (!str_starts_with($modulePath, static::VENDOR_PATH_PREFIX)) { + continue; + } + + $packageName = strtolower(substr($modulePath, strlen(static::VENDOR_PATH_PREFIX))); + $modules[] = [ + 'package' => $packageName, + 'path' => $modulePath, + 'optional' => $this->isOptionalApiPackage($packageName), + 'installed' => $installedPackages === null ? null : isset($installedPackages[$packageName]), + 'version' => $installedPackages[$packageName] ?? null, + ]; + } + + return $modules; + } + + protected function isOptionalApiPackage(string $packageName): bool + { + foreach (static::OPTIONAL_API_PACKAGE_MARKERS as $marker) { + if (str_contains($packageName, $marker)) { + return true; + } + } + + return false; + } + + /** + * @param array> $features + * @param array> $modules + * @param array|null $installedPackages + */ + protected function resolveInstallStatus(array $features, array $modules, ?array $installedPackages): string + { + if ($installedPackages === null) { + return static::STATUS_UNKNOWN; + } + + $requiredModules = array_filter($modules, fn (array $module): bool => !$module['optional']) ?: $modules; + if ($requiredModules === []) { + return count($this->collectMissing($features, 'name')) < count($features) ? static::STATUS_INSTALLED : static::STATUS_NOT_INSTALLED; + } + + $installedCount = count(array_filter($requiredModules, fn (array $module): bool => $module['installed'] === true)); + + if ($installedCount === count($requiredModules)) { + return static::STATUS_INSTALLED; + } + + return $installedCount > 0 ? static::STATUS_PARTIALLY_INSTALLED : static::STATUS_NOT_INSTALLED; + } + + /** + * @param array> $entries + * + * @return array + */ + protected function collectMissing(array $entries, string $nameKey): array + { + $missing = []; + foreach ($entries as $entry) { + if ($entry['installed'] === false) { + $missing[] = $entry[$nameKey]; + } + } + + return $missing; + } + + /** + * A card with several features lists alternatives (each ships some of its modules), so only a single missing feature is required by name. + * + * @param array> $features + * @param array $missingFeatures + * @param array $missingPackages + */ + protected function buildComposerRequire(array $features, array $missingFeatures, array $missingPackages): ?string + { + $packagesToRequire = count($features) === 1 && $missingFeatures !== [] ? $missingFeatures : $missingPackages; + + if ($packagesToRequire === []) { + return null; + } + + return static::COMPOSER_REQUIRE_COMMAND . ' ' . implode(' ', $packagesToRequire); + } +} diff --git a/src/SprykerSdk/Zed/AiDev/Business/CapabilityMap/CapabilityInstallStatusResolverInterface.php b/src/SprykerSdk/Zed/AiDev/Business/CapabilityMap/CapabilityInstallStatusResolverInterface.php new file mode 100644 index 0000000..af85a51 --- /dev/null +++ b/src/SprykerSdk/Zed/AiDev/Business/CapabilityMap/CapabilityInstallStatusResolverInterface.php @@ -0,0 +1,25 @@ + $card + * @param array|null $installedPackages + * + * @return array + */ + public function resolve(array $card, ?array $installedPackages): array; +} diff --git a/src/SprykerSdk/Zed/AiDev/Business/CapabilityMap/CapabilityMapFinder.php b/src/SprykerSdk/Zed/AiDev/Business/CapabilityMap/CapabilityMapFinder.php new file mode 100644 index 0000000..5cc4f27 --- /dev/null +++ b/src/SprykerSdk/Zed/AiDev/Business/CapabilityMap/CapabilityMapFinder.php @@ -0,0 +1,165 @@ + + */ + public function searchCapabilities(string $query, int $limit): array + { + $terms = $this->capabilitySearcher->extractTerms($query); + if ($terms === []) { + return ['error' => static::ERROR_EMPTY_QUERY]; + } + + try { + $cards = $this->capabilityMapReader->getCards(); + } catch (CapabilityMapUnavailableException $exception) { + return ['error' => $exception->getMessage()]; + } + + $installedPackages = $this->composerLockReader->getInstalledPackages(); + $searchHits = $this->capabilitySearcher->search($cards, $terms, min(max(1, $limit), static::MAX_LIMIT)); + + $hits = []; + foreach ($searchHits as $searchHit) { + $card = $searchHit['card']; + $installStatus = $this->capabilityInstallStatusResolver->resolve($card, $installedPackages); + + $hits[] = [ + 'slug' => $this->getSlug($card), + 'capability' => $card['capability'] ?? '', + 'status' => $card['status'] ?? '', + 'matched' => $searchHit['matched'], + 'installStatus' => $installStatus['installStatus'], + 'features' => $installStatus['features'], + 'missingPackages' => $installStatus['missingPackages'], + 'missingOptionalPackages' => $installStatus['missingOptionalPackages'], + 'composerRequire' => $installStatus['composerRequire'], + 'extend' => $card['sections'][static::SECTION_EXTEND] ?? '', + 'url' => $this->getCardUrl($card), + ]; + } + + return [ + 'query' => $query, + 'terms' => $terms, + 'count' => count($hits), + 'hits' => $hits, + 'source' => $this->getSource(), + 'note' => static::NOTE_NO_PROOF_OF_ABSENCE, + ]; + } + + /** + * @return array + */ + public function getCapability(string $slug): array + { + try { + $cards = $this->capabilityMapReader->getCards(); + } catch (CapabilityMapUnavailableException $exception) { + return ['error' => $exception->getMessage()]; + } + + $card = $this->findCardBySlug($cards, $slug); + if ($card === null) { + return ['error' => sprintf(static::ERROR_UNKNOWN_SLUG, $slug)]; + } + + $installStatus = $this->capabilityInstallStatusResolver->resolve($card, $this->composerLockReader->getInstalledPackages()); + + return [ + 'slug' => $this->getSlug($card), + 'capability' => $card['capability'] ?? '', + 'status' => $card['status'] ?? '', + 'synonyms' => $card['synonyms'] ?? [], + 'url' => $this->getCardUrl($card), + ] + $installStatus + [ + 'sections' => $card['sections'] ?? [], + 'source' => $this->getSource(), + ]; + } + + /** + * @param array> $cards + * + * @return array|null + */ + protected function findCardBySlug(array $cards, string $slug): ?array + { + $normalizedSlug = strtolower(trim($slug)); + if (str_ends_with($normalizedSlug, static::CARD_FILE_EXTENSION)) { + $normalizedSlug = substr($normalizedSlug, 0, -strlen(static::CARD_FILE_EXTENSION)); + } + + foreach ($cards as $card) { + if ($this->getSlug($card) === $normalizedSlug) { + return $card; + } + } + + return null; + } + + /** + * @param array $card + */ + protected function getSlug(array $card): string + { + return basename((string)($card['file'] ?? ''), static::CARD_FILE_EXTENSION); + } + + /** + * @param array $card + */ + protected function getCardUrl(array $card): string + { + $sourceUrl = $this->capabilityMapReader->getSourceUrl(); + + return substr($sourceUrl, 0, (int)strrpos($sourceUrl, '/') + 1) . ($card['file'] ?? ''); + } + + /** + * @return array + */ + protected function getSource(): array + { + return [ + 'url' => $this->capabilityMapReader->getSourceUrl(), + 'stale' => $this->capabilityMapReader->isStale(), + ]; + } +} diff --git a/src/SprykerSdk/Zed/AiDev/Business/CapabilityMap/CapabilityMapFinderInterface.php b/src/SprykerSdk/Zed/AiDev/Business/CapabilityMap/CapabilityMapFinderInterface.php new file mode 100644 index 0000000..620cb6d --- /dev/null +++ b/src/SprykerSdk/Zed/AiDev/Business/CapabilityMap/CapabilityMapFinderInterface.php @@ -0,0 +1,30 @@ + + */ + public function searchCapabilities(string $query, int $limit): array; + + /** + * Specification: + * - Returns the full card for the slug (`cart` or `cart.md`), with the install status of each feature and module. + * - Returns an `error` key when the slug is unknown or the map cannot be loaded. + * + * @return array + */ + public function getCapability(string $slug): array; +} diff --git a/src/SprykerSdk/Zed/AiDev/Business/CapabilityMap/CapabilityMapReader.php b/src/SprykerSdk/Zed/AiDev/Business/CapabilityMap/CapabilityMapReader.php new file mode 100644 index 0000000..5b49720 --- /dev/null +++ b/src/SprykerSdk/Zed/AiDev/Business/CapabilityMap/CapabilityMapReader.php @@ -0,0 +1,163 @@ +> + */ + public function getCards(): array + { + $cards = $this->loadIndex()[static::KEY_CARDS]; + + return array_values(array_filter( + $cards, + fn (array $card): bool => ($card[static::KEY_STATUS] ?? '') !== static::STATUS_PLANNED, + )); + } + + public function getSourceUrl(): string + { + return $this->indexUrl; + } + + public function isStale(): bool + { + return $this->isStale; + } + + /** + * @throws \SprykerSdk\Zed\AiDev\Business\CapabilityMap\Exception\CapabilityMapUnavailableException + * + * @return array + */ + protected function loadIndex(): array + { + $this->isStale = false; + + if ($this->isCacheFresh()) { + $index = $this->readCache(); + if ($index !== null) { + return $index; + } + } + + $downloadError = 'the response is not a capability map index'; + + try { + $body = (string)$this->httpClient->request('GET', $this->indexUrl, ['timeout' => static::REQUEST_TIMEOUT])->getBody(); + $index = $this->decodeIndex($body); + if ($index !== null) { + $this->writeCache($body); + + return $index; + } + } catch (GuzzleException $exception) { + $downloadError = $exception->getMessage(); + } + + $index = $this->readCache(); + if ($index !== null) { + $this->isStale = true; + + return $index; + } + + throw new CapabilityMapUnavailableException(sprintf( + 'The capability map could not be loaded from %s: %s', + $this->indexUrl, + $downloadError, + )); + } + + protected function isCacheFresh(): bool + { + if (!is_file($this->cacheFilePath)) { + return false; + } + + return time() - (int)filemtime($this->cacheFilePath) < $this->cacheTtl; + } + + /** + * @return array|null + */ + protected function readCache(): ?array + { + if (!is_file($this->cacheFilePath)) { + return null; + } + + $content = file_get_contents($this->cacheFilePath); + + return $content === false ? null : $this->decodeIndex($content); + } + + /** + * @return array|null + */ + protected function decodeIndex(string $content): ?array + { + $index = json_decode($content, true); + + if (!is_array($index) || !isset($index[static::KEY_CARDS]) || !is_array($index[static::KEY_CARDS])) { + return null; + } + + return $index; + } + + /** + * The cache is an optimisation: a project directory that cannot be written must not fail the lookup. + */ + protected function writeCache(string $content): void + { + $directory = dirname($this->cacheFilePath); + $temporaryFilePath = $this->cacheFilePath . '.' . getmypid() . '.tmp'; + + try { + if (!is_dir($directory) && !mkdir($directory, 0775, true) && !is_dir($directory)) { + return; + } + + if (!is_writable($directory) || file_put_contents($temporaryFilePath, $content) === false) { + return; + } + + rename($temporaryFilePath, $this->cacheFilePath); + } catch (Throwable $exception) { + return; + } + } +} diff --git a/src/SprykerSdk/Zed/AiDev/Business/CapabilityMap/CapabilityMapReaderInterface.php b/src/SprykerSdk/Zed/AiDev/Business/CapabilityMap/CapabilityMapReaderInterface.php new file mode 100644 index 0000000..2e29fa5 --- /dev/null +++ b/src/SprykerSdk/Zed/AiDev/Business/CapabilityMap/CapabilityMapReaderInterface.php @@ -0,0 +1,31 @@ +> + */ + public function getCards(): array; + + public function getSourceUrl(): string; + + /** + * Specification: + * - Returns true when the last `getCards()` call had to use an expired cache. + */ + public function isStale(): bool; +} diff --git a/src/SprykerSdk/Zed/AiDev/Business/CapabilityMap/CapabilitySearcher.php b/src/SprykerSdk/Zed/AiDev/Business/CapabilityMap/CapabilitySearcher.php new file mode 100644 index 0000000..c6ad60c --- /dev/null +++ b/src/SprykerSdk/Zed/AiDev/Business/CapabilityMap/CapabilitySearcher.php @@ -0,0 +1,167 @@ + 0, 'partial' => 1, 'planned' => 2]; + + protected const int UNKNOWN_STATUS_RANK = 3; + + protected const string KEY_CAPABILITY = 'capability'; + + protected const string KEY_SYNONYMS = 'synonyms'; + + protected const string KEY_MODULES = 'modules'; + + protected const string KEY_SECTIONS = 'sections'; + + protected const string KEY_STATUS = 'status'; + + /** + * @return array + */ + public function extractTerms(string $query): array + { + $terms = preg_split('/[\s,;]+/u', mb_strtolower(trim($query)), -1, PREG_SPLIT_NO_EMPTY) ?: []; + + return array_values(array_unique(array_filter( + $terms, + fn (string $term): bool => mb_strlen($term) >= static::MIN_TERM_LENGTH, + ))); + } + + /** + * @param array> $cards + * @param array $terms + * + * @return array, matched: array{capability: array, modules: array, body: array}}> + */ + public function search(array $cards, array $terms, int $limit): array + { + if ($terms === []) { + return []; + } + + $scoredHits = []; + foreach ($cards as $card) { + $scoredHit = $this->scoreCard($card, $terms); + if ($scoredHit !== null) { + $scoredHits[] = $scoredHit; + } + } + + usort($scoredHits, fn (array $left, array $right): int => $left['sortKey'] <=> $right['sortKey']); + + return array_map( + fn (array $scoredHit): array => ['card' => $scoredHit['card'], 'matched' => $scoredHit['matched']], + array_slice($scoredHits, 0, max(1, $limit)), + ); + } + + /** + * @param array $card + * @param array $terms + * + * @return array|null + */ + protected function scoreCard(array $card, array $terms): ?array + { + $strongText = ($card[static::KEY_CAPABILITY] ?? '') . ' ' . implode(' ', $card[static::KEY_SYNONYMS] ?? []); + $moduleText = implode(' ', $card[static::KEY_MODULES] ?? []); + $bodyText = implode("\n", $card[static::KEY_SECTIONS] ?? []); + + $strongWeight = 0; + $matchedStrong = []; + $matchedModules = []; + $matchedBody = []; + + foreach ($terms as $term) { + $strongCount = $this->countOccurrences($term, $strongText); + $strongWeight += $strongCount; + + if ($strongCount > 0) { + $matchedStrong[] = $term; + } + + if ($this->countOccurrences($term, $moduleText) > 0) { + $matchedModules[] = $term; + } + + if ($this->countOccurrences($term, $bodyText) > 0) { + $matchedBody[] = $term; + } + } + + if ($matchedStrong === [] && $matchedModules === [] && $matchedBody === []) { + return null; + } + + $matchedBodyOnly = array_values(array_diff($matchedBody, $matchedStrong, $matchedModules)); + + return [ + 'card' => $card, + 'matched' => [ + 'capability' => $matchedStrong, + 'modules' => $matchedModules, + 'body' => $matchedBodyOnly, + ], + 'sortKey' => [ + -count($matchedStrong), + -$strongWeight, + -count($matchedModules), + -count($matchedBodyOnly), + static::STATUS_RANK[$card[static::KEY_STATUS] ?? ''] ?? static::UNKNOWN_STATUS_RANK, + ], + ]; + } + + protected function countOccurrences(string $term, string $text): int + { + $lowerText = mb_strtolower($text); + $lowerTerm = mb_strtolower($term); + $variants = array_unique([$this->stem($lowerTerm), $lowerTerm]); + + $total = 0; + foreach ($variants as $variant) { + if (mb_strlen($variant) <= static::SHORT_TERM_LENGTH) { + $total += (int)preg_match_all('/\b' . preg_quote($variant, '/') . '\w{0,2}\b/u', $lowerText); + + continue; + } + + $total += substr_count($lowerText, $variant); + } + + return $total; + } + + protected function stem(string $term): string + { + foreach (static::STEM_SUFFIXES as $suffix) { + if (str_ends_with($term, $suffix) && mb_strlen($term) - mb_strlen($suffix) >= static::MIN_STEM_LENGTH) { + return mb_substr($term, 0, -mb_strlen($suffix)); + } + } + + return $term; + } +} diff --git a/src/SprykerSdk/Zed/AiDev/Business/CapabilityMap/CapabilitySearcherInterface.php b/src/SprykerSdk/Zed/AiDev/Business/CapabilityMap/CapabilitySearcherInterface.php new file mode 100644 index 0000000..047e09d --- /dev/null +++ b/src/SprykerSdk/Zed/AiDev/Business/CapabilityMap/CapabilitySearcherInterface.php @@ -0,0 +1,32 @@ + + */ + public function extractTerms(string $query): array; + + /** + * Specification: + * - Ranks cards by the number of distinct terms found in the capability title and synonyms, then by how often they occur there, then by module path hits, then by body-only hits, then shipped before partial before planned. + * - Terms of 4 characters or fewer match whole words only, so `sso` does not hit `processor`. + * - Returns at most `$limit` hits with the card and the terms matched per field. + * + * @param array> $cards + * @param array $terms + * + * @return array, matched: array{capability: array, modules: array, body: array}}> + */ + public function search(array $cards, array $terms, int $limit): array; +} diff --git a/src/SprykerSdk/Zed/AiDev/Business/CapabilityMap/ComposerLockReader.php b/src/SprykerSdk/Zed/AiDev/Business/CapabilityMap/ComposerLockReader.php new file mode 100644 index 0000000..7d99b86 --- /dev/null +++ b/src/SprykerSdk/Zed/AiDev/Business/CapabilityMap/ComposerLockReader.php @@ -0,0 +1,52 @@ +|null + */ + public function getInstalledPackages(): ?array + { + if (!is_file($this->composerLockFilePath)) { + return null; + } + + $content = file_get_contents($this->composerLockFilePath); + $lock = $content === false ? null : json_decode($content, true); + if (!is_array($lock)) { + return null; + } + + $installedPackages = []; + foreach (static::PACKAGE_SECTIONS as $section) { + foreach ($lock[$section] ?? [] as $package) { + if (!is_array($package) || !isset($package[static::KEY_NAME])) { + continue; + } + + $installedPackages[strtolower((string)$package[static::KEY_NAME])] = (string)($package[static::KEY_VERSION] ?? ''); + } + } + + return $installedPackages; + } +} diff --git a/src/SprykerSdk/Zed/AiDev/Business/CapabilityMap/ComposerLockReaderInterface.php b/src/SprykerSdk/Zed/AiDev/Business/CapabilityMap/ComposerLockReaderInterface.php new file mode 100644 index 0000000..f81603c --- /dev/null +++ b/src/SprykerSdk/Zed/AiDev/Business/CapabilityMap/ComposerLockReaderInterface.php @@ -0,0 +1,20 @@ +|null + */ + public function getInstalledPackages(): ?array; +} diff --git a/src/SprykerSdk/Zed/AiDev/Business/CapabilityMap/Exception/CapabilityMapUnavailableException.php b/src/SprykerSdk/Zed/AiDev/Business/CapabilityMap/Exception/CapabilityMapUnavailableException.php new file mode 100644 index 0000000..39e2c73 --- /dev/null +++ b/src/SprykerSdk/Zed/AiDev/Business/CapabilityMap/Exception/CapabilityMapUnavailableException.php @@ -0,0 +1,16 @@ +getBusinessFactory() + ->createCapabilityMapFinder() + ->getCapability($slug); + + return (string)json_encode($result, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); + } +} diff --git a/src/SprykerSdk/Zed/AiDev/Communication/Plugins/AiDevMcpTools/SearchSprykerCapabilitiesAiDevMcpToolPlugin.php b/src/SprykerSdk/Zed/AiDev/Communication/Plugins/AiDevMcpTools/SearchSprykerCapabilitiesAiDevMcpToolPlugin.php new file mode 100644 index 0000000..7d67508 --- /dev/null +++ b/src/SprykerSdk/Zed/AiDev/Communication/Plugins/AiDevMcpTools/SearchSprykerCapabilitiesAiDevMcpToolPlugin.php @@ -0,0 +1,45 @@ +getBusinessFactory() + ->createCapabilityMapFinder() + ->searchCapabilities($query, $limit); + + return (string)json_encode($result, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); + } +} diff --git a/tests/SprykerSdkTest/Zed/AiDev/Business/CapabilityMap/CapabilityInstallStatusResolverTest.php b/tests/SprykerSdkTest/Zed/AiDev/Business/CapabilityMap/CapabilityInstallStatusResolverTest.php new file mode 100644 index 0000000..64d059e --- /dev/null +++ b/tests/SprykerSdkTest/Zed/AiDev/Business/CapabilityMap/CapabilityInstallStatusResolverTest.php @@ -0,0 +1,140 @@ +capabilityInstallStatusResolver = new CapabilityInstallStatusResolver(); + } + + public function testResolveReturnsInstalledWhenFeatureAndRequiredPackagesAreInstalled(): void + { + // Arrange + $installedPackages = ['spryker-feature/cart' => '202512.0', 'spryker/cart' => '7.20.0', 'spryker/cart-extension' => '4.5.0']; + + // Act + $result = $this->capabilityInstallStatusResolver->resolve($this->getCards()[0], $installedPackages); + + // Assert + $this->assertSame(CapabilityInstallStatusResolver::STATUS_INSTALLED, $result['installStatus']); + $this->assertSame([['name' => 'spryker-feature/cart', 'installed' => true, 'version' => '202512.0']], $result['features']); + $this->assertNull($result['composerRequire']); + } + + public function testResolveIgnoresMissingApiPackagesForInstalledStatus(): void + { + // Arrange + $installedPackages = ['spryker/cart' => '7.20.0', 'spryker/cart-extension' => '4.5.0']; + + // Act + $result = $this->capabilityInstallStatusResolver->resolve($this->getCards()[0], $installedPackages); + + // Assert + $this->assertSame(CapabilityInstallStatusResolver::STATUS_INSTALLED, $result['installStatus']); + $this->assertSame([], $result['missingPackages']); + $this->assertSame(['spryker/carts-rest-api'], $result['missingOptionalPackages']); + } + + public function testResolveReturnsPartiallyInstalledWithMissingFeatureInComposerRequire(): void + { + // Arrange + $installedPackages = ['spryker/purchasing-control' => '1.2.0']; + + // Act + $result = $this->capabilityInstallStatusResolver->resolve($this->getCards()[1], $installedPackages); + + // Assert + $this->assertSame(CapabilityInstallStatusResolver::STATUS_PARTIALLY_INSTALLED, $result['installStatus']); + $this->assertSame(['spryker/purchasing-control-extension'], $result['missingPackages']); + $this->assertSame('composer require spryker-feature/purchasing-control', $result['composerRequire']); + } + + public function testResolveReturnsNotInstalledWithModulePackagesWhenCardHasNoFeature(): void + { + // Act + $result = $this->capabilityInstallStatusResolver->resolve($this->getCards()[2], ['spryker/cart' => '7.20.0']); + + // Assert + $this->assertSame(CapabilityInstallStatusResolver::STATUS_NOT_INSTALLED, $result['installStatus']); + $this->assertSame('composer require spryker/oauth-client', $result['composerRequire']); + } + + public function testResolveReturnsUnknownWithoutComposerLock(): void + { + // Act + $result = $this->capabilityInstallStatusResolver->resolve($this->getCards()[0], null); + + // Assert + $this->assertSame(CapabilityInstallStatusResolver::STATUS_UNKNOWN, $result['installStatus']); + $this->assertNull($result['modules'][0]['installed']); + $this->assertNull($result['composerRequire']); + } + + public function testResolveRequiresMissingPackagesInsteadOfAlternativeFeatures(): void + { + // Arrange + $card = $this->createCard( + 'wishlist.md', + 'Wishlist', + ['wishlist'], + ['spryker-feature/marketplace-wishlist', 'spryker-feature/wishlist'], + ['vendor/spryker/wishlist', 'vendor/spryker/merchant-product-wishlist'], + ); + + // Act + $result = $this->capabilityInstallStatusResolver->resolve($card, ['spryker/wishlist' => '8.0.0']); + + // Assert + $this->assertSame(CapabilityInstallStatusResolver::STATUS_PARTIALLY_INSTALLED, $result['installStatus']); + $this->assertSame('composer require spryker/merchant-product-wishlist', $result['composerRequire']); + } + + public function testResolveUsesFeaturesForCardWithoutVendorModules(): void + { + // Arrange + $card = $this->createCard('glue.md', 'Glue', ['glue'], ['spryker-feature/glue-application'], ['src/Spryker/Glue']); + + // Act + $result = $this->capabilityInstallStatusResolver->resolve($card, ['spryker-feature/glue-application' => '202512.0']); + + // Assert + $this->assertSame(CapabilityInstallStatusResolver::STATUS_INSTALLED, $result['installStatus']); + } + + public function testResolveSkipsModulesOutsideVendor(): void + { + // Arrange + $card = $this->createCard('custom.md', 'Custom', [], [], ['src/Pyz/Zed/Custom', 'vendor/spryker/custom']); + + // Act + $result = $this->capabilityInstallStatusResolver->resolve($card, []); + + // Assert + $this->assertCount(1, $result['modules']); + $this->assertSame('spryker/custom', $result['modules'][0]['package']); + } +} diff --git a/tests/SprykerSdkTest/Zed/AiDev/Business/CapabilityMap/CapabilityMapReaderTest.php b/tests/SprykerSdkTest/Zed/AiDev/Business/CapabilityMap/CapabilityMapReaderTest.php new file mode 100644 index 0000000..516c623 --- /dev/null +++ b/tests/SprykerSdkTest/Zed/AiDev/Business/CapabilityMap/CapabilityMapReaderTest.php @@ -0,0 +1,155 @@ +cacheFilePath = sys_get_temp_dir() . '/ai-dev-capability-map-test-' . uniqid() . '/index.json'; + $this->mockHandler = new MockHandler(); + } + + protected function tearDown(): void + { + if (is_file($this->cacheFilePath)) { + unlink($this->cacheFilePath); + } + if (is_dir(dirname($this->cacheFilePath))) { + rmdir(dirname($this->cacheFilePath)); + } + + parent::tearDown(); + } + + public function testGetCardsDownloadsIndexWritesCacheAndDropsPlannedCards(): void + { + // Arrange + $this->mockHandler->append(new Response(200, [], $this->createIndexJson())); + + // Act + $cards = $this->createReader()->getCards(); + + // Assert + $this->assertSame(['cart.md'], array_column($cards, 'file')); + $this->assertFileExists($this->cacheFilePath); + } + + public function testGetCardsUsesFreshCacheWithoutDownload(): void + { + // Arrange + $this->writeCacheFile($this->createIndexJson()); + $reader = $this->createReader(); + + // Act + $cards = $reader->getCards(); + + // Assert + $this->assertCount(1, $cards); + $this->assertNull($this->mockHandler->getLastRequest()); + $this->assertFalse($reader->isStale()); + } + + public function testGetCardsFallsBackToExpiredCacheWhenDownloadFails(): void + { + // Arrange + $this->writeCacheFile($this->createIndexJson()); + touch($this->cacheFilePath, time() - 7200); + $this->mockHandler->append(new ConnectException('Network down', new Request('GET', static::INDEX_URL))); + $reader = $this->createReader(); + + // Act + $cards = $reader->getCards(); + + // Assert + $this->assertCount(1, $cards); + $this->assertTrue($reader->isStale()); + } + + public function testGetCardsIgnoresInvalidResponseAndFallsBackToCache(): void + { + // Arrange + $this->writeCacheFile($this->createIndexJson()); + touch($this->cacheFilePath, time() - 7200); + $this->mockHandler->append(new Response(200, [], 'Access denied')); + $reader = $this->createReader(); + + // Act + $cards = $reader->getCards(); + + // Assert + $this->assertCount(1, $cards); + $this->assertTrue($reader->isStale()); + } + + public function testGetCardsThrowsWhenDownloadFailsWithoutCache(): void + { + // Arrange + $this->mockHandler->append(new ConnectException('Network down', new Request('GET', static::INDEX_URL))); + + // Assert + $this->expectException(CapabilityMapUnavailableException::class); + $this->expectExceptionMessage('Network down'); + + // Act + $this->createReader()->getCards(); + } + + protected function createReader(): CapabilityMapReader + { + return new CapabilityMapReader( + new Client(['handler' => HandlerStack::create($this->mockHandler)]), + static::INDEX_URL, + $this->cacheFilePath, + 3600, + ); + } + + protected function createIndexJson(): string + { + return (string)json_encode([ + 'cards' => [ + $this->getCards()[0], + $this->createCard('invoice.md', 'Invoices', ['invoice'], status: 'planned'), + ]]); + } + + protected function writeCacheFile(string $content): void + { + mkdir(dirname($this->cacheFilePath), 0777, true); + file_put_contents($this->cacheFilePath, $content); + } +} diff --git a/tests/SprykerSdkTest/Zed/AiDev/Business/CapabilityMap/CapabilityMapTestDataTrait.php b/tests/SprykerSdkTest/Zed/AiDev/Business/CapabilityMap/CapabilityMapTestDataTrait.php new file mode 100644 index 0000000..a915b87 --- /dev/null +++ b/tests/SprykerSdkTest/Zed/AiDev/Business/CapabilityMap/CapabilityMapTestDataTrait.php @@ -0,0 +1,85 @@ +> + */ + protected function getCards(): array + { + return [ + $this->createCard( + 'cart.md', + 'Shopping cart - add/remove items, quantity changes, validation', + ['cart', 'basket', 'line items'], + ['spryker-feature/cart'], + ['vendor/spryker/cart', 'vendor/spryker/cart-extension', 'vendor/spryker/carts-rest-api'], + 'Cart-level business rules (budget enforcement, availability checks) belong here via `CartPreCheckPluginInterface`.', + ), + $this->createCard( + 'purchasing-control.md', + 'Budgets and cost centers for company purchasing', + ['budget', 'cost center', 'spending limit'], + ['spryker-feature/purchasing-control'], + ['vendor/spryker/purchasing-control', 'vendor/spryker/purchasing-control-extension'], + 'Extend budget rules through `BudgetValidatorPluginInterface`.', + ), + $this->createCard( + 'sso-authentication.md', + 'Single sign-on for customers', + ['sso', 'single sign-on'], + [], + ['vendor/spryker/oauth-client'], + 'Add an identity provider through `OauthClientPluginInterface`.', + ), + $this->createCard( + 'order-processor.md', + 'Order processor - checkout save order steps', + ['checkout processor'], + [], + ['vendor/spryker/checkout'], + 'Plug in through `CheckoutDoSaveOrderInterface`.', + ), + ]; + } + + /** + * @param array $synonyms + * @param array $features + * @param array $modules + * + * @return array + */ + protected function createCard( + string $file, + string $capability, + array $synonyms, + array $features = [], + array $modules = [], + string $extend = '', + string $status = 'shipped', + ): array { + return [ + 'file' => $file, + 'capability' => $capability, + 'status' => $status, + 'synonyms' => $synonyms, + 'features' => $features, + 'modules' => $modules, + 'sections' => [ + 'What it does' => $capability, + "Extend, don't duplicate" => $extend, + 'Install' => $features === [] ? '- Feature: none' : sprintf('- Feature: `%s`', $features[0]), + ], + ]; + } +} diff --git a/tests/SprykerSdkTest/Zed/AiDev/Business/CapabilityMap/CapabilitySearcherTest.php b/tests/SprykerSdkTest/Zed/AiDev/Business/CapabilityMap/CapabilitySearcherTest.php new file mode 100644 index 0000000..9bb2943 --- /dev/null +++ b/tests/SprykerSdkTest/Zed/AiDev/Business/CapabilityMap/CapabilitySearcherTest.php @@ -0,0 +1,126 @@ +capabilitySearcher = new CapabilitySearcher(); + } + + public function testExtractTermsLowercasesDeduplicatesAndDropsShortTerms(): void + { + // Act + $terms = $this->capabilitySearcher->extractTerms('Budget, budget of SSO;approval'); + + // Assert + $this->assertSame(['budget', 'sso', 'approval'], $terms); + } + + public function testSearchRanksSynonymHitAboveBodyOnlyHit(): void + { + // Act + $hits = $this->capabilitySearcher->search($this->getCards(), ['budget'], 10); + + // Assert + $this->assertSame('purchasing-control.md', $hits[0]['card']['file']); + $this->assertSame(['budget'], $hits[0]['matched']['capability']); + $this->assertSame('cart.md', $hits[1]['card']['file']); + $this->assertSame(['budget'], $hits[1]['matched']['body']); + } + + public function testSearchRanksMoreDistinctStrongTermsFirst(): void + { + // Act + $hits = $this->capabilitySearcher->search($this->getCards(), ['cart', 'basket'], 10); + + // Assert + $this->assertSame('cart.md', $hits[0]['card']['file']); + $this->assertSame(['cart', 'basket'], $hits[0]['matched']['capability']); + } + + public function testSearchMatchesPluralTermsThroughStem(): void + { + // Act + $hits = $this->capabilitySearcher->search($this->getCards(), ['budgets'], 10); + + // Assert + $this->assertSame('purchasing-control.md', $hits[0]['card']['file']); + } + + public function testSearchMatchesShortTermsOnWholeWordsOnly(): void + { + // Act + $hits = $this->capabilitySearcher->search($this->getCards(), ['sso'], 10); + + // Assert + $this->assertCount(1, $hits); + $this->assertSame('sso-authentication.md', $hits[0]['card']['file']); + } + + public function testSearchCountsModulePathHits(): void + { + // Act + $hits = $this->capabilitySearcher->search($this->getCards(), ['purchasing'], 10); + + // Assert + $this->assertSame('purchasing-control.md', $hits[0]['card']['file']); + $this->assertContains('purchasing', $hits[0]['matched']['modules']); + } + + public function testSearchRanksShippedBeforePartialOnTies(): void + { + // Arrange + $cards = [ + $this->createCard('a-partial.md', 'Loyalty points', ['loyalty'], status: 'partial'), + $this->createCard('b-shipped.md', 'Loyalty points', ['loyalty']), + ]; + + // Act + $hits = $this->capabilitySearcher->search($cards, ['loyalty'], 10); + + // Assert + $this->assertSame('b-shipped.md', $hits[0]['card']['file']); + } + + public function testSearchReturnsNothingForUnknownTerms(): void + { + // Act + $hits = $this->capabilitySearcher->search($this->getCards(), ['spaceship'], 10); + + // Assert + $this->assertSame([], $hits); + } + + public function testSearchRespectsLimit(): void + { + // Act + $hits = $this->capabilitySearcher->search($this->getCards(), ['budget'], 1); + + // Assert + $this->assertCount(1, $hits); + } +} diff --git a/tests/SprykerSdkTest/Zed/AiDev/Business/CapabilityMap/ComposerLockReaderTest.php b/tests/SprykerSdkTest/Zed/AiDev/Business/CapabilityMap/ComposerLockReaderTest.php new file mode 100644 index 0000000..03153c5 --- /dev/null +++ b/tests/SprykerSdkTest/Zed/AiDev/Business/CapabilityMap/ComposerLockReaderTest.php @@ -0,0 +1,86 @@ +composerLockFilePath = sys_get_temp_dir() . '/ai-dev-composer-lock-test-' . uniqid() . '.lock'; + } + + protected function tearDown(): void + { + if (is_file($this->composerLockFilePath)) { + unlink($this->composerLockFilePath); + } + + parent::tearDown(); + } + + public function testGetInstalledPackagesReadsPackagesAndDevPackagesWithLowercaseNames(): void + { + // Arrange + file_put_contents($this->composerLockFilePath, (string)json_encode([ + 'packages' => [ + ['name' => 'Spryker/Cart', 'version' => '7.20.0'], + ['name' => 'spryker-feature/cart', 'version' => '202512.0'], + ['version' => '1.0.0'], + ], + 'packages-dev' => [ + ['name' => 'spryker-sdk/ai-dev', 'version' => 'dev-master'], + ], + ])); + + // Act + $installedPackages = (new ComposerLockReader($this->composerLockFilePath))->getInstalledPackages(); + + // Assert + $this->assertSame([ + 'spryker/cart' => '7.20.0', + 'spryker-feature/cart' => '202512.0', + 'spryker-sdk/ai-dev' => 'dev-master', + ], $installedPackages); + } + + public function testGetInstalledPackagesReturnsNullWithoutLockFile(): void + { + // Act + $installedPackages = (new ComposerLockReader($this->composerLockFilePath))->getInstalledPackages(); + + // Assert + $this->assertNull($installedPackages); + } + + public function testGetInstalledPackagesReturnsNullForInvalidLockFile(): void + { + // Arrange + file_put_contents($this->composerLockFilePath, 'not json'); + + // Act + $installedPackages = (new ComposerLockReader($this->composerLockFilePath))->getInstalledPackages(); + + // Assert + $this->assertNull($installedPackages); + } +} From 8d546ad8ac3a9fe4cbf22be56b4a4e930d53a289 Mon Sep 17 00:00:00 2001 From: Dmitriy Krainiy Date: Fri, 6 Nov 2026 14:36:52 +0100 Subject: [PATCH 02/18] Added optional Yves Twig integration step to feature install and upgrade yves-twig-integration scans which feature widgets and components the project's storefront no longer renders because a project override replaced the vendor template that places them, suggests the placements, and applies only the picked ones in the project's design. spryker-feature-install offers it as Step 6b, spryker-upgrade as Phase 6.1 (gaps new since the Phase 0 snapshot). --- .../references/delegation.md | 1 + .../skills/spryker-feature-install/SKILL.md | 15 +- .../skills/spryker-upgrade/README.md | 2 + .../skills/spryker-upgrade/SKILL.md | 25 +- .../references/handover-report.md | 4 +- .../skills/yves-atomic-frontend/SKILL.md | 1 + .../skills/yves-twig-integration/README.md | 33 + .../skills/yves-twig-integration/SKILL.md | 122 ++++ .../references/placement-rules.md | 52 ++ .../scripts/yves-integration-scan.php | 678 ++++++++++++++++++ .../scripts/yves-integration-scan.test.php | 172 +++++ 11 files changed, 1101 insertions(+), 4 deletions(-) create mode 100644 plugins/spryker-ai-dev-sdk/skills/yves-twig-integration/README.md create mode 100644 plugins/spryker-ai-dev-sdk/skills/yves-twig-integration/SKILL.md create mode 100644 plugins/spryker-ai-dev-sdk/skills/yves-twig-integration/references/placement-rules.md create mode 100644 plugins/spryker-ai-dev-sdk/skills/yves-twig-integration/scripts/yves-integration-scan.php create mode 100644 plugins/spryker-ai-dev-sdk/skills/yves-twig-integration/scripts/yves-integration-scan.test.php diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-customization/references/delegation.md b/plugins/spryker-ai-dev-sdk/skills/spryker-customization/references/delegation.md index 16dd14a..d74f187 100644 --- a/plugins/spryker-ai-dev-sdk/skills/spryker-customization/references/delegation.md +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-customization/references/delegation.md @@ -37,4 +37,5 @@ These are **skills** (loaded into the main session), not subagents. Invoke each | `ai-runtime-debugging` | When you need to see runtime values that aren't surfacing in logs / DB / browser state — during Step 4 build or Step 7 self-correct. Teaches the `[AI-DEBUG]` tagged-log pattern and optional XDebug step-debug. Always paired with a cleanup pass in Step 7b. | | `cypress-tests` | Step 7a (when the Cypress E2E phase is on) — once all ACs are green, fix / improve / add a Cypress E2E spec locking in the user-visible behavior, run it targeted + the suite's quality gate. | | `yves-atomic-frontend` | Step 4 — before the first write to any `.scss` / `.ts` / atomic-component file under `Theme/default/components/`. | +| `yves-twig-integration` | Step 4 - when the work relies on a core widget or component that the storefront does not render, or after `spryker-feature-install`: suggests where the vendor templates place it in templates the project overrides, and places the picked ones in the project's design. | | `static-validation` | Step 7b — lint / phpcs / phpstan over the final diff before commit. | diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/SKILL.md b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/SKILL.md index 1e96d04..870349e 100644 --- a/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/SKILL.md +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/SKILL.md @@ -49,6 +49,7 @@ Present one confirmation block and wait for the user's answer. It carries: - the feature, the packages `composer require` will add, and any required features that would be installed first; - the **version constraint**: match the project's other `spryker-feature/*` constraints and release line in `composer.json` (for example the same `^202xxx.x` style); do not introduce a different style; - the **optional integrations** the user wants: Glue API, Storefront API, Back Office, data import with demo data. Default to the project's existing surfaces (an API the project does not expose is not installed); +- that the **storefront placement** (Step 6b) comes after the backend steps as a suggestion list: the guide registers the feature's widgets but does not place them in the project's Twig templates, and nothing is placed unless the developer picks it then; - which guide will be followed and its version line; - the branch: work on a dedicated branch (`ai-feature/` from `HEAD`, as `spryker-customization` does with `ai-customize/`) when `git status` is clean; if it is not, ask first. @@ -87,7 +88,8 @@ Typical step kinds, and the care each needs: | Dependency-provider plugin wiring | **Read the current plugin stack first** and insert at the guide's position; respect the existing order. Follow the project's own pattern for stack overrides (`parent::` plus a positional insert anchored on a named neighbour class, never a numeric index). Skip a plugin the project has already registered. | | Transfer definitions (`*.transfer.xml`) | Project layer; check fields with `getTransferStructureByName`. | | Propel schema (`*.schema.xml`) | Project layer; follow `propel-schema` conventions. | -| Navigation (`navigation.xml`), routes, route providers, widgets, module configs | Add the entry; do not reorder existing ones. | +| Navigation (`navigation.xml`), routes, route providers, module configs | Add the entry; do not reorder existing ones. | +| Widget plugins (`ShopApplicationDependencyProvider::getGlobalWidgets()`) | Register the widgets the guide lists. Registration alone renders nothing in templates the project overrides; placing them is Step 6b. | | Glossary and translations | Add the keys for every configured locale. | | Data import (import config, `data/import/**`, demo data) | Set up the importer wiring when the guide requires it. Load **demo data only if the user asked**; otherwise skip and record "demo data skipped". Use `project-data` and the `data-import` skill for CSV and importer work. | | Publish and sync, queues, event wiring | Wire as the guide says; queue-worker restarts are project specific, report them. | @@ -101,6 +103,16 @@ Invoke `spryker-refresher` with the list of files you changed; it owns the file- A new `*.schema.xml` triggers `propel:install`, which changes the database schema: say so before it runs. If a command fails, show its output and diagnose before retrying (`spryker-issue-diagnoser`); do not skip a failing guide step to look green. +## Step 6b - Optional: storefront placement (suggested, not applied by default) + +Only when the feature has Yves code (a card module under `vendor/spryker-shop/`, or a package with a `src/*/Yves/` directory) and the project has a storefront. Install guides stop at registering widgets; the vendor templates place them, and every vendor template the project overrides has lost those calls. + +1. Run the `yves-twig-integration` scanner scoped to the feature's Yves packages (`--package=,...`). It lists, per widget and component, whether a template the project renders already uses it, and where the vendor places it in templates the project replaced. +2. Present its suggestion table and ask which placements to apply (all, some, none). `not_registered` items mean a widget from the guide is still unregistered: finish that in Step 5 first. +3. On a pick, invoke the `yves-twig-integration` skill (`/yves-twig-integration`, or `/spryker-ai-dev-sdk:yves-twig-integration` on a plugin install) with the picked items; it places each one in the project's design and verifies it. On "none", record the suggestions as a follow-up and continue. + +Do not apply a placement in an unattended run; the table goes into the report. + ## Step 7 - Verify - Run the guide's own **verify** steps (the pages, console commands or API calls it names) and record the evidence. @@ -120,6 +132,7 @@ Leave the changes **unstaged for review**; never commit or push without the user - Checklist: - [done] - - [skipped - ] +- Storefront placement: - Verification: - Follow-ups: - Files changed: diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/README.md b/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/README.md index dcbc911..d7146c8 100644 --- a/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/README.md +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/README.md @@ -51,6 +51,8 @@ SPRYKER_UPGRADE_STATE_DIR=/path/to/state # move baselines/reports (e.g. a CI | `storage-search-counts.php` | 0 (`--snapshot before`), 4.9/5.5 (`--snapshot after`, `--compare`) | did any `*_storage` / `*_search` table lose rows after the same import? | | `check-performance.php` | 3, Lane 2, 6.2, 7 | which pages do Spryker's performance guidelines have today, has every page its fixes or a no-fix reason, every fix a size and a final status and every M/L fix the developer's decision, which fixes are deferred, and did shop-ui 1.103.0 remove product group rendering the project relies on? | +Phase 0 (`snapshot`) and Phase 6.1 (`diff`) also run `yves-integration-scan.php` from the sibling `yves-twig-integration` skill: which widgets the upgrade added that no template the project renders calls. Its findings are suggestions for the developer, not upgrade damage. + `bootstrap.php` is the shared library the scripts load. `upgrade-scripts.test.php` is the maintainer test suite for the scripts (`php $UP/upgrade-scripts.test.php`); it is not part of an upgrade run. diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/SKILL.md b/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/SKILL.md index de55081..e1ec6a2 100644 --- a/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/SKILL.md +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/SKILL.md @@ -42,7 +42,7 @@ These five rules apply to every phase and lane; § Hard rules at the end does no exclude, or a detector's exclude list — none of which is ever part of an upgrade's deliverable. **Plan tracking is mandatory.** At the end of Phase 0, create one `TaskCreate` task each for Phase -0.5, 1, 1.2, 1.5, 2, 3, Lane 0, Lanes 1–4, Lane 5 (if reached), Phase 4.9, 5, 5.5, 6, 6.2, 6.5, 6.8 and 7, +0.5, 1, 1.2, 1.5, 2, 3, Lane 0, Lanes 1–4, Lane 5 (if reached), Phase 4.9, 5, 5.5, 6, 6.1, 6.2, 6.5, 6.8 and 7, and drive them with `TaskUpdate`: `in_progress` on entry, `completed` only once its checks are green; a detector re-run that reopens a lane reopens its task. `TaskList` survives compaction; nothing else does. @@ -127,6 +127,7 @@ you cannot place, and before the Phase 7 report; a new failure mode gets a row a php $UP/check-test-coverage.php || true # baseline: is the override surface verifiable at all? php $UP/check-vendor-class-replacement.php || true # baseline: classes declared in vendor namespaces php $UP/check-constant-overrides.php --snapshot # core values under project constants + php $YI/yves-integration-scan.php snapshot # storefront widgets the project already does not render (Phase 6.1) cp composer.lock .spryker-upgrade/state/composer.lock.before cp $UP/storage-search-counts.php .spryker-upgrade/state/ # publish baseline: drain the queues first script -q /dev/null docker/sdk cli php .spryker-upgrade/state/storage-search-counts.php --snapshot before @@ -470,7 +471,27 @@ Two kinds of "new" need this gate, and only the first is visible in the lock dif Fetch each description (`composer show ` + release notes) and ask the user a structured question (use your harness's question tool if it has one, otherwise ask in chat and wait) (multiSelect): integrate now / defer / never. Nothing new is wired without an explicit yes; each -accepted feature follows its integration guide, in its own commit. REMOVED packages: explain each. +accepted feature follows its integration guide, in its own commit (the `spryker-feature-install` skill +runs a guide end to end, including its optional storefront placement step). REMOVED packages: explain each. + +## Phase 6.1 — Storefront placement (optional, suggested) + +Lane 2 merges vendor changes into templates the project shadows, but only into files whose vendor +version changed. Integration guides never place widgets in Twig. So after the lanes and Phase 6, the +storefront can still miss widgets the upgrade added: a vendor template gained a widget call in a block +the project replaced, or a newly registered widget is called only in vendor templates the project +overrides. Skip this phase when the project has no Yves storefront. + +1. `php $YI/yves-integration-scan.php diff` (against the Phase 0 snapshot). It lists only the gaps that + are new since Phase 0; the omissions the project lived with before stay out. +2. Present its suggestion table to the developer: place now / defer / never, per item. This is a + suggestion, not damage: a project may leave a new widget out on purpose. +3. For the picked items, follow the `yves-twig-integration` skill (vendor reference for what and where, + the project's design for how), in its own commit; render each changed page. +4. Unpicked and deferred items go to the handover report (3.5), with their vendor reference. + +`$YI` is `/../yves-twig-integration/scripts/` (the sibling skill shipped in the same plugin), +substituted inline like `$UP`; it writes to `/.ai-dev/yves-integration/`. For the handover report, also list what Spryker released after the starting release, up to the target, that the project could adopt — from the release notes (`spryker-docs-research`), not only the lock diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/references/handover-report.md b/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/references/handover-report.md index 0d1803f..3ad1023 100644 --- a/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/references/handover-report.md +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/references/handover-report.md @@ -179,7 +179,9 @@ release, which ones were fixed and in which pull request, and a pointer to Part are not verified, and list the candidates. - **3.5 Not done in this upgrade** — each item with the reason it was not done: deprecations deferred or kept, features left for later, security fixes that a project override blocks (with the - recommended fix), and topics that a reader can expect but that were out of scope. + recommended fix), storefront placements from Phase 6.1 the developer deferred or declined (widget, + vendor template and block, project file), and topics that a reader can expect but that were out of + scope. ### 4. Existing issues observed diff --git a/plugins/spryker-ai-dev-sdk/skills/yves-atomic-frontend/SKILL.md b/plugins/spryker-ai-dev-sdk/skills/yves-atomic-frontend/SKILL.md index 0d6b46b..1d15df7 100644 --- a/plugins/spryker-ai-dev-sdk/skills/yves-atomic-frontend/SKILL.md +++ b/plugins/spryker-ai-dev-sdk/skills/yves-atomic-frontend/SKILL.md @@ -130,6 +130,7 @@ PHP `src/{ProjectNamespace}/Yves/{Module}/Widget/{Name}Widget.php` + `Theme/defa `{Module}Factory` / `{Module}DependencyProvider` when it calls `getFactory()`. Register in `src/{ProjectNamespace}/Yves/ShopApplication/ShopApplicationDependencyProvider::getGlobalWidgets()` — unregistered widgets render nothing. The tag needs `{% endwidget %}`. Details: `references/components.md`. +A registered core widget that does not show usually lost its call in a project override of the vendor template that places it: `yves-twig-integration` finds those places and puts the call back in the project's design. ## Build and verify diff --git a/plugins/spryker-ai-dev-sdk/skills/yves-twig-integration/README.md b/plugins/spryker-ai-dev-sdk/skills/yves-twig-integration/README.md new file mode 100644 index 0000000..9610947 --- /dev/null +++ b/plugins/spryker-ai-dev-sdk/skills/yves-twig-integration/README.md @@ -0,0 +1,33 @@ +# yves-twig-integration + +Optional storefront step for Spryker feature installs and upgrades. It suggests where a feature's Yves widgets and components belong in the project's own Twig templates and applies only the placements the developer picks. + +Integration guides wire a feature's backend (plugins, config, schema) and leave Yves templates to the project. The vendor templates call the feature's widgets, but a project that overrides a vendor template (page layouts, header, footer, product item) renders its own copy, and the call is gone: the widget is registered and renders nothing. In the b2b marketplace demo, 13 registered widgets are called only in vendor templates the project replaced. + +## How it works + +`scripts/yves-integration-scan.php` builds the template tree the project renders - project templates, vendor templates the project does not override, and the vendor blocks an extending override keeps (an `{% embed %}` block counts as the embedded component's) - and reports each widget or component as `placed`, `missing` (with the vendor call sites the project replaced), `not_registered` or `no_reference`. Plain PHP on the host, no Spryker boot; about a second on a demo shop. + +The skill turns the `missing` items into a suggestion table, waits for the developer's pick, and places each picked item at the equivalent spot of the project template: the vendor decides what and where, the project decides how it looks ([references/placement-rules.md](references/placement-rules.md)). + +## Flow schema + +```mermaid +flowchart TD + A([spryker-feature-install, spryker-upgrade, or the user]) --> B["1 - Scan
--package for a feature
snapshot / diff for an upgrade"] + B --> C["2 - Suggestion table
missing items per project file
not_registered and no_reference listed"] + C --> D{"Developer picks"} + D -- "none / unattended" --> R + D -- "some or all" --> E["3 - Apply one placement
vendor: widget, args, guard, neighbour
project: variables, wrapper, components"] + E --> F["4 - Verify
twig cache, render desktop + mobile,
re-scan reads placed"] + F --> G{"More picked?"} + G -- "yes" --> E + G -- "no" --> R(["5 - Report: applied, declined, not applied"]) +``` + +## Scripts + +| Script | Use | +|---|---| +| `scripts/yves-integration-scan.php` | `scan` (default), `snapshot`, `diff`; `--package=`, `--module=`, `--json`. Writes `.ai-dev/yves-integration/report.json`. | +| `scripts/yves-integration-scan.test.php` | Zero-dependency tests on a generated fixture project: `php scripts/yves-integration-scan.test.php`. | diff --git a/plugins/spryker-ai-dev-sdk/skills/yves-twig-integration/SKILL.md b/plugins/spryker-ai-dev-sdk/skills/yves-twig-integration/SKILL.md new file mode 100644 index 0000000..065504e --- /dev/null +++ b/plugins/spryker-ai-dev-sdk/skills/yves-twig-integration/SKILL.md @@ -0,0 +1,122 @@ +--- +name: yves-twig-integration +description: > + Optional storefront step after a Spryker feature install or upgrade: suggests where the + feature's Yves widgets and components belong in the project's own Twig templates, using the + vendor templates as the reference for what goes where and the project's design for how it looks, + and applies only the placements the developer picks. Integration guides wire the backend + (plugins, config, schema) but leave Yves templates to the project, and a project that overrides a + vendor template loses every widget call inside it, so a registered widget renders nothing. Use + when spryker-feature-install or spryker-upgrade offers the storefront step, or when the user asks + "place the X widget", "why is widget X not shown", "integrate the feature into our storefront", + "which widgets does our shop not render". Never applies anything without the developer's choice. +--- + +# Yves Twig Integration + +Integration guides stop at the backend: they register a widget plugin, but they do not place `{% widget 'X' %}` into the project's templates. The vendor templates do place it, and that only reaches the page while the project uses the vendor template. A project that overrides the template (most demo-based projects override the page layouts, the header, the footer, the product item) renders its own copy, and the call is gone. The widget is registered, the feature is "installed", and the shopper sees nothing. + +This skill closes that gap **as a suggestion**. A scanner compares the vendor templates with the templates the project actually renders and lists every place where the vendor puts a feature's widget or component and the project's override does not. The developer picks which suggestions to apply; the agent applies each one in the project's design, not the vendor's. + +**Optional by design.** Projects drop widgets on purpose (no newsletter in the footer, no reviews on the product card). Present the suggestions, recommend, and apply nothing the developer did not pick. "None" is a valid answer and ends the skill. + +## When it runs + +- **After `spryker-feature-install`**, as its optional storefront step: scoped to the feature's Yves packages. +- **After `spryker-upgrade`**, as its optional storefront lane: the `diff` mode lists only the gaps the upgrade added (a vendor template gained a widget call, a new widget was registered), not the omissions the project lived with before. +- **Standalone**: "why is the X widget not shown", "which widgets does our storefront not render", "place the X widget". Unscoped, the scan covers every registered widget. + +Not for building new widgets or restyling components (`yves-atomic-frontend`), matching a reference site (`match-reference-design`), or the backend wiring of a feature (`spryker-feature-install`). + +## Locate the scanner + +`/scripts/yves-integration-scan.php`, where `` is the path reported as `Base directory for this skill:` when this skill loaded. `$YI` below stands for that scripts directory; substitute it inline as a literal path, run from the project root on the host (plain PHP, no Spryker boot, no container). It writes `report.json` (and `snapshot.json`) to `/.ai-dev/yves-integration/`, created self-gitignoring. It exits 0 with or without suggestions; 2 means a usage error, no project root, or `diff` without a snapshot. + +```bash +php $YI/yves-integration-scan.php --package=spryker-shop/wishlist-widget,spryker-shop/wishlist-page # a feature's packages +php $YI/yves-integration-scan.php --module=WishlistWidget # or Yves module names +php $YI/yves-integration-scan.php # every registered widget +php $YI/yves-integration-scan.php snapshot # before an upgrade +php $YI/yves-integration-scan.php diff # after it: new gaps only +``` + +What it reports per widget or component (statuses, most actionable first): + +| Status | Meaning | What you do | +|---|---|---| +| `missing` | Vendor templates call it, but every call sits in a template or block the project replaced. Each vendor call site is a suggestion: vendor file and line, block chain, snippet, neighbouring lines, the project file that replaced it, and whether that file `extends` the vendor template or `replaces` it. | Offer the placement. | +| `not_registered` | Vendor templates call the widget, but no project dependency provider registers its class. | The backend step is missing: registering it in `ShopApplicationDependencyProvider::getGlobalWidgets()` comes first (`spryker-feature-install` Step 5). A placement renders nothing until then. | +| `no_reference` | No vendor template calls it. | Nothing to copy. Say where the docs place it if they do (`searchAlgoliaDocumentation` ""), or ask the developer. | +| `placed` | A template the project renders calls it. | Nothing to do. | + +With `--package`/`--module`, the scope also covers the module's components that another module's vendor template includes (`molecule('x', 'Module')`), reported as `:@`. In block chains, a `~` marks a block inside an `{% embed %}`: it belongs to the embedded component, so an override of the outer template cannot drop it. + +What it does not see: Twig functions that render content from CMS (`content_banner(...)`, CMS slots), widgets passed in variables, templates of a non-default vendor theme, and whether a vendor template the project does not override is actually reached from a page. Say so when it matters. + +## Step 1 - Scope and scan + +- From a feature install: the Yves packages of the feature - the card's `modules[]` from `getSprykerCapability` that live under `vendor/spryker-shop/` or have a `Yves/` directory, or the packages the feature metapackage required (`composer show spryker-feature/`). Pass them as `--package`. +- From an upgrade: `snapshot` in Phase 0 before `composer update`, `diff` in the storefront lane after it, unscoped. +- Standalone: the widget's package or module, or unscoped. + +Read `report.json`, not only the printed summary: the suggestions carry the snippets and context you need. + +## Step 2 - Suggest, then wait + +Group the `missing` items by project file (one page or component at a time is easier to judge) and present one table: + +```markdown +| # | Widget / component | Where the vendor puts it | Project file (mode) | Recommendation | +|---|---|---|---|---| +| 1 | NewsletterSubscriptionWidget | footer, block body, inside `.box` | ShopUi/.../organisms/footer/footer.twig (replaces) | place - the project footer has a matching content column | +| 2 | DisplayProductAbstractReviewWidget | product item, block rating | ShopUi/.../molecules/product-item/product-item.twig (extends, redefines rating) | skip unless reviews are wanted on cards - the project removed the rating on purpose | +``` + +Base the recommendation on evidence: a project block that was emptied (`{% block rating %}{% endblock %}`) or a comment is a deliberate removal; a project copy that predates the widget, or a redesign that kept the surrounding region, is a candidate. List `not_registered` and `no_reference` items under the table with their next step. + +Ask which numbers to apply (all, some, none). **Apply nothing before the answer.** In an unattended run (no developer to ask), stop here: the table is the result, and the caller's report carries it as a follow-up. + +## Step 3 - Apply each picked placement in the project's design + +Read [references/placement-rules.md](references/placement-rules.md) before the first edit. In short: **the vendor decides what and where, the project decides how it looks.** + +1. **Read the vendor reference** in full - the snippet, its block chain and context, and the surrounding vendor template: the widget's arguments, the condition around it (`{% if widgetExists(...) %}`, a feature flag, a data check), and which neighbouring element it belongs to. +2. **Find the equivalent spot in the project file**, by meaning, never by line number: + - `extends` and the project redefines the block: put the call inside the project's version of that block, where the vendor neighbours are in the project markup. + - `replaces`: find the element that plays the vendor neighbour's role (the same data variable, the same child component, the same block name), and place it there. + - No equivalent region (the page was redesigned): propose a spot with a reason and ask before writing. +3. **Write the call the vendor way, wrap it the project way**: same widget name, arguments (mapped to the variable names the project template defines) and `only`; the vendor guard kept; the vendor wrapper markup and classes not copied - use the wrapper, BEM element and spacing pattern the project file already uses for its siblings. +4. When the widget's own view does not fit the project's design, override **the widget's view** at project level (Twig-only override, project classes) following `yves-atomic-frontend` and the `yves-frontend` rule - never restyle a shared component for it, never edit `vendor/`. +5. Check the glossary keys the widget's view uses exist for every configured locale; a missing key renders as the raw key. + +Edit only the project layer (`src/{ProjectNamespace}/Yves/...`). One placement at a time, then verify it before the next. + +## Step 4 - Verify + +- `docker/sdk console twig:cache:warmer` after a Twig change; `docker/sdk cli npm run yves` only when SCSS or TS changed. +- Render the page that uses the template (the template name usually names it: `page-layout-cart` is the cart, `product-item` appears on catalog and search pages, `footer` on every page), on desktop and mobile widths, with the data the widget needs (a logged-in customer for account widgets, a product with reviews for a review widget). +- Check that the widget renders, sits where the vendor puts it relative to its neighbours, and looks like the project (spacing, typography, buttons) rather than the vendor demo; measure, do not guess (`match-reference-design` section 7 for how). +- Hand per-page checks to the `spryker-verifier` agent when the caller uses it. +- Re-run the scan with the same scope: the applied items read `placed`. + +## Step 5 - Report + +```markdown +## Storefront placement + +- Scope: +- Applied: <# - widget - project file - page verified (evidence)> +- Declined by the developer: <#s> +- Not applied: +- Not covered by the scan: +``` + +Leave the changes unstaged for review; never commit without the developer's confirmation. + +## What you do not do + +- Do not apply a placement the developer did not pick, and do not treat a `missing` item as a defect. +- Do not paste vendor markup or vendor classes into a project template; reuse the project's patterns. +- Do not place by line number, and do not replace a project override with a fresh copy of the vendor template. +- Do not edit `vendor/`, `src/Generated/` or build output. +- Do not place a `not_registered` widget before its registration exists. diff --git a/plugins/spryker-ai-dev-sdk/skills/yves-twig-integration/references/placement-rules.md b/plugins/spryker-ai-dev-sdk/skills/yves-twig-integration/references/placement-rules.md new file mode 100644 index 0000000..fbaac88 --- /dev/null +++ b/plugins/spryker-ai-dev-sdk/skills/yves-twig-integration/references/placement-rules.md @@ -0,0 +1,52 @@ +# Placement rules - vendor reference, project design + +The vendor template answers three questions: **which** widget or component, **with which arguments and condition**, and **next to what**. The project answers the fourth: **how it looks**. Mixing them up produces either a widget in the wrong place or a vendor-styled island in the project's design. + +## Contents + +- Take from the vendor +- Take from the project +- Finding the spot +- Examples +- Traps + +## Take from the vendor + +- The widget name and the full tag: `{% widget 'X' args [...] only %}{% endwidget %}`. Keep `only` and the argument order; a widget's constructor takes positional arguments. +- The guard around it: `{% if widgetExists('X') %}`, `{% widget 'X' %}...{% elsewidget %}...{% endwidget %}`, a data check (`{% if data.product.idProductAbstract %}`), a config or feature flag. Copy it; a missing guard turns an optional widget into an error or an empty wrapper. +- The `use` argument blocks inside the tag (`{% block body %}` inside `{% widget %}`) when the vendor passes markup into the widget: these are part of the call, adapt their classes to the project. +- The position relative to its neighbours: "after the price", "inside the summary, before the checkout button", "in the user menu, after the account link". This is what you look for in the project file. + +## Take from the project + +- Variable names. The vendor passes `data.product.idProductAbstract`; the project override may define `data.product` differently or call it `data.item`. Read the project template's `{% define data = {...} %}` / `{% set %}` lines and map each argument to what exists. When an argument has no equivalent, stop and ask - do not invent a variable. +- The wrapper. Look at how the project file wraps its siblings in the same region - a BEM element (`
`), a grid or spacing class, a project atom - and wrap the widget the same way. Do not copy vendor wrapper classes (`box`, `grid__col--6`, `spacing-bottom--big`) unless the project file already uses them in that region. +- Components. Where the vendor wraps the widget in a ShopUi component (a `title`, a `toggler-item`), use the component the project uses for the same job in that file, if it uses a different one. +- The block structure. Add the call inside an existing project block; when the project template is an `extends`, never add content outside a block (Twig drops it). +- Breakpoints. The vendor may place a widget in a mobile-only or desktop-only container; place it where the project shows the equivalent content on each width. + +When the widget's own view (its `views//.twig`) clashes with the project's design, override that view at project level: `src/{ProjectNamespace}/Yves//Theme/default/views//.twig`, extending the vendor view and changing the blocks that carry markup and classes. That keeps the page template clean and the change local to the widget. + +## Finding the spot + +1. Read the suggestion's `context.before` / `context.after` lines and the vendor template around the call: name the neighbour in words ("the price block", "the add-to-cart form"). +2. Search the project file for that neighbour: the same block name, the same child component include (`molecule('money-price', ...)`), the same data key, the same glossary key in `| trans`. +3. Found: place the call in the same relation to it (before / after / inside), in the project's wrapper. +4. Not found, but the region exists (a summary, a menu): propose the closest position with a reason, ask, then place. +5. Region missing (the project removed or redesigned it): report it as "no equivalent region", do not create one unasked. + +## Examples + +**Extends, block redefined.** Vendor `product-configurator.twig` renders `ProductGroupWidget` in `{% block product_group_widget %}` inside `body`; the project extends it and redefines `body` without `parent()`, so the widget is gone. Place the vendor tag inside the project's `body`, where the project renders the variant selection (the vendor neighbour), in the wrapper the project uses there; or, when the project's `body` is a small change, propose restoring the vendor block with `{{ parent() }}` around the project's additions instead - one line, and later vendor changes keep reaching the page. + +**Replaces.** Vendor `footer.twig` renders `NewsletterSubscriptionWidget` in a `.box` before `footerNavigation`; the project footer is its own markup with `project-footer__column` columns. Place the tag in a new `project-footer__column` (the project's sibling pattern) before the navigation column, not in a `.box` div. + +**Navigation item.** Vendor `navigation-top.twig` renders `CompanyMenuItemWidget` between the customer menu entries; the project header uses its own `user-navigation` molecule. Find where the project renders the account entries, place the widget there, and check the widget's view uses the project's menu item classes - override the widget view if not. + +## Traps + +- `{% widget %}` without `{% endwidget %}` is a Twig syntax error that breaks the whole page. +- A widget placed inside a block that the project template never renders (an `extends` file with content outside blocks, a block hidden by an `{% if %}` that is always false for the test customer) looks applied and shows nothing: render it. +- The compiled Twig cache keeps the old template until `twig:cache:warmer` (or the cache directory is cleared); `yves-atomic-frontend`'s `references/storefront-fixes.md` lists where it lives. +- A widget that needs a logged-in customer, a company user, a cart or a specific product renders empty for the wrong test data; pick data that makes it show before concluding it does not work. +- Two placements of the same widget on one page (the vendor sometimes renders it in a mobile and a desktop container) both need the project's equivalents, or one of them stays empty on that width. diff --git a/plugins/spryker-ai-dev-sdk/skills/yves-twig-integration/scripts/yves-integration-scan.php b/plugins/spryker-ai-dev-sdk/skills/yves-twig-integration/scripts/yves-integration-scan.php new file mode 100644 index 0000000..0d6cd9e --- /dev/null +++ b/plugins/spryker-ai-dev-sdk/skills/yves-twig-integration/scripts/yves-integration-scan.php @@ -0,0 +1,678 @@ +/Yves//Theme// shadows + * vendor///src//Yves//Theme/default/), so the call is gone. + * + * The scanner builds the effective template tree (project files, plus vendor files the project + * does not shadow, plus the vendor blocks an extending project override keeps) and reports per + * subject: + * placed a template the project renders calls it + * missing vendor templates call it, but only in places the project replaced: each + * vendor call site is a suggestion, with the project file that replaced it + * not_registered vendor templates call the widget, but no project dependency provider + * registers its class: the backend step is missing, a placement renders nothing + * no_reference no vendor template calls it: nothing to copy, the developer decides + * + * Subjects: by default every widget a project dependency provider registers. With --module or + * --package, every widget those modules define (registered or not) and every component of those + * modules that another module's vendor template includes (molecule('x', 'Module')). + * + * The report is a list of suggestions, never an instruction: projects drop widgets on purpose. + * + * Usage (from the project root, or set SPRYKER_PROJECT_ROOT): + * php yves-integration-scan.php [scan] [--module=WishlistWidget] [--package=spryker-shop/wishlist-widget] [--json] + * php yves-integration-scan.php snapshot [filters] # before an upgrade: record today's gaps + * php yves-integration-scan.php diff [filters] # after it: only the gaps the upgrade added + * + * Writes report.json (and snapshot.json) to .ai-dev/yves-integration/, or YVES_INTEGRATION_STATE_DIR. + * Exit code: 0 with or without suggestions (they are optional), 2 on a usage or project error. + */ + +declare(strict_types=1); + +const YVES_SCAN_STATUS_PLACED = 'placed'; +const YVES_SCAN_STATUS_MISSING = 'missing'; +const YVES_SCAN_STATUS_NOT_REGISTERED = 'not_registered'; +const YVES_SCAN_STATUS_NO_REFERENCE = 'no_reference'; +const YVES_SCAN_SNIPPET_MAX_LINES = 12; +const YVES_SCAN_CONTEXT_LINES = 2; + +function yves_scan_project_root(): string +{ + $explicit = getenv('SPRYKER_PROJECT_ROOT'); + if (is_string($explicit) && $explicit !== '') { + $real = realpath($explicit); + if ($real === false || !is_file($real . '/composer.json')) { + fwrite(STDERR, "SPRYKER_PROJECT_ROOT does not point at a composer project: $explicit\n"); + exit(2); + } + + return $real; + } + + $dir = (string)getcwd(); + while (true) { + if (is_file($dir . '/composer.json') && is_dir($dir . '/src') && is_dir($dir . '/vendor')) { + return $dir; + } + $parent = dirname($dir); + if ($parent === $dir) { + fwrite(STDERR, "Could not find a Spryker project root (composer.json, src/, vendor/) above the current directory.\n"); + exit(2); + } + $dir = $parent; + } +} + +function yves_scan_state_dir(string $root): string +{ + $explicit = getenv('YVES_INTEGRATION_STATE_DIR'); + $dir = is_string($explicit) && $explicit !== '' ? $explicit : $root . '/.ai-dev/yves-integration'; + if (!is_dir($dir)) { + mkdir($dir, 0775, true); + } + if (!is_file($dir . '/.gitignore')) { + file_put_contents($dir . '/.gitignore', "*\n"); + } + + return $dir; +} + +/** + * @return list project namespaces that have Yves code (src//Yves) + */ +function yves_scan_project_namespaces(string $root): array +{ + $namespaces = []; + foreach (glob($root . '/src/*/Yves', GLOB_ONLYDIR) ?: [] as $dir) { + $namespace = basename(dirname($dir)); + if (!in_array($namespace, ['Generated', 'Orm'], true)) { + $namespaces[] = $namespace; + } + } + + return $namespaces; +} + +/** + * @return list + */ +function yves_scan_files(string $dir, string $extension): array +{ + if (!is_dir($dir)) { + return []; + } + $files = []; + $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir, FilesystemIterator::SKIP_DOTS)); + foreach ($iterator as $file) { + if ($file->isFile() && $file->getExtension() === $extension) { + $files[] = $file->getPathname(); + } + } + sort($files); + + return $files; +} + +/** + * Vendor Yves modules: module name => [package, namespace, dir]. + * + * @return array + */ +function yves_scan_vendor_modules(string $root): array +{ + $modules = []; + foreach (glob($root . '/vendor/*/*/src/*/Yves/*', GLOB_ONLYDIR) ?: [] as $dir) { + if (!preg_match('#/vendor/([^/]+/[^/]+)/src/([^/]+)/Yves/([^/]+)$#', $dir, $m)) { + continue; + } + $modules[$m[3]] ??= ['package' => $m[1], 'namespace' => $m[2], 'dir' => $dir]; + } + + return $modules; +} + +/** + * Template key: "/>", the unit Twig resolves project-first. + */ +function yves_scan_template_key(string $path): ?string +{ + return preg_match('#/Yves/([^/]+)/Theme/[^/]+/(.+\.twig)$#', $path, $m) ? $m[1] . '/' . $m[2] : null; +} + +/** + * Widget classes defined in a Yves module dir: FQCN => name (from getName(), else the class name). + * + * @return array + */ +function yves_scan_widget_classes(string $moduleDir): array +{ + $widgets = []; + foreach (glob($moduleDir . '/Widget/*.php') ?: [] as $file) { + $code = (string)file_get_contents($file); + if (!preg_match('/^namespace\s+([\w\\\\]+);/m', $code, $ns) || !preg_match('/^(final\s+|abstract\s+)?class\s+(\w+)/m', $code, $class)) { + continue; + } + if (trim($class[1]) === 'abstract') { + continue; + } + $name = preg_match('/function\s+getName\s*\(\s*\)[^{]*\{\s*return\s+[\'"]([^\'"]+)[\'"]/', $code, $n) ? $n[1] : $class[2]; + $widgets[$ns[1] . '\\' . $class[2]] = $name; + } + + return $widgets; +} + +/** + * FQCNs referenced as Foo::class in the project's Yves dependency providers, resolved through use statements. + * + * @param list $namespaces + * + * @return array FQCN => dependency provider (relative path) + */ +function yves_scan_registered_classes(string $root, array $namespaces): array +{ + $registered = []; + foreach ($namespaces as $namespace) { + foreach (glob($root . '/src/' . $namespace . '/Yves/*/*DependencyProvider.php') ?: [] as $file) { + $code = (string)file_get_contents($file); + $uses = []; + preg_match_all('/^use\s+([\w\\\\]+)(?:\s+as\s+(\w+))?;/m', $code, $useMatches, PREG_SET_ORDER); + foreach ($useMatches as $use) { + $alias = $use[2] ?? ''; + $uses[$alias !== '' ? $alias : substr((string)strrchr('\\' . $use[1], '\\'), 1)] = $use[1]; + } + preg_match('/^namespace\s+([\w\\\\]+);/m', $code, $ownNamespace); + preg_match_all('/\\\\?([\w\\\\]+)::class/', $code, $classMatches); + foreach ($classMatches[1] as $reference) { + $head = explode('\\', $reference)[0]; + $fqcn = isset($uses[$head]) + ? $uses[$head] . substr($reference, strlen($head)) + : (str_contains($reference, '\\') ? $reference : ($ownNamespace[1] ?? '') . '\\' . $reference); + $registered[ltrim($fqcn, '\\')] ??= substr($file, strlen($root) + 1); + } + } + } + + return $registered; +} + +/** + * Parse a Twig file: references with their enclosing block chain, the blocks it defines, its extends target. + * + * @return array{references: list>, blocks: array, extends: ?string, lines: list} + */ +function yves_scan_parse_twig(string $file): array +{ + $lines = explode("\n", (string)file_get_contents($file)); + $stack = []; + $references = []; + $blocks = []; + $blockStarts = []; + $embedDepth = 0; + $extends = null; + $referenceRe = '/\{%-?\s*widget\s+[\'"](\w+)[\'"]|(?:findWidget|widgetExists|widgetGlobalExists|widgetGlobal)\(\s*[\'"](\w+)[\'"]|\b(atom|molecule|organism|template|view)\(\s*[\'"]([\w-]+)[\'"]\s*,\s*[\'"]@?(?:[\w]+:)?(\w+)[\'"]/'; + + foreach ($lines as $index => $line) { + if ($extends === null && preg_match('/\{%-?\s*extends\s+(.+?)\s*-?%\}/', $line, $m)) { + $extends = $m[1]; + } + + if (preg_match_all($referenceRe, $line, $matches, PREG_SET_ORDER)) { + foreach ($matches as $match) { + if (($match[1] ?? '') !== '') { + $references[] = ['type' => 'widget', 'name' => $match[1], 'kind' => 'tag', 'line' => $index + 1, 'blocks' => $stack]; + } elseif (($match[2] ?? '') !== '') { + $references[] = ['type' => 'widget', 'name' => $match[2], 'kind' => 'function', 'line' => $index + 1, 'blocks' => $stack]; + } elseif (($match[4] ?? '') !== '') { + $references[] = ['type' => 'component', 'name' => $match[3] . ':' . $match[4] . '@' . $match[5], 'module' => $match[5], 'kind' => 'include', 'line' => $index + 1, 'blocks' => $stack]; + } + } + } + + // Blocks inside {% embed %} belong to the embedded component, not to this template: an + // override of this template cannot redefine them, so they are marked with a leading '~'. + preg_match_all('/\{%-?\s*(block\s+(\w+)(.*?)|endblock\b.*?|embed\b.*?|endembed\b.*?)\s*-?%\}/', $line, $tags, PREG_SET_ORDER); + foreach ($tags as $tag) { + if (str_starts_with($tag[1], 'embed')) { + $embedDepth++; + + continue; + } + if (str_starts_with($tag[1], 'endembed')) { + $embedDepth = max(0, $embedDepth - 1); + + continue; + } + if (str_starts_with($tag[1], 'endblock')) { + $closed = array_pop($stack); + if ($closed !== null && !str_starts_with($closed, '~') && isset($blockStarts[$closed])) { + $body = implode("\n", array_slice($lines, $blockStarts[$closed], $index - $blockStarts[$closed] + 1)); + $blocks[$closed] = str_contains($body, 'parent()'); + } + + continue; + } + if (trim($tag[3]) !== '') { + // {% block title 'Shop' %}: a one-line block without endblock. + if ($embedDepth === 0) { + $blocks[$tag[2]] = false; + } + + continue; + } + $stack[] = $embedDepth > 0 ? '~' . $tag[2] : $tag[2]; + if ($embedDepth === 0) { + $blockStarts[$tag[2]] = $index; + } + } + } + + return ['references' => $references, 'blocks' => $blocks, 'extends' => $extends, 'lines' => $lines]; +} + +/** + * Does the project override render the vendor content at this block chain? + * A replacing override renders none of it. An extending one renders it unless it redefines + * a block of the chain without calling parent(). + * + * @param list $chain + * @param array $overrideBlocks block => calls parent() + */ +function yves_scan_vendor_site_survives(bool $overrideExtends, array $chain, array $overrideBlocks): bool +{ + if (!$overrideExtends) { + return false; + } + foreach ($chain as $block) { + if (isset($overrideBlocks[$block]) && $overrideBlocks[$block] === false) { + return false; + } + } + + return true; +} + +/** + * Does the override extend the vendor version of itself (rather than replace it)? + */ +function yves_scan_override_extends_vendor(?string $extends, string $key): bool +{ + if ($extends === null) { + return false; + } + [$module] = explode('/', $key, 2); + + return (bool)preg_match('/[\'"]@(?:Spryker\w*|Spryker):' . preg_quote($module, '/') . '[\'"]/', $extends); +} + +/** + * @param list $lines + */ +function yves_scan_snippet(array $lines, int $line, string $type): string +{ + $start = $line - 1; + $end = $start; + if ($type === 'widget' && preg_match('/\{%-?\s*widget\b/', $lines[$start] ?? '')) { + for ($i = $start; $i < min(count($lines), $start + YVES_SCAN_SNIPPET_MAX_LINES); $i++) { + $end = $i; + if (preg_match('/\{%-?\s*endwidget/', $lines[$i])) { + break; + } + } + } + + return rtrim(implode("\n", array_slice($lines, $start, $end - $start + 1))); +} + +/** + * @param list $lines + * + * @return array{before: list, after: list} + */ +function yves_scan_context(array $lines, int $line, string $snippet): array +{ + $before = []; + for ($i = $line - 2; $i >= 0 && count($before) < YVES_SCAN_CONTEXT_LINES; $i--) { + if (trim($lines[$i]) !== '') { + array_unshift($before, trim($lines[$i])); + } + } + $after = []; + for ($i = $line - 1 + substr_count($snippet, "\n") + 1; $i < count($lines) && count($after) < YVES_SCAN_CONTEXT_LINES; $i++) { + if (trim($lines[$i]) !== '') { + $after[] = trim($lines[$i]); + } + } + + return ['before' => $before, 'after' => $after]; +} + +/** + * @param array{modules: list, packages: list} $filters + * + * @return array + */ +function yves_scan_run(string $root, array $filters): array +{ + $namespaces = yves_scan_project_namespaces($root); + $vendorModules = yves_scan_vendor_modules($root); + + $vendorTemplates = []; + foreach ($vendorModules as $module => $info) { + foreach (yves_scan_files($info['dir'] . '/Theme/default', 'twig') as $file) { + $key = yves_scan_template_key($file); + if ($key !== null) { + $vendorTemplates[$key] = $file; + } + } + } + $projectTemplates = []; + foreach ($namespaces as $namespace) { + foreach (yves_scan_files($root . '/src/' . $namespace . '/Yves', 'twig') as $file) { + $key = yves_scan_template_key($file); + if ($key !== null) { + $projectTemplates[$key] ??= $file; + } + } + } + + $widgetClasses = []; + $widgetModules = []; + foreach ($vendorModules as $module => $info) { + foreach (yves_scan_widget_classes($info['dir']) as $fqcn => $name) { + $widgetClasses[$fqcn] = $name; + $widgetModules[$name] ??= $module; + } + } + foreach ($namespaces as $namespace) { + foreach (glob($root . '/src/' . $namespace . '/Yves/*', GLOB_ONLYDIR) ?: [] as $dir) { + foreach (yves_scan_widget_classes($dir) as $fqcn => $name) { + $widgetClasses[$fqcn] = $name; + $widgetModules[$name] ??= basename($dir); + } + } + } + $registeredNames = []; + foreach (yves_scan_registered_classes($root, $namespaces) as $fqcn => $provider) { + if (isset($widgetClasses[$fqcn])) { + $registeredNames[$widgetClasses[$fqcn]] = $provider; + } + } + + $effective = []; + $vendorSites = []; + $vendorComponentReferences = []; + $parsedProject = []; + foreach ($projectTemplates as $key => $file) { + $parsedProject[$key] = yves_scan_parse_twig($file); + foreach ($parsedProject[$key]['references'] as $reference) { + $effective[$reference['name']][] = substr($file, strlen($root) + 1) . ':' . $reference['line']; + } + } + foreach ($vendorTemplates as $key => $file) { + $parsed = yves_scan_parse_twig($file); + $override = $parsedProject[$key] ?? null; + $overrideExtends = $override !== null && yves_scan_override_extends_vendor($override['extends'], $key); + foreach ($parsed['references'] as $reference) { + $relative = substr($file, strlen($root) + 1); + if ($reference['type'] === 'component') { + $vendorComponentReferences[] = $reference + ['fromModule' => explode('/', $key, 2)[0]]; + } + if ($override === null || yves_scan_vendor_site_survives($overrideExtends, $reference['blocks'], $override['blocks'])) { + $effective[$reference['name']][] = $relative . ':' . $reference['line']; + + continue; + } + $snippet = yves_scan_snippet($parsed['lines'], $reference['line'], $reference['type']); + $sharedBlocks = array_values(array_filter($reference['blocks'], fn (string $block): bool => isset($override['blocks'][$block]))); + $vendorSites[$reference['name']][] = [ + 'vendorFile' => $relative, + 'line' => $reference['line'], + 'kind' => $reference['kind'], + 'blocks' => $reference['blocks'], + 'snippet' => $snippet, + 'context' => yves_scan_context($parsed['lines'], $reference['line'], $snippet), + 'projectFile' => substr($projectTemplates[$key], strlen($root) + 1), + 'overrideMode' => $overrideExtends ? 'extends' : 'replaces', + 'projectBlocks' => $sharedBlocks, + ]; + } + } + + $scopeModules = $filters['modules']; + foreach ($filters['packages'] as $package) { + foreach ($vendorModules as $module => $info) { + if ($info['package'] === strtolower($package)) { + $scopeModules[] = $module; + } + } + } + $scopeModules = array_values(array_unique($scopeModules)); + $scoped = $filters['modules'] !== [] || $filters['packages'] !== []; + + $subjects = []; + if ($scoped) { + foreach ($widgetModules as $name => $module) { + if (in_array($module, $scopeModules, true)) { + $subjects[$name] = ['type' => 'widget', 'module' => $module]; + } + } + // Components of the scoped modules that another module's vendor template includes: the + // page-level placements. Includes inside the module itself travel with its own widgets. + foreach ($vendorComponentReferences as $reference) { + if (in_array($reference['module'], $scopeModules, true) && $reference['fromModule'] !== $reference['module']) { + $subjects[$reference['name']] = ['type' => 'component', 'module' => $reference['module']]; + } + } + } else { + foreach ($registeredNames as $name => $provider) { + $subjects[$name] = ['type' => 'widget', 'module' => $widgetModules[$name] ?? '']; + } + } + + $items = []; + foreach ($subjects as $name => $subject) { + $id = $name; + $placed = $effective[$name] ?? []; + $sites = $vendorSites[$name] ?? []; + $registered = $subject['type'] === 'component' || isset($registeredNames[$name]); + + if (!$registered && ($sites !== [] || $placed !== [])) { + $status = YVES_SCAN_STATUS_NOT_REGISTERED; + } elseif ($placed !== []) { + $status = YVES_SCAN_STATUS_PLACED; + } elseif ($sites !== []) { + $status = YVES_SCAN_STATUS_MISSING; + } else { + $status = YVES_SCAN_STATUS_NO_REFERENCE; + } + + $items[] = [ + 'id' => $id, + 'type' => $subject['type'], + 'name' => $name, + 'module' => $subject['module'], + 'package' => $vendorModules[$subject['module']]['package'] ?? null, + 'registered' => $subject['type'] === 'component' ? null : $registered, + 'registeredIn' => $registeredNames[$name] ?? null, + 'status' => $status, + 'placedAt' => $placed, + 'suggestions' => $status === YVES_SCAN_STATUS_PLACED ? [] : $sites, + ]; + } + usort($items, fn (array $a, array $b): int => [yves_scan_status_rank($a['status']), $a['id']] <=> [yves_scan_status_rank($b['status']), $b['id']]); + + return [ + 'scope' => $scoped ? ['modules' => $scopeModules, 'filters' => $filters] : 'registered widgets', + 'projectNamespaces' => $namespaces, + 'counts' => array_count_values(array_column($items, 'status')), + 'items' => $items, + ]; +} + +function yves_scan_status_rank(string $status): int +{ + return [YVES_SCAN_STATUS_MISSING => 0, YVES_SCAN_STATUS_NOT_REGISTERED => 1, YVES_SCAN_STATUS_NO_REFERENCE => 2, YVES_SCAN_STATUS_PLACED => 3][$status] ?? 4; +} + +/** + * Gap identity for snapshot/diff: the subject, its status and its vendor call sites. + * + * @param array $report + * + * @return array + */ +function yves_scan_gap_keys(array $report): array +{ + $keys = []; + foreach ($report['items'] as $item) { + if ($item['status'] === YVES_SCAN_STATUS_PLACED) { + continue; + } + $keys[$item['id'] . '|' . $item['status']] = true; + foreach ($item['suggestions'] as $site) { + $keys[$item['id'] . '|' . $item['status'] . '|' . $site['vendorFile'] . '|' . trim($site['snippet'])] = true; + } + } + + return $keys; +} + +/** + * Keep only the gaps and call sites that the snapshot did not have. + * + * @param array $report + * @param array $snapshotKeys + * + * @return array + */ +function yves_scan_new_gaps(array $report, array $snapshotKeys): array +{ + $items = []; + foreach ($report['items'] as $item) { + if ($item['status'] === YVES_SCAN_STATUS_PLACED) { + continue; + } + $itemKey = $item['id'] . '|' . $item['status']; + $item['suggestions'] = array_values(array_filter( + $item['suggestions'], + fn (array $site): bool => !isset($snapshotKeys[$itemKey . '|' . $site['vendorFile'] . '|' . trim($site['snippet'])]), + )); + if (!isset($snapshotKeys[$itemKey]) || $item['suggestions'] !== []) { + $items[] = $item; + } + } + $report['items'] = $items; + $report['counts'] = array_count_values(array_column($items, 'status')); + + return $report; +} + +/** + * @param array $report + */ +function yves_scan_print(array $report): void +{ + $counts = $report['counts']; + if (is_array($report['scope']) && $report['scope']['modules'] === []) { + printf( + "Scope: no installed Yves module matches %s - nothing to place (is the package installed, and does it have Yves code?)\n", + implode(', ', array_merge($report['scope']['filters']['modules'], $report['scope']['filters']['packages'])), + ); + + return; + } + printf( + "Scope: %s\nplaced %d, missing %d, not_registered %d, no_reference %d\n", + is_array($report['scope']) ? implode(', ', $report['scope']['modules']) : $report['scope'], + $counts[YVES_SCAN_STATUS_PLACED] ?? 0, + $counts[YVES_SCAN_STATUS_MISSING] ?? 0, + $counts[YVES_SCAN_STATUS_NOT_REGISTERED] ?? 0, + $counts[YVES_SCAN_STATUS_NO_REFERENCE] ?? 0, + ); + foreach ($report['items'] as $item) { + if ($item['status'] === YVES_SCAN_STATUS_PLACED) { + continue; + } + printf("\n[%s] %s %s (%s)\n", $item['status'], $item['type'], $item['name'], $item['package'] ?? $item['module']); + foreach ($item['suggestions'] as $site) { + printf( + " vendor %s:%d%s\n -> project %s (%s%s)\n", + $site['vendorFile'], + $site['line'], + $site['blocks'] !== [] ? ' in block ' . implode(' > ', $site['blocks']) : '', + $site['projectFile'], + $site['overrideMode'], + $site['projectBlocks'] !== [] ? '; project redefines ' . implode(', ', $site['projectBlocks']) : '', + ); + } + } +} + +/** + * @param list $argv + */ +function yves_scan_main(array $argv): int +{ + $mode = 'scan'; + $filters = ['modules' => [], 'packages' => []]; + $json = false; + foreach (array_slice($argv, 1) as $argument) { + if (in_array($argument, ['scan', 'snapshot', 'diff'], true)) { + $mode = $argument; + } elseif (str_starts_with($argument, '--module=')) { + array_push($filters['modules'], ...array_filter(explode(',', substr($argument, 9)))); + } elseif (str_starts_with($argument, '--package=')) { + array_push($filters['packages'], ...array_filter(explode(',', substr($argument, 10)))); + } elseif ($argument === '--json') { + $json = true; + } else { + fwrite(STDERR, "Usage: yves-integration-scan.php [scan|snapshot|diff] [--module=Name,...] [--package=vendor/name,...] [--json]\n"); + + return 2; + } + } + + $root = yves_scan_project_root(); + $stateDir = yves_scan_state_dir($root); + $report = yves_scan_run($root, $filters); + + if ($mode === 'snapshot') { + file_put_contents($stateDir . '/snapshot.json', json_encode(array_keys(yves_scan_gap_keys($report)), JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES)); + printf("Snapshot of %d gap(s) written to %s/snapshot.json\n", count(array_filter($report['items'], fn (array $item): bool => $item['status'] !== YVES_SCAN_STATUS_PLACED)), $stateDir); + + return 0; + } + if ($mode === 'diff') { + $snapshotFile = $stateDir . '/snapshot.json'; + if (!is_file($snapshotFile)) { + fwrite(STDERR, "No snapshot at $snapshotFile: run `snapshot` before the update.\n"); + + return 2; + } + $report = yves_scan_new_gaps($report, array_fill_keys((array)json_decode((string)file_get_contents($snapshotFile), true), true)); + $report['mode'] = 'diff: gaps that are new since the snapshot'; + } + + file_put_contents($stateDir . '/report.json', json_encode($report, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE)); + if ($json) { + echo json_encode($report, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE), "\n"; + } else { + yves_scan_print($report); + printf("\nReport: %s/report.json\n", $stateDir); + } + + return 0; +} + +if (realpath($argv[0] ?? '') === __FILE__) { + exit(yves_scan_main($argv)); +} diff --git a/plugins/spryker-ai-dev-sdk/skills/yves-twig-integration/scripts/yves-integration-scan.test.php b/plugins/spryker-ai-dev-sdk/skills/yves-twig-integration/scripts/yves-integration-scan.test.php new file mode 100644 index 0000000..ff50c60 --- /dev/null +++ b/plugins/spryker-ai-dev-sdk/skills/yves-twig-integration/scripts/yves-integration-scan.test.php @@ -0,0 +1,172 @@ + $classes FQCNs registered in ShopApplicationDependencyProvider + */ +function register_widgets(string $root, array $classes): void +{ + $uses = implode("\n", array_map(fn (string $fqcn): string => "use $fqcn;", $classes)); + $list = implode(",\n ", array_map(fn (string $fqcn): string => substr((string)strrchr($fqcn, '\\'), 1) . '::class', $classes)); + write_file( + "$root/src/Pyz/Yves/ShopApplication/ShopApplicationDependencyProvider.php", + "\n {% widget 'NewsletterSubscriptionWidget' only %}{% endwidget %}\n
\n{% endblock %}\n"); + project_twig($root, 'ShopUi', 'components/organisms/footer/footer.twig', "{% block body %}\n
\n{% endblock %}\n"); + + // Product item: the project extends it; it redefines `rating` without parent(), keeps `groups`, + // and the review widget sits inside an embed whose blocks the override cannot touch. + vendor_twig($root, 'spryker-shop/shop-ui', 'ShopUi', 'components/molecules/product-item/product-item.twig', implode("\n", [ + '{% block body %}', + ' {% block groups %}', + " {% widget 'ProductGroupWidget' args [data.idProductAbstract] only %}{% endwidget %}", + ' {% endblock %}', + ' {% block rating %}', + " {% embed molecule('rating-box', 'ShopUi') %}", + ' {% block content %}', + " {% widget 'DisplayProductAbstractReviewWidget' args [data.idProductAbstract] only %}{% endwidget %}", + ' {% endblock %}', + ' {% endembed %}', + ' {% endblock %}', + " {% include molecule('wishlist-badge', 'WishlistWidget') only %}", + '{% endblock %}', + '', + ])); + project_twig($root, 'ShopUi', 'components/molecules/product-item/product-item.twig', implode("\n", [ + "{% extends molecule('product-item', '@SprykerShop:ShopUi') %}", + '{% block rating %}{% endblock %}', + '', + ])); + + // Cart page: the project keeps the block with parent(), so the note widget still renders. + vendor_twig($root, 'spryker-shop/cart-page', 'CartPage', 'templates/page-layout-cart/page-layout-cart.twig', "{% block content %}\n {% widget 'CartNoteFormWidget' only %}{% endwidget %}\n{% endblock %}\n"); + project_twig($root, 'CartPage', 'templates/page-layout-cart/page-layout-cart.twig', "{% extends template('page-layout-cart', '@SprykerShop:CartPage') %}\n{% block content %}\n
{{ parent() }}
\n{% endblock %}\n"); + + // Navigation calls the wishlist widget, but no dependency provider registers it. + vendor_twig($root, 'spryker-shop/shop-ui', 'ShopUi', 'components/organisms/navigation-top/navigation-top.twig', "{% block body %}\n {% widget 'WishlistMenuItemWidget' only %}{% endwidget %}\n{% endblock %}\n"); + + register_widgets($root, [ + 'SprykerShop\\Yves\\NewsletterWidget\\Widget\\NewsletterSubscriptionWidget', + 'SprykerShop\\Yves\\ProductGroupWidget\\Widget\\ProductGroupWidget', + 'SprykerShop\\Yves\\ProductReviewWidget\\Widget\\DisplayProductAbstractReviewWidget', + 'SprykerShop\\Yves\\CartNoteWidget\\Widget\\CartNoteFormWidget', + 'SprykerShop\\Yves\\OrphanWidget\\Widget\\OrphanWidget', + ]); + + return $root; +} + +/** + * @param array $report + * + * @return array|null + */ +function item(array $report, string $id): ?array +{ + foreach ($report['items'] as $item) { + if ($item['id'] === $id) { + return $item; + } + } + + return null; +} + +$root = fixture_project(); +$empty = ['modules' => [], 'packages' => []]; +$report = yves_scan_run($root, $empty); + +echo "registered widgets\n"; +$newsletter = item($report, 'NewsletterSubscriptionWidget'); +check('a replacing override that drops the call is missing', $newsletter['status'] === YVES_SCAN_STATUS_MISSING); +check('the suggestion names the vendor site and the project file', $newsletter['suggestions'][0]['projectFile'] === 'src/Pyz/Yves/ShopUi/Theme/default/components/organisms/footer/footer.twig' + && $newsletter['suggestions'][0]['overrideMode'] === 'replaces' + && str_contains($newsletter['suggestions'][0]['snippet'], "{% widget 'NewsletterSubscriptionWidget' only %}")); +check('the suggestion carries the neighbouring vendor lines', $newsletter['suggestions'][0]['context']['before'] === ['{% block body %}', '
']); +check('an extending override that keeps the block renders the widget', item($report, 'ProductGroupWidget')['status'] === YVES_SCAN_STATUS_PLACED); +check('a redefined block without parent() drops the widget inside it', item($report, 'DisplayProductAbstractReviewWidget')['status'] === YVES_SCAN_STATUS_MISSING); +check('blocks of an embed are not counted as overridable', item($report, 'DisplayProductAbstractReviewWidget')['suggestions'][0]['blocks'] === ['body', 'rating', '~content']); +check('a redefined block with parent() keeps the widget', item($report, 'CartNoteFormWidget')['status'] === YVES_SCAN_STATUS_PLACED); +check('a registered widget no vendor template calls has no reference', item($report, 'OrphanWidget')['status'] === YVES_SCAN_STATUS_NO_REFERENCE); +check('an unregistered widget is not a subject without a filter', item($report, 'WishlistMenuItemWidget') === null); +check('missing items are listed first', $report['items'][0]['status'] === YVES_SCAN_STATUS_MISSING); + +echo "scoped to packages\n"; +$scoped = yves_scan_run($root, ['modules' => [], 'packages' => ['spryker-shop/wishlist-widget']]); +check('a widget called in vendor but not registered is not_registered', item($scoped, 'WishlistMenuItemWidget')['status'] === YVES_SCAN_STATUS_NOT_REGISTERED); +check('a component another module includes is a subject, placed through a kept block', item($scoped, 'molecule:wishlist-badge@WishlistWidget')['status'] === YVES_SCAN_STATUS_PLACED); +check('only the scoped module is reported', count($scoped['items']) === 2); +$none = yves_scan_run($root, ['modules' => [], 'packages' => ['spryker-shop/not-installed']]); +check('a filter matching no installed module reports nothing', $none['items'] === [] && $none['scope']['modules'] === []); + +echo "snapshot and diff\n"; +$snapshot = yves_scan_gap_keys($report); +check('an unchanged tree has no new gaps', yves_scan_new_gaps(yves_scan_run($root, $empty), $snapshot)['items'] === []); +vendor_twig($root, 'spryker-shop/shop-ui', 'ShopUi', 'components/organisms/footer/footer.twig', "{% block body %}\n
\n {% widget 'NewsletterSubscriptionWidget' only %}{% endwidget %}\n {% widget 'OrphanWidget' only %}{% endwidget %}\n
\n{% endblock %}\n"); +$diff = yves_scan_new_gaps(yves_scan_run($root, $empty), $snapshot); +check('a call site the update added shows up', item($diff, 'OrphanWidget')['status'] === YVES_SCAN_STATUS_MISSING); +check('gaps that existed before stay out of the diff', item($diff, 'NewsletterSubscriptionWidget') === null && count($diff['items']) === 1); + +exec('rm -rf ' . escapeshellarg($root)); +echo "\n$count checks, $failures failed\n"; +exit($failures === 0 ? 0 : 1); From 77f1156f8b0b239994bc4286c236ab795274793c Mon Sep 17 00:00:00 2001 From: Dmitriy Krainiy Date: Fri, 6 Nov 2026 14:46:40 +0100 Subject: [PATCH 03/18] Dropped demo shop examples from the Yves Twig integration skill --- .../spryker-ai-dev-sdk/skills/yves-twig-integration/README.md | 2 +- .../spryker-ai-dev-sdk/skills/yves-twig-integration/SKILL.md | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/plugins/spryker-ai-dev-sdk/skills/yves-twig-integration/README.md b/plugins/spryker-ai-dev-sdk/skills/yves-twig-integration/README.md index 9610947..e6b6b87 100644 --- a/plugins/spryker-ai-dev-sdk/skills/yves-twig-integration/README.md +++ b/plugins/spryker-ai-dev-sdk/skills/yves-twig-integration/README.md @@ -2,7 +2,7 @@ Optional storefront step for Spryker feature installs and upgrades. It suggests where a feature's Yves widgets and components belong in the project's own Twig templates and applies only the placements the developer picks. -Integration guides wire a feature's backend (plugins, config, schema) and leave Yves templates to the project. The vendor templates call the feature's widgets, but a project that overrides a vendor template (page layouts, header, footer, product item) renders its own copy, and the call is gone: the widget is registered and renders nothing. In the b2b marketplace demo, 13 registered widgets are called only in vendor templates the project replaced. +Integration guides wire a feature's backend (plugins, config, schema) and leave Yves templates to the project. The vendor templates call the feature's widgets, but a project that overrides a vendor template (page layouts, header, footer, product item) renders its own copy, and the call is gone: the widget is registered and renders nothing. ## How it works diff --git a/plugins/spryker-ai-dev-sdk/skills/yves-twig-integration/SKILL.md b/plugins/spryker-ai-dev-sdk/skills/yves-twig-integration/SKILL.md index 065504e..1053fc8 100644 --- a/plugins/spryker-ai-dev-sdk/skills/yves-twig-integration/SKILL.md +++ b/plugins/spryker-ai-dev-sdk/skills/yves-twig-integration/SKILL.md @@ -14,7 +14,7 @@ description: > # Yves Twig Integration -Integration guides stop at the backend: they register a widget plugin, but they do not place `{% widget 'X' %}` into the project's templates. The vendor templates do place it, and that only reaches the page while the project uses the vendor template. A project that overrides the template (most demo-based projects override the page layouts, the header, the footer, the product item) renders its own copy, and the call is gone. The widget is registered, the feature is "installed", and the shopper sees nothing. +Integration guides stop at the backend: they register a widget plugin, but they do not place `{% widget 'X' %}` into the project's templates. The vendor templates do place it, and that only reaches the page while the project uses the vendor template. A project that overrides the template (page layouts, the header, the footer and the product item are the usual ones) renders its own copy, and the call is gone. The widget is registered, the feature is "installed", and the shopper sees nothing. This skill closes that gap **as a suggestion**. A scanner compares the vendor templates with the templates the project actually renders and lists every place where the vendor puts a feature's widget or component and the project's override does not. The developer picks which suggestions to apply; the agent applies each one in the project's design, not the vendor's. @@ -95,7 +95,7 @@ Edit only the project layer (`src/{ProjectNamespace}/Yves/...`). One placement a - `docker/sdk console twig:cache:warmer` after a Twig change; `docker/sdk cli npm run yves` only when SCSS or TS changed. - Render the page that uses the template (the template name usually names it: `page-layout-cart` is the cart, `product-item` appears on catalog and search pages, `footer` on every page), on desktop and mobile widths, with the data the widget needs (a logged-in customer for account widgets, a product with reviews for a review widget). -- Check that the widget renders, sits where the vendor puts it relative to its neighbours, and looks like the project (spacing, typography, buttons) rather than the vendor demo; measure, do not guess (`match-reference-design` section 7 for how). +- Check that the widget renders, sits where the vendor puts it relative to its neighbours, and looks like the project (spacing, typography, buttons) rather than the vendor default; measure, do not guess (`match-reference-design` section 7 for how). - Hand per-page checks to the `spryker-verifier` agent when the caller uses it. - Re-run the scan with the same scope: the applied items read `placed`. From 6927a44795738b0cb74afc37a5504560c0f68270 Mon Sep 17 00:00:00 2001 From: Dmitriy Krainiy Date: Mon, 9 Nov 2026 11:32:44 +0100 Subject: [PATCH 04/18] Applied wishlist install trial findings to install, refresh, scan and verify skills - yves-integration-scan: strip Twig comments, check that the including vendor template is reachable or replaced in the project, report placedUndecided and overrideMode "unreachable". - spryker-feature-install: environment preflight reference (stack check, bootstrap proposal, never reset) and glossary-key-check script; spryker-upgrade points to the same preflight. - spryker-refresher: resolve Glue applications from public/Glue*/index.php and deploy entry points instead of the install recipe; API Platform resource, composer.lock and frontend drift rows. - find-existing-capability: capability-search script fallback when the MCP tools are not registered; near-equivalent and leftover-wiring rules. - spryker-verifier: authenticate once per surface before the first AC, check the fixture password hash, report BLOCKED with credentials or environment cause. Co-Authored-By: Claude --- .../agents/spryker-verifier.agent.md | 9 +- .../skills/find-existing-capability/README.md | 8 +- .../skills/find-existing-capability/SKILL.md | 23 +- .../scripts/capability-search.php | 429 ++++++++++++++++++ .../skills/spryker-feature-install/README.md | 21 +- .../skills/spryker-feature-install/SKILL.md | 18 +- .../references/environment-preflight.md | 28 ++ .../scripts/glossary-key-check.php | 219 +++++++++ .../skills/spryker-refresher/README.md | 4 + .../skills/spryker-refresher/SKILL.md | 30 +- .../skills/spryker-upgrade/SKILL.md | 2 + .../skills/yves-twig-integration/README.md | 2 +- .../skills/yves-twig-integration/SKILL.md | 4 +- .../scripts/yves-integration-scan.php | 272 ++++++++++- .../scripts/yves-integration-scan.test.php | 76 ++++ 15 files changed, 1092 insertions(+), 53 deletions(-) create mode 100644 plugins/spryker-ai-dev-sdk/skills/find-existing-capability/scripts/capability-search.php create mode 100644 plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/references/environment-preflight.md create mode 100644 plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/glossary-key-check.php diff --git a/plugins/spryker-ai-dev-sdk/agents/spryker-verifier.agent.md b/plugins/spryker-ai-dev-sdk/agents/spryker-verifier.agent.md index 3d9004d..a1ba364 100644 --- a/plugins/spryker-ai-dev-sdk/agents/spryker-verifier.agent.md +++ b/plugins/spryker-ai-dev-sdk/agents/spryker-verifier.agent.md @@ -40,7 +40,7 @@ Then wait ~500ms for the stylesheet to re-fetch, then assert. Same applies to bu `spryker-qa-coverage` covers permission-gated-failures-aren't-defects, picking the actor whose role matches, the reproduce-before-fail (≥3 loads) discipline for inert-button claims, and ruling out stale cache / the inert Zed-JS bootstrap race before failing. Apply all of that. The two points that bind *tighter* for an assertion-only gate: -- **Login failure is a credentials question, not a defect — report, don't debug.** If a login attempt fails (401, "invalid credentials", redirect back to login, role-mismatch), **stop and return BLOCKED** naming the account that failed and the credential needed. Do not try alternate emails/passwords, do not invoke `spryker-issue-diagnoser`, do not dig through logs. (`spryker-runtime` covers the DB lookup for real accounts; if that still doesn't authenticate, return BLOCKED.) +- **Login failure is a credentials question, not a defect — report, don't debug.** If a login attempt fails (401, "invalid credentials", redirect back to login, role-mismatch), **stop and return BLOCKED** naming the account that failed and the credential needed. Do not try alternate emails/passwords, do not invoke `spryker-issue-diagnoser`, do not dig through logs. (`spryker-runtime` covers the DB lookup for real accounts; if that still doesn't authenticate, return BLOCKED.) One read-only check separates the two causes: compare the fixture password with the account's stored hash (`password_verify` against the `spy_customer` / `spy_user` row). No match → **BLOCKED (credentials)**, naming the credential needed. Match, yet the login still fails → **BLOCKED (environment: authentication)**: the account is right and the stack's login path is broken (in one trial, every fixture customer got a Glue 401 although the hashes matched and the OAuth table had never issued a token). Say so under `## Environment caveats` and recommend `spryker-issue-diagnoser` to the caller instead of failing feature criteria. - **A permission-gated denial maps to a verdict, not a FAIL.** When an action fails because the test user's role lacks the required permission plugin, that's expected behavior — mark **BLOCKED** (naming the missing permission) or switch to a user who has it. Never mark the AC FAIL or escalate to `spryker-issue-diagnoser` for a defect that doesn't exist. ## Running in the browser @@ -48,8 +48,9 @@ Then wait ~500ms for the stylesheet to re-fetch, then assert. Same applies to bu **Drive the local shop through a browser-automation MCP server**, not a built-in browser pane that prompts the person for each action on a local host. The `spryker-runtime` skill's **Browser tool map** gives the tool name for each capability under Claude in Chrome and under Playwright MCP. - **Seeded credentials are test fixtures, and logging in with them is part of your task.** They - live in the repository (the customer rows and the installer user config); read the account you need and - use it. Never guess a password, and do not report a login-gated criterion as unverifiable: the executor + live in the repository (the customer rows, the installer user config, and the E2E fixtures under + `tests/cypress-tests/cypress/fixtures/**`, which carry the customer emails and a shared `defaultPassword`); + read the account you need and use it. Never print a password in the report; name the fixture file instead. Never guess a password, and do not report a login-gated criterion as unverifiable: the executor that spawned you does not log in, so the login is yours to perform. When your prompt says the browser is already logged in as the user you need, confirm it on the first page and skip the login; if it is not, log in yourself. @@ -89,7 +90,7 @@ For each AC: 1. **Restate the AC in your own words.** If compound (*"X happens AND Y happens AND Z happens"*), enumerate each part separately. **Every part is verified individually** — a PASS verdict requires all parts asserted, not a subset. 2. **Decompose into observable assertions; pick the right surface(s)** (UI / API / DB / Console — `spryker-qa-coverage` chooses the lightest mode that genuinely proves each and tags the execution layer; for a user-facing AC that means the real UI path, not a cheaper endpoint hit). Each part of the AC must have at least one assertion targeting it directly — not a related-but-different one. *"The page loaded without errors"* does not substitute for *"the new badge displayed the value X"*. -3. **Confirm preconditions** (logged-in user with the right role, target entity exists). If a precondition isn't met, mark **BLOCKED** (noting the missing precondition) and stop — do not seed data yourself. +3. **Confirm preconditions** (logged-in user with the right role, target entity exists). If a precondition isn't met, mark **BLOCKED** (noting the missing precondition) and stop — do not seed data yourself. **Authenticate once before the first AC, per surface the ACs use:** one storefront login, one Glue `access-tokens` request, one Back Office login. A failure there blocks every AC on that surface: return early with the cause (credentials or environment, see the login rule above) instead of running each AC into the same wall. 4. **Execute assertions adversarially — try to fail the AC.** For each assertion ask: *"What's the most realistic way this could be broken? If it were broken, would my current assertion catch it?"* If it can't distinguish broken from working (e.g. you're only asserting absence-of-errors), strengthen it. 5. **Capture concrete evidence per assertion** — actual values, screenshots or GIFs (use `spryker-runtime`'s capture flow; where GIF recording is unavailable, a numbered screenshot per step), actual DB rows. *"It looked right"* is not evidence. Evidence must be reproducible by a third party. 6. **Verdict per AC** — use `spryker-qa-coverage`'s status vocabulary so the report is unified: diff --git a/plugins/spryker-ai-dev-sdk/skills/find-existing-capability/README.md b/plugins/spryker-ai-dev-sdk/skills/find-existing-capability/README.md index e82aede..6efb278 100644 --- a/plugins/spryker-ai-dev-sdk/skills/find-existing-capability/README.md +++ b/plugins/spryker-ai-dev-sdk/skills/find-existing-capability/README.md @@ -17,7 +17,9 @@ flowchart TD A([Feature request / requirement list]) --> B["1 - Capability nouns + synonyms
3-6 short queries per requirement"] B --> C["2 - searchSprykerCapabilities
one call per query, merge by slug"] C --> T{"Tool available?"} - T -- "no" --> T1["Start server, ask for /mcp reload
after two failures: web fallback
INDEX.md + card, compare composer.lock
(weaker ranking, say so)"] --> D + T -- "no" --> T0{"Server registered?"} + T0 -- "no" --> T2["Say so once, point to ai-dev-setup Step 3
run scripts/capability-search.php
(weaker ranking, say so)"] --> D + T0 -- "yes, not connected" --> T1["Start server, ask for an MCP reload
after two failures: the same script
PHP or network fails: INDEX.md + card"] --> D T -- "yes" --> D["3 - getSprykerCapability
on the top hits
read What it does, Extend don't duplicate,
Extension points, Install, Related cards"] D --> V{"4 - Verdict per hit"} V -- "installed" --> V1["Extend it
extension points + getSprykerModuleMap
then spryker-customization"] @@ -34,11 +36,11 @@ flowchart TD ## Tools -Matched by tool name (server names are install-specific): `searchSprykerCapabilities`, `getSprykerCapability`, `getSprykerModuleMap`, `getSprykerModules`, `searchAlgoliaDocumentation`. Without the MCP server the skill falls back to fetching `INDEX.md` and `.md` from `https://spryker-capability-map.s3.eu-central-1.amazonaws.com/` and comparing the card's packages to `composer.lock` by hand. +Matched by tool name (server names are install-specific): `searchSprykerCapabilities`, `getSprykerCapability`, `getSprykerModuleMap`, `getSprykerModules`, `searchAlgoliaDocumentation`. Without the MCP server the skill first checks whether the server is registered at all (`.mcp.json`, `.vscode/mcp.json`, the harness's list); if not, it points to `ai-dev-setup` Step 3 once and skips the start-and-reload loop. The fallback is the bundled `scripts/capability-search.php`, which reads the published `index.json` (cached 24 h; `--index` or `CAPABILITY_MAP_INDEX_URL` for a mirror or a local file), searches it and prints the same fields as the tool, with `installStatus` computed from `composer.lock`; its ranking is simpler than the tool's. Only when PHP or the network fails does it fetch `INDEX.md` and `.md` from `https://spryker-capability-map.s3.eu-central-1.amazonaws.com/` and compare the card's packages to `composer.lock` by hand. ## Output -A verdict table (requirement, capability and card, verdict, next step) and one **Reuse decision** block per capability: capability, verdict, evidence, next step, and the card link `https://spryker-capability-map.s3.eu-central-1.amazonaws.com/.md`. +A verdict table (requirement, capability and card, verdict, next step) and one **Reuse decision** block per capability: capability, verdict, evidence, "may already cover this" (an installed card matching through its title or synonyms, e.g. `shopping-list` for a wishlist request), existing project wiring (plugins, routes, widgets already tied to the card's modules), next step, and the card link `https://spryker-capability-map.s3.eu-central-1.amazonaws.com/.md`. ## Design decisions baked in diff --git a/plugins/spryker-ai-dev-sdk/skills/find-existing-capability/SKILL.md b/plugins/spryker-ai-dev-sdk/skills/find-existing-capability/SKILL.md index e0b433c..48d3ebc 100644 --- a/plugins/spryker-ai-dev-sdk/skills/find-existing-capability/SKILL.md +++ b/plugins/spryker-ai-dev-sdk/skills/find-existing-capability/SKILL.md @@ -39,14 +39,27 @@ Match tools by **tool name** (server names vary by install; some clients namespa A tool result of `{"error": "..."}` is a failure, not an empty result: report it and use the fallback below. -**If the capability tools are not available** (the Spryker tooling MCP server is not connected): try to start the server the way `product-requirement-document` does - the underlying server backs the local app, so `script -q /dev/null docker/sdk run` (or `up`) brings it up - then ask the user to reload the MCP connection (for example `/mcp`) and wait for confirmation. After a second failed reconnect, use the **web fallback**: +**If the capability tools are not available**, first tell the two causes apart. The server is **not registered** when no `ai-dev:mcp-server` entry exists in the project's MCP config files (`.mcp.json`, `.vscode/mcp.json`) and the harness's MCP server list does not show it. It is **registered but not connected** when an entry exists and the tools are still missing. + +- **Not registered:** say so once, in one line - the project has not run `ai-dev-setup` Step 3 (it registers the server; `.mcp.json` is its project-scoped option) - and go straight to the script fallback below. Do not start the stack or ask for a reload: there is nothing to reconnect. Offer `ai-dev-setup` at the end of the report as the way to get the tools in a new session. +- **Registered but not connected:** try to start the server the way `product-requirement-document` does - the underlying server backs the local app, so `script -q /dev/null docker/sdk run` (or `up`) brings it up - then ask the user to reload the MCP connection (the harness's MCP command) and wait for confirmation. After a second failed reconnect, use the fallback. + +**Fallback.** Run the bundled script from the project root. It reads `index.json` (cached 24 h), searches it and prints, per hit, the fields the tool returns (`slug`, `capability`, `status`, `matched`, `installStatus` from `composer.lock`, `features`, `missingPackages`, `missingOptionalPackages`, `composerRequire`, `url`), so the rest of this skill applies unchanged: + +```bash +php /scripts/capability-search.php "wishlist" "shopping list" "budget spending limit" [--limit=10] [--index=] [--lock=] +``` + +Each quoted argument is one query (Step 1). It prints a one-line summary, then one line of JSON; the mirror can also be set with the `CAPABILITY_MAP_INDEX_URL` environment variable. Exit code 2 is a usage error, 3 means the index could not be loaded. In place of `getSprykerCapability`, fetch the hit's `url` (the card). + +If PHP is not available or the script cannot load the index, use the **web fallback**: 1. Fetch `https://spryker-capability-map.s3.eu-central-1.amazonaws.com/INDEX.md` with the harness's web fetch tool, or `curl -s`. It has one entry per card with its modules, features and synonyms. 2. Search it for each term and its synonyms yourself; note the candidate slugs. 3. Fetch each candidate card from `https://spryker-capability-map.s3.eu-central-1.amazonaws.com/.md`. 4. Compare the card's `vendor/spryker/` modules and its `spryker-feature/` against the project's `composer.lock` by hand (the built-in file read/search tools). -Say plainly in the report that you used the fallback and that **ranking is weaker** in that mode (no scoring, no computed install status), so a miss means less. +Say plainly in the report that you used a fallback and that **ranking is weaker** in that mode (the script scores by title, synonyms, modules and body text, simpler than the tool; the web fallback has no scoring and no computed install status), so a miss means less. ## Step 1 - Extract the capability nouns @@ -83,6 +96,10 @@ One verdict per capability, driven by the card's `status` and the computed `inst **One request, several hits.** When two cards cover parts of the request, give each its own verdict and say how they combine. When a hit only partly matches (it does half of what was asked), say which half. +**Installed near-equivalent.** When the main verdict is install or build, and an **installed** card matches the need through its title or synonyms (`shopping-list`, with the synonyms "wish list" and "save for later", for a wishlist request), report it as **"may already cover this"** next to the main verdict, with the synonym that matched and what it would not do. The user may prefer the installed alternative to a new install. + +**Leftover project wiring.** Whatever the verdict, grep the project namespace (`src//`, the `psr-4` prefix in `composer.json`; skip `src/Generated` and `src/Orm`) for the card's modules (module names, `Spryker\...\` namespaces) and its plugin classes, and list what is already wired: plugins in dependency providers, content types, route patterns, widgets. A project can carry wiring for a feature that is not installed (the project once had it, or a demo shop removed it partly), and that changes the install scope. + ## Version drift The map describes the latest release line. The project may be older. When a capability matters and a module's installed `version` (from the card's `modules[]`) looks old for the feature, read the module's code in `vendor/spryker/` or call `getSprykerModuleMap` before relying on a card detail (an extension point, a Glue resource, a config key). When the project is clearly behind, say so and suggest the `spryker-upgrade` skill instead of working around the gap. @@ -103,6 +120,8 @@ End with a verdict table and one **Reuse decision** block per capability that ma - Capability: - Verdict: extend (installed) | install missing part | install feature then extend | build only the gap | build new (no relevant hit) - Evidence: +- May already cover this: +- Existing wiring: - Next step: - Card: https://spryker-capability-map.s3.eu-central-1.amazonaws.com/.md ``` diff --git a/plugins/spryker-ai-dev-sdk/skills/find-existing-capability/scripts/capability-search.php b/plugins/spryker-ai-dev-sdk/skills/find-existing-capability/scripts/capability-search.php new file mode 100644 index 0000000..4d7d3cb --- /dev/null +++ b/plugins/spryker-ai-dev-sdk/skills/find-existing-capability/scripts/capability-search.php @@ -0,0 +1,429 @@ +" ["" ...] [--limit=10] [--index=] [--lock=] [--json] + * + * Each positional argument is one query of space-separated terms (3+ characters; short terms + * match whole words only), like the tool's `query`. Run several short queries in one call. + * --index index.json URL or local file; a mirror. Default: env CAPABILITY_MAP_INDEX_URL, then + * https://spryker-capability-map.s3.eu-central-1.amazonaws.com/index.json + * --lock composer.lock to read (default: /composer.lock) + * --json print only the JSON line (no summary line) + * + * Output: a one-line summary, then one line of compact JSON + * {queries: [{query, terms, count, hits[]}], source: {url, stale}, note}. + * A downloaded index is cached for 24 hours in CAPABILITY_MAP_STATE_DIR (default: + * /ai-dev-capability-map); an expired cache is used, flagged stale, when the download fails. + * Exit code: 0 on success (also with no hits), 2 on a usage error, 3 when the index cannot be loaded. + */ + +declare(strict_types=1); + +const CAPSEARCH_DEFAULT_INDEX_URL = 'https://spryker-capability-map.s3.eu-central-1.amazonaws.com/index.json'; +const CAPSEARCH_CACHE_TTL = 86400; +const CAPSEARCH_TIMEOUT = 15; +const CAPSEARCH_MIN_TERM_LENGTH = 3; +const CAPSEARCH_SHORT_TERM_LENGTH = 4; +const CAPSEARCH_MIN_STEM_LENGTH = 3; +const CAPSEARCH_MAX_LIMIT = 50; +const CAPSEARCH_STEM_SUFFIXES = ['ies', 'es', 's']; +const CAPSEARCH_STATUS_RANK = ['shipped' => 0, 'partial' => 1, 'planned' => 2]; +const CAPSEARCH_OPTIONAL_MARKERS = ['-rest-api', '-storefront-api', '-backend-api']; +const CAPSEARCH_NOTE = 'Fallback search (no MCP server): ranking is weaker than the tool. The map describes the latest Spryker release line; ' + . 'an installed package may be older than its card. No hit is not proof that Spryker lacks the capability: also search the documentation and the installed modules before building new.'; + +function capsearch_fail(string $message, int $code): never +{ + fwrite(STDERR, $message . "\n"); + exit($code); +} + +/** + * @return array{queries: array, limit: int, index: string, lock: string|null, json: bool} + */ +function capsearch_parse_args(array $argv): array +{ + $queries = []; + $limit = 10; + $index = null; + $lock = null; + $json = false; + + foreach (array_slice($argv, 1) as $arg) { + if (str_starts_with($arg, '--limit=')) { + $limit = max(1, min(CAPSEARCH_MAX_LIMIT, (int)substr($arg, 8))); + } elseif (str_starts_with($arg, '--index=')) { + $index = substr($arg, 8); + } elseif (str_starts_with($arg, '--lock=')) { + $lock = substr($arg, 7); + } elseif ($arg === '--json') { + $json = true; + } elseif (str_starts_with($arg, '--')) { + capsearch_fail("Unknown option: $arg", 2); + } else { + $queries[] = $arg; + } + } + + if ($queries === []) { + capsearch_fail('Usage: php capability-search.php "" ["" ...] [--limit=10] [--index=] [--lock=] [--json]', 2); + } + + if ($index === null || $index === '') { + $env = getenv('CAPABILITY_MAP_INDEX_URL'); + $index = is_string($env) && $env !== '' ? $env : CAPSEARCH_DEFAULT_INDEX_URL; + } + + return ['queries' => $queries, 'limit' => $limit, 'index' => $index, 'lock' => $lock, 'json' => $json]; +} + +function capsearch_project_root(): ?string +{ + $explicit = getenv('SPRYKER_PROJECT_ROOT'); + if (is_string($explicit) && $explicit !== '') { + $real = realpath($explicit); + + return $real === false ? null : $real; + } + + $dir = (string)getcwd(); + while (true) { + if (is_file($dir . '/composer.json')) { + return $dir; + } + $parent = dirname($dir); + if ($parent === $dir) { + return null; + } + $dir = $parent; + } +} + +/** + * @return array|null package name (lowercase) => version, null without a readable composer.lock + */ +function capsearch_installed_packages(?string $lockPath): ?array +{ + if ($lockPath === null || !is_file($lockPath)) { + return null; + } + + $lock = json_decode((string)file_get_contents($lockPath), true); + if (!is_array($lock)) { + return null; + } + + $installed = []; + foreach (['packages', 'packages-dev'] as $section) { + foreach ($lock[$section] ?? [] as $package) { + if (is_array($package) && isset($package['name'])) { + $installed[strtolower((string)$package['name'])] = (string)($package['version'] ?? ''); + } + } + } + + return $installed; +} + +function capsearch_decode_index(string $content): ?array +{ + $index = json_decode($content, true); + + return is_array($index) && isset($index['cards']) && is_array($index['cards']) ? $index : null; +} + +function capsearch_download(string $url): ?string +{ + if (function_exists('curl_init')) { + $handle = curl_init($url); + curl_setopt_array($handle, [CURLOPT_RETURNTRANSFER => true, CURLOPT_FOLLOWLOCATION => true, CURLOPT_TIMEOUT => CAPSEARCH_TIMEOUT, CURLOPT_FAILONERROR => true]); + $body = curl_exec($handle); + + return is_string($body) ? $body : null; + } + + $context = stream_context_create(['http' => ['timeout' => CAPSEARCH_TIMEOUT], 'https' => ['timeout' => CAPSEARCH_TIMEOUT]]); + $body = @file_get_contents($url, false, $context); + + return is_string($body) ? $body : null; +} + +/** + * @return array{cards: array>, stale: bool} + */ +function capsearch_load_index(string $source): array +{ + $isUrl = (bool)preg_match('#^https?://#i', $source); + + if (!$isUrl) { + $content = is_file($source) ? (string)file_get_contents($source) : ''; + $index = capsearch_decode_index($content); + if ($index === null) { + capsearch_fail("The capability map index could not be read from $source", 3); + } + + return ['cards' => $index['cards'], 'stale' => false]; + } + + $stateDir = getenv('CAPABILITY_MAP_STATE_DIR'); + $stateDir = is_string($stateDir) && $stateDir !== '' ? $stateDir : sys_get_temp_dir() . '/ai-dev-capability-map'; + $cacheFile = $stateDir . '/index-' . substr(md5($source), 0, 12) . '.json'; + + if (is_file($cacheFile) && time() - (int)filemtime($cacheFile) < CAPSEARCH_CACHE_TTL) { + $index = capsearch_decode_index((string)file_get_contents($cacheFile)); + if ($index !== null) { + return ['cards' => $index['cards'], 'stale' => false]; + } + } + + $body = capsearch_download($source); + $index = $body === null ? null : capsearch_decode_index($body); + if ($index !== null) { + if (is_dir($stateDir) || @mkdir($stateDir, 0775, true)) { + $tmp = $cacheFile . '.' . getmypid() . '.tmp'; + if (@file_put_contents($tmp, $body) !== false) { + @rename($tmp, $cacheFile); + } + } + + return ['cards' => $index['cards'], 'stale' => false]; + } + + $index = is_file($cacheFile) ? capsearch_decode_index((string)file_get_contents($cacheFile)) : null; + if ($index !== null) { + return ['cards' => $index['cards'], 'stale' => true]; + } + + capsearch_fail("The capability map could not be loaded from $source (download failed, no cache). Use the INDEX.md and card fetch fallback.", 3); +} + +/** + * @return array + */ +function capsearch_extract_terms(string $query): array +{ + $terms = preg_split('/[\s,;]+/u', mb_strtolower(trim($query)), -1, PREG_SPLIT_NO_EMPTY) ?: []; + + return array_values(array_unique(array_filter($terms, fn (string $term): bool => mb_strlen($term) >= CAPSEARCH_MIN_TERM_LENGTH))); +} + +function capsearch_stem(string $term): string +{ + foreach (CAPSEARCH_STEM_SUFFIXES as $suffix) { + if (str_ends_with($term, $suffix) && mb_strlen($term) - mb_strlen($suffix) >= CAPSEARCH_MIN_STEM_LENGTH) { + return mb_substr($term, 0, -mb_strlen($suffix)); + } + } + + return $term; +} + +function capsearch_count(string $term, string $lowerText): int +{ + $total = 0; + foreach (array_unique([capsearch_stem($term), $term]) as $variant) { + if (mb_strlen($variant) <= CAPSEARCH_SHORT_TERM_LENGTH) { + $total += (int)preg_match_all('/\b' . preg_quote($variant, '/') . '\w{0,2}\b/u', $lowerText); + + continue; + } + $total += substr_count($lowerText, $variant); + } + + return $total; +} + +/** + * @param array $card + * @param array $terms + * + * @return array{card: array, matched: array>, sortKey: array}|null + */ +function capsearch_score_card(array $card, array $terms): ?array +{ + $strongText = mb_strtolower(($card['capability'] ?? '') . ' ' . implode(' ', $card['synonyms'] ?? [])); + $moduleText = mb_strtolower(implode(' ', $card['modules'] ?? [])); + $bodyText = mb_strtolower(implode("\n", $card['sections'] ?? [])); + + $strongWeight = 0; + $strong = $modules = $body = []; + foreach ($terms as $term) { + $count = capsearch_count($term, $strongText); + $strongWeight += $count; + if ($count > 0) { + $strong[] = $term; + } + if (capsearch_count($term, $moduleText) > 0) { + $modules[] = $term; + } + if (capsearch_count($term, $bodyText) > 0) { + $body[] = $term; + } + } + + if ($strong === [] && $modules === [] && $body === []) { + return null; + } + + $bodyOnly = array_values(array_diff($body, $strong, $modules)); + + return [ + 'card' => $card, + 'matched' => ['capability' => $strong, 'modules' => $modules, 'body' => $bodyOnly], + 'sortKey' => [-count($strong), -$strongWeight, -count($modules), -count($bodyOnly), CAPSEARCH_STATUS_RANK[$card['status'] ?? ''] ?? 3], + ]; +} + +/** + * @param array $card + * @param array|null $installed + * + * @return array + */ +function capsearch_install_status(array $card, ?array $installed): array +{ + $features = []; + foreach ($card['features'] ?? [] as $name) { + $key = strtolower((string)$name); + $features[] = ['name' => $name, 'installed' => $installed === null ? null : isset($installed[$key]), 'version' => $installed[$key] ?? null]; + } + + $modules = []; + foreach ($card['modules'] ?? [] as $path) { + if (!str_starts_with((string)$path, 'vendor/')) { + continue; + } + $package = strtolower(substr((string)$path, 7)); + $optional = false; + foreach (CAPSEARCH_OPTIONAL_MARKERS as $marker) { + $optional = $optional || str_contains($package, $marker); + } + $modules[] = ['package' => $package, 'optional' => $optional, 'installed' => $installed === null ? null : isset($installed[$package])]; + } + + $missing = fn (array $entries, string $key): array => array_values(array_map(fn (array $e) => $e[$key], array_filter($entries, fn (array $e): bool => $e['installed'] === false))); + $required = array_filter($modules, fn (array $m): bool => !$m['optional']); + $missingPackages = $missing($required, 'package'); + $missingOptional = $missing(array_filter($modules, fn (array $m): bool => $m['optional']), 'package'); + $missingFeatures = $missing($features, 'name'); + + if ($installed === null) { + $status = 'unknown'; + } else { + $checked = $required ?: $modules; + if ($checked === []) { + $status = count($missingFeatures) < count($features) ? 'installed' : 'not_installed'; + } else { + $count = count(array_filter($checked, fn (array $m): bool => $m['installed'] === true)); + $status = $count === count($checked) ? 'installed' : ($count > 0 ? 'partially_installed' : 'not_installed'); + } + } + + // One feature is required by name; several features are alternatives, so the missing module packages are named instead. + $toRequire = count($features) === 1 && $missingFeatures !== [] ? $missingFeatures : $missingPackages; + $composerRequire = $status === 'installed' || $toRequire === [] ? null : 'composer require ' . implode(' ', $toRequire); + + return [ + 'installStatus' => $status, + 'features' => $features, + 'missingPackages' => $missingPackages, + 'missingOptionalPackages' => $missingOptional, + 'composerRequire' => $composerRequire, + ]; +} + +function capsearch_card_url(string $indexSource, array $card): string +{ + $isUrl = (bool)preg_match('#^https?://#i', $indexSource); + $base = $isUrl ? substr($indexSource, 0, (int)strrpos($indexSource, '/') + 1) : CAPSEARCH_DEFAULT_INDEX_URL; + $base = $isUrl ? $base : substr($base, 0, (int)strrpos($base, '/') + 1); + + return $base . ($card['file'] ?? ''); +} + +/** + * @param array> $cards + * @param array|null $installed + * + * @return array + */ +function capsearch_run_query(string $query, array $cards, ?array $installed, int $limit, string $indexSource): array +{ + $terms = capsearch_extract_terms($query); + $scored = []; + foreach ($cards as $card) { + if (($card['status'] ?? '') === 'planned') { + continue; + } + $hit = $terms === [] ? null : capsearch_score_card($card, $terms); + if ($hit !== null) { + $scored[] = $hit; + } + } + usort($scored, fn (array $a, array $b): int => $a['sortKey'] <=> $b['sortKey']); + + $hits = []; + foreach (array_slice($scored, 0, $limit) as $hit) { + $card = $hit['card']; + $hits[] = [ + 'slug' => basename((string)($card['file'] ?? ''), '.md'), + 'capability' => $card['capability'] ?? '', + 'status' => $card['status'] ?? '', + 'matched' => $hit['matched'], + ] + capsearch_install_status($card, $installed) + ['url' => capsearch_card_url($indexSource, $card)]; + } + + return ['query' => $query, 'terms' => $terms, 'count' => count($hits), 'hits' => $hits]; +} + +function capsearch_main(array $argv): void +{ + $args = capsearch_parse_args($argv); + + $lockPath = $args['lock']; + if ($lockPath === null) { + $root = capsearch_project_root(); + $lockPath = $root === null ? null : $root . '/composer.lock'; + } + $installed = capsearch_installed_packages($lockPath); + + $index = capsearch_load_index($args['index']); + + $queries = []; + $summary = []; + foreach ($args['queries'] as $query) { + $result = capsearch_run_query($query, $index['cards'], $installed, $args['limit'], $args['index']); + $queries[] = $result; + $top = array_slice(array_map(fn (array $h): string => $h['slug'] . ' (' . $h['installStatus'] . ')', $result['hits']), 0, 3); + $summary[] = '"' . $query . '": ' . ($result['count'] === 0 ? 'no hits' : implode(', ', $top)); + } + + $output = [ + 'queries' => $queries, + 'source' => ['url' => $args['index'], 'stale' => $index['stale']], + 'note' => CAPSEARCH_NOTE, + ]; + + if (!$args['json']) { + echo 'capability-search: ' . implode(' | ', $summary) + . ($installed === null ? ' [no composer.lock: installStatus unknown]' : '') + . ($index['stale'] ? ' [stale cache]' : '') . "\n"; + } + echo json_encode($output, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) . "\n"; +} + +capsearch_main($argv); diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/README.md b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/README.md index a95d974..a85c63c 100644 --- a/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/README.md +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/README.md @@ -12,23 +12,23 @@ Where `find-existing-capability` decides "install it instead of building it", th ```mermaid flowchart TD - A([Feature name or capability card]) --> B["1 - Resolve
getSprykerCapability: Install section
feature, requires features, docs guides,
Glue API, Storefront API"] + A([Feature name or capability card]) --> P0["0 - Environment preflight
stack up, container sees host files,
vendor in line with lock, frontend deps"] --> B["1 - Resolve
getSprykerCapability: Install section
feature, requires features, docs guides,
Glue API, Storefront API"] B --> RQ{"Required features
installed?"} RQ -- "no" --> RQ1["Offer to install them first
(recursively)"] --> C RQ -- "yes" --> C - C{"2 - Confirm with the user
feature, packages, version constraint,
optional APIs and demo data, branch"} + C{"2 - Confirm with the user
feature, packages, version constraint,
optional APIs and demo data, branch,
environment bootstrap when needed"} C -- "no / change" --> C - C -- "yes" --> D["3 - Fetch the install guide
spryker-docs-research or docs markdown
match the project's release line
build the step checklist"] - D --> E["4 - composer require
docker/sdk cli composer require
conflict: stop and report"] - E --> F["5 - Integration steps, project layer only
config - plugin wiring - transfers - schema
navigation - routes - glossary - data import"] - F --> G["6 - spryker-refresher
codegen, caches, setup commands
+ the guide's own setup commands"] - G --> H["7 - Verify
guide's verify steps - boot-and-verify
spryker-verifier agent"] + C -- "yes" --> D["3 - Fetch the install guide
spryker-docs-research or docs markdown
match the project's release line
deprecated plugins, no-guide wiring
build the step checklist"] + D --> E["4 - composer require
explicit ^x.y.z constraint
conflict: stop and report"] + E --> F["5 - Integration steps, project layer only
config - plugin wiring - transfers - schema
navigation - routes - glossary check - data import
API Platform resources: skip route plugins"] + F --> G["6 - spryker-refresher
codegen, caches, setup commands
glue per existing application
+ the guide's own setup commands"] + G --> H["7 - Verify
auth precondition, guide's verify steps
boot-and-verify - spryker-verifier agent"] H --> R(["8 - Report
installed - done / skipped checklist
follow-ups - unstaged changes"]) ``` ## Tools -Matched by tool name: `searchSprykerCapabilities`, `getSprykerCapability`, `searchAlgoliaDocumentation`, `getSprykerModules`, `getSprykerModuleMap`, `getTransferStructureByName`. Skills it hands to: `spryker-docs-research`, `spryker-refresher`, `boot-and-verify`, `project-data` / `data-import`; agents: `spryker-verifier`, `spryker-issue-diagnoser`. +Bundled: `scripts/glossary-key-check.php` (translation keys of a feature's Yves modules missing from the project glossary) and `references/environment-preflight.md` (shared with `spryker-upgrade`). Matched by tool name: `searchSprykerCapabilities`, `getSprykerCapability`, `searchAlgoliaDocumentation`, `getSprykerModules`, `getSprykerModuleMap`, `getTransferStructureByName`. Skills it hands to: `spryker-docs-research`, `spryker-refresher`, `boot-and-verify`, `project-data` / `data-import`; agents: `spryker-verifier`, `spryker-issue-diagnoser`. ## Output @@ -39,5 +39,8 @@ A feature install report: what was installed (packages, versions, required featu - **Confirm before changing.** Nothing is required or edited before the user agrees to the feature, constraint and optional integrations. - **The guide is the source of truth for steps; the installed code is the source of truth for names.** Identifier spellings are confirmed against `vendor/` (read-only) before they are written. - **Project layer only.** Never `vendor/`, `src/Generated/` or `src/Orm/`; existing plugin stacks keep their order. +- **Preflight the environment.** A stack that is down, out of sync or behind `composer.lock` is reported as a pre-existing issue and a bootstrap is suggested in the confirmation; never `reset`. +- **Glue applications are resolved, not assumed.** `glue` commands run per application that exists (`public/Glue*/index.php`, deploy entry points); API Platform resources replace the guide's route and relationship plugins. - **No silent gaps.** Every guide step ends done or skipped with a reason; a failing step is diagnosed, not dropped. -- **No destructive commands, no auto-commit.** A rebuild (`docker/sdk up`) or `reset` is reported, not run. +- **No destructive commands, no auto-commit.** A rebuild (`docker/sdk up`) or `reset` is reported, not run; the environment bootstrap is proposed in the confirmation and `reset` never. +- **Blocked is not failed.** When a fixture login fails, logged-in checks are reported BLOCKED (environment) and handed to `spryker-issue-diagnoser`. diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/SKILL.md b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/SKILL.md index 870349e..d020aed 100644 --- a/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/SKILL.md +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/SKILL.md @@ -32,6 +32,10 @@ Match tools by **tool name** (server names vary by install; some clients namespa If the capability tools are not connected, start the MCP server and ask for a reload the way `find-existing-capability` describes; after two failed reconnects take the feature name and guide URL from the user, or fetch `https://spryker-capability-map.s3.eu-central-1.amazonaws.com/.md` with the web fetch tool and compare its packages with `composer.lock` by hand, and say that the install status is then unverified. +## Step 0 - Environment preflight + +The install needs a running, in-sync stack (composer in the container, codegen, `propel:install`, verification), and the planning steps below do not. Run the checks in [references/environment-preflight.md](references/environment-preflight.md) before Step 2, so a stack that is down, a container that does not see the host files, a `vendor/` behind `composer.lock` or a broken frontend dependency tree is reported as a **pre-existing environment issue** and not mistaken for a feature failure. Reading the card and the guide needs no stack; skip the boot for a plan-only run. + ## Step 1 - Resolve the feature 1. From a card: `getSprykerCapability(slug)`. From a name: `searchSprykerCapabilities` with the name and its synonyms, then open the best card. Read the **Install** section; it lists: @@ -47,10 +51,11 @@ If the capability tools are not connected, start the MCP server and ask for a re Present one confirmation block and wait for the user's answer. It carries: - the feature, the packages `composer require` will add, and any required features that would be installed first; -- the **version constraint**: match the project's other `spryker-feature/*` constraints and release line in `composer.json` (for example the same `^202xxx.x` style); do not introduce a different style; +- the **version constraint**: match the project's other `spryker-feature/*` constraints and release line in `composer.json` (for example the same `^202xxx.x` style); do not introduce a different style. For module packages the project pins as `^x.y.z` (the `*-rest-api` entries, for example), the explicit constraint is the resolved version, see Step 4; - the **optional integrations** the user wants: Glue API, Storefront API, Back Office, data import with demo data. Default to the project's existing surfaces (an API the project does not expose is not installed); - that the **storefront placement** (Step 6b) comes after the backend steps as a suggestion list: the guide registers the feature's widgets but does not place them in the project's Twig templates, and nothing is placed unless the developer picks it then; - which guide will be followed and its version line; +- the **environment**: when the preflight found the stack down or not bootstrapped, propose the bootstrap here (the deploy file, `docker/sdk boot ` plus `docker/sdk start` or `docker/sdk up`, port clashes with other running stacks; see the reference) and list any pre-existing environment issue it found; never `reset`; - the branch: work on a dedicated branch (`ai-feature/` from `HEAD`, as `spryker-customization` does with `ai-customize/`) when `git status` is clean; if it is not, ask first. No `composer require` and no edit before this answer. @@ -63,7 +68,9 @@ The Install section gives a docs URL (usually `/latest/` or a versioned path). R - `searchAlgoliaDocumentation` and the markdown at its `github_api_url` (the docs markdown lives in `github.com/spryker/spryker-docs`), or - the web fetch tool on the page itself. -**Version match.** When the URL is `/latest/` and the project's release line (from `composer.json` and the installed `spryker/*` versions) is older than the docs' current one, prefer the guide for the project's line if the docs site offers it; if you cannot tell which line a step belongs to, say so and ask rather than apply a step that may not exist in the project's modules. Treat the guide as the source of truth for **steps and order**, but docs are not trusted for exact identifier spellings: confirm class, constant and transfer names against the installed packages in `vendor/` (read-only) or `getSprykerModuleMap` before writing them. +**Version match.** When the URL is `/latest/` and the project's release line (from `composer.json` and the installed `spryker/*` versions) is older than the docs' current one, prefer the guide for the project's line if the docs site offers it; if you cannot tell which line a step belongs to, say so and ask rather than apply a step that may not exist in the project's modules. Treat the guide as the source of truth for **steps and order**, but docs are not trusted for exact identifier spellings: confirm class, constant and transfer names against the installed packages in `vendor/` (read-only) or `getSprykerModuleMap` before writing them. Check every plugin the guide names for `@deprecated` in its vendor class: use the named replacement, skip a deprecated plugin that has none, and record each case in the checklist. + +**No guide, or a guide that assumes a base feature that has none** (the marketplace guide assumes the base wishlist wiring; the card says "no install guide found" for the base feature): take the project-layer wiring from a reference project that ships the feature, the suite or the demo shop of the same release line, read through `gh api` or raw GitHub, or from a project on disk. Verify every class against `vendor/`, and record the reference source in the checklist. Turn the guide into a **checklist** of its steps (install, integrate, verify), grouped as the guide groups them. This checklist is the run's state: every step ends `done` or `skipped (reason)`. @@ -71,6 +78,7 @@ Turn the guide into a **checklist** of its steps (install, integrate, verify), g Run inside the project's PHP environment. On Docker SDK that is `docker/sdk cli composer require :`, the form `spryker-refresher` and `spryker-upgrade` use (wrap in `script -q /dev/null` where the command needs a TTY). Without Docker SDK, run `composer require` in the project root. +- Pass an explicit `^x.y.z` constraint for every package, matching the project style: for a bare module package use the version the resolver would pick, found with `composer require --dry-run` first and then required as `^`; a bare `composer require ` writes a looser `^x.y` than the project's entries. - Require the feature metapackage agreed in Step 2, with the agreed constraint. The card's `composerRequire` names the feature only when the card has exactly one; for a card with several features (alternatives such as `wishlist` and `marketplace-wishlist`) it names the missing module packages, so take the feature the user chose from the Install section instead. Require bare module packages only when the capability has no feature metapackage. - Add the API packages only if the user chose that integration. - On a resolution conflict, do not loosen constraints or add `--ignore-platform-reqs` on your own. Report the conflict (which package, which constraint) and stop; the cause is often a project behind the feature's release line, which is `spryker-upgrade` territory. @@ -90,8 +98,9 @@ Typical step kinds, and the care each needs: | Propel schema (`*.schema.xml`) | Project layer; follow `propel-schema` conventions. | | Navigation (`navigation.xml`), routes, route providers, module configs | Add the entry; do not reorder existing ones. | | Widget plugins (`ShopApplicationDependencyProvider::getGlobalWidgets()`) | Register the widgets the guide lists. Registration alone renders nothing in templates the project overrides; placing them is Step 6b. | -| Glossary and translations | Add the keys for every configured locale. | +| Glossary and translations | Add the keys for every configured locale. Guides often have no glossary step, so run `php /scripts/glossary-key-check.php --module=` from the project root (`` is the path reported as `Base directory for this skill:`): it lists the `'key' \| trans` keys of those modules that no `data/import/**/glossary*.csv` row defines, per locale. Propose rows from the reference project or the suite glossary, append them to the project's glossary file, and report keys with no source; a missing key renders raw on the page. | | Data import (import config, `data/import/**`, demo data) | Set up the importer wiring when the guide requires it. Load **demo data only if the user asked**; otherwise skip and record "demo data skipped". Use `project-data` and the `data-import` skill for CSV and importer work. | +| Storefront API resources (`resources/api/storefront/*.resource.yml` in a module) | When the module ships them and the project already generates API Platform resources (`src/Generated/Api/Storefront` exists; `config/GlueStorefront` alone is no proof), the guide's `GlueApplicationDependencyProvider` route and relationship plugin steps do not apply: mark them `skipped (API Platform resource)`, keep the attribute-mapper and strategy plugin stacks (the resource mapper reads them through `#[Plugins(dependencyProviderMethod: ...)]`), and rely on code generation in Step 6. | | Publish and sync, queues, event wiring | Wire as the guide says; queue-worker restarts are project specific, report them. | | New service in `deploy.dev.yml` (search, key-value, broker) | Do not change the deploy file silently; this usually needs a `docker/sdk up`, which is a rebuild. Ask the user. Never run `docker/sdk reset` or `clean-data`. | @@ -99,7 +108,7 @@ Where a step conflicts with something the project already built (a plugin alread ## Step 6 - Codegen and setup -Invoke `spryker-refresher` with the list of files you changed; it owns the file-pattern to command mapping (`transfer:generate`, `propel:install`, `cache:class-resolver:build`, router cache warm-up, `navigation:build-cache`, glossary and data import, search setup, cache clears, frontend builds). Do not improvise the command chain, and run Yves/Zed frontend builds only when the guide touches the frontend. Then run the **feature-specific setup commands the guide lists** that the refresher mapping does not cover (for example a search setup or a feature importer), verifying each command exists first with `docker/sdk console list`. +Invoke `spryker-refresher` with the list of files you changed; it owns the file-pattern to command mapping (`transfer:generate`, `propel:install`, `cache:class-resolver:build`, router cache warm-up, `navigation:build-cache`, glossary and data import, search setup, cache clears, frontend builds). Resolve the Glue applications the project really has before any `glue` command: list `public/Glue*/index.php` and cross-check the `entry-point: Glue*` values in the active deploy file, then run `vendor/bin/glue ` for `public/Glue` and `GLUE_APPLICATION=GLUE_BACKEND vendor/bin/glue ` for `public/GlueBackend`; use `GLUE_APPLICATION=GLUE_STOREFRONT` only when `public/GlueStorefront/index.php` exists and an entry point uses it. A recipe step (`config/install/docker.yml`) for an application that does not exist is `skipped (no such Glue application)`, not run. Do not improvise the command chain, and run Yves/Zed frontend builds only when the guide touches the frontend. Then run the **feature-specific setup commands the guide lists** that the refresher mapping does not cover (for example a search setup or a feature importer), verifying each command exists first with `docker/sdk console list`. A new `*.schema.xml` triggers `propel:install`, which changes the database schema: say so before it runs. If a command fails, show its output and diagnose before retrying (`spryker-issue-diagnoser`); do not skip a failing guide step to look green. @@ -115,6 +124,7 @@ Do not apply a placement in an unattended run; the table goes into the report. ## Step 7 - Verify +- **Authentication precondition first** for any check that needs a login: one fixture customer login through Glue (`POST /access-tokens`) and one through Yves. Test credentials come from `tests/cypress-tests/cypress/fixtures/**` (customer emails, `defaultPassword`) and the project's seed and fixture files; never ask for or print real credentials. When the login fails, report the logged-in checks as **BLOCKED (environment)** and hand over to `spryker-issue-diagnoser` (a stack problem that predates the install, such as no OAuth token ever issued), instead of failing the feature checks. - Run the guide's own **verify** steps (the pages, console commands or API calls it names) and record the evidence. - Use `boot-and-verify` for standalone verification of what the feature touches (storefront, Back Office, search, queues); this is a running stack, not a first boot. - Hand per-behaviour checks to the `spryker-verifier` agent with the guide's verification steps as acceptance criteria; it only asserts and reports. Weigh a FAIL as a hypothesis before acting (browser reasons look like feature failures). diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/references/environment-preflight.md b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/references/environment-preflight.md new file mode 100644 index 0000000..ffecd21 --- /dev/null +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/references/environment-preflight.md @@ -0,0 +1,28 @@ +# Environment preflight + +Shared by `spryker-feature-install` (Step 0) and `spryker-upgrade`. Run it before the first `composer require` or `composer update`, and before any step that needs the stack (codegen, `propel:install`, imports, verification). Reading a guide or planning a checklist needs no stack: skip the preflight for a plan-only run. Everything here is read-only except the bootstrap, which the user confirms first. + +Report a failure as a **pre-existing environment issue**, before the confirmation block, and not as a feature or upgrade failure. + +## 1. Is the stack needed, and is it up + +`composer` runs in the project's PHP container (`docker/sdk cli composer ...`); `--ignore-platform-reqs` is not an option. Check `docker info` and the running containers of the project (`docker ps`). `docker/` is usually a submodule: `git submodule status` before calling it absent (see `../../spryker-upgrade/references/environment.md`). + +When the stack is down or was never booted, **suggest the bootstrap in the confirmation block** instead of failing at `composer require`: + +- name the deploy file: the project's `deploy.*.yml` files, with the one the user named or the last-booted one first; +- check for port clashes with other running stacks (`docker ps` published ports, the deploy file's hosts); +- offer `docker/sdk boot ` plus `docker/sdk start` when containers exist, `docker/sdk up` when they do not (that is a build and takes a while, say so); +- never `docker/sdk reset` or `clean-data`. + +## 2. Does the container see the host files + +Compare a checksum of `composer.json` and `composer.lock` on the host and in the container (`docker/sdk cli sha1sum composer.json composer.lock`). On a mutagen-synced project a mismatch means the sync is behind: run `mutagen sync flush` (the project's sync session, `mutagen sync list`), re-compare, and report sync conflicts (for example from deleted `vendor/` folders) without resolving them silently. + +## 3. Is `vendor/` in line with `composer.lock` + +`docker/sdk cli composer install --dry-run`: expect no operations. Operations listed mean `vendor/` is behind the lock (a dry run of one new package would then show every pending package); report the count, and offer `composer install` as the first step of the run, not as part of the feature. + +## 4. Do the frontend dependencies resolve + +For every `vendor/**/package.json` the Yves build uses (`spryker-shop/*`, `spryker/*`), check that each dependency appears in the project's `package-lock.json`. A package that requires a dependency the lock lacks (for example `style-dictionary` required by `spryker-shop/shop-ui`) fails the frontend build with `ERR_MODULE_NOT_FOUND`. Report it before the install; the fix is `frontend:project:install-dependencies` or a lock update, offered to the user. diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/glossary-key-check.php b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/glossary-key-check.php new file mode 100644 index 0000000..b1ab4f0 --- /dev/null +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/glossary-key-check.php @@ -0,0 +1,219 @@ + + */ +function glossary_check_files(string $dir, callable $accept): array +{ + if (!is_dir($dir)) { + return []; + } + $files = []; + $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir, FilesystemIterator::SKIP_DOTS)); + foreach ($iterator as $file) { + if ($file->isFile() && $accept($file->getPathname())) { + $files[] = $file->getPathname(); + } + } + sort($files); + + return $files; +} + +/** + * Directories holding the Yves code of a module: vendor packages (any vendor) and the project layer. + * + * @param list $modules + * @param list $packages + * + * @return array> module or package => directories + */ +function glossary_check_module_dirs(string $root, array $modules, array $packages): array +{ + $dirs = []; + foreach ($packages as $package) { + $dir = $root . '/vendor/' . $package; + if (is_dir($dir)) { + $dirs[$package][] = $dir; + } + } + foreach ($modules as $module) { + foreach (glob($root . '/vendor/*/*/src/*/Yves/' . $module) ?: [] as $dir) { + $dirs[$module][] = $dir; + } + foreach (glob($root . '/src/*/Yves/' . $module) ?: [] as $dir) { + $dirs[$module][] = $dir; + } + } + + return $dirs; +} + +/** + * @return list + */ +function glossary_check_keys_in_twig(string $file): array +{ + $source = (string)file_get_contents($file); + $source = (string)preg_replace('/\{#.*?#\}/s', '', $source); + preg_match_all('/([\'"])([A-Za-z0-9_.\-]+)\1\s*\|\s*trans\b/', $source, $matches); + + return array_values(array_unique(array_filter($matches[2], fn (string $key): bool => str_contains($key, '.')))); +} + +/** + * @return list + */ +function glossary_check_locales(string $root, array $glossary): array +{ + $stores = $root . '/config/Shared/stores.php'; + if (is_file($stores) && preg_match_all('/[\'"][a-z]{2}[\'"]\s*=>\s*[\'"]([a-z]{2}_[A-Z]{2})[\'"]/', (string)file_get_contents($stores), $matches)) { + return array_values(array_unique($matches[1])); + } + $locales = []; + foreach ($glossary as $byLocale) { + foreach (array_keys($byLocale) as $locale) { + $locales[$locale] = true; + } + } + + return array_keys($locales); +} + +/** + * @return array> key => locale => true + */ +function glossary_check_load_glossary(string $root): array +{ + $glossary = []; + $files = glossary_check_files($root . '/data/import', fn (string $path): bool => (bool)preg_match('/\/glossary[^\/]*\.csv$/', $path)); + foreach ($files as $file) { + $handle = fopen($file, 'r'); + if ($handle === false) { + continue; + } + fgetcsv($handle, 0, ',', '"', ''); + while (($row = fgetcsv($handle, 0, ',', '"', '')) !== false) { + if (isset($row[0], $row[2]) && $row[0] !== '') { + $glossary[$row[0]][trim($row[2])] = true; + } + } + fclose($handle); + } + + return $glossary; +} + +function glossary_check_main(array $argv): int +{ + $modules = []; + $packages = []; + foreach (array_slice($argv, 1) as $argument) { + if (str_starts_with($argument, '--module=')) { + array_push($modules, ...array_filter(explode(',', substr($argument, 9)))); + } elseif (str_starts_with($argument, '--package=')) { + array_push($packages, ...array_filter(explode(',', substr($argument, 10)))); + } else { + fwrite(STDERR, "Usage: glossary-key-check.php [--module=Name,...] [--package=vendor/name,...]\n"); + + return 2; + } + } + if ($modules === [] && $packages === []) { + fwrite(STDERR, "Usage: glossary-key-check.php [--module=Name,...] [--package=vendor/name,...]\n"); + + return 2; + } + + $root = glossary_check_project_root(); + $dirs = glossary_check_module_dirs($root, $modules, $packages); + $keys = []; + foreach ($dirs as $directories) { + foreach ($directories as $dir) { + foreach (glossary_check_files($dir, fn (string $path): bool => str_ends_with($path, '.twig')) as $file) { + foreach (glossary_check_keys_in_twig($file) as $key) { + $keys[$key] = true; + } + } + } + } + $keys = array_keys($keys); + sort($keys); + + $glossary = glossary_check_load_glossary($root); + $locales = glossary_check_locales($root, $glossary); + $missing = array_fill_keys($locales, []); + foreach ($keys as $key) { + foreach ($locales as $locale) { + if (!isset($glossary[$key][$locale])) { + $missing[$locale][] = $key; + } + } + } + $total = array_sum(array_map('count', $missing)); + $notFound = array_values(array_diff(array_merge($modules, $packages), array_keys($dirs))); + + echo json_encode([ + 'modules' => array_keys($dirs), + 'modules_not_found' => $notFound, + 'locales' => $locales, + 'keys' => count($keys), + 'missing' => $missing, + ], JSON_UNESCAPED_SLASHES), "\n"; + printf("%d key(s) in %d module(s), %d missing locale row(s) across %s\n", count($keys), count($dirs), $total, implode(', ', $locales) ?: 'no locales'); + + return $total > 0 ? 1 : 0; +} + +if (realpath($argv[0] ?? '') === __FILE__) { + exit(glossary_check_main($argv)); +} diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-refresher/README.md b/plugins/spryker-ai-dev-sdk/skills/spryker-refresher/README.md index 9821b0e..c328dd6 100644 --- a/plugins/spryker-ai-dev-sdk/skills/spryker-refresher/README.md +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-refresher/README.md @@ -71,6 +71,9 @@ the change set. Your coding agent runs on the host, so commands are invoked as ` | Twig file added / moved / deleted (new override) | `twig:cache:warmer` — edits to an existing Twig file need nothing | | `navigation.xml` changed | `navigation:cache:remove` → `navigation:build-cache` | | Glue / SAPI / BAPI route or `*RestApi*` plugin changed | `rest-api:remove-validation-cache` → `rest-api:build-request-validation-cache` | +| API Platform resource (`resources/api/{storefront,backend}/*.resource.yml`) added/updated, or `*RestApi` dependency provider changed, in a project with `src/Generated/Api/` | `glue api:generate` → `glue cache:clear` → `glue cache:warmup`, per Glue application resolved from `public/Glue*/index.php` and the deploy file (never from the install recipe) | +| `composer.lock` changed (modules added/updated) | `transfer:generate`, `propel:install` (module ships `*.schema.xml`), `transfer:entity:generate`, `composer dump-autoload`, `dev:ide-auto-completion:generate` + phpstan cache clear, `cache:class-resolver:build`, `glue api:generate` (API resources), `router:cache:warm-up*` (route providers), `frontend:project:install-dependencies` (changed `package.json`) | +| Before a frontend build after vendor changes / `ERR_MODULE_NOT_FOUND: Cannot find package` | Check vendor `package.json` dependencies against `package-lock.json` / `node_modules`; the error is a pre-existing environment issue - fix with `frontend:project:install-dependencies` (lock update needs user approval), not code | | `RouteProvider` plugin or route config added/changed/deleted, or a new Zed controller/action | `router:cache:warm-up` and/or `:backoffice` / `:backend-gateway` / `:merchant-portal` | | OMS XML (`config/Zed/oms/*.xml`) changed | `oms:process-cache:warm-up` | | Glossary CSV changed | `data:import:glossary` (Yves translations only — not Zed BO labels) | @@ -102,6 +105,7 @@ storefront hard refresh. - **Recipes over memory.** The mapping table narrows the search; `config/install/*.yml` is authoritative for this project's ordering and flags. +- **Exception: Glue applications come from the project.** Install recipes list steps for applications the project may not run (the demo shop has no `GlueStorefront` entry point; the storefront API runs in `Glue`). The skill lists `public/Glue*/index.php`, cross-checks the deploy file's `entry-point: Glue*` and reports other steps as `skipped (no such Glue application)`. `glue` runs via `docker/sdk cli`, not `docker/sdk console`. - **Surgical, never the full chain.** Only the commands the actual file list demands. - **One command per Bash call.** So every step's exit code and output tail is captured individually. - **Stop on the first failure.** Dependents are not skipped-over — the run stops and the caller decides diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-refresher/SKILL.md b/plugins/spryker-ai-dev-sdk/skills/spryker-refresher/SKILL.md index a7ed3a3..3e78953 100644 --- a/plugins/spryker-ai-dev-sdk/skills/spryker-refresher/SKILL.md +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-refresher/SKILL.md @@ -39,10 +39,13 @@ Your coding agent runs on the host, not in the container. Use these invocation f - Spryker console commands → `docker/sdk console ` - Composer → `docker/sdk cli composer ` +- Glue console (`glue`, a separate binary from `console`) → `docker/sdk cli "vendor/bin/glue "`; `docker/sdk console` does not reach it + +On macOS, `docker/sdk` needs a pseudo-TTY in a non-interactive shell (seen with `console list`). Wrap the call: `script -q /dev/null docker/sdk console list`. ## Touched-file → command mapping -Commands below exist in this project (verified via `docker/sdk console list`). Install recipes under `config/install/*.yml` are authoritative for this project's ordering and flags — read them before improvising. The table just narrows the search. +Commands below exist in this project (verified via `docker/sdk console list`). Install recipes under `config/install/*.yml` are authoritative for this project's ordering and flags — read them before improvising. The table just narrows the search. One exception: which Glue applications exist is resolved from the project, never taken from a recipe (see "Resolve the Glue applications first" below). Each row's trigger is independent. Apply every row whose trigger matches a file in your change set. @@ -62,12 +65,16 @@ Each row's trigger is independent. Apply every row whose trigger matches a file | Twig file **added, moved, or deleted** in Zed or MP (a new override) | `twig:cache:warmer` (the template path cache otherwise keeps resolving the old file). | | `navigation.xml` changed | `navigation:cache:remove` → `navigation:build-cache` | | Glue / SAPI / BAPI route or `*RestApi*` plugin changed | `rest-api:remove-validation-cache` → `rest-api:build-request-validation-cache` | +| A module's `resources/api/{storefront,backend}/*.resource.yml` added or updated, or a `*RestApi` dependency provider changed, in a project that generates API Platform resources (`src/Generated/Api/` exists) | Per resolved Glue application (see below): `glue api:generate` → `glue cache:clear` → `glue cache:warmup`. Without `api:generate` the new endpoints do not exist; the REST validation-cache row above does not cover them. | +| `composer.lock` changed (modules added or updated; check `git diff composer.lock` for which) | The chain a new vendor module needs, each part only when the changed modules need it: `transfer:generate`; `propel:install` when a changed module ships `*.schema.xml` (this changes the DB schema - say so in the report); `transfer:entity:generate`; `composer dump-autoload`; `dev:ide-auto-completion:generate` (+ `vendor/bin/phpstan clear-result-cache`); `cache:class-resolver:build`; `glue api:generate` per resolved Glue application when a module ships API resources; `router:cache:warm-up*` when a module ships route providers; `frontend:project:install-dependencies` when a changed module's `package.json` changed. Order them with the steps in "Approach". | | `RouteProvider` plugin or route configuration file added / changed / deleted, or a **new Zed controller / action** (a 404 on the new URL) — NOT controller body edits | `router:cache:warm-up` (Zed) and/or the per-application variant — `router:cache:warm-up:backoffice`, `router:cache:warm-up:backend-gateway`, `router:cache:warm-up:merchant-portal` — for the applications the route belongs to | | OMS XML (`config/Zed/oms/*.xml`) changed | `oms:process-cache:warm-up` | | Glossary CSV changed (e.g. `data/import/**/glossary*.csv`) | `data:import:glossary` (Yves storefront translations only — does NOT cover Zed BO labels) | | Zed translator CSV changed (`src//Zed/Translator/data//*.csv`) | `translator:generate-cache` (Zed BO labels — separate pipeline from glossary; verify the command via `docker/sdk console list`) | | Search schema / index-map file changed (project-layer JSON under `src//Shared/Search/Schema/*.json`) | `search:source-map:remove` → `search:setup:source-map` → `search:setup:sources` | | Data import CSV changed (entity-specific) — **rows ADDED only** | `data:import:` (verify the entity importer exists in `docker/sdk console list`). **Not for a changed VALUE on `product-price`, `product-price-schedule`, `discount-amount` or `cms-block`, and not for a removed row:** those importers look rows up by value, so a re-import duplicates the row or fails on a unique key, and no importer deletes. They follow `project-data`'s reset ladder (`boot-and-verify` §3b) — out of scope here, since this skill runs no `reset`; report the file and hand it over. | +| Before `frontend:yves:build` (and `frontend:zed:build`, `frontend:mp:build`), after vendor modules were added or updated | Cheap check, no build: every dependency in the changed `vendor/spryker*/**/package.json` files is present in the project's `package-lock.json` / `node_modules` (`docker/sdk cli "ls -d /data/node_modules/"`). A gap → run `frontend:project:install-dependencies` first; if the lock itself lacks the package, that needs a lock update the user must approve. | +| **Failure signature:** `ERR_MODULE_NOT_FOUND: Cannot find package ''` from `vendor/spryker-shop/shop-ui/.../FrontendBuilder` during a frontend build | Stale or incomplete frontend dependencies, not a code defect (seen: `style-dictionary`, required by `spryker-shop/shop-ui` but missing from the project's `package-lock.json`, also on upstream master). Report it as a **pre-existing environment issue**. Fix: `frontend:project:install-dependencies`; if the lock lacks the package, propose a lock update for the user to approve. Do not edit source. | | Publisher plugin / queue config changed | Queue workers need a manual restart — project-specific. Document in the report; don't auto-run. | | A data import or `publish:trigger-events` ran and the KV/search read model must catch up, in a **DMS (dynamic multi-store)** project | `docker/sdk cli "APPLICATION_STORE= vendor/bin/console queue:worker:start --stop-when-empty"` — **once per store** (same `APPLICATION_STORE=` prefix on `queue:task:start` and `publish:trigger-events`). In DMS these commands resolve the store from `APPLICATION_STORE`; the bare `docker/sdk console queue:worker:start --stop-when-empty` prints the env banner, exits 0 and processes **nothing**. Assert the drain, don't infer it: discover the broker container via `docker ps --format '{{.Names}}'` (filter for `broker`; it is `_broker_1` — never hardcode `spryker_broker_1`) and confirm `docker exec rabbitmqctl list_queues -p / name messages` fell to 0. **Signature:** worker exits immediately with only the env banner while the queues stay full → missing `APPLICATION_STORE`, not a broken publisher. | | BO showing stale template after a clean refresh (rare) | `rm -f src/Generated/Zed/Twig/codeBucket/.pathCache` → `twig:cache:warmer` | @@ -75,6 +82,15 @@ Each row's trigger is independent. Apply every row whose trigger matches a file If a command not in the table seems needed, verify it exists in `docker/sdk console list` first. +### Resolve the Glue applications first + +Do not take the Glue applications from an install recipe: `config/install/docker.yml` lists steps for `GLUE_STOREFRONT`, `GLUE_BACKEND` and the default application regardless of what the project runs. In the demo shop `GLUE_APPLICATION=GLUE_STOREFRONT ...` makes no sense - `public/GlueStorefront/` holds only `assets/` and no `index.php`, and the deploy file declares only the `Glue` and `GlueBackend` entry points; the storefront API runs in the default `Glue` application. + +1. List `public/Glue*/index.php`. +2. Cross-check `entry-point: Glue*` in the active deploy file. +3. Run plain `docker/sdk cli "vendor/bin/glue "` for `public/Glue`, `docker/sdk cli "GLUE_APPLICATION=GLUE_BACKEND vendor/bin/glue "` for `public/GlueBackend`, and `GLUE_APPLICATION=GLUE_STOREFRONT` only when `public/GlueStorefront/index.php` exists and an entry point uses it. +4. Report a recipe step for an application that does not exist as `skipped (no such Glue application)`. + ## Approach 1. **Get the file list.** Caller-supplied is best. Otherwise: `git status` / `git diff --name-only HEAD~1`. If you can't figure it out, ask. @@ -84,16 +100,16 @@ If a command not in the table seems needed, verify it exists in `docker/sdk cons 3. **Order the resulting commands** (this matches the pattern in `config/install/development.yml` and similar recipes — clear-then-codegen-then-build-then-resolve-then-import-then-frontend): 1. **Cache removes** — `cache:empty-all`, `navigation:cache:remove`, `rest-api:remove-validation-cache`, `search:source-map:remove`, `docker/sdk cli "rm -rf src/Generated/Yves/Twig/codeBucket"` (Twig — never `data/cache/Yves/`, which is the DI container). Clear old cached state before new state is written. - 2. **Codegen** — `transfer:generate`, `propel:install`. - 3. **Autoload** — `composer dumpautoload --apcu`. + 2. **Codegen** — `transfer:generate`, `propel:install`, then `transfer:entity:generate` (after `propel:install`), then `glue api:generate` per resolved Glue application (after `transfer:generate`). + 3. **Autoload** — `composer dumpautoload --apcu` (`composer dump-autoload` after a `composer.lock` change). 4. **IDE/locator stubs** — `dev:ide-auto-completion:generate`. After autoload (the stub generator reads the class map), before the class-resolver build. - 5. **Cache builds / warmups** — `twig:cache:warmer`, `navigation:build-cache`, `rest-api:build-request-validation-cache`, `search:setup:source-map`, `search:setup:sources`, `oms:process-cache:warm-up`, `router:cache:warm-up*`. + 5. **Cache builds / warmups** — `twig:cache:warmer`, `navigation:build-cache`, `rest-api:build-request-validation-cache`, `search:setup:source-map`, `search:setup:sources`, `oms:process-cache:warm-up`, `router:cache:warm-up*`, `glue cache:clear` then `glue cache:warmup` per resolved Glue application (after `glue api:generate`). 6. **Class resolver build** — `cache:class-resolver:build`. Runs after the class layout AND caches are in their final state. 7. **Data imports** — `data:import:glossary`, `data:import:`. Spryker translations are looked up at runtime, so glossary import can run after twig warmup safely. In a DMS project, follow an entity import with the **per-store** drain from the table (`APPLICATION_STORE= … queue:worker:start --stop-when-empty`) and the broker depth check — the bare worker is a silent no-op there. - 8. **Frontend builds** — `frontend:yves:build`, `frontend:zed:build`, `frontend:mp:build`. Last. + 8. **Frontend builds** — `frontend:project:install-dependencies` first when a changed module's `package.json` changed (after the dependency-drift check from the table), then `frontend:yves:build`, `frontend:zed:build`, `frontend:mp:build`. Last. 9. **Stale-analysis cache clear** — `vendor/bin/phpstan clear-result-cache` (via `docker/sdk cli`), whenever step 4 ran. Last, so no later step repopulates a stale entry. - Each step runs only if its commands appeared in your matched set from step 2. Install recipes (`config/install/*.yml`) are authoritative — if a recipe orders commands differently for this project, defer to the recipe. + Each step runs only if its commands appeared in your matched set from step 2. Install recipes (`config/install/*.yml`) are authoritative — if a recipe orders commands differently for this project, defer to the recipe. Exception: the recipe never decides which Glue applications exist; resolve them from `public/Glue*/index.php` and the deploy file. 4. **Run each command separately via Bash** so you capture exit code and tail of output per step. @@ -152,6 +168,6 @@ If a command not in the table seems needed, verify it exists in `docker/sdk cons - Do not skip dependents after a failure. Stop, report, let the caller decide. - Do not run the entire install chain when only a subset is needed. Be surgical. - Do not run commands across multiple stores / regions without the caller specifying which one. -- Do not skip the install-recipe read. The mapping in this prompt is a starting point; the recipes are the source of truth for this project's command ordering and flags. +- Do not skip the install-recipe read. The mapping in this prompt is a starting point; the recipes are the source of truth for this project's command ordering and flags - except for the set of Glue applications, which comes from `public/Glue*/index.php` and the deploy file. Do not run a recipe's `GLUE_APPLICATION=GLUE_STOREFRONT` step when that application has no `index.php`. - Do not prepend `cd /absolute/path && ...` to any `Bash` command. The harness already runs every `Bash` invocation in the project root — `cd` shifts the command to a different allowlist pattern and causes permission prompts. - **Do not omit `cache:class-resolver:build` after any `.php` change under a project namespace directory in `src/`.** Without it, the override file lands in the project layer, but Spryker keeps resolving to the vendor class because the resolver map wasn't rebuilt. Self-correction signal: if your file list contains any `src//**/*.php` (new or edited) and your command plan doesn't include `docker/sdk console cache:class-resolver:build`, stop and add it before reporting. diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/SKILL.md b/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/SKILL.md index e1ec6a2..1e9c53b 100644 --- a/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/SKILL.md +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/SKILL.md @@ -101,6 +101,8 @@ sniffer and the tests in the container (`script -q /dev/null docker/sdk cli :@`. In block chains, a `~` marks a block inside an `{% embed %}`: it belongs to the embedded component, so an override of the outer template cannot drop it. -What it does not see: Twig functions that render content from CMS (`content_banner(...)`, CMS slots), widgets passed in variables, templates of a non-default vendor theme, and whether a vendor template the project does not override is actually reached from a page. Say so when it matters. +A vendor call counts as placed only when its template is reachable: vendor `views/` and `templates/` are roots (a controller or widget renders them), a component is reachable when a reachable template, or a project template, includes it. A call in a vendor component that only a replaced vendor view included is `missing` with `overrideMode: unreachable` and `projectFile` set to the project template that replaced the including one (`null` when there is none). Twig comments (`{# ... #}`) are not placements. A template nothing references, or one reached only through a variable name (`atom(type)`), cannot be judged: it still counts as before and is listed in the item's `placedUndecided`. + +What it does not see: Twig functions that render content from CMS (`content_banner(...)`, CMS slots), widgets passed in variables, templates of a non-default vendor theme, single-argument includes (`atom('x')`), and templates a PHP class renders by name outside `views/` and `templates/`. Say so when it matters. ## Step 1 - Scope and scan diff --git a/plugins/spryker-ai-dev-sdk/skills/yves-twig-integration/scripts/yves-integration-scan.php b/plugins/spryker-ai-dev-sdk/skills/yves-twig-integration/scripts/yves-integration-scan.php index 0d6cd9e..b8352e2 100644 --- a/plugins/spryker-ai-dev-sdk/skills/yves-twig-integration/scripts/yves-integration-scan.php +++ b/plugins/spryker-ai-dev-sdk/skills/yves-twig-integration/scripts/yves-integration-scan.php @@ -11,11 +11,14 @@ * vendor///src//Yves//Theme/default/), so the call is gone. * * The scanner builds the effective template tree (project files, plus vendor files the project - * does not shadow, plus the vendor blocks an extending project override keeps) and reports per + * does not shadow and that something reaches - see yves_scan_reachable_vendor_keys() - plus the + * vendor blocks an extending project override keeps; Twig comments are ignored) and reports per * subject: * placed a template the project renders calls it - * missing vendor templates call it, but only in places the project replaced: each - * vendor call site is a suggestion, with the project file that replaced it + * missing vendor templates call it, but only in places the project replaced or that + * no template the project uses includes: each vendor call site is a + * suggestion, with the project file that replaced it (overrideMode + * replaces/extends) or that dropped the include (overrideMode unreachable) * not_registered vendor templates call the widget, but no project dependency provider * registers its class: the backend step is missing, a placement renders nothing * no_reference no vendor template calls it: nothing to copy, the developer decides @@ -204,14 +207,42 @@ function yves_scan_registered_classes(string $root, array $namespaces): array return $registered; } +/** + * Blank out Twig comments ({# ... #}, possibly spanning lines) so that nothing inside them is + * matched as a reference, an extends or a block tag. Newlines are kept, so line numbers stay valid. + */ +function yves_scan_strip_twig_comments(string $code): string +{ + return (string)preg_replace_callback('/\{#.*?#\}/s', fn (array $m): string => (string)preg_replace('/[^\n]/', ' ', $m[0]), $code); +} + +/** + * Template key a component reference points at ("molecule:x@Module" => "Module/components/molecules/x/x.twig"). + */ +function yves_scan_reference_key(string $name): ?string +{ + if (!preg_match('/^(atom|molecule|organism|template|view):([\w-]+)@(\w+)$/', $name, $m)) { + return null; + } + $directory = ['atom' => 'components/atoms', 'molecule' => 'components/molecules', 'organism' => 'components/organisms', 'template' => 'templates', 'view' => 'views'][$m[1]]; + + return $m[3] . '/' . $directory . '/' . $m[2] . '/' . $m[2] . '.twig'; +} + /** * Parse a Twig file: references with their enclosing block chain, the blocks it defines, its extends target. + * Twig comments are ignored. "dynamic" lists ":" for atom/molecule/organism calls whose + * template name is a variable: they can reach any component of that tier in that module. + * "lines" are the original lines (for snippets); matching runs on the comment-free copy. * - * @return array{references: list>, blocks: array, extends: ?string, lines: list} + * @return array{references: list>, blocks: array, extends: ?string, lines: list, dynamic: list} */ function yves_scan_parse_twig(string $file): array { - $lines = explode("\n", (string)file_get_contents($file)); + $code = (string)file_get_contents($file); + $lines = explode("\n", $code); + $matchLines = explode("\n", yves_scan_strip_twig_comments($code)); + $dynamic = []; $stack = []; $references = []; $blocks = []; @@ -220,10 +251,20 @@ function yves_scan_parse_twig(string $file): array $extends = null; $referenceRe = '/\{%-?\s*widget\s+[\'"](\w+)[\'"]|(?:findWidget|widgetExists|widgetGlobalExists|widgetGlobal)\(\s*[\'"](\w+)[\'"]|\b(atom|molecule|organism|template|view)\(\s*[\'"]([\w-]+)[\'"]\s*,\s*[\'"]@?(?:[\w]+:)?(\w+)[\'"]/'; - foreach ($lines as $index => $line) { + foreach ($matchLines as $index => $line) { if ($extends === null && preg_match('/\{%-?\s*extends\s+(.+?)\s*-?%\}/', $line, $m)) { $extends = $m[1]; } + // A variable as the template name with a literal (or omitted, i.e. ShopUi) module: atom(type), + // molecule(data.template, 'Module'). A variable module as well (the generic widget dispatch + // templates) names nothing the scanner could narrow down and is left out. + if (preg_match_all('/\b(atom|molecule|organism)\(\s*[a-zA-Z_][^,()]*(?:,\s*(?:[\'"]@?(?:\w+:)?(?\w+)[\'"]|(?[a-zA-Z_])))?/', $line, $dynamicMatches, PREG_SET_ORDER)) { + foreach ($dynamicMatches as $dynamicMatch) { + if (($dynamicMatch['variable'] ?? '') === '') { + $dynamic[] = $dynamicMatch[1] . ':' . (($dynamicMatch['module'] ?? '') !== '' ? $dynamicMatch['module'] : 'ShopUi'); + } + } + } if (preg_match_all($referenceRe, $line, $matches, PREG_SET_ORDER)) { foreach ($matches as $match) { @@ -254,7 +295,7 @@ function yves_scan_parse_twig(string $file): array if (str_starts_with($tag[1], 'endblock')) { $closed = array_pop($stack); if ($closed !== null && !str_starts_with($closed, '~') && isset($blockStarts[$closed])) { - $body = implode("\n", array_slice($lines, $blockStarts[$closed], $index - $blockStarts[$closed] + 1)); + $body = implode("\n", array_slice($matchLines, $blockStarts[$closed], $index - $blockStarts[$closed] + 1)); $blocks[$closed] = str_contains($body, 'parent()'); } @@ -275,7 +316,7 @@ function yves_scan_parse_twig(string $file): array } } - return ['references' => $references, 'blocks' => $blocks, 'extends' => $extends, 'lines' => $lines]; + return ['references' => $references, 'blocks' => $blocks, 'extends' => $extends, 'lines' => $lines, 'dynamic' => array_values(array_unique($dynamic))]; } /** @@ -313,6 +354,141 @@ function yves_scan_override_extends_vendor(?string $extends, string $key): bool return (bool)preg_match('/[\'"]@(?:Spryker\w*|Spryker):' . preg_quote($module, '/') . '[\'"]/', $extends); } +/** + * Which vendor templates can actually be rendered, by template key. + * + * A vendor template renders when the project does not replace it (an override that extends the + * vendor template keeps it alive) and something reaches it: + * - roots: vendor views/ and templates/ (controllers and widgets render them), and every vendor + * template that nothing in any scanned template references (its consumer is unknown, so the + * old behaviour holds: it counts, marked 'undecided'); + * - components (atoms, molecules, organisms): when a reachable template includes them through a + * reference that survives the project's override of the including template, or the project + * includes them itself; + * - dynamic names (atom(type), molecule(data.template, 'Module')): a reachable template with one + * reaches every component of that tier in that module, marked 'undecided'. Calls with a + * variable module (the generic widget dispatch templates) are ignored. + * 'certain' means a chain of literal references from a root or a project template; 'undecided' + * means the chain starts at an unreferenced template or goes through a dynamic name. + * + * @param array> $vendorParsed template key => parsed vendor template + * @param array> $projectParsed template key => parsed project template + * + * @return array template key => 'certain' | 'undecided' (keys of vendor templates not listed are unreachable) + */ +function yves_scan_reachable_vendor_keys(array $vendorParsed, array $projectParsed): array +{ + $alive = []; + foreach ($vendorParsed as $key => $parsed) { + $alive[$key] = !isset($projectParsed[$key]) || yves_scan_override_extends_vendor($projectParsed[$key]['extends'], $key); + } + + $referenced = []; + foreach ([$vendorParsed, $projectParsed] as $templates) { + foreach ($templates as $key => $parsed) { + foreach ($parsed['references'] as $reference) { + $target = $reference['type'] === 'component' ? yves_scan_reference_key($reference['name']) : null; + if ($target !== null && $target !== $key) { + $referenced[$target] = true; + } + } + } + } + + $state = []; + $queue = []; + $mark = function (string $key, string $level) use (&$state, &$queue, $vendorParsed): void { + if (!isset($vendorParsed[$key]) || ($state[$key] ?? null) === 'certain' || ($state[$key] ?? null) === $level) { + return; + } + $state[$key] = $level; + $queue[] = $key; + }; + $dynamicModules = []; + $expand = function (string $dynamic) use (&$dynamicModules, $mark, $vendorParsed): void { + if (isset($dynamicModules[$dynamic])) { + return; + } + $dynamicModules[$dynamic] = true; + [$tier, $module] = explode(':', $dynamic, 2); + $prefix = $module . '/components/' . $tier . 's/'; + foreach (array_keys($vendorParsed) as $key) { + if (str_starts_with($key, $prefix)) { + $mark($key, 'undecided'); + } + } + }; + + foreach (array_keys($vendorParsed) as $key) { + if (preg_match('#^\w+/(views|templates)/#', $key)) { + $mark($key, 'certain'); + } elseif (!isset($referenced[$key])) { + $mark($key, 'undecided'); + } + } + foreach ($projectParsed as $parsed) { + foreach ($parsed['references'] as $reference) { + $target = $reference['type'] === 'component' ? yves_scan_reference_key($reference['name']) : null; + if ($target !== null) { + $mark($target, 'certain'); + } + } + foreach ($parsed['dynamic'] as $module) { + $expand($module); + } + } + + while ($queue !== []) { + $key = array_shift($queue); + if (!$alive[$key]) { + continue; + } + $parsed = $vendorParsed[$key]; + $override = $projectParsed[$key] ?? null; + foreach ($parsed['dynamic'] as $module) { + $expand($module); + } + foreach ($parsed['references'] as $reference) { + $target = $reference['type'] === 'component' ? yves_scan_reference_key($reference['name']) : null; + if ($target === null) { + continue; + } + if ($override === null || yves_scan_vendor_site_survives(true, $reference['blocks'], $override['blocks'])) { + $mark($target, $state[$key]); + } + } + } + + return $state; +} + +/** + * The project template that replaced the nearest ancestor of an unreachable vendor template: the + * file the developer would look at to see why the template is no longer included. + * + * @param array> $referencers template key => keys of the vendor templates referencing it + * @param array $projectTemplates template key => project file + */ +function yves_scan_replacing_project_file(string $key, array $referencers, array $projectTemplates): ?string +{ + $queue = [$key]; + $seen = [$key => true]; + while ($queue !== []) { + $current = array_shift($queue); + if (isset($projectTemplates[$current])) { + return $projectTemplates[$current]; + } + foreach ($referencers[$current] ?? [] as $parent) { + if (!isset($seen[$parent])) { + $seen[$parent] = true; + $queue[] = $parent; + } + } + } + + return null; +} + /** * @param list $lines */ @@ -408,6 +584,7 @@ function yves_scan_run(string $root, array $filters): array } $effective = []; + $undecidedAt = []; $vendorSites = []; $vendorComponentReferences = []; $parsedProject = []; @@ -417,32 +594,73 @@ function yves_scan_run(string $root, array $filters): array $effective[$reference['name']][] = substr($file, strlen($root) + 1) . ':' . $reference['line']; } } + $parsedVendor = []; + $referencers = []; foreach ($vendorTemplates as $key => $file) { - $parsed = yves_scan_parse_twig($file); + $parsedVendor[$key] = yves_scan_parse_twig($file); + foreach ($parsedVendor[$key]['references'] as $reference) { + $target = $reference['type'] === 'component' ? yves_scan_reference_key($reference['name']) : null; + if ($target !== null && $target !== $key) { + $referencers[$target][] = $key; + } + } + } + $reachable = yves_scan_reachable_vendor_keys($parsedVendor, $parsedProject); + + foreach ($parsedVendor as $key => $parsed) { + $file = $vendorTemplates[$key]; $override = $parsedProject[$key] ?? null; $overrideExtends = $override !== null && yves_scan_override_extends_vendor($override['extends'], $key); + $fromModule = explode('/', $key, 2)[0]; + $level = $override === null || $overrideExtends ? ($reachable[$key] ?? null) : null; foreach ($parsed['references'] as $reference) { $relative = substr($file, strlen($root) + 1); if ($reference['type'] === 'component') { - $vendorComponentReferences[] = $reference + ['fromModule' => explode('/', $key, 2)[0]]; + $vendorComponentReferences[] = $reference + ['fromModule' => $fromModule]; } - if ($override === null || yves_scan_vendor_site_survives($overrideExtends, $reference['blocks'], $override['blocks'])) { - $effective[$reference['name']][] = $relative . ':' . $reference['line']; + $survives = $override === null || yves_scan_vendor_site_survives($overrideExtends, $reference['blocks'], $override['blocks']); + if ($survives && $level !== null) { + // A template nothing references (consumer unknown) counts as before, except for a + // component of its own module: that one is no placement of the module's feature. + $subjectModule = $reference['type'] === 'widget' ? ($widgetModules[$reference['name']] ?? '') : $reference['module']; + if ($level === 'certain') { + $effective[$reference['name']][] = $relative . ':' . $reference['line']; + + continue; + } + if ($fromModule !== $subjectModule) { + $effective[$reference['name']][] = $relative . ':' . $reference['line']; + $undecidedAt[$reference['name']][] = $relative . ':' . $reference['line']; - continue; + continue; + } } $snippet = yves_scan_snippet($parsed['lines'], $reference['line'], $reference['type']); - $sharedBlocks = array_values(array_filter($reference['blocks'], fn (string $block): bool => isset($override['blocks'][$block]))); - $vendorSites[$reference['name']][] = [ + $site = [ 'vendorFile' => $relative, 'line' => $reference['line'], 'kind' => $reference['kind'], 'blocks' => $reference['blocks'], 'snippet' => $snippet, 'context' => yves_scan_context($parsed['lines'], $reference['line'], $snippet), - 'projectFile' => substr($projectTemplates[$key], strlen($root) + 1), - 'overrideMode' => $overrideExtends ? 'extends' : 'replaces', - 'projectBlocks' => $sharedBlocks, + ]; + if (!$survives) { + $sharedBlocks = array_values(array_filter($reference['blocks'], fn (string $block): bool => isset($override['blocks'][$block]))); + $vendorSites[$reference['name']][] = $site + [ + 'projectFile' => substr($projectTemplates[$key], strlen($root) + 1), + 'overrideMode' => $overrideExtends ? 'extends' : 'replaces', + 'projectBlocks' => $sharedBlocks, + ]; + + continue; + } + // The template is not replaced (or its block survives), but nothing the project renders + // includes it: the nearest replaced ancestor is the project file that dropped the include. + $replacing = yves_scan_replacing_project_file($key, $referencers, $projectTemplates); + $vendorSites[$reference['name']][] = $site + [ + 'projectFile' => $replacing !== null ? substr($replacing, strlen($root) + 1) : null, + 'overrideMode' => 'unreachable', + 'projectBlocks' => [], ]; } } @@ -505,6 +723,8 @@ function yves_scan_run(string $root, array $filters): array 'registeredIn' => $registeredNames[$name] ?? null, 'status' => $status, 'placedAt' => $placed, + // Subset of placedAt whose template nothing references (reachability undecided). + 'placedUndecided' => $undecidedAt[$name] ?? [], 'suggestions' => $status === YVES_SCAN_STATUS_PLACED ? [] : $sites, ]; } @@ -604,11 +824,19 @@ function yves_scan_print(array $report): void } printf("\n[%s] %s %s (%s)\n", $item['status'], $item['type'], $item['name'], $item['package'] ?? $item['module']); foreach ($item['suggestions'] as $site) { + $where = sprintf(' vendor %s:%d%s', $site['vendorFile'], $site['line'], $site['blocks'] !== [] ? ' in block ' . implode(' > ', $site['blocks']) : ''); + if ($site['overrideMode'] === 'unreachable') { + printf( + "%s\n -> not rendered: no template the project uses includes it%s\n", + $where, + $site['projectFile'] !== null ? '; the including template was replaced by ' . $site['projectFile'] : '', + ); + + continue; + } printf( - " vendor %s:%d%s\n -> project %s (%s%s)\n", - $site['vendorFile'], - $site['line'], - $site['blocks'] !== [] ? ' in block ' . implode(' > ', $site['blocks']) : '', + "%s\n -> project %s (%s%s)\n", + $where, $site['projectFile'], $site['overrideMode'], $site['projectBlocks'] !== [] ? '; project redefines ' . implode(', ', $site['projectBlocks']) : '', diff --git a/plugins/spryker-ai-dev-sdk/skills/yves-twig-integration/scripts/yves-integration-scan.test.php b/plugins/spryker-ai-dev-sdk/skills/yves-twig-integration/scripts/yves-integration-scan.test.php index ff50c60..378b8f0 100644 --- a/plugins/spryker-ai-dev-sdk/skills/yves-twig-integration/scripts/yves-integration-scan.test.php +++ b/plugins/spryker-ai-dev-sdk/skills/yves-twig-integration/scripts/yves-integration-scan.test.php @@ -168,5 +168,81 @@ function item(array $report, string $id): ?array check('gaps that existed before stay out of the diff', item($diff, 'NewsletterSubscriptionWidget') === null && count($diff['items']) === 1); exec('rm -rf ' . escapeshellarg($root)); + +/** + * Reachability and comments: a project that replaces the view including a molecule, a widget + * mentioned only in a Twig comment, a component of the feature's own module nobody includes. + */ +function reachability_project(): string +{ + $root = sys_get_temp_dir() . '/yves-scan-reach-' . uniqid(); + write_file("$root/composer.json", '{}'); + foreach (['CommentedWidget', 'LiveWidget', 'DeadWidget', 'ReachableWidget', 'SelfWidget', 'DynamicWidget'] as $name) { + widget_class($root, 'spryker-shop/' . strtolower($name), $name, $name, $name); + } + + // The comment spans lines; LiveWidget on line 5 must keep its line number. + vendor_twig($root, 'spryker-shop/shop-ui', 'ShopUi', 'views/home/home.twig', implode("\n", [ + "{# Old: {% widget 'CommentedWidget' only %}{% endwidget %}", + " molecule('ghost', 'GhostModule')", + '#}', + '{% block body %}', + " {% widget 'LiveWidget' only %}{% endwidget %}", + " {% include molecule('live-list', 'ShopUi') only %}", + " {% include molecule(data.dynamicName, 'ShopUi') only %}", + '{% endblock %}', + '', + ])); + // Reached through a root view that the project does not override. + vendor_twig($root, 'spryker-shop/shop-ui', 'ShopUi', 'components/molecules/live-list/live-list.twig', "{% widget 'ReachableWidget' only %}{% endwidget %}\n"); + // Reached only through a dynamic name in a reachable template. + vendor_twig($root, 'spryker-shop/shop-ui', 'ShopUi', 'components/molecules/dynamic-item/dynamic-item.twig', "{% widget 'DynamicWidget' only %}{% endwidget %}\n{% include molecule('anchor', 'ShopUi') only %}\n"); + vendor_twig($root, 'spryker-shop/shop-ui', 'ShopUi', 'components/molecules/anchor/anchor.twig', "\n"); + + // The vendor view includes the molecule; the project replaces the view and drops the include. + vendor_twig($root, 'spryker-shop/customer-page', 'CustomerPage', 'views/nav/nav.twig', "{% include molecule('nav-list', 'CustomerPage') only %}\n"); + vendor_twig($root, 'spryker-shop/customer-page', 'CustomerPage', 'components/molecules/nav-list/nav-list.twig', "{% widget 'DeadWidget' only %}{% endwidget %}\n"); + project_twig($root, 'CustomerPage', 'views/nav/nav.twig', "\n"); + + // A component of the widget's own module that nothing includes is no placement of that widget. + vendor_twig($root, 'spryker-shop/selfwidget', 'SelfWidget', 'components/molecules/self-box/self-box.twig', "{% widget 'SelfWidget' only %}{% endwidget %}\n"); + + register_widgets($root, array_map(fn (string $name): string => "SprykerShop\\Yves\\$name\\Widget\\$name", ['CommentedWidget', 'LiveWidget', 'DeadWidget', 'ReachableWidget', 'SelfWidget', 'DynamicWidget'])); + + return $root; +} + +echo "comments\n"; +$reach = reachability_project(); +$parsed = yves_scan_parse_twig("$reach/vendor/spryker-shop/shop-ui/src/SprykerShop/Yves/ShopUi/Theme/default/views/home/home.twig"); +$names = array_column($parsed['references'], 'name'); +check('a reference inside a multi-line Twig comment is not parsed', !in_array('CommentedWidget', $names, true) && !in_array('molecule:ghost@GhostModule', $names, true)); +check('line numbers survive the comment', $parsed['references'][0]['name'] === 'LiveWidget' && $parsed['references'][0]['line'] === 5); + +echo "reachability\n"; +$reachReport = yves_scan_run($reach, $empty); +check('a widget named only in a comment has no reference', item($reachReport, 'CommentedWidget')['status'] === YVES_SCAN_STATUS_NO_REFERENCE); +check('a widget in a root view the project keeps stays placed', item($reachReport, 'LiveWidget')['status'] === YVES_SCAN_STATUS_PLACED); +check('a widget in a molecule included by a kept view stays placed', item($reachReport, 'ReachableWidget')['status'] === YVES_SCAN_STATUS_PLACED + && item($reachReport, 'ReachableWidget')['placedUndecided'] === []); +$dead = item($reachReport, 'DeadWidget'); +check('a widget in a molecule whose including view the project replaced is missing', $dead['status'] === YVES_SCAN_STATUS_MISSING && $dead['placedAt'] === []); +check('the suggestion is marked unreachable and names the replacing project file', $dead['suggestions'][0]['overrideMode'] === 'unreachable' + && $dead['suggestions'][0]['projectFile'] === 'src/Pyz/Yves/CustomerPage/Theme/default/views/nav/nav.twig'); +check('a component of the widget\'s own module nobody includes is not a placement', item($reachReport, 'SelfWidget')['status'] === YVES_SCAN_STATUS_MISSING + && item($reachReport, 'SelfWidget')['suggestions'][0]['projectFile'] === null); +$dynamicWidget = item($reachReport, 'DynamicWidget'); +check('a dynamic molecule name keeps the old behaviour and is marked undecided', $dynamicWidget['status'] === YVES_SCAN_STATUS_PLACED && count($dynamicWidget['placedUndecided']) === 1); +$scopedReach = yves_scan_run($reach, ['modules' => [], 'packages' => ['spryker-shop/deadwidget']]); +check('the scoped scan reports the same unreachable widget', item($scopedReach, 'DeadWidget')['status'] === YVES_SCAN_STATUS_MISSING); + +// An extending override of the view keeps the vendor include alive. +project_twig($reach, 'CustomerPage', 'views/nav/nav.twig', "{% extends template('nav', '@SprykerShop:CustomerPage') %}\n"); +check('an extending view override keeps the vendor include reachable', item(yves_scan_run($reach, $empty), 'DeadWidget')['status'] === YVES_SCAN_STATUS_PLACED); +// Once the project's own template includes the molecule, it is reachable again. +write_file("$reach/src/Pyz/Yves/CustomerPage/Theme/default/views/nav/nav.twig", "{% include molecule('nav-list', 'CustomerPage') only %}\n"); +check('a project template that includes the molecule makes it reachable', item(yves_scan_run($reach, $empty), 'DeadWidget')['status'] === YVES_SCAN_STATUS_PLACED); + +exec('rm -rf ' . escapeshellarg($reach)); echo "\n$count checks, $failures failed\n"; exit($failures === 0 ? 0 : 1); From bb73e506f195a0a7d15548c379c922f60ecff574 Mon Sep 17 00:00:00 2001 From: Dmitriy Krainiy Date: Mon, 9 Nov 2026 13:23:37 +0100 Subject: [PATCH 05/18] Report capability map tool failures as MCP tool errors getSprykerCapability and searchSprykerCapabilities returned failures (unknown slug, query without a usable term, map not loadable) as a successful result with an "error" field, so clients saw isError false. The plugins now throw ToolCallException, which the MCP SDK returns as a tool result with isError true and the message as text. The business layer keeps its error key and stays free of MCP code. Co-Authored-By: Claude --- .../skills/find-existing-capability/SKILL.md | 2 +- ...GetSprykerCapabilityAiDevMcpToolPlugin.php | 8 ++ ...hSprykerCapabilitiesAiDevMcpToolPlugin.php | 8 ++ .../CapabilityMapAiDevMcpToolPluginTest.php | 100 ++++++++++++++++++ 4 files changed, 117 insertions(+), 1 deletion(-) create mode 100644 tests/SprykerSdkTest/Zed/AiDev/Communication/Plugins/AiDevMcpTools/CapabilityMapAiDevMcpToolPluginTest.php diff --git a/plugins/spryker-ai-dev-sdk/skills/find-existing-capability/SKILL.md b/plugins/spryker-ai-dev-sdk/skills/find-existing-capability/SKILL.md index 48d3ebc..07ecdbf 100644 --- a/plugins/spryker-ai-dev-sdk/skills/find-existing-capability/SKILL.md +++ b/plugins/spryker-ai-dev-sdk/skills/find-existing-capability/SKILL.md @@ -37,7 +37,7 @@ Match tools by **tool name** (server names vary by install; some clients namespa | `getSprykerModules` | Which modules the project has, and the exact module names. | | `searchAlgoliaDocumentation` | Official docs search, for the "no relevant hit" cross-check. | -A tool result of `{"error": "..."}` is a failure, not an empty result: report it and use the fallback below. +A tool error (for example "Unknown capability", "The query needs at least one term", or the map cannot be loaded) is a failure, not an empty result: report its message and use the fallback below. **If the capability tools are not available**, first tell the two causes apart. The server is **not registered** when no `ai-dev:mcp-server` entry exists in the project's MCP config files (`.mcp.json`, `.vscode/mcp.json`) and the harness's MCP server list does not show it. It is **registered but not connected** when an entry exists and the tools are still missing. diff --git a/src/SprykerSdk/Zed/AiDev/Communication/Plugins/AiDevMcpTools/GetSprykerCapabilityAiDevMcpToolPlugin.php b/src/SprykerSdk/Zed/AiDev/Communication/Plugins/AiDevMcpTools/GetSprykerCapabilityAiDevMcpToolPlugin.php index b426997..ab69460 100644 --- a/src/SprykerSdk/Zed/AiDev/Communication/Plugins/AiDevMcpTools/GetSprykerCapabilityAiDevMcpToolPlugin.php +++ b/src/SprykerSdk/Zed/AiDev/Communication/Plugins/AiDevMcpTools/GetSprykerCapabilityAiDevMcpToolPlugin.php @@ -9,6 +9,7 @@ namespace SprykerSdk\Zed\AiDev\Communication\Plugins\AiDevMcpTools; +use Mcp\Exception\ToolCallException; use Spryker\Zed\Kernel\Communication\AbstractPlugin; use SprykerSdk\Zed\AiDev\Dependency\AiDevMcpToolPluginInterface; @@ -33,12 +34,19 @@ public function getDescription(): string . 'Use the extension points to plan an extension and the Install section to install a missing feature; check exact classes with getSprykerModuleMap.'; } + /** + * @throws \Mcp\Exception\ToolCallException + */ public function getSprykerCapability(string $slug): string { $result = $this->getBusinessFactory() ->createCapabilityMapFinder() ->getCapability($slug); + if (isset($result['error'])) { + throw new ToolCallException($result['error']); + } + return (string)json_encode($result, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); } } diff --git a/src/SprykerSdk/Zed/AiDev/Communication/Plugins/AiDevMcpTools/SearchSprykerCapabilitiesAiDevMcpToolPlugin.php b/src/SprykerSdk/Zed/AiDev/Communication/Plugins/AiDevMcpTools/SearchSprykerCapabilitiesAiDevMcpToolPlugin.php index 7d67508..6b7c231 100644 --- a/src/SprykerSdk/Zed/AiDev/Communication/Plugins/AiDevMcpTools/SearchSprykerCapabilitiesAiDevMcpToolPlugin.php +++ b/src/SprykerSdk/Zed/AiDev/Communication/Plugins/AiDevMcpTools/SearchSprykerCapabilitiesAiDevMcpToolPlugin.php @@ -9,6 +9,7 @@ namespace SprykerSdk\Zed\AiDev\Communication\Plugins\AiDevMcpTools; +use Mcp\Exception\ToolCallException; use Spryker\Zed\Kernel\Communication\AbstractPlugin; use SprykerSdk\Zed\AiDev\Dependency\AiDevMcpToolPluginInterface; @@ -34,12 +35,19 @@ public function getDescription(): string . 'Open a hit with getSprykerCapability for its extension points, configuration and install guide. No hit is not proof of absence.'; } + /** + * @throws \Mcp\Exception\ToolCallException + */ public function searchSprykerCapabilities(string $query, int $limit = 10): string { $result = $this->getBusinessFactory() ->createCapabilityMapFinder() ->searchCapabilities($query, $limit); + if (isset($result['error'])) { + throw new ToolCallException($result['error']); + } + return (string)json_encode($result, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); } } diff --git a/tests/SprykerSdkTest/Zed/AiDev/Communication/Plugins/AiDevMcpTools/CapabilityMapAiDevMcpToolPluginTest.php b/tests/SprykerSdkTest/Zed/AiDev/Communication/Plugins/AiDevMcpTools/CapabilityMapAiDevMcpToolPluginTest.php new file mode 100644 index 0000000..2f39771 --- /dev/null +++ b/tests/SprykerSdkTest/Zed/AiDev/Communication/Plugins/AiDevMcpTools/CapabilityMapAiDevMcpToolPluginTest.php @@ -0,0 +1,100 @@ +setBusinessFactory($this->createBusinessFactoryMock( + 'searchCapabilities', + ['query' => 'wishlist', 'count' => 1, 'hits' => [['slug' => 'wishlist']]], + )); + + // Act + $result = json_decode($plugin->searchSprykerCapabilities('wishlist'), true); + + // Assert + $this->assertSame('wishlist', $result['hits'][0]['slug']); + } + + public function testSearchSprykerCapabilitiesThrowsToolCallExceptionOnError(): void + { + // Arrange + $plugin = new SearchSprykerCapabilitiesAiDevMcpToolPlugin(); + $plugin->setBusinessFactory($this->createBusinessFactoryMock('searchCapabilities', ['error' => static::ERROR_MESSAGE])); + + // Assert + $this->expectException(ToolCallException::class); + $this->expectExceptionMessage(static::ERROR_MESSAGE); + + // Act + $plugin->searchSprykerCapabilities('ab'); + } + + public function testGetSprykerCapabilityReturnsJsonOnSuccess(): void + { + // Arrange + $plugin = new GetSprykerCapabilityAiDevMcpToolPlugin(); + $plugin->setBusinessFactory($this->createBusinessFactoryMock('getCapability', ['slug' => 'wishlist', 'installStatus' => 'installed'])); + + // Act + $result = json_decode($plugin->getSprykerCapability('wishlist'), true); + + // Assert + $this->assertSame('installed', $result['installStatus']); + } + + public function testGetSprykerCapabilityThrowsToolCallExceptionOnError(): void + { + // Arrange + $plugin = new GetSprykerCapabilityAiDevMcpToolPlugin(); + $plugin->setBusinessFactory($this->createBusinessFactoryMock('getCapability', ['error' => static::ERROR_MESSAGE])); + + // Assert + $this->expectException(ToolCallException::class); + $this->expectExceptionMessage(static::ERROR_MESSAGE); + + // Act + $plugin->getSprykerCapability('missing'); + } + + /** + * @param array $finderResult + */ + protected function createBusinessFactoryMock(string $finderMethod, array $finderResult): AiDevBusinessFactory + { + $capabilityMapFinderMock = $this->createMock(CapabilityMapFinderInterface::class); + $capabilityMapFinderMock->method($finderMethod)->willReturn($finderResult); + + $businessFactoryMock = $this->createMock(AiDevBusinessFactory::class); + $businessFactoryMock->method('createCapabilityMapFinder')->willReturn($capabilityMapFinderMock); + + return $businessFactoryMock; + } +} From 3407e190e550695059deda258486957a4a65f5b3 Mon Sep 17 00:00:00 2001 From: Dmitriy Krainiy Date: Mon, 9 Nov 2026 13:25:31 +0100 Subject: [PATCH 06/18] Update version of spryker-ai-dev-sdk to 0.10.0 --- .claude-plugin/marketplace.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index 0f4165b..937c9e2 100644 --- a/.claude-plugin/marketplace.json +++ b/.claude-plugin/marketplace.json @@ -10,7 +10,7 @@ { "name": "spryker-ai-dev-sdk", "description": "Set of setup tools, skills and agents for Spryker project development.", - "version": "0.9.0", + "version": "0.10.0", "author": { "name": "Spryker Systems GmbH", "email": "support@spryker.com" From 1ff40bfa595da83c86610f27c415f981fb426420 Mon Sep 17 00:00:00 2001 From: Dmitriy Krainiy Date: Mon, 9 Nov 2026 13:25:45 +0100 Subject: [PATCH 07/18] Bump version from 0.9.0 to 0.10.0 --- plugins/spryker-ai-dev-sdk/.claude-plugin/plugin.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plugins/spryker-ai-dev-sdk/.claude-plugin/plugin.json b/plugins/spryker-ai-dev-sdk/.claude-plugin/plugin.json index a846f44..ba0c6bb 100644 --- a/plugins/spryker-ai-dev-sdk/.claude-plugin/plugin.json +++ b/plugins/spryker-ai-dev-sdk/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "spryker-ai-dev-sdk", - "version": "0.9.0", + "version": "0.10.0", "description": "Set of setup tools, skills and agents for Spryker project development. Works with Claude Code and GitHub Copilot.", "author": { "name": "Spryker Systems GmbH", From 9274eb81404a76ea31751934a6a99768290ec2fb Mon Sep 17 00:00:00 2001 From: Veronika Golska Date: Tue, 10 Nov 2026 09:06:49 +0100 Subject: [PATCH 08/18] Add checklist engine, reconcile and release steps to spryker-feature-install - Parse the install guide into a checklist with one row per step; gate the install and the report on undecided or open rows (check-checklist.php). - Reconcile each row with the reference demo shop (b2b-demo-marketplace): plugin subset and order, merged config, and the files the guide does not name (find-feature-change.php adds them as reference-only rows). - Resolve the release the feature needs; allow the module moves it needs, stop on another feature package or a third-party root pin. - Record baselines; check overrides after module moves; verify each guide Verification block; find and prove release steps (diff-release-steps.php). - Hand data rows to project-data with a fixed row list. - find-existing-capability hands installs to spryker-feature-install; spryker-upgrade Phase 6 hands accepted features over after the upgrade PR. --- .../skills/find-existing-capability/SKILL.md | 2 +- .../skills/project-data/SKILL.md | 1 + .../skills/spryker-feature-install/README.md | 116 +- .../skills/spryker-feature-install/SKILL.md | 400 ++- .../references/apply-steps.md | 55 + .../references/data-classes.md | 51 + .../references/environment-preflight.md | 2 +- .../references/reconcile.md | 70 + .../references/release-steps.md | 118 + .../references/sources.md | 110 + .../scripts/check-checklist.php | 120 + .../scripts/check-feature-installed.php | 232 ++ .../scripts/check-lock-diff.php | 170 + .../scripts/diff-release-steps.php | 167 + .../scripts/feature-install.test.php | 293 ++ .../scripts/find-feature-change.php | 199 ++ .../guides/multiple-carts-glue-api.txt | 101 + .../fixtures/guides/order-amendment.txt | 2888 +++++++++++++++++ .../fixtures/guides/ssp-asset-management.txt | 1448 +++++++++ .../spryker-feature-install/scripts/lib.php | 100 + .../scripts/parse-integration-guide.php | 608 ++++ .../skills/spryker-upgrade/SKILL.md | 6 +- 22 files changed, 7080 insertions(+), 177 deletions(-) create mode 100644 plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/references/apply-steps.md create mode 100644 plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/references/data-classes.md create mode 100644 plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/references/reconcile.md create mode 100644 plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/references/release-steps.md create mode 100644 plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/references/sources.md create mode 100644 plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/check-checklist.php create mode 100644 plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/check-feature-installed.php create mode 100644 plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/check-lock-diff.php create mode 100644 plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/diff-release-steps.php create mode 100644 plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/feature-install.test.php create mode 100644 plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/find-feature-change.php create mode 100644 plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/fixtures/guides/multiple-carts-glue-api.txt create mode 100644 plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/fixtures/guides/order-amendment.txt create mode 100644 plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/fixtures/guides/ssp-asset-management.txt create mode 100644 plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/lib.php create mode 100644 plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/parse-integration-guide.php diff --git a/plugins/spryker-ai-dev-sdk/skills/find-existing-capability/SKILL.md b/plugins/spryker-ai-dev-sdk/skills/find-existing-capability/SKILL.md index 07ecdbf..ca1abe8 100644 --- a/plugins/spryker-ai-dev-sdk/skills/find-existing-capability/SKILL.md +++ b/plugins/spryker-ai-dev-sdk/skills/find-existing-capability/SKILL.md @@ -102,7 +102,7 @@ One verdict per capability, driven by the card's `status` and the computed `inst ## Version drift -The map describes the latest release line. The project may be older. When a capability matters and a module's installed `version` (from the card's `modules[]`) looks old for the feature, read the module's code in `vendor/spryker/` or call `getSprykerModuleMap` before relying on a card detail (an extension point, a Glue resource, a config key). When the project is clearly behind, say so and suggest the `spryker-upgrade` skill instead of working around the gap. +The map describes the latest release line. The project may be older. When a capability matters and a module's installed `version` (from the card's `modules[]`) looks old for the feature, read the module's code in `vendor/spryker/` or call `getSprykerModuleMap` before relying on a card detail (an extension point, a Glue resource, a config key). When the verdict is an install, say that the project is older than the map, and hand it to `spryker-feature-install` anyway: its Phase 1 finds the release the feature needs and decides whether that takes an upgrade. Do not propose `spryker-upgrade` from this skill. ## Step 5 - Report diff --git a/plugins/spryker-ai-dev-sdk/skills/project-data/SKILL.md b/plugins/spryker-ai-dev-sdk/skills/project-data/SKILL.md index 17fe1d8..dc5da99 100644 --- a/plugins/spryker-ai-dev-sdk/skills/project-data/SKILL.md +++ b/plugins/spryker-ai-dev-sdk/skills/project-data/SKILL.md @@ -22,6 +22,7 @@ You drive the `spryker-import-tools` scripts (`csv.php` + `validate.php`) with j Ad-hoc **add / edit / filter / one-off remove** on import data that isn't one of the above is the same tools driven directly (`csv filter`/`delete`/`set`/`duplicate-*` → `validate` → apply) — no separate strategy; use the shared core and the closest reference for the cascade rules. +- **A data hand-off from `spryker-feature-install`** (`.ai-dev/feature-install//data-handoff-
.md`) is an ad-hoc add with a fixed row list: add exactly the rows it names, to the files it names, with the project's locales and stores; change no other row. Apply with the reset ladder below, then report per hand-off row: added, or not added with the reason. The feature skill checks the result and owns the checklist. - Standalone (a user asks directly), classify their words against the table — **never make them name a strategy or a file.** "Add demo data for my shop" → generate. "Drop the demo customers" → cleanup. "We only sell heat-recovery" → reduce. If the request is ambiguous, ask one plain question. - In the **wizard**, `data.mode` picks it: `adapt`→adapt, `clean`→clean, `generate`→generate, `leave`→skip entirely; plus a `reduce` pass after adapt if `reduce_catalog ≠ keep:all`. `generate` carries a **`source` axis**: `authored` (interactive authoring — the not-hands-off warning attaches here) or `dataset: ` (a supplied structured catalogue: the path plus a field mapping; conversion into the import CSVs goes through `php append`/`add-row`, and where a JSON→CSV conversion needs a script, state it as a deviation in the step report with the reason, write LF, and run `php preflight ` right after). Never record an invented marker (`authoring: none`) to mean "dataset" — use the axis. diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/README.md b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/README.md index a85c63c..f49c59e 100644 --- a/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/README.md +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/README.md @@ -1,46 +1,108 @@ # spryker-feature-install -Install a Spryker feature into a project **end to end**, from a capability card or a feature name: resolve the feature and its required features, confirm scope, fetch the official install guide, `composer require`, apply the guide's integration steps in the project layer, run codegen and setup, verify, and report what was done and skipped. +Install a Spryker feature into a project **end to end**, from a capability card or a feature name: +resolve the feature, its required features and the release it needs; turn the official install guide +into a checklist with one row per step; reconcile each row with the reference demo shop; apply it in +the project layer; suggest storefront placement; verify; and prove the release steps that existing +environments need. -Where `find-existing-capability` decides "install it instead of building it", this skill does the install - always after the user confirms the feature, packages, version constraint and optional integrations. +Where `find-existing-capability` decides "install it instead of building it", this skill does the +install — always after the developer confirms the feature, packages, release and optional +integrations. ## When it triggers -"Install the X feature", "add `spryker-feature/x`", "integrate feature X", "install the X Glue API", or after `find-existing-capability` proposed an install (`not_installed` / `partially_installed`). +"Install the X feature", "add `spryker-feature/x`", "integrate feature X", "install the X Glue API", +after `find-existing-capability` proposed an install (`not_installed` / `partially_installed`), or a +feature that `spryker-upgrade` Phase 6 accepted. ## Flow schema ```mermaid flowchart TD - A([Feature name or capability card]) --> P0["0 - Environment preflight
stack up, container sees host files,
vendor in line with lock, frontend deps"] --> B["1 - Resolve
getSprykerCapability: Install section
feature, requires features, docs guides,
Glue API, Storefront API"] - B --> RQ{"Required features
installed?"} - RQ -- "no" --> RQ1["Offer to install them first
(recursively)"] --> C - RQ -- "yes" --> C - C{"2 - Confirm with the user
feature, packages, version constraint,
optional APIs and demo data, branch,
environment bootstrap when needed"} - C -- "no / change" --> C - C -- "yes" --> D["3 - Fetch the install guide
spryker-docs-research or docs markdown
match the project's release line
deprecated plugins, no-guide wiring
build the step checklist"] - D --> E["4 - composer require
explicit ^x.y.z constraint
conflict: stop and report"] - E --> F["5 - Integration steps, project layer only
config - plugin wiring - transfers - schema
navigation - routes - glossary check - data import
API Platform resources: skip route plugins"] - F --> G["6 - spryker-refresher
codegen, caches, setup commands
glue per existing application
+ the guide's own setup commands"] - G --> H["7 - Verify
auth precondition, guide's verify steps
boot-and-verify - spryker-verifier agent"] - H --> R(["8 - Report
installed - done / skipped checklist
follow-ups - unstaged changes"]) + A([Feature name or capability card]) --> P0["0 - Preflight and baselines
stack, container sync, vendor vs lock,
frontend deps; PHPStan, sniffer, tests, crawl"] + P0 --> B["1 - Resolve
card: feature, required features, guide
install release; modules the feature needs"] + B --> UP{"Another feature package
or a root pin must move?"} + UP -- "yes" --> X(["Stop: offer spryker-upgrade"]) + UP -- "no" --> S["2 - Sources
guide, prerequisite guides,
reference demo shop and its history"] + S --> C["3 - Checklist and confirmation
parse-integration-guide, check-feature-installed
data classes; developer gate #1"] + C --> R["4 - Reconcile
find-feature-change adds reference-only rows
decision per row; gate: check-checklist decide"] + R --> I["5 - Install
composer, check-lock-diff, override checks
one guide section at a time, spryker-refresher
gate: check-feature-installed --wiring"] + I --> Y["5b - Storefront placement
yves-integration-scan suggestions
yves-twig-integration on the developer's pick"] + Y --> V["6 - Verify
auth precondition, spryker-verifier per
Verification row, baselines compared"] + V --> RS["7 - Release steps
diff-release-steps, prove with
deployed vs fresh comparison"] + RS --> RP(["8 - Report
gate: check-checklist report"]) ``` -## Tools +## Scripts -Bundled: `scripts/glossary-key-check.php` (translation keys of a feature's Yves modules missing from the project glossary) and `references/environment-preflight.md` (shared with `spryker-upgrade`). Matched by tool name: `searchSprykerCapabilities`, `getSprykerCapability`, `searchAlgoliaDocumentation`, `getSprykerModules`, `getSprykerModuleMap`, `getTransferStructureByName`. Skills it hands to: `spryker-docs-research`, `spryker-refresher`, `boot-and-verify`, `project-data` / `data-import`; agents: `spryker-verifier`, `spryker-issue-diagnoser`. +`$FI` in every example is `/scripts`. Run the scripts from the project root; +`SPRYKER_PROJECT_ROOT` overrides it. All run on host PHP, with no Spryker bootstrap. -## Output +| Script | Phase | What it answers | +|---|---|---| +| `parse-integration-guide.php` | 3 | which steps does the guide have, of which kind, in which scenario? | +| `check-feature-installed.php` | 3 (`--mark`), 5 (`--wiring`) | which modules and wiring does the project have already; is the decided wiring in place; which plugins belong to modules the project does not install? | +| `find-feature-change.php` | 4 | which pull request brought the feature into the reference demo shop, and which of its files does no row name? | +| `check-checklist.php` | 4 (`--phase decide`), 8 (`--phase report`) | is every row decided; is every row done and every verification passed? | +| `check-lock-diff.php` | 5 | which packages did the install move outside the feature's dependency tree; does a required package have a dev constraint? | +| `glossary-key-check.php` | 5 | which translation keys of the feature's Yves modules have no glossary row? | +| `diff-release-steps.php` | 7 | which commands, imports, republishes and variables does the deploy recipe not cover? | -A feature install report: what was installed (packages, versions, required features), the guide followed, the step checklist with `done` / `skipped (reason)`, verification evidence, follow-ups (for example the Glue API integration not done) and the changed files, left unstaged. +`lib.php` is the shared library. `feature-install.test.php` is the maintainer test suite +(`php $FI/feature-install.test.php`); its guide fixtures in `fixtures/guides/` are copies of real +integration guides in both guide styles. It is not part of an install run. The baselines and the +override checks reuse `../spryker-upgrade/scripts/`; storefront placement uses +`../yves-twig-integration/scripts/`. + +## State + +Everything a run writes is in the project, under `.ai-dev/feature-install//`: + +| Path | Content | +|---|---| +| `state.md` | The phase table: phase, status, evidence; the install release and added modules | +| `sources/` | The guides, the feature `composer.json`, the reference demo shop clone and its history | +| `checklist.json` | One row per guide step, with its decision, status and verdict | +| `composer.lock.before` | The lock before the install | +| `baseline/` | The baselines of the `spryker-upgrade` scripts, PHPStan, sniffer and tests | +| `data-handoff-
.md` | The fixed row lists for `project-data` | +| `release-steps.md` | The release-steps log | +| `report.md` | The report | + +## The checklist row + +| Field | Content | +|---|---| +| `id`, `guide`, `section`, `lines` | Where the step comes from | +| `kind` | `composer`, `config`, `schema`, `event`, `transfer`, `oms`, `navigation`, `glossary`, `data-row`, `data-import`, `plugin`, `route`, `widget`, `queue`, `search-index`, `frontend`, `code`, `recipe`, `deploy`, `console`, `verification`, `linked-guide`, `unknown` | +| `tag` | `required`, `optional-scenario:`, `demo-data`, `fresh-install-only` | +| `data_class` | Data rows only: `feature-data`, `project-content`, `demo-data`, or null until decided | +| `target` | The file, the command, the plugin class, or the linked page | +| `plugins`, `packages`, `env` | The plugin classes a snippet wires, the packages a composer line requires, the environment variables a snippet reads | +| `source` | `guide`, or `reference-only` for a file only the reference demo shop changed | +| `reference` | `same`, `differs` or `absent`, with the reference path | +| `decision` | `apply-guide`, `apply-reference`, `merge`, `already-present`, `skip:` | +| `status` | `open`, `done`, `skipped`, `failed` | +| `verdict`, `verdict_note` | Verification rows: `PASS`, `FAIL`, `BLOCKED`, or `ACCEPTED` with the note | + +A plugin row with a class name as its `target` and a `note` comes from a plugin table that has no +wiring snippet in the guide: the guide lists the plugin and shows nowhere how to wire it. ## Design decisions baked in -- **Confirm before changing.** Nothing is required or edited before the user agrees to the feature, constraint and optional integrations. -- **The guide is the source of truth for steps; the installed code is the source of truth for names.** Identifier spellings are confirmed against `vendor/` (read-only) before they are written. -- **Project layer only.** Never `vendor/`, `src/Generated/` or `src/Orm/`; existing plugin stacks keep their order. -- **Preflight the environment.** A stack that is down, out of sync or behind `composer.lock` is reported as a pre-existing issue and a bootstrap is suggested in the confirmation; never `reset`. -- **Glue applications are resolved, not assumed.** `glue` commands run per application that exists (`public/Glue*/index.php`, deploy entry points); API Platform resources replace the guide's route and relationship plugins. -- **No silent gaps.** Every guide step ends done or skipped with a reason; a failing step is diagnosed, not dropped. -- **No destructive commands, no auto-commit.** A rebuild (`docker/sdk up`) or `reset` is reported, not run; the environment bootstrap is proposed in the confirmation and `reset` never. -- **Blocked is not failed.** When a fixture login fails, logged-in checks are reported BLOCKED (environment) and handed to `spryker-issue-diagnoser`. +- **Confirm before changing.** Nothing is required or edited before the developer agrees to the + feature, release, constraint and optional integrations. +- **Every step is a row; every row is decided.** The checklist gates block the install and the + report while a row is undecided or open. +- **The reference demo shop decides the plugin subset and order; the project decides its config.** + The reference is `b2b-demo-marketplace` for every project type; plugins of capabilities the + project does not have are skipped. +- **The release the feature needs, not the latest.** The feature may move the modules it needs; + another feature package or a third-party root pin means an upgrade. +- **The guide is the source of truth for steps; the installed code for names.** +- **Project layer only.** Never `vendor/`, `src/Generated/` or `src/Orm/`. +- **Release steps are proven.** A command the guide runs locally is a release step until a recipe + covers it. +- **Blocked is not failed.** A failed fixture login makes logged-in checks BLOCKED (environment). +- **No destructive commands, no auto-commit.** diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/SKILL.md b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/SKILL.md index d020aed..1869999 100644 --- a/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/SKILL.md +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/SKILL.md @@ -2,159 +2,269 @@ name: spryker-feature-install description: > Install a Spryker feature into the project end to end, from a capability card or a feature name: - resolve the feature metapackage and its required features, confirm scope with the user, fetch the - official install guide, `composer require`, apply the guide's integration steps in the project layer - only (config, dependency-provider plugin wiring, transfers, schema, navigation, routes, glossary, - data import), run codegen and setup, verify, and report done / skipped steps. Use when the user says "install the X feature", "add spryker-feature/x", "integrate feature X", "install the X Glue API", - or after `find-existing-capability` proposed installing a feature instead of building one. Always - confirms before changing anything; never edits vendor/ or generated code; never auto-commits. + after find-existing-capability proposed an install, or a feature that spryker-upgrade Phase 6 + accepted. Resolves the feature, its required features and the release it needs (moving only the + modules it needs); parses the official install guide into a checklist with one row per step; + reconciles every row with the reference demo shop (plugin subset and order, merged config, files + the guide does not name); applies it in the project layer one guide section at a time; suggests + storefront placement; verifies each guide Verification block; and finds and proves the release + steps existing environments need (imports, republish, environment variables). Always confirms + before changing anything; never edits vendor/ or generated code; never auto-commits. --- # Spryker Feature Install -Take a Spryker feature from "not in the project" to "installed, wired and verified", following the **official install guide** for that feature. The goal is the documented integration, not a lookalike: a feature that ships should be installed, then extended, not rebuilt. - -Typical entry: `find-existing-capability` returned `not_installed` or `partially_installed` for a capability and the user agreed to install it. Also used standalone ("install the Cart feature", "add `spryker-feature/wishlist`"). - -Delegate with your harness's subagent tool; invoke skills by slash command (`/spryker-refresher`, or `/spryker-ai-dev-sdk:spryker-refresher` on a plugin install). **Agent names carry the plugin prefix on a plugin install and the separator differs by harness** (`spryker-ai-dev-sdk:spryker-verifier` or `spryker-ai-dev-sdk/spryker-verifier`); try the bare name only on a setup install, and if it does not resolve retry with your harness's prefixed form (see `../spryker-customization/references/delegation.md`). +Take a Spryker feature from "not in the project" to "installed, wired, verified and releasable". +The goal is the documented integration, not a lookalike: a feature that ships is installed, then +extended, not rebuilt. Typical entry: `find-existing-capability` returned `not_installed` or +`partially_installed` and the developer agreed to install. + +## Non-negotiables — read these before Phase 0, re-read them on every compaction + +1. **Nothing changes before the developer confirms** the feature, the packages, the release, the + optional integrations and the branch (gate #1, Phase 3). +2. **One feature per run, at the release the feature needs.** A feature that exists at the + project's release installs at that release. A feature of a later release may move the modules it + needs; it may not move another `spryker-feature/*` package — that is a release upgrade, and the + run stops and offers `spryker-upgrade` (Phase 1). + *Failure signature:* a `composer require` that moves another `spryker-feature/*` package. +3. **Every guide step is a checklist row, and every row gets a decision.** The guide is never + followed from the prose. A step the parser cannot classify is a row of kind `unknown`, decided by + hand. `check-checklist.php` blocks the install while a row has no decision, and the report while a + row is open. *Failure signature:* an edit to a project file that no checklist row names. +4. **Merge into existing config and plugin stacks; never overwrite them.** The guide shows values + for a fresh project. A `...` in a guide snippet always means merge. + *Failure signature:* a diff line that removes a project value the guide does not name. +5. **The reference demo shop decides the plugin subset and order; the project decides its existing + config.** A guide plugin that the reference does not wire is a question for the developer. A + plugin of a capability the project does not have (merchants, company accounts, marketplace + offers) is not a step. +6. **Data rows go to `project-data`.** This skill writes no row in `data/import/**`. +7. **A command the guide runs locally is a release step until a recipe covers it** (Phase 7). +8. **Project layer only, and no shortcuts:** never `vendor/`, `src/Generated/`, `src/Orm/` or a + hand-edited `composer.lock`; never `dev-*` constraints or `--ignore-platform-reqs`; never a + suppression; never `docker/sdk reset` or `clean-data`; never a commit or push without the + developer's yes. + +**Plan tracking is mandatory.** After Phase 0, create one task per phase in your harness's task +list, and keep the phase table in `$STATE/state.md`: it survives a compaction. + +**Locations.** `$FI` is `/scripts`, `$UP` is `/../spryker-upgrade/scripts`, +`$YI` is `/../yves-twig-integration/scripts`. `` is the path reported as +`Base directory for this skill:` when this skill loaded. `$STATE` is +`.ai-dev/feature-install//` in the project. Substitute each one inline as a literal +path; never set a shell variable and never `cd`. Run every script from the project root. + +**Delegation.** Invoke skills by slash command (`/spryker-refresher`, or +`/spryker-ai-dev-sdk:spryker-refresher` on a plugin install). Agent names carry the plugin prefix +on a plugin install, and the separator differs by harness (see +`../spryker-customization/references/delegation.md`). Siblings: `find-existing-capability`, +`spryker-docs-research`, `spryker-refresher`, `project-data`, `yves-twig-integration`, +`boot-and-verify`, `spryker-upgrade`; agents `spryker-verifier` and `spryker-issue-diagnoser`. ## Tools -Match tools by **tool name** (server names vary by install; some clients namespace them `mcp____`). +Match tools by **tool name** (server names vary by install; some clients namespace them +`mcp____`). | Tool | Use | |---|---| -| `searchSprykerCapabilities`, `getSprykerCapability` | Resolve the feature and read the card's Install section, modules and `installStatus` (computed from `composer.lock`). | -| `searchAlgoliaDocumentation` | Find the install guide pages; returns `github_api_url`s for the markdown. | -| `getSprykerModules`, `getSprykerModuleMap` | What the project has now; exact plugin interfaces and stack positions. | -| `getTransferStructureByName` | Check transfer fields before editing a transfer XML. | - -If the capability tools are not connected, start the MCP server and ask for a reload the way `find-existing-capability` describes; after two failed reconnects take the feature name and guide URL from the user, or fetch `https://spryker-capability-map.s3.eu-central-1.amazonaws.com/.md` with the web fetch tool and compare its packages with `composer.lock` by hand, and say that the install status is then unverified. - -## Step 0 - Environment preflight - -The install needs a running, in-sync stack (composer in the container, codegen, `propel:install`, verification), and the planning steps below do not. Run the checks in [references/environment-preflight.md](references/environment-preflight.md) before Step 2, so a stack that is down, a container that does not see the host files, a `vendor/` behind `composer.lock` or a broken frontend dependency tree is reported as a **pre-existing environment issue** and not mistaken for a feature failure. Reading the card and the guide needs no stack; skip the boot for a plan-only run. - -## Step 1 - Resolve the feature - -1. From a card: `getSprykerCapability(slug)`. From a name: `searchSprykerCapabilities` with the name and its synonyms, then open the best card. Read the **Install** section; it lists: - - `Feature:` the metapackage (`spryker-feature/`) and its docs install guide URL, or "no install guide found" - then search the docs with `searchAlgoliaDocumentation` ("install the feature") and, without a guide, tell the user the integration steps come from the module code and the feature's other guides, not from an official guide; - - `Requires features:` other features that must be installed first; - - `Glue API:` the guide for the Glue API integration, when one exists; - - `Storefront API (when the project exposes it):` the `*-rest-api` / `*-storefront-api` packages. -2. Read `installStatus`, `features[]` and `missingPackages`. `installed` means there is nothing to install: say so and hand back to `find-existing-capability` (extend it). `partially_installed` means install only what is missing. -3. **Required features first.** Check each feature in `Requires features:` against `composer.lock` / `getSprykerModules`. For each one that is missing, resolve its card the same way and offer to install it first (recursively). Spryker Core and other base features are usually present already; verify, do not assume. - -## Step 2 - Confirm before changing anything - -Present one confirmation block and wait for the user's answer. It carries: - -- the feature, the packages `composer require` will add, and any required features that would be installed first; -- the **version constraint**: match the project's other `spryker-feature/*` constraints and release line in `composer.json` (for example the same `^202xxx.x` style); do not introduce a different style. For module packages the project pins as `^x.y.z` (the `*-rest-api` entries, for example), the explicit constraint is the resolved version, see Step 4; -- the **optional integrations** the user wants: Glue API, Storefront API, Back Office, data import with demo data. Default to the project's existing surfaces (an API the project does not expose is not installed); -- that the **storefront placement** (Step 6b) comes after the backend steps as a suggestion list: the guide registers the feature's widgets but does not place them in the project's Twig templates, and nothing is placed unless the developer picks it then; -- which guide will be followed and its version line; -- the **environment**: when the preflight found the stack down or not bootstrapped, propose the bootstrap here (the deploy file, `docker/sdk boot ` plus `docker/sdk start` or `docker/sdk up`, port clashes with other running stacks; see the reference) and list any pre-existing environment issue it found; never `reset`; -- the branch: work on a dedicated branch (`ai-feature/` from `HEAD`, as `spryker-customization` does with `ai-customize/`) when `git status` is clean; if it is not, ask first. - -No `composer require` and no edit before this answer. - -## Step 3 - Fetch the install guide - -The Install section gives a docs URL (usually `/latest/` or a versioned path). Read the page by: - -- the `spryker-docs-research` skill, or -- `searchAlgoliaDocumentation` and the markdown at its `github_api_url` (the docs markdown lives in `github.com/spryker/spryker-docs`), or -- the web fetch tool on the page itself. - -**Version match.** When the URL is `/latest/` and the project's release line (from `composer.json` and the installed `spryker/*` versions) is older than the docs' current one, prefer the guide for the project's line if the docs site offers it; if you cannot tell which line a step belongs to, say so and ask rather than apply a step that may not exist in the project's modules. Treat the guide as the source of truth for **steps and order**, but docs are not trusted for exact identifier spellings: confirm class, constant and transfer names against the installed packages in `vendor/` (read-only) or `getSprykerModuleMap` before writing them. Check every plugin the guide names for `@deprecated` in its vendor class: use the named replacement, skip a deprecated plugin that has none, and record each case in the checklist. - -**No guide, or a guide that assumes a base feature that has none** (the marketplace guide assumes the base wishlist wiring; the card says "no install guide found" for the base feature): take the project-layer wiring from a reference project that ships the feature, the suite or the demo shop of the same release line, read through `gh api` or raw GitHub, or from a project on disk. Verify every class against `vendor/`, and record the reference source in the checklist. - -Turn the guide into a **checklist** of its steps (install, integrate, verify), grouped as the guide groups them. This checklist is the run's state: every step ends `done` or `skipped (reason)`. - -## Step 4 - `composer require` - -Run inside the project's PHP environment. On Docker SDK that is `docker/sdk cli composer require :`, the form `spryker-refresher` and `spryker-upgrade` use (wrap in `script -q /dev/null` where the command needs a TTY). Without Docker SDK, run `composer require` in the project root. - -- Pass an explicit `^x.y.z` constraint for every package, matching the project style: for a bare module package use the version the resolver would pick, found with `composer require --dry-run` first and then required as `^`; a bare `composer require ` writes a looser `^x.y` than the project's entries. -- Require the feature metapackage agreed in Step 2, with the agreed constraint. The card's `composerRequire` names the feature only when the card has exactly one; for a card with several features (alternatives such as `wishlist` and `marketplace-wishlist`) it names the missing module packages, so take the feature the user chose from the Install section instead. Require bare module packages only when the capability has no feature metapackage. -- Add the API packages only if the user chose that integration. -- On a resolution conflict, do not loosen constraints or add `--ignore-platform-reqs` on your own. Report the conflict (which package, which constraint) and stop; the cause is often a project behind the feature's release line, which is `spryker-upgrade` territory. -- Never edit `vendor/`; never hand-edit `composer.lock`. - -## Step 5 - Apply the guide's integration steps - -Apply the guide's steps in order, **in the project layer only**: under the project's namespace directories in `src/` (find them via `composer.json` `autoload.psr-4`; when there is a custom namespace ahead of `Pyz` in `KernelConstants::PROJECT_NAMESPACES`, new and overriding code goes there, extending the `Pyz` counterpart when one exists), plus `config/` and `data/import/`. Never `vendor/`, never `src/Generated/`, never `src/Orm/`. The `spryker-customization` project-layer rules apply; its `rules/` files (plugins, dependency providers, transfers) define the conventions. - -Typical step kinds, and the care each needs: - -| Guide step | Care | -|---|---| -| Config (`config/Shared/config_default.php`, module config, env overrides) | Read the existing file first; add keys in the surrounding style; no real secrets. | -| Dependency-provider plugin wiring | **Read the current plugin stack first** and insert at the guide's position; respect the existing order. Follow the project's own pattern for stack overrides (`parent::` plus a positional insert anchored on a named neighbour class, never a numeric index). Skip a plugin the project has already registered. | -| Transfer definitions (`*.transfer.xml`) | Project layer; check fields with `getTransferStructureByName`. | -| Propel schema (`*.schema.xml`) | Project layer; follow `propel-schema` conventions. | -| Navigation (`navigation.xml`), routes, route providers, module configs | Add the entry; do not reorder existing ones. | -| Widget plugins (`ShopApplicationDependencyProvider::getGlobalWidgets()`) | Register the widgets the guide lists. Registration alone renders nothing in templates the project overrides; placing them is Step 6b. | -| Glossary and translations | Add the keys for every configured locale. Guides often have no glossary step, so run `php /scripts/glossary-key-check.php --module=` from the project root (`` is the path reported as `Base directory for this skill:`): it lists the `'key' \| trans` keys of those modules that no `data/import/**/glossary*.csv` row defines, per locale. Propose rows from the reference project or the suite glossary, append them to the project's glossary file, and report keys with no source; a missing key renders raw on the page. | -| Data import (import config, `data/import/**`, demo data) | Set up the importer wiring when the guide requires it. Load **demo data only if the user asked**; otherwise skip and record "demo data skipped". Use `project-data` and the `data-import` skill for CSV and importer work. | -| Storefront API resources (`resources/api/storefront/*.resource.yml` in a module) | When the module ships them and the project already generates API Platform resources (`src/Generated/Api/Storefront` exists; `config/GlueStorefront` alone is no proof), the guide's `GlueApplicationDependencyProvider` route and relationship plugin steps do not apply: mark them `skipped (API Platform resource)`, keep the attribute-mapper and strategy plugin stacks (the resource mapper reads them through `#[Plugins(dependencyProviderMethod: ...)]`), and rely on code generation in Step 6. | -| Publish and sync, queues, event wiring | Wire as the guide says; queue-worker restarts are project specific, report them. | -| New service in `deploy.dev.yml` (search, key-value, broker) | Do not change the deploy file silently; this usually needs a `docker/sdk up`, which is a rebuild. Ask the user. Never run `docker/sdk reset` or `clean-data`. | - -Where a step conflicts with something the project already built (a plugin already registered, a field already present), stop on that step, show the conflict and let the user choose; do not overwrite. Where a step is for an integration the user declined, mark it `skipped (not requested)`. - -## Step 6 - Codegen and setup - -Invoke `spryker-refresher` with the list of files you changed; it owns the file-pattern to command mapping (`transfer:generate`, `propel:install`, `cache:class-resolver:build`, router cache warm-up, `navigation:build-cache`, glossary and data import, search setup, cache clears, frontend builds). Resolve the Glue applications the project really has before any `glue` command: list `public/Glue*/index.php` and cross-check the `entry-point: Glue*` values in the active deploy file, then run `vendor/bin/glue ` for `public/Glue` and `GLUE_APPLICATION=GLUE_BACKEND vendor/bin/glue ` for `public/GlueBackend`; use `GLUE_APPLICATION=GLUE_STOREFRONT` only when `public/GlueStorefront/index.php` exists and an entry point uses it. A recipe step (`config/install/docker.yml`) for an application that does not exist is `skipped (no such Glue application)`, not run. Do not improvise the command chain, and run Yves/Zed frontend builds only when the guide touches the frontend. Then run the **feature-specific setup commands the guide lists** that the refresher mapping does not cover (for example a search setup or a feature importer), verifying each command exists first with `docker/sdk console list`. - -A new `*.schema.xml` triggers `propel:install`, which changes the database schema: say so before it runs. If a command fails, show its output and diagnose before retrying (`spryker-issue-diagnoser`); do not skip a failing guide step to look green. - -## Step 6b - Optional: storefront placement (suggested, not applied by default) - -Only when the feature has Yves code (a card module under `vendor/spryker-shop/`, or a package with a `src/*/Yves/` directory) and the project has a storefront. Install guides stop at registering widgets; the vendor templates place them, and every vendor template the project overrides has lost those calls. - -1. Run the `yves-twig-integration` scanner scoped to the feature's Yves packages (`--package=,...`). It lists, per widget and component, whether a template the project renders already uses it, and where the vendor places it in templates the project replaced. -2. Present its suggestion table and ask which placements to apply (all, some, none). `not_registered` items mean a widget from the guide is still unregistered: finish that in Step 5 first. -3. On a pick, invoke the `yves-twig-integration` skill (`/yves-twig-integration`, or `/spryker-ai-dev-sdk:yves-twig-integration` on a plugin install) with the picked items; it places each one in the project's design and verifies it. On "none", record the suggestions as a follow-up and continue. - -Do not apply a placement in an unattended run; the table goes into the report. - -## Step 7 - Verify - -- **Authentication precondition first** for any check that needs a login: one fixture customer login through Glue (`POST /access-tokens`) and one through Yves. Test credentials come from `tests/cypress-tests/cypress/fixtures/**` (customer emails, `defaultPassword`) and the project's seed and fixture files; never ask for or print real credentials. When the login fails, report the logged-in checks as **BLOCKED (environment)** and hand over to `spryker-issue-diagnoser` (a stack problem that predates the install, such as no OAuth token ever issued), instead of failing the feature checks. -- Run the guide's own **verify** steps (the pages, console commands or API calls it names) and record the evidence. -- Use `boot-and-verify` for standalone verification of what the feature touches (storefront, Back Office, search, queues); this is a running stack, not a first boot. -- Hand per-behaviour checks to the `spryker-verifier` agent with the guide's verification steps as acceptance criteria; it only asserts and reports. Weigh a FAIL as a hypothesis before acting (browser reasons look like feature failures). -- Confirm the feature's modules are now reported as installed (`getSprykerCapability(slug)` should show `installed`, or `partially_installed` when you skipped API packages on purpose). - -## Step 8 - Report - -Leave the changes **unstaged for review**; never commit or push without the user's explicit confirmation, and stage only the files you changed, by path. - -```markdown -## Feature install report: - -- Installed: -- Guide followed: -- Checklist: - - [done] - - - [skipped - ] -- Storefront placement: -- Verification: -- Follow-ups: -- Files changed: -``` - -## What you do not do - -- Do not change anything (composer, files) before the Step 2 confirmation. -- Do not edit `vendor/`, `src/Generated/`, `src/Orm/` or `composer.lock` by hand. -- Do not loosen version constraints or ignore platform requirements to make a `composer require` pass. -- Do not install an optional integration (Glue API, Storefront API, demo data) the user did not choose. -- Do not reorder or overwrite existing plugin stacks, navigation or config; insert at the guide's position. -- Do not run `docker/sdk reset`, `clean-data` or any environment-destructive command; report when one is needed. -- Do not mark a guide step done without evidence, and do not drop a failing step silently. -- Do not commit or push without confirmation. +| `searchSprykerCapabilities`, `getSprykerCapability` | Resolve the feature; the card's Install section, modules and `installStatus` (from `composer.lock`). | +| `searchAlgoliaDocumentation` | Find install guide pages; `github_api_url` is the markdown. | +| `getSprykerModules`, `getSprykerModuleMap` | What the project has now; exact plugin interfaces. | +| `getTransferStructureByName` | Transfer fields before a transfer XML edit. | + +If the capability tools are not connected, start the MCP server and ask for a reload as +`find-existing-capability` describes. After two failed reconnects, take the feature name and guide +URL from the developer, or fetch `https://spryker-capability-map.s3.eu-central-1.amazonaws.com/.md` +and compare its packages with `composer.lock` by hand; the install status is then unverified. + +## Phase 0 — Preflight and baselines + +1. Run the checks in [references/environment-preflight.md](references/environment-preflight.md). A + stack that is down, a container that does not see the host files, a `vendor/` behind + `composer.lock` or a broken frontend dependency tree is a **pre-existing environment issue**, not + a feature failure. A plan-only run (Phases 1–4) needs no stack. +2. Create `$STATE/state.md` with the phase table (Phase, Status, Evidence). Copy `composer.lock` to + `$STATE/composer.lock.before`. +3. Before the install (Phase 5), record the baselines. The `$UP` scripts write into the directory + that `SPRYKER_UPGRADE_STATE_DIR` names: + ```bash + SPRYKER_UPGRADE_STATE_DIR=$STATE/baseline php $UP/check-plugin-usage.php || true + SPRYKER_UPGRADE_STATE_DIR=$STATE/baseline php $UP/check-config-constants.php || true + SPRYKER_UPGRADE_STATE_DIR=$STATE/baseline php $UP/check-dead-overrides.php snapshot + SPRYKER_UPGRADE_STATE_DIR=$STATE/baseline php $UP/twig-shadow-map.php snapshot + script -q /dev/null docker/sdk cli php -d memory_limit=2048M vendor/bin/phpstan analyze -c phpstan.neon src/ -l 6 2>&1 | tee $STATE/baseline/phpstan.txt + script -q /dev/null docker/sdk cli vendor/bin/console code:sniff:style 2>&1 | tee $STATE/baseline/sniff.txt + script -q /dev/null docker/sdk testing codecept run --no-exit 2>&1 | tee $STATE/baseline/codecept.txt + SPRYKER_UPGRADE_STATE_DIR=$STATE/baseline SPRYKER_BACKOFFICE_USER= SPRYKER_BACKOFFICE_PASSWORD= php $UP/backoffice-smoke.php --url --baseline + ``` + For the storage and search counts, copy `$UP/storage-search-counts.php` into `$STATE/baseline/` + and run it in the container with `--snapshot before`. A red baseline is not this run's damage: + record it in `state.md`. + +## Phase 1 — Resolve the feature and its release + +1. **The feature.** From a card: `getSprykerCapability(slug)`. From a name: `searchSprykerCapabilities` + with the name and its synonyms, then open the best card. Its Install section lists the + `spryker-feature/` package and guide URL, `Requires features:`, the Glue API guide and the + Storefront API packages. A card with several features offers alternatives: take the one that + matches the project. +2. **What is there.** `installed` → nothing to install: hand back to `find-existing-capability` + (extend it). `partially_installed` → install only `missingPackages`. +3. **Required features first.** Check each one against `composer.lock`. Each one that is missing is + its own run, before this one; offer it. +4. **The project type** in `state.md`: B2B or B2C, with or without marketplace. Phase 4 uses it. +5. **The install release.** Read the project's release (`spryker-feature/spryker-core` in + `composer.lock`) and the releases of the feature (`composer show -a spryker-feature/`): + - The feature exists at the project's release → install at that release. + - The feature first exists in a later release → dry-run in the container: + `composer require spryker-feature/:^ -W --dry-run`. A conflict that names + a `spryker/*` module and a minimum version → add `spryker/:^` to the same + `require` and dry-run again, until it resolves. Each major bump among the moved modules needs + its migration guide, as `spryker-upgrade` Lane 0 describes. + - Stop and offer `spryker-upgrade` (`/spryker-upgrade`, or `/spryker-ai-dev-sdk:spryker-upgrade` + on a plugin install) when another `spryker-feature/*` package must move, a conflict names a + package that is not a `spryker/*` module (a root pin of a Symfony or other third-party + package), the same package comes back in a later round, or nothing resolves. Name the + blocking packages from the composer output. + Record the install release and the added modules in `state.md`. + +## Phase 2 — Collect the sources + +Read [references/sources.md](references/sources.md) on entry. Put everything in `$STATE/sources/`: +the install guide (the docs page and the include it wraps, plus `_config.yml`), every prerequisite +and linked guide, the `spryker-feature/` `composer.json` at the install release, the reference +demo shop at that release tag, and its history as a bare clone. Record in `state.md` each source that +was not found. + +## Phase 3 — Checklist and confirmation (developer gate #1) + +1. Parse the guide, then append each prerequisite and linked guide: + ```bash + php $FI/parse-integration-guide.php $STATE/sources/docs/ --docs-root $STATE/sources/docs --release --out $STATE/checklist.json + php $FI/parse-integration-guide.php --docs-root $STATE/sources/docs --out $STATE/checklist.json --append + ``` + Exit 1: open each `unknown` row at its `lines` and set its `kind` by hand. +2. `php $FI/check-feature-installed.php $STATE/checklist.json --mark` — modules already installed, + and wiring rows already present (`already-present`). +3. Give every data row its `data_class` ([references/data-classes.md](references/data-classes.md)). +4. **Present one confirmation block and wait for the answer** (your harness's question tool, else + in chat). It carries: + - the feature, the packages `composer require` adds, the install release, the modules Phase 1 + added, and required features to install first; + - the version constraint in the project's style (`^` for features, `^x.y.z` for + modules); + - the optional blocks, one choice each: every `optional-scenario:*` tag, the Glue, Storefront and + Backend APIs (default: only the APIs the project already exposes), and demo data; + - that storefront placement comes after the backend steps, as a suggestion list; + - the environment: a bootstrap when the preflight found the stack down; any pre-existing issue; + - the branch: `ai-feature/` from `HEAD` when `git status` is clean; else ask first; + - commits: one per guide section (recommended), or none until the report. + + Set `skip:` on every row of a block the developer did not choose. + +## Phase 4 — Reconcile + +Read [references/reconcile.md](references/reconcile.md) on entry. + +1. Add the files the reference changed for the feature that no row names: + ```bash + php $FI/find-feature-change.php --repo $STATE/sources/reference-history.git --package spryker-feature/ --checklist $STATE/checklist.json --add-rows + ``` + Exit 1: record that no reference change was found; the guide rows are then the only source. +2. For each row without a decision, compare it with the reference demo shop at the same place. Set + `reference` (`same`, `differs`, `absent`, with the path) and `decision` (`apply-guide`, + `apply-reference`, `merge`, `already-present`, `skip:`) by the reconcile rules. +3. Gate: `php $FI/check-checklist.php $STATE/checklist.json --phase decide` exits 0. + +## Phase 5 — Install + +1. Run the `composer` rows in the container, with the install release and the modules Phase 1 + added. On a conflict, report it and stop. Then: + ```bash + php $FI/check-lock-diff.php --before $STATE/composer.lock.before --checklist $STATE/checklist.json + ``` + Exit 1 lists packages that moved outside the feature's dependency tree (a module Phase 1 added is + expected), or a dev constraint. The developer accepts each move, or you narrow the update. +2. When any module moved, check the project's customisations against it: + ```bash + SPRYKER_UPGRADE_STATE_DIR=$STATE/baseline php $UP/check-typed-members.php + SPRYKER_UPGRADE_STATE_DIR=$STATE/baseline php $UP/check-dead-overrides.php verify + SPRYKER_UPGRADE_STATE_DIR=$STATE/baseline php $UP/twig-shadow-map.php diff + ``` + A finding is damage from the module move: resolve it as `spryker-upgrade` Lanes 1 and 2 + describe, before the first guide section. +3. Work through the guide sections in guide order; prerequisite guides first. Per section, by + [references/apply-steps.md](references/apply-steps.md): + - apply the section's rows by their decision; set `status: done` or `failed` on each; + - hand the section's data rows to `project-data` (the hand-off format in + [references/data-classes.md](references/data-classes.md)); + - schema rows: run `propel:diff` and show the migration before `propel:migrate`; the guide's + `propel:install` is for a fresh local database only; + - codegen and setup: `spryker-refresher` with the changed files, then the section's own setup + commands; + - re-run `check-plugin-usage.php` and `check-config-constants.php`; a new finding blocks the + next section; + - commit the section, if the developer chose commits. +4. Gate: `php $FI/check-feature-installed.php $STATE/checklist.json --wiring` exits 0. + +## Phase 5b — Storefront placement (optional, suggested) + +Only when the feature has Yves code and the project has a storefront. Install guides register +widgets; every vendor template the project overrides has lost the vendor's calls to them. + +1. `php $YI/yves-integration-scan.php --package=,...` for the feature's Yves + packages. +2. Present its suggestion table; ask which placements to apply (all, some, none). A + `not_registered` item is an unfinished `widget` row: finish it in Phase 5 first. +3. On a pick, invoke `yves-twig-integration` (`/yves-twig-integration`, or + `/spryker-ai-dev-sdk:yves-twig-integration`) with the picked items. On "none", record the table as + a follow-up. In an unattended run, apply nothing: the table goes into the report. + +## Phase 6 — Verify (developer gate #2) + +1. **Authentication first** for every check that needs a login: one fixture customer login through + Glue (`POST /access-tokens`) and one through Yves. Test credentials come from + `tests/cypress-tests/cypress/fixtures/**` and the project's seed files; never ask for or print + real credentials. A failed login makes the logged-in checks **BLOCKED (environment)**: hand it to + `spryker-issue-diagnoser`. +2. Give every `verification` row that is not skipped to the `spryker-verifier` agent as one + acceptance criterion, in the guide's words. Record `verdict` PASS, FAIL or BLOCKED with the + evidence path. Weigh a FAIL as a hypothesis before acting: browser problems look like feature + failures. +3. Run PHPStan, the sniffer, the tests, the Back Office crawl and the storage and search counts + (`--snapshot after`, then `--compare before after`) again, each against its baseline. A new + failure is this run's damage. +4. `getSprykerCapability(slug)` shows `installed` (or `partially_installed` for API packages skipped + on purpose). +5. A FAIL goes to `spryker-issue-diagnoser`; fix its root cause as a checklist row. A FAIL or + BLOCKED that stays goes to the developer: fix it, or accept it (`verdict: ACCEPTED` with a + `verdict_note`: who and why). + +## Phase 7 — Release steps + +Do [references/release-steps.md](references/release-steps.md) exactly, in its order: list the +candidates with `php $FI/diff-release-steps.php $STATE/checklist.json`, write each uncovered one into +`$STATE/release-steps.md`, and prove the log with the comparison procedure, or record why it was not +proven. + +## Phase 8 — Report + +1. Gate: `php $FI/check-checklist.php $STATE/checklist.json --phase report` exits 0. +2. Write `$STATE/report.md` in the shape that + [references/release-steps.md](references/release-steps.md) § The report gives: installed, + differences from the guide, data, storefront placement, verification, release steps, not verified. +3. Leave uncommitted changes unstaged for review. Stage only the files you changed, by path, and + commit or push only on the developer's yes. + +## Hard rules + +- All state lives in `$STATE`. Never commit `$STATE/sources/` or the baselines. +- Offline, or a source not found → say so, record it in `state.md`, and stop for that source. Never + write a step from memory. +- A step is applied once. A row marked `already-present` is checked, not applied again. +- Never mark a row done without evidence, and never drop a failing row silently. +- Never claim "verified" for a row whose verdict is not PASS; an accepted row is reported as + accepted, with its note. diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/references/apply-steps.md b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/references/apply-steps.md new file mode 100644 index 0000000..0deddb9 --- /dev/null +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/references/apply-steps.md @@ -0,0 +1,55 @@ +# Applying checklist rows + +Apply each row by its decision, **in the project layer only**: the project's namespace directories +in `src/` (from `composer.json` `autoload.psr-4`; when a custom namespace comes before `Pyz` in +`KernelConstants::PROJECT_NAMESPACES`, new and overriding code goes there, and extends the `Pyz` +counterpart when one exists), plus `config/`, `data/import/` and the deploy files. Never `vendor/`, +`src/Generated/` or `src/Orm/`. The `spryker-customization` project-layer rules apply; its `rules/` +files (plugins, dependency providers, transfers) define the conventions. + +## Per row kind + +| Kind | How | +|---|---| +| `config` | Read the existing file first. Add the keys in the surrounding style; merge into an existing value (reconcile rule 2). No real secrets. | +| `plugin`, `route`, `widget`, `queue` | **Read the current plugin stack first.** Insert at the position the decision names (the reference order, else the guide's). Follow the project's own pattern for stack overrides: `parent::` plus a positional insert anchored on a named neighbour class, never a numeric index. A plugin the project already registers is `already-present`. | +| `plugin` with a `@deprecated` vendor class | Check every plugin class in `vendor/` for `@deprecated`. Use the named replacement; skip a deprecated plugin that has none. Record either case in the row's `note`. | +| `widget` | Register the widgets in `ShopApplicationDependencyProvider::getGlobalWidgets()`. Registration alone renders nothing in templates the project overrides: placing them is the storefront step. | +| `transfer` | Project layer; check fields with `getTransferStructureByName`. | +| `schema`, `event` | Project layer; follow the `propel-schema` conventions. | +| `navigation`, `route` | Add the entry; do not reorder existing ones. | +| `glossary` | Add the keys for every configured locale (through the `project-data` hand-off). Guides often have no glossary step, so also run `php $FI/glossary-key-check.php --module=`: it lists the `'key' \| trans` keys of those modules that no `data/import/**/glossary*.csv` row defines, per locale. Add a `glossary` row with `data_class: feature-data` for each missing key; a missing key renders raw on the page. | +| `data-row`, `data-import` | Through the `project-data` hand-off ([data-classes.md](data-classes.md)). The importer plugin and console command registration stays here. | +| `deploy` | A new service or environment variable in a deploy file usually needs `docker/sdk up`, which is a rebuild: ask the developer. Never `docker/sdk reset` or `clean-data`. | +| `console` | Through `spryker-refresher` and the guide's own setup commands (below). | + +When a row conflicts with something the project already built (a plugin already registered, a field +already present, a value the project set differently), stop on that row, show the conflict and let +the developer choose. Do not overwrite. + +## Storefront API resources (API Platform) + +When a module ships `resources/api/storefront/*.resource.yml` and the project generates API Platform +resources (`src/Generated/Api/Storefront` exists; `config/GlueStorefront` alone is no proof), the +guide's `GlueApplicationDependencyProvider` route and relationship plugin rows do not apply: set +`skip:API Platform resource`. Keep the attribute-mapper and strategy plugin stacks: the resource +mapper reads them through `#[Plugins(dependencyProviderMethod: ...)]`. Code generation creates the +resource. + +## Codegen and setup after each section + +Invoke `spryker-refresher` with the files the section changed. It owns the file-pattern to command +mapping. Then: + +- **Glue applications are resolved, not assumed.** List `public/Glue*/index.php` and cross-check + the `entry-point: Glue*` values in the active deploy file. Run `vendor/bin/glue ` for + `public/Glue` and `GLUE_APPLICATION=GLUE_BACKEND vendor/bin/glue ` for + `public/GlueBackend`. Use `GLUE_APPLICATION=GLUE_STOREFRONT` only when + `public/GlueStorefront/index.php` exists and an entry point uses it. A recipe step for an + application that does not exist is `skip:no such Glue application`. +- Run the section's other `console` rows (a search setup, a feature importer) after you check that + each command exists: `docker/sdk console list`. +- Run the Yves and Zed frontend builds only when the section touched the frontend. + +A failing command: show its output and hand it to the `spryker-issue-diagnoser` agent before a +retry. Never skip a failing row to look green. diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/references/data-classes.md b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/references/data-classes.md new file mode 100644 index 0000000..155e715 --- /dev/null +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/references/data-classes.md @@ -0,0 +1,51 @@ +# Data classes and the hand-off to project-data + +Every data row (`glossary`, `data-row`, `data-import`) gets a `data_class` before the install. The +parser sets it for translations and import configuration (`feature-data`) and for rows in a demo +data section (`demo-data`). Set the others by this test: + +| `data_class` | Test | Examples | What happens | +|---|---|---|---| +| `feature-data` | The feature fails, or shows raw glossary keys, with zero rows. | Glossary keys, permissions, ACL rules, type or status rows that have no Back Office create page, the entries in `data/import/*.yml`. | Always installed. | +| `project-content` | The feature needs at least one row, but the values are a project decision. | Service types, asset types, CMS slots for the feature. | Ask the developer for the values, or use the reference values as placeholders and list them for `curate-golive-data`. | +| `demo-data` | The feature works without the rows. | Sample assets, inquiries, orders. | Only when the developer chose demo data at gate #1. Otherwise `skip:demo data declined`. | + +When a row could be two classes, take the stricter one (`feature-data` before `project-content` +before `demo-data`) and write the reason in `note`. + +## What this skill writes, and what project-data writes + +| Part | Owner | +|---|---| +| Rows in `data/import/**` CSV files | `project-data` | +| Entries in the data import configuration (`data/import/**/*.yml`) | `project-data` | +| The importer plugin registration (`DataImportDependencyProvider`) and console commands (`ConsoleDependencyProvider`) | this skill | +| A new importer module | `data-import` skill | +| The check that the rows arrived | this skill | + +## The hand-off + +Write one file per guide section, `$STATE/data-handoff-.md`, and give it to +`project-data` (`/project-data`, or `/spryker-ai-dev-sdk:project-data` on a plugin install): + +```markdown +# Data hand-off: — + +Fixed row list. Add exactly these rows; change no other row. + +| Row | File | data_class | Rows to add | Source | Importer | +|---|---|---|---|---|---| +| R018 | data/import/common/common/glossary.csv | feature-data | keys, per project locale | guide lines – | data:import glossary | +| R041 | data/import/common/common/ssp_asset.csv | demo-data | rows | reference data/import/common/common/ssp_asset.csv | data:import:ssp-asset | + +Import config entries: . +Locales and stores: . +``` + +- `Rows to add` copies from the guide snippet or from the reference file. A `project-content` row + carries the values the developer gave, or says `placeholder` for each one. +- `project-data` writes and applies the rows with its apply ladder. Then check the result: the rows + are in the database and the feature shows them. Set the checklist rows to `done` only after that + check. +- Every `feature-data` and `project-content` row is also a release-step candidate: existing + environments do not import it on deploy ([release-steps.md](release-steps.md)). diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/references/environment-preflight.md b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/references/environment-preflight.md index ffecd21..8a2167f 100644 --- a/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/references/environment-preflight.md +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/references/environment-preflight.md @@ -1,6 +1,6 @@ # Environment preflight -Shared by `spryker-feature-install` (Step 0) and `spryker-upgrade`. Run it before the first `composer require` or `composer update`, and before any step that needs the stack (codegen, `propel:install`, imports, verification). Reading a guide or planning a checklist needs no stack: skip the preflight for a plan-only run. Everything here is read-only except the bootstrap, which the user confirms first. +Shared by `spryker-feature-install` (Phase 0) and `spryker-upgrade`. Run it before the first `composer require` or `composer update`, and before any step that needs the stack (codegen, `propel:install`, imports, verification). Reading a guide or planning a checklist needs no stack: skip the preflight for a plan-only run. Everything here is read-only except the bootstrap, which the user confirms first. Report a failure as a **pre-existing environment issue**, before the confirmation block, and not as a feature or upgrade failure. diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/references/reconcile.md b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/references/reconcile.md new file mode 100644 index 0000000..e67d214 --- /dev/null +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/references/reconcile.md @@ -0,0 +1,70 @@ +# Reconcile rules + +Compare each checklist row with the reference demo shop at the same release. Write the result into +the row: + +- `reference`: `same`, `differs` or `absent`, with the reference path — for example + `differs: src/Pyz/Zed/Checkout/CheckoutDependencyProvider.php`. +- `decision`: one value from the table below. +- `note`: the reason, when the decision is not `apply-guide`. + +| Decision | When | +|---|---| +| `apply-guide` | The reference is `same`, or the reference has no such file and the step is needed. | +| `apply-reference` | The reference differs and the reference is right for this project (rules 1 and 4). | +| `merge` | The project has the file and its own values: apply only what the feature adds (rules 2 and 3). | +| `already-present` | The project has it. `check-feature-installed.php --mark` sets it for complete wiring. | +| `skip:` | A scenario the developer did not choose, a plugin the reference does not wire and the developer declined, demo data declined. | + +## The rules + +1. **Plugin subset and order: the reference decides.** The guide lists plugins for every scenario + and every product type. Take the plugins the reference wires for the feature, in the reference's + order. A guide plugin that the reference does not wire → ask the developer, and record the answer + in `note`. + + The reference is `b2b-demo-marketplace`; the project can be another type (`state.md`). A plugin + the reference wires for a capability the project does not have — merchants, product offers, + company accounts, business units — is `skip: not in the project`. After the composer + step, `check-feature-installed.php` reports such plugins as `not in vendor/ (module not + installed)`: their module is not part of the project, so they cannot be wired. Do not add a module + to make a plugin wireable; ask the developer when the feature itself needs it. +2. **Existing config: the project decides.** Merge the feature's part into the project's value: + add the array element, add the regex alternative, add the plugin to the stack. Never replace + the value with the guide's. A `...` in a guide snippet always means merge. +3. **Example values take the project's values.** Store codes, locales, the `/en|/de` part of a URL + regex, region names and hosts in a guide snippet are examples. +4. **Files the guide does not name.** `find-feature-change.php --add-rows` adds a row with + `source: reference-only` for each file of the reference change that no row names: templates, + DependencyProviders of neighbouring modules, OMS processes, data, deploy and recipe files. Its + decision follows the same table. A guide data path is an example (`data/import/glossary.csv`): + when a `reference-only` row names the real file for the same data, decide the two rows together + and skip one of them with the reason. +5. **Integrator manifests check, never apply.** A manifest that wires a plugin no row names is a + finding: add a row, or record why it is not needed. +6. **`already-present` is checked, not applied again.** A second copy of a plugin in a stack runs it + twice. + +## Example: a guide value that replaces the project's value + +The Order Amendment guide sets the secured URL pattern to one regex: + +```php +$config[CustomerConstants::CUSTOMER_SECURED_PATTERN] = '(^(/en|/de)?/order-amendment($|/))'; +``` + +The project already protects many customer pages with that constant. A literal copy removes the +login protection from all of them. The reference adds the new path as one more alternative: + +```php +$config[CustomerConstants::CUSTOMER_SECURED_PATTERN] = '(...existing alternatives...|^(/en|/de)?/order-amendment($|/))'; +``` + +The row's decision is `merge`, the locales are the project's (rule 3), and `note` names the +constant. + +## Example: plugins the reference leaves out + +A guide's checkout plugin stack can include gift-card plugins. A marketplace reference does not wire +them, because the marketplace shop does not use gift cards. The plugins are not a step for a +marketplace project unless the developer says the project uses gift cards. diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/references/release-steps.md b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/references/release-steps.md new file mode 100644 index 0000000..0fb1104 --- /dev/null +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/references/release-steps.md @@ -0,0 +1,118 @@ +# Release steps + +**Goal:** find the commands that staging and production must run, once or on every deploy, so that +an existing environment gets the feature that the local install got. + +A guide is written for a local install. It runs imports, installers and republishes by hand. An +existing environment gets only what its deploy recipe runs, and it already has data: a new publisher +does not publish the rows that exist, and a glossary import that the deploy does not run never +happens. + +## 1. List the candidates + +```bash +php $FI/diff-release-steps.php $STATE/checklist.json +``` + +It compares the checklist with `config/install/production.yml` (all sections) and the `build` and +`build-static` sections of `config/install/docker.yml`. Check those defaults against the project: + +- Which recipe does each deploy file name (`pipeline:` in `deploy.*.yml`, the Docker SDK default + otherwise)? +- Which sections run on the image build, and which on the deploy? Read the pipeline in the + repository if it is there. + +Pass the real ones with `--recipe [:
,
]`. + +| Candidate | Comes from | +|---|---| +| A console command | A `console` row the guide runs | +| `data:import ...` | A `feature-data` or `project-content` row | +| `publish:trigger-events -r ` | A new publisher plugin: existing rows are not published | +| `queue:setup` | A new queue | +| `propel:migrate` | A schema row | +| `env ` | A config snippet that reads an environment variable | + +Write every candidate that is not `covered` into `$STATE/release-steps.md`: + +``` +| | | rows | to verify / verified / not needed | +``` + +Replace each `` placeholder with the resource name: the publisher plugin's +`getSubscribedEvents()` events, and the resource names that `publish:trigger-events --help` lists. + +## 2. Prove the steps + +**Ask the developer first:** + +- Which branch does production run? +- Which commands does the normal deployment run? Read them from the pipeline if it is in the + repository. +- May you run `docker/sdk reset` two times? It deletes the local data. + +**Then do these steps in this order.** Use the same deploy file in both parts. For a clean state, +use `docker/sdk reset`: it imports the project data, so load no other data. Wait until the queues +are empty after each reset and after the deployment. + +| # | Do | State | +|---|---|---| +| 1 | Commit all changes on the feature branch. Check out the production branch. | | +| 2 | `docker/sdk reset` | production today | +| 3 | Check out the feature branch. | | +| 4 | Build the images and assets as the pipeline does, without data: `docker/sdk up --build --assets`. Then run only the normal deployment commands. | | +| 5 | Dump the database, Redis and the search engine (documents, mappings, index settings). | **deployed** | +| 6 | `docker/sdk reset` | | +| 7 | Dump the same set as in step 5. | **fresh** | +| 8 | Compare **deployed** with **fresh**. Ignore IDs, UUIDs and timestamps. | | + +**For each difference:** + +- **A command fixes it** → find the smallest command, for example + `publish:trigger-events -r `. Do steps 1–5 again, run only that command, and compare + again. If the difference is gone, it is a release step: set the log row to `verified`. +- **No command fixes it** → write down what differs and what it changes. +- **Demo data you added on purpose** → the deployed state lacks it by design. Record it as `not + needed` for production, with that reason. + +**Never:** + +- `publish:trigger-events` without `-r`. +- A reset before the dump of the step before is saved. +- A command on the deployed state that the normal deployment does not run — ask first. +- Two Docker builds, resets or imports at the same time. +- Tests or page checks instead of the comparison. + +If the developer does not allow the resets, the log rows stay `to verify`, and the report says that +the release steps are not verified. + +## 3. Recipe or one-time job + +For each verified step, recommend one of these: + +| Recommend | When | Example | +|---|---|---| +| A recipe entry | Every deploy needs it | A new queue, an import of configuration data that changes with releases | +| A one-time job | Only the first deploy of the feature needs it | A republish of existing rows, a first import of `feature-data` | + +Environment variables: the team sets them in each environment before the deploy. Name the variable, +the file that reads it, and what it holds. + +## The report + +`$STATE/report.md`, in this order: + +1. **Feature and release** — the feature, the release, the guides used (with their source URLs). +2. **Installed** — per guide section: the rows applied, with their decision. +3. **Differences from the guide** — every row with `apply-reference`, `merge` or `skip:`, + with the reason. +4. **Data** — the hand-offs, per `data_class`, and the placeholders listed for `curate-golive-data`. +5. **Storefront placement** — the placements applied (widget, project file), declined, or the + suggestion table as a follow-up; "no Yves code" when the step did not apply. +6. **Verification** — each `verification` row: PASS, or ACCEPTED with its note. The baseline + comparison: PHPStan, sniffer, tests, Back Office crawl, storage and search counts. +7. **Release steps** — staging first, production after the check on staging passes. Per step: the + command, the reason, recipe entry or one-time job, and `verified` or `to verify`. +8. **Not verified** — every check that did not run, and what it would have found. + +Use only `verified` steps as instructions; list the `to verify` steps under their own heading. diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/references/sources.md b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/references/sources.md new file mode 100644 index 0000000..48c5e02 --- /dev/null +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/references/sources.md @@ -0,0 +1,110 @@ +# Sources + +Every source goes into `$STATE/sources/`. A source that is not found is recorded in `state.md` as +not found, with the place you looked. Never write a step from memory. + +| Source | Use | Required | +|---|---|---| +| Integration guide (docs page + include) | The steps: the checklist rows | yes | +| Prerequisite and linked guides | Steps of features the project does not have yet | yes, when the checklist names them | +| `spryker-feature/` `composer.json` at the tag | Which modules the feature package requires | yes | +| Reference demo shop at the tag | The plugin subset and order, merged config | yes | +| Reference demo shop history | The change that brought the feature in: the files the guide does not name | yes | +| Integrator manifests of the new modules | A machine-readable wiring list | no — a cross-check | + +## The integration guide + +The guide on docs.spryker.com is a page that wraps one include. The steps are in the include. + +1. Find the page: the capability card's Install section (`getSprykerCapability`) names it. Without + a card, use `searchAlgoliaDocumentation` (its `github_api_url` is the markdown), the + `spryker-docs-research` skill, or a web search for `site:docs.spryker.com install the + feature`. Integration guides are under + `docs/pbc/all//latest/.../install-and-upgrade/install-features/` (Glue API guides under + `.../install-glue-api/`). +2. Map the page URL to its source in `spryker/spryker-docs`: drop the host, replace `.html` with + `.md`. Fetch the raw file into `$STATE/sources/docs/`: + ```bash + curl -fsSL --create-dirs -o $STATE/sources/docs/.md https://raw.githubusercontent.com/spryker/spryker-docs/master/.md + ``` +3. The page has one line `{% include pbc/all/install-features/latest/.md %}`. Fetch + `_includes/` into `$STATE/sources/docs/_includes/` the same way. +4. Fetch `_config.yml` into `$STATE/sources/docs/_config.yml`. Its `release_version` is the value of + `{{page.release_tag}}` in the guide: the docs describe the latest release only. When the install + release (Phase 1) is older, run the parser with `--release `. A guide step for + a module version the install release does not have shows as `not in vendor/` in + `check-feature-installed.php` after the composer step: skip it with that reason. +5. Run the parser with `--docs-root $STATE/sources/docs`. + +A `linked-guide` row is a page the guide sends you to for steps (translations, frontend templates, +a sub-feature). Fetch it the same way, and append it to the checklist, or skip the row with a reason. + +**No guide, or a guide that assumes a base feature that has none** (a marketplace guide that assumes +the base wiring; a card that says "no install guide found"): the reference demo shop's change for the +feature is then the main source (`find-feature-change.php`, Phase 4). Without one, take the +project-layer wiring from the module code in `vendor/` and the feature's other guides. Record the +source of every row in its `note`, and say in the report that no official guide was followed. + +**Identifiers.** The docs contradict themselves on exact names. Confirm every class, constant and +transfer name against the installed packages in `vendor/` (read-only) or `getSprykerModuleMap` +before you write it. + +## The `spryker-feature/` package + +```bash +gh api repos/spryker-feature//contents/composer.json?ref= --jq .content | base64 -d > $STATE/sources/feature-composer.json +``` + +Two package types exist: + +- **Metapackage** — `composer.json` only, `"type": "metapackage"`. Its `require` is the module list. +- **Code package** — `"type": "library"`, code in the `SprykerFeature\` namespace, often with its + own `data/import/*.csv` and translations. Some of these packages also carry module-style tags + next to the release tags. Use the release tag. + +The guide's module table also lists transitive modules. The `require` block is the authority for +what the feature package itself pulls in. + +## The reference demo shop + +The reference is `spryker-shop/b2b-demo-marketplace`, for every project type. It is the demo shop +that the plugin supports; for a project of another type, reconcile rule 1 says which of its +decisions do not apply. + +```bash +git clone --depth 1 --branch https://github.com/spryker-shop/b2b-demo-marketplace.git $STATE/sources/reference +``` + +The release tag is the branch. Use the default branch's content only; demo-only extras (a separate +demo namespace or branch) are not the reference for a project. + +## The reference demo shop history + +```bash +git clone --bare https://github.com/spryker-shop/b2b-demo-marketplace.git $STATE/sources/reference-history.git +``` + +A full bare clone: a shallow or blob-filtered clone cannot search the history. +`find-feature-change.php` uses it in Phase 4. It takes the first commit that added the feature +package to `composer.json`, and the merge that brought that commit into the default branch. That +merge is the reference change: every file it changed is named by a checklist row, added as a +`reference-only` row, or listed as not a step (tests, generated code, lock files). + +No label or link convention ties a pull request to a feature, so a title search can find nothing +or the wrong pull request. A feature that came through a long-lived branch is found at its merge +into the default branch. A feature that the default branch never required has no reference +change: the guide rows are then the only source. + +## The integrator manifests (optional) + +`spryker-sdk/integrator-manifests` has one `installer-manifest.json` per module version, under +`///`: + +```bash +gh api repos/spryker-sdk/integrator-manifests/contents// --jq '.[].name' +gh api repos/spryker-sdk/integrator-manifests/contents////installer-manifest.json --jq .content | base64 -d +``` + +Use a manifest to check that the wiring is complete. Never run the integrator to apply it: it +applies every manifest of every module when the project has no `integrator.lock`, and it covers +wiring only (no data import, OMS, Twig, schema or deploy recipe). diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/check-checklist.php b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/check-checklist.php new file mode 100644 index 0000000..4f95503 --- /dev/null +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/check-checklist.php @@ -0,0 +1,120 @@ + [--phase decide|report] + * + * --phase decide after reconcile, before the install: every row has a valid decision, no row + * is `unknown`, every data row that is not skipped has a `data_class` + * --phase report (default) before the report: the decide checks, plus every row is `done` or + * `skipped`, and every verified row has a passing verdict + * + * A row's `decision` is one of apply-guide, apply-reference, merge, already-present or + * skip:. A `verification` row that is not skipped needs `verdict` PASS, or ACCEPTED with a + * `verdict_note` that names who accepted it and why. + * + * Exit codes: 0 clean; 1 problems (listed by row); 2 usage or unreadable checklist. + */ + +declare(strict_types=1); + +require_once __DIR__ . '/lib.php'; + +/** + * @return list one line per problem + */ +function cc_problems(array $checklist, string $phase): array +{ + $problems = []; + foreach ($checklist['rows'] as $row) { + $id = (string)($row['id'] ?? '?'); + $where = sprintf('%s %s %s', $id, $row['kind'] ?? '?', $row['target'] ?? ''); + $decision = $row['decision'] ?? null; + $status = $row['status'] ?? null; + + if (($row['kind'] ?? '') === 'unknown') { + $problems[] = "$where: kind is unknown — read the guide at lines " . implode('-', $row['lines'] ?? []) . ' and set the kind'; + } + if (in_array($row['kind'] ?? '', FI_DATA_KINDS, true) && !fi_is_skip($decision) && !in_array($row['data_class'] ?? null, FI_DATA_CLASSES, true)) { + $problems[] = "$where: data row without a data class — set data_class to feature-data, project-content or demo-data"; + } + if ($decision === null || $decision === '') { + $problems[] = "$where: no decision"; + } elseif (fi_is_skip($decision)) { + if (trim(substr($decision, 5)) === '') { + $problems[] = "$where: skip without a reason — write skip:"; + } + } elseif (!in_array($decision, FI_DECISIONS, true)) { + $problems[] = "$where: unknown decision '$decision'"; + } elseif (in_array($decision, ['apply-reference', 'merge'], true) && empty($row['reference'])) { + $problems[] = "$where: decision $decision without the reference it is based on"; + } + if ($status !== null && !in_array($status, FI_STATUSES, true)) { + $problems[] = "$where: unknown status '$status'"; + } + + if ($phase !== 'report') { + continue; + } + if ($status === 'failed') { + $problems[] = "$where: failed"; + } elseif (!in_array($status, ['done', 'skipped'], true)) { + $problems[] = "$where: still $status"; + } elseif ($status === 'skipped' && !fi_is_skip($decision)) { + $problems[] = "$where: skipped, but the decision is not skip:"; + } + if (($row['kind'] ?? '') === 'verification' && !fi_is_skip($decision)) { + $verdict = $row['verdict'] ?? null; + if (!in_array($verdict, FI_VERDICTS_PASSING, true)) { + $problems[] = "$where: verdict " . ($verdict ?? 'missing') . ' — a verification row needs PASS, or ACCEPTED with a verdict_note'; + } elseif ($verdict === 'ACCEPTED' && trim((string)($row['verdict_note'] ?? '')) === '') { + $problems[] = "$where: ACCEPTED without a verdict_note"; + } + } + } + + return $problems; +} + +function cc_main(array $argv): int +{ + $path = null; + $phase = 'report'; + for ($i = 1; $i < count($argv); $i++) { + if ($argv[$i] === '--phase') { + $phase = (string)($argv[++$i] ?? ''); + } else { + $path = $argv[$i]; + } + } + if ($path === null || !in_array($phase, ['decide', 'report'], true)) { + fwrite(STDERR, "usage: php check-checklist.php [--phase decide|report]\n"); + + return 2; + } + $checklist = fi_load_checklist($path); + if ($checklist === null) { + fwrite(STDERR, "$path is not a readable checklist\n"); + + return 2; + } + $problems = cc_problems($checklist, $phase); + if ($problems === []) { + fwrite(STDOUT, sprintf("OK: %d rows, phase %s.\n", count($checklist['rows']), $phase)); + + return 0; + } + fwrite(STDOUT, sprintf("%d problem(s), phase %s:\n", count($problems), $phase)); + foreach ($problems as $problem) { + fwrite(STDOUT, " $problem\n"); + } + + return 1; +} + +if (realpath($argv[0] ?? '') === __FILE__) { + exit(cc_main($argv)); +} diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/check-feature-installed.php b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/check-feature-installed.php new file mode 100644 index 0000000..ebefeab --- /dev/null +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/check-feature-installed.php @@ -0,0 +1,232 @@ + [--mark] + * php check-feature-installed.php --wiring + * + * (default) modules of each guide's module table: installed or missing; wiring rows: present, + * partial or absent in the project + * --mark also sets decision `already-present` on undecided wiring rows that are fully present + * --wiring gate after the install: every wiring row that is not skipped must be fully present + * + * The guide's `src/Pyz/` paths are matched against every project namespace in composer.json. A + * plugin whose class is not in `vendor/` is reported as not installed: its module is not part of + * the project, so the plugin is not a step (a marketplace plugin in a B2C project). + * + * Exit codes: 0 report (default, --mark) or all wiring present (--wiring); 1 --wiring found missing + * plugins; 2 usage or unreadable checklist. + */ + +declare(strict_types=1); + +require_once __DIR__ . '/lib.php'; + +const CFI_WIRING_KINDS = ['plugin', 'route', 'widget', 'queue']; + +/** + * @return list project namespaces, e.g. ['Pyz', 'Demo'] + */ +function cfi_project_namespaces(string $root): array +{ + $composer = json_decode((string)@file_get_contents($root . '/composer.json'), true); + $namespaces = []; + foreach ($composer['autoload']['psr-4'] ?? [] as $prefix => $dirs) { + foreach ((array)$dirs as $dir) { + if (preg_match('#^src/([A-Z]\w*)/?$#', rtrim((string)$dir, '/') . '/', $m) && !in_array($m[1], ['Generated', 'Orm'], true)) { + $namespaces[] = $m[1]; + } + } + if (preg_match('/^([A-Z]\w*)\\\\$/', (string)$prefix, $m) && is_dir($root . '/src/' . $m[1]) && !in_array($m[1], ['Generated', 'Orm'], true)) { + $namespaces[] = $m[1]; + } + } + if ($namespaces === [] && is_dir($root . '/src/Pyz')) { + $namespaces[] = 'Pyz'; + } + + return array_values(array_unique($namespaces)); +} + +/** + * @return list existing project files a guide path maps to + */ +function cfi_project_files(string $root, string $guidePath, array $namespaces): array +{ + $files = []; + foreach ($namespaces as $namespace) { + $candidate = (string)preg_replace('#^src/Pyz/#', 'src/' . $namespace . '/', $guidePath); + if (is_file($root . '/' . $candidate)) { + $files[] = $candidate; + } + } + + return array_values(array_unique($files)); +} + +/** + * @return list every DependencyProvider under the project namespaces + */ +function cfi_dependency_providers(string $root, array $namespaces): array +{ + $files = []; + foreach ($namespaces as $namespace) { + $base = $root . '/src/' . $namespace; + if (!is_dir($base)) { + continue; + } + $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($base, FilesystemIterator::SKIP_DOTS)); + foreach ($iterator as $file) { + if (str_ends_with($file->getFilename(), 'DependencyProvider.php')) { + $files[] = substr($file->getPathname(), strlen($root) + 1); + } + } + } + sort($files); + + return $files; +} + +/** + * The source wires the plugin: its short name is used, and no `use` statement imports a class of + * that name from another namespace. A deprecated class and its replacement often share the name. + */ +function cfi_mentions(string $source, string $plugin): bool +{ + $short = fi_short_name($plugin); + if (!preg_match('/\b' . preg_quote($short, '/') . '\b/', $source)) { + return false; + } + if (!str_contains($plugin, '\\') || str_contains($source, $plugin)) { + return true; + } + + return !preg_match('/^use\s+[A-Za-z0-9_\\\\]+\\\\' . preg_quote($short, '/') . '\s*;/m', $source); +} + +/** + * A vendor class is available when its file is in a package's `src/` under `vendor/`. A plugin of a + * module the project does not install (a marketplace or company-account plugin in a B2C project) + * cannot be wired. Without a `vendor/` directory nothing can be said, so every class counts as + * available. + */ +function cfi_class_available(string $root, string $class): bool +{ + if (!str_contains($class, '\\') || !is_dir($root . '/vendor')) { + return true; + } + + return glob($root . '/vendor/*/*/src/' . str_replace('\\', '/', $class) . '.php') !== []; +} + +/** + * @return array{state: string, files: list, missing: list, unavailable: list} + */ +function cfi_wiring_state(string $root, array $row, array $namespaces, array $providers): array +{ + $plugins = $row['plugins'] ?? []; + $target = (string)($row['target'] ?? ''); + $unavailable = array_values(array_filter($plugins, static fn (string $plugin): bool => !cfi_class_available($root, $plugin))); + $files = str_contains($target, '/') ? cfi_project_files($root, $target, $namespaces) : $providers; + if ($files === []) { + return ['state' => 'absent', 'files' => [], 'missing' => $plugins, 'unavailable' => $unavailable]; + } + $source = ''; + foreach ($files as $file) { + $source .= (string)file_get_contents($root . '/' . $file) . "\n"; + } + $missing = array_values(array_filter($plugins, static fn (string $plugin): bool => !cfi_mentions($source, $plugin))); + $state = match (true) { + $plugins === [] => 'file-present', + $missing === [] => 'present', + count($missing) === count($plugins) => 'absent', + default => 'partial', + }; + if (!str_contains($target, '/')) { + $files = array_values(array_filter($files, static fn (string $file): bool => cfi_mentions((string)file_get_contents($root . '/' . $file), $plugins[0] ?? ''))); + } + + return ['state' => $state, 'files' => $files, 'missing' => $missing, 'unavailable' => $unavailable]; +} + +function cfi_main(array $argv): int +{ + $path = null; + $mark = false; + $wiring = false; + for ($i = 1; $i < count($argv); $i++) { + match ($argv[$i]) { + '--mark' => $mark = true, + '--wiring' => $wiring = true, + default => $path = $argv[$i], + }; + } + $checklist = $path !== null ? fi_load_checklist($path) : null; + if ($checklist === null) { + fwrite(STDERR, "usage: php check-feature-installed.php [--mark | --wiring]\n"); + + return 2; + } + $root = fi_project_root(); + $namespaces = cfi_project_namespaces($root); + $providers = cfi_dependency_providers($root, $namespaces); + + if (!$wiring) { + foreach ($checklist['guides'] as $guide) { + $modules = $guide['modules'] ?? []; + $missing = array_filter($modules, static fn (array $m): bool => $m['directory'] === '' || !is_dir($root . '/' . trim($m['directory'], '/'))); + fwrite(STDOUT, sprintf("%s: %d of %d modules installed\n", $guide['file'], count($modules) - count($missing), count($modules))); + foreach ($missing as $module) { + fwrite(STDOUT, sprintf(" missing %-40s %s\n", $module['module'], $module['directory'])); + } + } + } + + $gaps = 0; + $marked = 0; + fwrite(STDOUT, sprintf("\nWiring rows (project namespaces: %s):\n", implode(', ', $namespaces))); + foreach ($checklist['rows'] as $index => $row) { + if (!in_array($row['kind'] ?? '', CFI_WIRING_KINDS, true)) { + continue; + } + $decision = $row['decision'] ?? null; + if ($wiring && ($decision === null || fi_is_skip($decision))) { + continue; + } + $state = cfi_wiring_state($root, $row, $namespaces, $providers); + if ($wiring && $state['state'] !== 'present' && $state['state'] !== 'file-present') { + $gaps++; + } + if ($mark && $decision === null && $state['state'] === 'present') { + $checklist['rows'][$index]['decision'] = 'already-present'; + $marked++; + } + fwrite(STDOUT, sprintf(" %-5s %-12s %s%s%s\n", $row['id'], $state['state'], $row['target'], $state['missing'] !== [] && $state['state'] === 'partial' + ? ' — missing: ' . implode(', ', array_map('fi_short_name', $state['missing'])) + : '', $state['unavailable'] !== [] + ? ' — not in vendor/ (module not installed): ' . implode(', ', array_map('fi_short_name', $state['unavailable'])) + : '')); + } + if ($mark) { + fi_save_checklist((string)$path, $checklist); + fwrite(STDOUT, "\n$marked row(s) marked already-present.\n"); + } + if ($wiring) { + fwrite(STDOUT, $gaps === 0 ? "\nOK: every decided wiring row is present.\n" : "\n$gaps decided wiring row(s) not fully present.\n"); + + return $gaps === 0 ? 0 : 1; + } + + return 0; +} + +if (realpath($argv[0] ?? '') === __FILE__) { + exit(cfi_main($argv)); +} diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/check-lock-diff.php b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/check-lock-diff.php new file mode 100644 index 0000000..61c9906 --- /dev/null +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/check-lock-diff.php @@ -0,0 +1,170 @@ + [--after composer.lock] + * [--composer composer.json] (--feature ... | --checklist ) + * + * --feature a package the install requires; repeatable + * --checklist read the packages from the composer rows that are not skipped + * + * Exit codes: 0 every move is inside the feature tree and no required package has a dev + * constraint; 1 moves outside the tree or such a dev constraint (listed); 2 usage or unreadable input. + */ + +declare(strict_types=1); + +require_once __DIR__ . '/lib.php'; + +/** + * @return array + */ +function cld_moved(array $before, array $after): array +{ + $moved = []; + foreach (array_unique(array_merge(array_keys($before), array_keys($after))) as $name) { + $old = $before[$name]['version'] ?? null; + $new = $after[$name]['version'] ?? null; + if ($old !== $new) { + $moved[$name] = ['before' => $old, 'after' => $new]; + } + } + ksort($moved); + + return $moved; +} + +/** + * @param list $roots + * + * @return array every package reachable from the roots through `require` + */ +function cld_tree(array $packages, array $roots): array +{ + $seen = []; + $queue = array_map('strtolower', $roots); + while ($queue !== []) { + $name = array_shift($queue); + if (isset($seen[$name])) { + continue; + } + $seen[$name] = true; + foreach (array_keys($packages[$name]['require'] ?? []) as $dependency) { + $dependency = strtolower($dependency); + if (isset($packages[$dependency]) && !isset($seen[$dependency])) { + $queue[] = $dependency; + } + } + } + + return $seen; +} + +/** + * @return array package => dev constraint, for Spryker packages + */ +function cld_dev_constraints(array $composerJson): array +{ + $dev = []; + foreach (['require', 'require-dev'] as $section) { + foreach ($composerJson[$section] ?? [] as $name => $constraint) { + if (preg_match('#^spryker[a-z\-]*/#', (string)$name) && preg_match('/(^|\s|\|)dev-/', (string)$constraint)) { + $dev[$name] = (string)$constraint; + } + } + } + + return $dev; +} + +/** + * @return list + */ +function cld_features_from_checklist(array $checklist): array +{ + $features = []; + foreach ($checklist['rows'] as $row) { + if (($row['kind'] ?? '') === 'composer' && !fi_is_skip($row['decision'] ?? null)) { + array_push($features, ...array_keys($row['packages'] ?? [])); + } + } + + return array_values(array_unique($features)); +} + +function cld_main(array $argv): int +{ + $root = fi_project_root(); + $options = ['before' => null, 'after' => $root . '/composer.lock', 'composer' => $root . '/composer.json', 'checklist' => null]; + $features = []; + for ($i = 1; $i < count($argv); $i++) { + $arg = $argv[$i]; + if ($arg === '--feature') { + $features[] = (string)($argv[++$i] ?? ''); + } elseif (in_array($arg, ['--before', '--after', '--composer', '--checklist'], true)) { + $options[substr($arg, 2)] = $argv[++$i] ?? null; + } else { + fwrite(STDERR, "unknown argument $arg\n"); + + return 2; + } + } + if ($options['checklist'] !== null) { + $checklist = fi_load_checklist($options['checklist']); + if ($checklist === null) { + fwrite(STDERR, "{$options['checklist']} is not a readable checklist\n"); + + return 2; + } + array_push($features, ...cld_features_from_checklist($checklist)); + } + if ($options['before'] === null || $features === [] || !is_file($options['before']) || !is_file($options['after'])) { + fwrite(STDERR, "usage: php check-lock-diff.php --before [--after composer.lock] [--composer composer.json] (--feature ... | --checklist )\n"); + + return 2; + } + + $after = fi_lock_packages($options['after']); + $moved = cld_moved(fi_lock_packages($options['before']), $after); + $tree = cld_tree($after, $features); + $outside = array_diff_key($moved, $tree); + $dev = cld_dev_constraints((array)json_decode((string)@file_get_contents($options['composer']), true)); + + fwrite(STDOUT, sprintf("%d package(s) moved; %d inside the tree of %s.\n", count($moved), count($moved) - count($outside), implode(', ', array_unique($features)))); + if ($outside !== []) { + fwrite(STDOUT, "\nMoved outside the feature tree — accept each, or narrow the update:\n"); + foreach ($outside as $name => $versions) { + fwrite(STDOUT, sprintf(" %-55s %s -> %s\n", $name, $versions['before'] ?? '(new)', $versions['after'] ?? '(removed)')); + } + } + $featureSet = array_map('strtolower', $features); + $devOnFeature = array_filter($dev, static fn (string $name): bool => in_array(strtolower($name), $featureSet, true), ARRAY_FILTER_USE_KEY); + if ($devOnFeature !== []) { + fwrite(STDOUT, "\nDev constraint on a package this install requires — set a released constraint (^):\n"); + foreach ($devOnFeature as $name => $constraint) { + fwrite(STDOUT, sprintf(" %-55s %s\n", $name, $constraint)); + } + } + $devOther = array_diff_key($dev, $devOnFeature); + if ($devOther !== []) { + fwrite(STDOUT, "\nnote: other dev constraints in composer.json (not part of this install):\n"); + foreach ($devOther as $name => $constraint) { + fwrite(STDOUT, sprintf(" %-55s %s\n", $name, $constraint)); + } + } + + return ($outside === [] && $devOnFeature === []) ? 0 : 1; +} + +if (realpath($argv[0] ?? '') === __FILE__) { + exit(cld_main($argv)); +} diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/diff-release-steps.php b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/diff-release-steps.php new file mode 100644 index 0000000..dde186e --- /dev/null +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/diff-release-steps.php @@ -0,0 +1,167 @@ + [--recipe [:
,
]]... + * + * --recipe an install recipe and, optionally, the sections of it that run on a deploy. + * Default: config/install/production.yml (all sections) and + * config/install/docker.yml:build,build-static. + * + * Candidates: console rows; imports of feature-data and project-content rows; a republish per new + * publisher plugin; queue:setup for new queues; new environment variables; propel:migrate for + * schema rows. Rows whose decision is skip: or already-present are not candidates. + * + * Exit codes: 0 every candidate is covered by a recipe; 1 candidates to prove (listed); 2 usage. + */ + +declare(strict_types=1); + +require_once __DIR__ . '/lib.php'; + +/** + * Commands that only prepare a local stack (code generation is part of the image build, which the + * recipes' build sections cover) or only read state. + */ +const DRS_LOCAL_ONLY = ['frontend:yves:build', 'frontend:zed:build', 'frontend:mp:build', 'frontend:project:install-dependencies', 'cache:empty-all', 'dev:ide-auto-completion:generate']; + +/** A local command and the command a deploy runs for the same effect. */ +const DRS_DEPLOY_EQUIVALENT = ['propel:install' => 'propel:migrate']; + +/** + * @return list command signatures a recipe runs, from `command:` lines of the chosen sections + */ +function drs_recipe_commands(string $file, ?array $sections): array +{ + if (!is_file($file)) { + return []; + } + $commands = []; + $current = null; + foreach (file($file, FILE_IGNORE_NEW_LINES) ?: [] as $line) { + if (preg_match('/^ ([A-Za-z0-9_\-]+):\s*$/', $line, $m)) { + $current = $m[1]; + continue; + } + if (preg_match("/^\s+command:\s*['\"]?(.+?)['\"]?\s*$/", $line, $m) && ($sections === null || in_array($current, $sections, true))) { + $commands[] = fi_command_signature($m[1]); + } + } + + return $commands; +} + +function drs_covered(string $signature, array $recipeCommands): bool +{ + foreach ($recipeCommands as $recipeCommand) { + if ($recipeCommand === $signature || str_starts_with($signature, $recipeCommand . ' ') || fi_command_name($recipeCommand) === $signature) { + return true; + } + } + + return false; +} + +/** + * @return list}> + */ +function drs_candidates(array $checklist): array +{ + $candidates = []; + $add = static function (string $step, string $why, string $rowId) use (&$candidates): void { + $step = DRS_DEPLOY_EQUIVALENT[$step] ?? $step; + $candidates[$step] ??= ['step' => $step, 'why' => $why, 'rows' => []]; + if (!in_array($rowId, $candidates[$step]['rows'], true)) { + $candidates[$step]['rows'][] = $rowId; + } + }; + foreach ($checklist['rows'] as $row) { + $decision = $row['decision'] ?? null; + if (fi_is_skip($decision) || $decision === 'already-present') { + continue; + } + $id = (string)$row['id']; + $kind = $row['kind'] ?? ''; + $target = (string)($row['target'] ?? ''); + if ($kind === 'console') { + $signature = fi_command_signature($target); + if (!in_array(fi_command_name($target), DRS_LOCAL_ONLY, true)) { + $add($signature, 'the guide runs it', $id); + } + } + if (in_array($kind, FI_DATA_KINDS, true) && in_array($row['data_class'] ?? null, ['feature-data', 'project-content'], true)) { + $add($kind === 'glossary' ? 'data:import glossary' : 'data:import ', ($row['data_class']) . ' rows the feature needs', $id); + } + if (in_array($kind, ['schema', 'event'], true)) { + $add('propel:migrate', 'schema change', $id); + } + if ($kind === 'queue') { + $add('queue:setup', 'new queue', $id); + } + foreach ($row['plugins'] ?? [] as $plugin) { + if (str_contains($plugin, '\\Plugin\\Publisher\\')) { + $add('publish:trigger-events -r ', 'new publisher: existing rows are not published', $id); + } + } + foreach ($row['env'] ?? [] as $variable) { + $add('env ' . $variable, 'environment variable the code reads', $id); + } + } + + return array_values($candidates); +} + +function drs_main(array $argv): int +{ + $path = null; + $recipes = []; + for ($i = 1; $i < count($argv); $i++) { + if ($argv[$i] === '--recipe') { + $recipes[] = (string)($argv[++$i] ?? ''); + } else { + $path = $argv[$i]; + } + } + $checklist = $path !== null ? fi_load_checklist($path) : null; + if ($checklist === null) { + fwrite(STDERR, "usage: php diff-release-steps.php [--recipe [:
,
]]...\n"); + + return 2; + } + $root = fi_project_root(); + if ($recipes === []) { + $recipes = ['config/install/production.yml', 'config/install/docker.yml:build,build-static']; + } + $recipeCommands = []; + foreach ($recipes as $recipe) { + [$file, $sectionList] = array_pad(explode(':', $recipe, 2), 2, null); + $file = str_starts_with((string)$file, '/') ? (string)$file : $root . '/' . $file; + if (!is_file($file)) { + fwrite(STDOUT, "note: recipe $recipe not found — its commands count as not covered\n"); + } + array_push($recipeCommands, ...drs_recipe_commands($file, $sectionList !== null ? explode(',', $sectionList) : null)); + } + + $open = 0; + fwrite(STDOUT, sprintf("| %-60s | %-9s | %-45s | %s |\n", 'step', 'recipe', 'why', 'rows')); + fwrite(STDOUT, '|' . str_repeat('-', 62) . '|' . str_repeat('-', 11) . '|' . str_repeat('-', 47) . "|------|\n"); + foreach (drs_candidates($checklist) as $candidate) { + $isEnv = str_starts_with($candidate['step'], 'env '); + $covered = !$isEnv && drs_covered($candidate['step'], $recipeCommands); + $open += $covered ? 0 : 1; + fwrite(STDOUT, sprintf("| %-60s | %-9s | %-45s | %s |\n", $candidate['step'], $covered ? 'covered' : ($isEnv ? 'set it' : 'to prove'), $candidate['why'], implode(' ', $candidate['rows']))); + } + fwrite(STDOUT, $open === 0 ? "\nOK: every candidate is covered by a recipe.\n" : "\n$open candidate(s) not covered: add each to the release-steps log and prove it.\n"); + + return $open === 0 ? 0 : 1; +} + +if (realpath($argv[0] ?? '') === __FILE__) { + exit(drs_main($argv)); +} diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/feature-install.test.php b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/feature-install.test.php new file mode 100644 index 0000000..e4d21f5 --- /dev/null +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/feature-install.test.php @@ -0,0 +1,293 @@ + ['pipe', 'w'], 2 => ['pipe', 'w']], + $pipes, + $projectDir, + array_merge(getenv(), ['SPRYKER_PROJECT_ROOT' => $projectDir]) + ); + $output = stream_get_contents($pipes[1]) . stream_get_contents($pipes[2]); + fclose($pipes[1]); + fclose($pipes[2]); + + return [proc_close($process), (string)$output]; +} + +function write_file(string $path, string $contents): void +{ + if (!is_dir(dirname($path))) { + mkdir(dirname($path), 0777, true); + } + file_put_contents($path, $contents); +} + +function temp_dir(string $name): string +{ + $dir = sys_get_temp_dir() . '/fi-test-' . $name . '-' . bin2hex(random_bytes(4)); + mkdir($dir, 0777, true); + + return $dir; +} + +function parse_fixture(string $name): array +{ + $errors = []; + + return pig_build_checklist([__DIR__ . '/fixtures/guides/' . $name . '.txt'], null, '202610.0', null, $errors); +} + +/** + * @return list> + */ +function rows_where(array $checklist, callable $filter): array +{ + return array_values(array_filter($checklist['rows'], $filter)); +} + +function count_kind(array $checklist, string $kind): int +{ + return count(rows_where($checklist, static fn (array $r): bool => $r['kind'] === $kind)); +} + +function decided_row(array $overrides): array +{ + return $overrides + ['id' => 'R001', 'kind' => 'config', 'target' => 'config/Shared/config_default.php', 'tag' => 'required', 'source' => 'guide', 'reference' => null, 'decision' => 'apply-guide', 'status' => 'done']; +} + +echo "parse-integration-guide: classic style (Order Amendment)\n"; +$oa = parse_fixture('order-amendment'); +check('no unknown rows', count_kind($oa, 'unknown') === 0); +check('composer line with a space after the colon keeps the constraint', ($oa['rows'][0]['packages']['spryker-feature/order-amendment'] ?? null) === '202610.0'); +check('every composer line is a row', count_kind($oa, 'composer') === 5); +check('the four OMS files are rows', count_kind($oa, 'oms') === 4); +check('every Verification block is a row', count_kind($oa, 'verification') === 27); +check('module table read', count($oa['guides'][0]['modules']) === 11); +check('prerequisites read with their guide link', ($oa['guides'][0]['prerequisites'][0]['url'] ?? null) !== null); +$scenarios = array_unique(array_filter(array_column($oa['rows'], 'tag'), static fn (string $t): bool => str_starts_with($t, 'optional-scenario:'))); +check('the three optional scenarios are tagged apart', count($scenarios) === 3); +check('a numbered ## step stays required', rows_where($oa, static fn (array $r): bool => $r['target'] === 'console transfer:generate')[0]['tag'] === 'required'); +check('propel:install is fresh-install-only', rows_where($oa, static fn (array $r): bool => $r['target'] === 'console propel:install')[0]['tag'] === 'fresh-install-only'); +check('glossary in a required section is feature-data', rows_where($oa, static fn (array $r): bool => $r['kind'] === 'glossary' && $r['tag'] === 'required')[0]['data_class'] === 'feature-data'); +$inferred = rows_where($oa, static fn (array $r): bool => !empty($r['inferred_target'])); +check('a block without a header gets its file from namespace and class', ($inferred[0]['target'] ?? '') === 'src/Pyz/Zed/SalesOrderAmendment/SalesOrderAmendmentConfig.php'); +$tableOnly = array_column(rows_where($oa, static fn (array $r): bool => isset($r['note']) && $r['kind'] === 'plugin'), 'target'); +check('a plugin listed in a required table but wired only in a scenario stays a row', in_array('Spryker\Zed\ProductBundle\Communication\Plugin\CartReorder\OriginalOrderBundleItemCartPreReorderPlugin', $tableOnly, true)); +check('a wired class without the Plugin suffix is matched to its table entry', !in_array('Spryker\Zed\GiftCardMailConnector\Communication\Plugin\Checkout\SendEmailToGiftCardUser', $tableOnly, true)); + +echo "parse-integration-guide: newer style (SSP Asset Management)\n"; +$ssp = parse_fixture('ssp-asset-management'); +check('no unknown rows', count_kind($ssp, 'unknown') === 0); +check('API request and response examples are not rows', count_kind($ssp, 'verification') === 9 && rows_where($ssp, static fn (array $r): bool => $r['kind'] !== 'verification' && str_contains((string)$r['target'], 'https://')) === []); +check('demo data section rows are demo-data', count(rows_where($ssp, static fn (array $r): bool => $r['tag'] === 'demo-data')) === 6); +check('a demo CSV gets data_class demo-data', rows_where($ssp, static fn (array $r): bool => $r['kind'] === 'data-row')[0]['data_class'] === 'demo-data'); +check('steps on a linked page are rows', in_array('/docs/pbc/all/self-service-portal/latest/install/ssp-glossary-data-import.html', array_column($ssp['rows'], 'target'), true)); +check('environment variables in config snippets are collected', in_array('SPRYKER_S3_SSP_ASSETS_BUCKET', $ssp['guides'][0]['env'], true)); +$sspTableOnly = array_map('fi_short_name', array_column(rows_where($ssp, static fn (array $r): bool => isset($r['note']) && $r['kind'] === 'plugin'), 'target')); +check('a plugin wired under an alias is matched to its table entry', !in_array('SearchSspAssetToCompanyBusinessUnitWritePublisherPlugin', $sspTableOnly, true)); +check('a table plugin with no wiring snippet stays a row', $sspTableOnly === ['SspItemAssetSelectorWidget']); +check('the Backend API block is an optional scenario', count(rows_where($ssp, static fn (array $r): bool => $r['tag'] === 'optional-scenario:enable-the-backend-api-endpoints')) === 3); +check('schema with the event behavior is kind event', count_kind($ssp, 'event') === 1); + +echo "parse-integration-guide: Glue API guide\n"; +$glue = parse_fixture('multiple-carts-glue-api'); +check('all rows required, none unknown', count($glue['rows']) === 8 && count_kind($glue, 'unknown') === 0); +check('module-level composer line', ($glue['rows'][0]['packages']['spryker/multi-carts-rest-api'] ?? null) === '^1.0.0'); +check('three prerequisites', count($glue['guides'][0]['prerequisites']) === 3); +check(' header names the file', rows_where($glue, static fn (array $r): bool => $r['kind'] === 'plugin')[0]['target'] === 'src/Pyz/Zed/CartsRestApi/CartsRestApiDependencyProvider.php'); + +echo "parse-integration-guide: units\n"; +check('header **path**', pig_header_path('**src/Pyz/Zed/Sales/SalesDependencyProvider.php**') === 'src/Pyz/Zed/Sales/SalesDependencyProvider.php'); +check('header with a stray > and leading slash', pig_header_path('**>/data/import/local/full_EU.yml**') === 'data/import/local/full_EU.yml'); +check('header without its closing tag', pig_header_path(' src/Pyz/Zed/Oms/OmsDependencyProvider.php') === 'src/Pyz/Zed/Oms/OmsDependencyProvider.php'); +check('src/data/import is data/import', pig_header_path('**src/data/import/glossary.csv**') === 'data/import/glossary.csv'); +check('a sentence is not a header', pig_header_path('1. Add the following configuration:') === null); +check('two packages, flags ignored', pig_composer_packages('composer require a/b: "^1.3.0" c/d:"^2.0" --update-with-dependencies') === ['a/b' => '^1.3.0', 'c/d' => '^2.0']); +check('package without a constraint', pig_composer_packages('composer require spryker/x') === ['spryker/x' => '']); +check('a header-less key,text,locale block is the glossary', pig_infer_path("a.b,Compare products,en_US\na.b,Vergleichen,de_DE", 'csv') === 'data/import/glossary.csv'); +check('a header-less block with deploy-file keys goes to every deploy file', pig_infer_path("image:\n environment:\n X: 1", 'yml') === 'deploy.*.yml' && pig_classify_path('deploy.*.yml', '') === 'deploy'); +check('an html file is frontend', pig_classify_path('public/Yves/push_notification_spa/index.html', '') === 'frontend'); +check('table cells decode HTML entities', pig_parse_table(['| NAME | VERSION |', '|---|---|', '| Mailing & Notifications | 1 |'])['rows'][0][0] === 'Mailing & Notifications'); +check('$config block goes to config_default.php', pig_infer_path("\$config[KernelConstants::X] = 1;", 'php') === 'config/Shared/config_default.php'); + +$docs = temp_dir('docs'); +write_file($docs . '/_config.yml', "release_version: \"202610.0\"\n"); +write_file($docs . '/_includes/pbc/x/install-the-x-feature.md', "## Install feature core\n\n### 1) Install the required modules\n\n```bash\ncomposer require spryker-feature/x:\"{{page.release_tag}}\" --update-with-dependencies\n```\n"); +write_file($docs . '/docs/install-the-x-feature.md', "---\ntitle: Install the X feature\ntemplate: feature-integration-guide-template\n---\n\n{% include pbc/x/install-the-x-feature.md %} \n"); +$out = $docs . '/state/checklist.json'; +[$exit, $output] = run_script('parse-integration-guide.php', [$docs . '/docs/install-the-x-feature.md', '--docs-root', $docs, '--out', $out], $docs); +$parsed = fi_load_checklist($out); +check('wrapper page resolves its include and the release from _config.yml', $exit === 0 && ($parsed['rows'][0]['packages']['spryker-feature/x'] ?? null) === '202610.0'); +[$exit] = run_script('parse-integration-guide.php', [$docs . '/docs/install-the-x-feature.md', '--out', $out], $docs); +check('an existing checklist is not overwritten without --force', $exit === 2); +[$exit, $output] = run_script('parse-integration-guide.php', [$docs . '/docs/install-the-x-feature.md', '--out', $out, '--append'], $docs); +check('--append skips a guide already in the checklist', $exit === 0 && str_contains($output, 'already in the checklist') && count(fi_load_checklist($out)['rows']) === 1); +[$exit, $output] = run_script('parse-integration-guide.php', [$docs . '/_includes/pbc/x/install-the-x-feature.md', '--out', $docs . '/state/no-release.json'], $docs); +check('an unresolved release placeholder exits 1', $exit === 1 && str_contains($output, 'not resolved')); + +echo "check-checklist\n"; +$undecided = parse_fixture('multiple-carts-glue-api'); +check('a fresh checklist fails decide: no decisions', in_array(true, array_map(static fn (string $p): bool => str_contains($p, 'no decision'), cc_problems($undecided, 'decide')), true)); +$clean = ['rows' => [decided_row([]), decided_row(['id' => 'R002', 'kind' => 'verification', 'verdict' => 'PASS'])]]; +check('a decided, done, verified checklist passes report', cc_problems($clean, 'report') === []); +check('skip without a reason fails', cc_problems(['rows' => [decided_row(['decision' => 'skip:', 'status' => 'skipped'])]], 'decide') !== []); +check('apply-reference without a reference fails', cc_problems(['rows' => [decided_row(['decision' => 'apply-reference'])]], 'decide') !== []); +check('a data row without data_class fails', cc_problems(['rows' => [decided_row(['kind' => 'data-row', 'target' => 'data/import/x.csv'])]], 'decide') !== []); +check('a skipped data row needs no data_class', cc_problems(['rows' => [decided_row(['kind' => 'data-row', 'decision' => 'skip:demo data declined', 'status' => 'skipped'])]], 'report') === []); +check('an unknown kind fails', cc_problems(['rows' => [decided_row(['kind' => 'unknown', 'lines' => [3, 9]])]], 'decide') !== []); +check('an open row passes decide but fails report', cc_problems(['rows' => [decided_row(['status' => 'open'])]], 'decide') === [] && cc_problems(['rows' => [decided_row(['status' => 'open'])]], 'report') !== []); +check('a verification row without a verdict fails report', cc_problems(['rows' => [decided_row(['kind' => 'verification'])]], 'report') !== []); +check('ACCEPTED without a verdict_note fails', cc_problems(['rows' => [decided_row(['kind' => 'verification', 'verdict' => 'ACCEPTED'])]], 'report') !== []); +check('ACCEPTED with a verdict_note passes', cc_problems(['rows' => [decided_row(['kind' => 'verification', 'verdict' => 'ACCEPTED', 'verdict_note' => 'developer: covered by the API test'])]], 'report') === []); + +echo "check-lock-diff\n"; +$lockDir = temp_dir('lock'); +$lock = static fn (array $packages): string => json_encode(['packages' => array_map(static fn (string $n, array $p): array => ['name' => $n] + $p, array_keys($packages), $packages)]); +write_file($lockDir . '/before.lock', $lock(['spryker/kernel' => ['version' => '3.70.0'], 'spryker/unrelated' => ['version' => '1.0.0']])); +write_file($lockDir . '/composer.lock', $lock([ + 'spryker-feature/x' => ['version' => '202610.0', 'require' => ['spryker/x' => '^1.0']], + 'spryker/x' => ['version' => '1.0.0', 'require' => ['spryker/kernel' => '^3.71']], + 'spryker/kernel' => ['version' => '3.71.0'], + 'spryker/unrelated' => ['version' => '1.1.0'], +])); +write_file($lockDir . '/composer.json', json_encode(['require' => ['spryker-feature/x' => '^202610.0', 'spryker-feature/y' => 'dev-master as 202610.0']])); +[$exit, $output] = run_script('check-lock-diff.php', ['--before', 'before.lock', '--feature', 'spryker-feature/x'], $lockDir); +check('a move outside the feature tree exits 1 and is named', $exit === 1 && str_contains($output, 'spryker/unrelated') && !str_contains($output, 'spryker/kernel ')); +check('a dev constraint outside the install is only a note', str_contains($output, 'note: other dev constraints') && str_contains($output, 'spryker-feature/y')); +write_file($lockDir . '/composer.json', json_encode(['require' => ['spryker-feature/x' => 'dev-master as 202610.0']])); +write_file($lockDir . '/composer.lock', $lock(['spryker-feature/x' => ['version' => 'dev-master'], 'spryker/kernel' => ['version' => '3.70.0'], 'spryker/unrelated' => ['version' => '1.0.0']])); +[$exit, $output] = run_script('check-lock-diff.php', ['--before', 'before.lock', '--feature', 'spryker-feature/x'], $lockDir); +check('a dev constraint on the required feature exits 1', $exit === 1 && str_contains($output, 'Dev constraint on a package this install requires')); +check('tree walk follows require', array_keys(cld_tree(['a/a' => ['require' => ['b/b' => '1']], 'b/b' => ['require' => ['c/c' => '1']], 'c/c' => [], 'd/d' => []], ['a/a'])) === ['a/a', 'b/b', 'c/c']); + +echo "check-feature-installed\n"; +$project = temp_dir('project'); +write_file($project . '/composer.json', json_encode(['autoload' => ['psr-4' => ['Pyz\\' => 'src/Pyz/']]])); +write_file($project . '/src/Pyz/Zed/Cart/CartDependencyProvider.php', " [['file' => 'g.md', 'modules' => [['module' => 'A', 'directory' => 'vendor/spryker/a'], ['module' => 'B', 'directory' => 'vendor/spryker/b']]]], + 'rows' => [ + decided_row(['id' => 'R001', 'kind' => 'plugin', 'target' => 'src/Pyz/Zed/Cart/CartDependencyProvider.php', 'plugins' => ['Spryker\Zed\A\APlugin', 'Spryker\Zed\B\BPlugin'], 'decision' => null]), + decided_row(['id' => 'R002', 'kind' => 'plugin', 'target' => 'src/Pyz/Zed/Cart/CartDependencyProvider.php', 'plugins' => ['Spryker\Zed\A\APlugin', 'Spryker\Zed\C\CPlugin'], 'decision' => 'apply-guide']), + decided_row(['id' => 'R003', 'kind' => 'plugin', 'target' => 'Spryker\Zed\B\BPlugin', 'plugins' => ['Spryker\Zed\B\BPlugin'], 'decision' => null]), + ], +]; +fi_save_checklist($project . '/checklist.json', $installed); +[$exit, $output] = run_script('check-feature-installed.php', ['checklist.json', '--mark'], $project); +$marked = fi_load_checklist($project . '/checklist.json'); +check('module table: installed and missing', str_contains($output, '1 of 2 modules installed') && str_contains($output, 'vendor/spryker/b')); +check('partial wiring names the missing plugin', str_contains($output, 'missing: CPlugin')); +check('--mark sets already-present on fully present undecided rows only', $marked['rows'][0]['decision'] === 'already-present' && $marked['rows'][1]['decision'] === 'apply-guide' && $marked['rows'][2]['decision'] === 'already-present'); +[$exit] = run_script('check-feature-installed.php', ['checklist.json', '--wiring'], $project); +check('--wiring exits 1 while a decided row is partial', $exit === 1); +write_file($project . '/src/Pyz/Zed/Cart/CartDependencyProvider.php', " [ + decided_row(['id' => 'R001', 'kind' => 'console', 'target' => 'console transfer:generate']), + decided_row(['id' => 'R002', 'kind' => 'console', 'target' => 'console propel:install']), + decided_row(['id' => 'R003', 'kind' => 'glossary', 'target' => 'data/import/glossary.csv', 'data_class' => 'feature-data']), + decided_row(['id' => 'R004', 'kind' => 'console', 'target' => 'console setup:init-db', 'decision' => 'skip:not needed']), + decided_row(['id' => 'R005', 'kind' => 'config', 'env' => ['SPRYKER_X_BUCKET']]), + decided_row(['id' => 'R006', 'kind' => 'plugin', 'plugins' => ['Spryker\Zed\X\Communication\Plugin\Publisher\XWritePublisherPlugin']]), + decided_row(['id' => 'R007', 'kind' => 'data-row', 'target' => 'data/import/common/x.csv', 'data_class' => 'demo-data']), +]]; +fi_save_checklist($recipeProject . '/checklist.json', $releaseChecklist); +[$exit, $output] = run_script('diff-release-steps.php', ['checklist.json'], $recipeProject); +$lineOf = static function (string $output, string $step): string { + foreach (explode("\n", $output) as $line) { + if (str_starts_with($line, '| ' . $step . ' ')) { + return $line; + } + } + + return ''; +}; +check('a command in the build section is covered', str_contains($lineOf($output, 'transfer:generate'), 'covered')); +check('propel:install is covered by the deploy propel:migrate', str_contains($lineOf($output, 'propel:migrate'), 'covered') && $lineOf($output, 'propel:install') === ''); +check('a command only in a section the deploy does not run is to prove', str_contains($lineOf($output, 'data:import glossary'), 'to prove')); +check('a skipped row is no candidate', !str_contains($output, 'setup:init-db')); +check('an environment variable is listed to set', str_contains($lineOf($output, 'env SPRYKER_X_BUCKET'), 'set it')); +check('a new publisher needs a republish', str_contains($output, 'publish:trigger-events -r ')); +check('demo-data rows are no release step', !str_contains($output, 'x.csv')); +check('uncovered candidates exit 1', $exit === 1); + +echo "find-feature-change\n"; +$repo = temp_dir('reference'); +$git = static function (string ...$args) use ($repo): string { + $command = 'git -C ' . escapeshellarg($repo) . ' -c user.name=test -c user.email=test@example.com -c commit.gpgsign=false'; + foreach ($args as $arg) { + $command .= ' ' . escapeshellarg($arg); + } + + return trim((string)shell_exec($command . ' 2>&1')); +}; +$git('init', '-q', '-b', 'master'); +write_file($repo . '/composer.json', "{\n \"require\": {}\n}\n"); +$git('add', '.'); +$git('commit', '-q', '-m', 'init'); +$git('checkout', '-q', '-b', 'feature/x'); +write_file($repo . '/composer.json', "{\n \"require\": {\n \"spryker-feature/x\": \"^202610.0\"\n }\n}\n"); +write_file($repo . '/src/Pyz/Zed/Cart/CartDependencyProvider.php', " 1, 'release' => '202610.0', 'guides' => [], 'rows' => [decided_row(['id' => 'R001', 'kind' => 'plugin', 'target' => 'src/Pyz/Zed/Cart/CartDependencyProvider.php'])]]; +fi_save_checklist($repo . '/../ref-checklist-' . basename($repo) . '.json', $refChecklist); +$refPath = $repo . '/../ref-checklist-' . basename($repo) . '.json'; +[$exit, $output] = run_script('find-feature-change.php', ['--repo', $repo, '--package', 'spryker-feature/x', '--checklist', $refPath, '--add-rows'], $repo); +$withRef = fi_load_checklist($refPath); +check('the merge of the first commit that required the package is found', $exit === 0 && str_contains($output, 'Merge pull request #12') && ($withRef['reference_change']['pr'] ?? null) === 12); +check('a changed file no row names becomes a reference-only row', array_column(rows_where($withRef, static fn (array $r): bool => $r['source'] === 'reference-only'), 'target') === ['src/Pyz/Yves/CartPage/Theme/default/views/cart/cart.twig']); +check('a reference-only row is classified and undecided', ($withRef['rows'][1]['kind'] ?? '') === 'frontend' && $withRef['rows'][1]['decision'] === null); +check('tests and composer files are not steps', str_contains($output, '2 not a step')); +[$exit] = run_script('find-feature-change.php', ['--repo', $repo, '--package', 'spryker-feature/never'], $repo); +check('a package the reference never required exits 1', $exit === 1); + +echo "\n$count checks, $failures failed\n"; +exit($failures === 0 ? 0 : 1); diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/find-feature-change.php b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/find-feature-change.php new file mode 100644 index 0000000..e879d8a --- /dev/null +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/find-feature-change.php @@ -0,0 +1,199 @@ + --package + * [--branch master] [--checklist --add-rows] + * + * --repo a full clone (a bare clone is enough): git clone --bare https://github.com/spryker-shop/b2b-demo-marketplace.git + * --add-rows adds a `reference-only` row for each changed file that no checklist row names + * + * Exit codes: 0 change found; 1 the branch never required the package, or no merge was found; + * 2 usage or git error. + */ + +declare(strict_types=1); + +require_once __DIR__ . '/lib.php'; +require_once __DIR__ . '/parse-integration-guide.php'; + +/** Files a reference change carries that are never a step for the project. */ +const FFC_NOT_A_STEP = '#^(tests/|src/Orm/|src/Generated/|composer\.(json|lock)$|package-lock\.json$|\.github/|codeception|phpstan|architecture-baseline)#'; + +/** + * @return array{0: int, 1: string} + */ +function ffc_git(string $repo, array $args): array +{ + $command = 'git -C ' . escapeshellarg($repo); + foreach ($args as $arg) { + $command .= ' ' . escapeshellarg($arg); + } + $output = []; + exec($command . ' 2>&1', $output, $exit); + + return [$exit, implode("\n", $output)]; +} + +/** + * @return array{pr: ?int, merge: string, subject: string, via: string}|null + */ +function ffc_find_merge(string $repo, string $first, string $branch): ?array +{ + [, $firstParent] = ffc_git($repo, ['rev-list', '--first-parent', $branch]); + $onBranch = array_flip(array_filter(explode("\n", $firstParent))); + $subjectOf = static fn (string $sha): string => ffc_git($repo, ['log', '-1', '--format=%s', $sha])[1]; + + if (isset($onBranch[$first])) { + $subject = $subjectOf($first); + + return ['pr' => preg_match('/\(#(\d+)\)\s*$/', $subject, $m) ? (int)$m[1] : null, 'merge' => $first, 'subject' => $subject, 'via' => 'commit on the branch']; + } + [, $merges] = ffc_git($repo, ['rev-list', '--ancestry-path', '--merges', '--reverse', $first . '..' . $branch]); + $fallback = null; + foreach (array_filter(explode("\n", $merges)) as $sha) { + $subject = $subjectOf($sha); + if (!preg_match('/^Merge pull request #(\d+)/', $subject, $m)) { + continue; + } + if (isset($onBranch[$sha])) { + return ['pr' => (int)$m[1], 'merge' => $sha, 'subject' => $subject, 'via' => 'merge into ' . $branch]; + } + $fallback ??= ['pr' => (int)$m[1], 'merge' => $sha, 'subject' => $subject, 'via' => 'first pull request after the commit; it merged into another branch']; + } + + return $fallback; +} + +/** + * @return list + */ +function ffc_changed_files(string $repo, array $merge): array +{ + $parents = array_filter(explode(' ', ffc_git($repo, ['log', '-1', '--format=%P', $merge['merge']])[1])); + $base = count($parents) > 0 ? $parents[0] : $merge['merge'] . '^'; + [, $files] = ffc_git($repo, ['diff', '--name-only', $base, $merge['merge']]); + + return array_values(array_filter(explode("\n", $files))); +} + +/** + * @return array{added: list, covered: list, not_a_step: list} + */ +function ffc_add_rows(array &$checklist, array $files, array $merge): array +{ + $named = []; + foreach ($checklist['rows'] as $row) { + $named[(string)($row['target'] ?? '')] = true; + } + $result = ['added' => [], 'covered' => [], 'not_a_step' => []]; + $next = count($checklist['rows']) + 1; + foreach ($files as $file) { + if (preg_match(FFC_NOT_A_STEP, $file)) { + $result['not_a_step'][] = $file; + continue; + } + if (isset($named[$file])) { + $result['covered'][] = $file; + continue; + } + $kind = pig_classify_path($file, ''); + $row = [ + 'id' => sprintf('R%03d', $next++), + 'guide' => null, + 'section' => 'reference change' . ($merge['pr'] !== null ? ' #' . $merge['pr'] : ''), + 'lines' => [0, 0], + 'kind' => $kind, + 'target' => $file, + 'tag' => 'required', + 'source' => 'reference-only', + 'reference' => 'changed: ' . substr($merge['merge'], 0, 10), + 'decision' => null, + 'status' => 'open', + ]; + if (in_array($kind, FI_DATA_KINDS, true)) { + $row['data_class'] = null; + } + $checklist['rows'][] = $row; + $result['added'][] = $file; + } + + return $result; +} + +function ffc_main(array $argv): int +{ + $options = ['repo' => null, 'package' => null, 'branch' => 'master', 'checklist' => null, 'add-rows' => false]; + for ($i = 1; $i < count($argv); $i++) { + $arg = $argv[$i]; + if ($arg === '--add-rows') { + $options['add-rows'] = true; + } elseif (in_array($arg, ['--repo', '--package', '--branch', '--checklist'], true)) { + $options[substr($arg, 2)] = $argv[++$i] ?? null; + } else { + fwrite(STDERR, "unknown argument $arg\n"); + + return 2; + } + } + if ($options['repo'] === null || $options['package'] === null || ($options['add-rows'] && $options['checklist'] === null)) { + fwrite(STDERR, "usage: php find-feature-change.php --repo --package [--branch master] [--checklist --add-rows]\n"); + + return 2; + } + [$exit, $first] = ffc_git($options['repo'], ['log', '--reverse', '--format=%H', '-S"' . $options['package'] . '"', $options['branch'], '--', 'composer.json']); + if ($exit !== 0) { + fwrite(STDERR, "git failed: $first\n"); + + return 2; + } + $first = strtok($first, "\n") ?: ''; + if ($first === '') { + fwrite(STDOUT, "{$options['branch']} never required {$options['package']} in composer.json.\n"); + + return 1; + } + $merge = ffc_find_merge($options['repo'], $first, $options['branch']); + if ($merge === null) { + fwrite(STDOUT, sprintf("First commit with %s: %s. No merge into %s found.\n", $options['package'], substr($first, 0, 10), $options['branch'])); + + return 1; + } + $files = ffc_changed_files($options['repo'], $merge); + fwrite(STDOUT, sprintf("%s: %s (%s), %d file(s) changed.\n", $options['package'], $merge['subject'], $merge['via'], count($files))); + + if ($options['add-rows']) { + $checklist = fi_load_checklist((string)$options['checklist']); + if ($checklist === null) { + fwrite(STDERR, "{$options['checklist']} is not a readable checklist\n"); + + return 2; + } + $result = ffc_add_rows($checklist, $files, $merge); + $checklist['reference_change'] = ['package' => $options['package'], 'pr' => $merge['pr'], 'merge' => $merge['merge'], 'via' => $merge['via']]; + fi_save_checklist((string)$options['checklist'], $checklist); + fwrite(STDOUT, sprintf(" %d named by a row already, %d not a step (tests, generated code, lock files), %d reference-only row(s) added.\n", count($result['covered']), count($result['not_a_step']), count($result['added']))); + foreach ($result['added'] as $file) { + fwrite(STDOUT, " + $file\n"); + } + } else { + foreach ($files as $file) { + fwrite(STDOUT, " $file\n"); + } + } + + return 0; +} + +if (realpath($argv[0] ?? '') === __FILE__) { + exit(ffc_main($argv)); +} diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/fixtures/guides/multiple-carts-glue-api.txt b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/fixtures/guides/multiple-carts-glue-api.txt new file mode 100644 index 0000000..80720ba --- /dev/null +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/fixtures/guides/multiple-carts-glue-api.txt @@ -0,0 +1,101 @@ +This document describes how to install the Multiple Carts Glue API. + + +## Prerequisites + +Install the required features: + +| Name | Version | INSTALLATION GUIDE | +| --- | --- | --- | +| Spryker Core | {{page.release_tag}} | [Install the Spryker Core Glue API](/docs/pbc/all/miscellaneous/latest/install-and-upgrade/install-glue-api/install-the-spryker-core-glue-api.html) | +| Multiple Carts | {{page.release_tag}} | [Install the Multiple Carts feature](/docs/pbc/all/cart-and-checkout/latest/base-shop/install-and-upgrade/install-features/install-the-multiple-carts-feature.html) | +| Cart | {{page.release_tag}} | [Install the Cart feature](/docs/pbc/all/cart-and-checkout/latest/base-shop/install-and-upgrade/install-features/install-the-cart-feature.html) | + +## 1) Install the required modules + +Install the required modules using Composer: + +```bash +composer require spryker/multi-carts-rest-api:"^1.0.0" --update-with-dependencies +``` + +{% info_block warningBox "Verification" %} + +Make sure that the following modules have been installed: + +{% endinfo_block %} + +| MODULE | EXPECTED DIRECTORY | +| --- | --- | +| `MultiCartsRestApi` | `vendor/spryker/multi-carts-rest-api` | + +## 2) Set up transfer objects + +Generate transfer changes: + +```bash +console transfer:generate +``` + +{% info_block warningBox "Verification" %} + +Make sure the following changes have been applied in transfer objects: +{% endinfo_block %} + +| Transfer | Type | Event | Path | +| --- | --- | --- | --- | +| `RestCartsAttributesTransfer:name` | property | added | `src/Generated/Shared/Transfer/RestCartsAttributesTransfer` | +| `RestCartsAttributesTransfer:isDefault` | property | added | `src/Generated/Shared/Transfer/RestCartsAttributesTransfer` | + +## 3) Enable resources and relationships + +On a project level, install the following plugins: + +| Plugin | Specification | Prerequisites | Namespace | +| --- | --- | --- | --- | +| `QuoteCreatorPlugin` | Creates a quote for a customer. | None | `Spryker\Zed\PersistentCart\Communication\Plugin\CartsRestApi` | + +
+src/Pyz/Zed/CartsRestApi/CartsRestApiDependencyProvider.php + +```php + + +{% info_block warningBox "Verification" %} + +Make sure that the following endpoints are available: +- `https://glue.mysprykershop.com/carts` +- `https://glue.mysprykershop.com/guest-carts` + +{% endinfo_block %} + +{% info_block warningBox "Verification" %} + +Make sure that it's possible to create more than one cart. + +{% endinfo_block %} + +{% info_block warningBox "Verification" %} + +Make sure that after creating several carts, a response from the `GET https://glue.mysprykershop.com/carts` request contains data about all created carts. +{% endinfo_block %} diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/fixtures/guides/order-amendment.txt b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/fixtures/guides/order-amendment.txt new file mode 100644 index 0000000..b7bf019 --- /dev/null +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/fixtures/guides/order-amendment.txt @@ -0,0 +1,2888 @@ +This document describes how to install the Order Amendment feature. + +## Install feature core + +Some plugins are needed only for optional features. The document provides a list of plugins for all possible integration scenarios, but you need to include only the plugins that match your setup. + +### Prerequisites + +Install the required features: + +| NAME | VERSION | INSTALLATION GUIDE | +|------------------|------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| Spryker Core | {{page.release_tag}} | [Install the Spryker Core feature](/docs/pbc/all/miscellaneous/latest/install-and-upgrade/install-features/install-the-spryker-core-feature.html) | +| Order Management | {{page.release_tag}} | [Install the Order Management feature](/docs/pbc/all/order-management-system/latest/base-shop/install-and-upgrade/install-features/install-the-order-management-feature.html) | +| Reorder | {{page.release_tag}} | [Install the Reorder feature](/docs/pbc/all/order-management-system/latest/base-shop/install-and-upgrade/install-features/install-the-reorder-feature.html) | +| Prices | {{page.release_tag}} | [Install the Prices feature](/docs/pbc/all/price-management/latest/base-shop/install-and-upgrade/install-features/install-the-prices-feature.html) | + +### 1) Install the required modules + +Install the required modules using Composer: + +```bash +composer require spryker-feature/order-amendment: "{{page.release_tag}}" --update-with-dependencies +``` + +{% info_block warningBox "Verification" %} + +Make sure that the following modules have been installed: + +| MODULE | EXPECTED DIRECTORY | +|------------------------------------------|--------------------------------------------------------------| +| SalesOrderAmendment | vendor/spryker/sales-order-amendment | +| SalesOrderAmendmentOms | vendor/spryker/sales-order-amendment-oms | +| SalesOrderAmendmentExtension | vendor/spryker/sales-order-amendment-extension | +| OrderAmendmentsRestApi | vendor/spryker/sales-order-amendments-rest-api | +| PriceProductSalesOrderAmendment | vendor/spryker/price-product-sales-order-amendment | +| PriceProductSalesOrderAmendmentExtension | vendor/spryker/price-product-sales-order-amendment-extension | + +{% endinfo_block %} + +### 2) Set up configuration + +1. Add the following configuration: + +| CONFIGURATION | SPECIFICATION | NAMESPACE | +|-----------------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------|-----------------------------| +| A regular expression, see `config/Shared/config_default.php`. | Closes access for non-logged-in users. | | +| MultiCartConfig::getQuoteFieldsAllowedForCustomerQuoteCollectionInSession() | Defines which quote fields can be saved in the quote collection of a customer's session. | Pyz\Client\MultiCart | +| QuoteConfig::getQuoteFieldsAllowedForSaving() | Enables saving order amendment-related quote fields to the database. | Pyz\Zed\Quote | +| SalesOrderAmendmentConfig::getQuoteFieldsAllowedForSaving() | Enables saving quote-related fields to the database. | Pyz\Zed\SalesOrderAmendment | + +**config/Shared/config_default.php** + +```php +> + */ + public function getQuoteFieldsAllowedForCustomerQuoteCollectionInSession(): array + { + return array_merge(parent::getQuoteFieldsAllowedForCustomerQuoteCollectionInSession(), [ + QuoteTransfer::AMENDMENT_ORDER_REFERENCE + ]); + } +} +``` + +{% info_block warningBox "Verification" %} + +Make sure that only configured fields are saved in a customer's session. + +{% endinfo_block %} + +**src/Pyz/Zed/Quote/QuoteConfig.php** + +```php + + */ + public function getQuoteFieldsAllowedForSaving() + { + return array_merge(parent::getQuoteFieldsAllowedForSaving(), [ + QuoteTransfer::AMENDMENT_ORDER_REFERENCE, + QuoteTransfer::QUOTE_PROCESS_FLOW, + QuoteTransfer::ORIGINAL_SALES_ORDER_ITEM_UNIT_PRICES, + QuoteTransfer::ORIGINAL_SALES_ORDER_ITEMS, + ]); + } +} +``` + +{% info_block warningBox "Verification" %} + +Make sure that when you edit an order, the following applies: +- `amendmentOrderReference` and `quoteProcessFlow` are added to the JSON data in the `spy_quote.quote_data` database column of the corresponding quote. +- `originalSalesOrderItems` is added to the JSON data in the `spy_quote.quote_data` database column of the corresponding quote. + +{% endinfo_block %} + +**src/Pyz/Zed/SalesOrderAmendment/SalesOrderAmendmentConfig.php** + +```php + + */ + public function getQuoteFieldsAllowedForSaving(): array + { + return array_merge(parent::getQuoteFieldsAllowedForSaving(), [ + QuoteTransfer::BUNDLE_ITEMS, + QuoteTransfer::CART_NOTE, + QuoteTransfer::EXPENSES, + QuoteTransfer::VOUCHER_DISCOUNTS, + QuoteTransfer::GIFT_CARDS, + QuoteTransfer::CART_RULE_DISCOUNTS, + QuoteTransfer::PROMOTION_ITEMS, + QuoteTransfer::IS_LOCKED, + QuoteTransfer::QUOTE_REQUEST_VERSION_REFERENCE, + QuoteTransfer::QUOTE_REQUEST_REFERENCE, + QuoteTransfer::MERCHANT_REFERENCE, + QuoteTransfer::IS_ORDER_PLACED_SUCCESSFULLY, + ]); + } +} +``` + +2. Remove the quote fields that are not relevant for your project. + +3. Configure the batch availability check facade method: + +**src/Pyz/Zed/SalesOrderAmendment/SalesOrderAmendmentConfig.php** + +```php + + config/Zed/oms/DummySubprocess/DummyOrderAmendment01.xml + +```xml + + + + + + + amendment in progress + + + + + + + grace period pending + deleted item unreserved + unreserve deleted items + + + + deleted item unreserved + grace period started + start grace period + + + + grace period started + order amendment + start-order-amendment + + + + order amendment + cancelled + finish-order-amendment + + + + order amendment + grace period started + cancel-order-amendment + + + + order amendment + grace period finished + skip-order-amendment + + + + + + + + + + + + + + +``` + +
+ +{% info_block warningBox "Verification" %} + +Verify the order amendment state machine configuration in the following step. + +{% endinfo_block %} + +2. Using the following process as an example, adjust your OMS state machine configuration according to your project's requirements. + +
config/Zed/oms/DummyPayment01.xml + +```xml + + + + + + DummyRefund + DummyReturn + DummyInvoice + DummyPicking + CreateGiftCard + WarehouseAllocation + DummyMerchantCommission + DummyOrderAmendment + + + + + cancellable + + + + cancellable + amendable + + + cancellable + + + cancellable + + + exclude from customer + + + + cancellable + + + + + + + + + + + + + + + new + grace period pending + + + + grace period started + grace period finished + skip grace period + + + + grace period finished + warehouse allocated + allocate warehouse + + + + warehouse allocated + payment pending + authorize + + + + warehouse allocated + invalid + authorize + + + + warehouse allocated + cancelled + cancel + + + + payment pending + paid + pay + + + + tax pending + tax invoice submitted + submit tax invoice + + + + payment pending + cancelled + pay + + + + payment pending + cancelled + cancel + + + + tax invoice submitted + product review requested + request product review + + + + product review requested + confirmed + confirm + + + + confirmed + waiting + skip timeout + + + + waiting + picking list generation scheduled + picking list generation schedule + + + + waiting + exported + skip picking + + + + picking finished + exported + finish picking + + + + waiting + gift card purchased + check giftcard purchase + + + + gift card shipped + delivered + complete gift card creation + + + + exported + shipped + ship + + + + shipped + delivered + stock-update + + + + delivered + closed + close + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +``` + +
+ +{% info_block warningBox "Verification" %} + +1. In the Back Office, go to **Administration > OMS**. + +2. Select **DummyPayment01** and check the following: + +- The `grace period started` state has the `amendable` tag +- The `order amendment` state exists + +{% endinfo_block %} + +## 3) Set up database schema and transfer objects + +Apply database changes and generate transfer changes: + +```bash +console transfer:generate +console propel:install +``` + +{% info_block warningBox "Verification" %} + +Make sure that the following changes have been applied in the database: + +| DATABASE ENTITY | TYPE | EVENT | +|---------------------------------|-------|---------| +| spy_sales_order_amendment | table | created | +| spy_sales_order_amendment_quote | table | created | + +Make sure the following changes have been applied in transfer objects: + +| TRANSFER | TYPE | EVENT | PATH | +|--------------------------------------------------|-------|---------|--------------------------------------------------------------------------------------------| +| SalesOrderAmendment | class | created | src/Generated/Shared/Transfer/SalesOrderAmendmentTransfer.php | +| SalesOrderAmendmentQuote | class | created | src/Generated/Shared/Transfer/SalesOrderAmendmentQuoteTransfer.php | +| SalesOrderAmendmentCriteria | class | created | src/Generated/Shared/Transfer/SalesOrderAmendmentCriteriaTransfer.php | +| SalesOrderAmendmentQuoteCriteria | class | created | src/Generated/Shared/Transfer/SalesOrderAmendmentQuoteCriteriaTransfer.php | +| SalesOrderAmendmentQuoteConditions | class | created | src/Generated/Shared/Transfer/SalesOrderAmendmentQuoteConditionsTransfer.php | +| SalesOrderAmendmentDeleteCriteria | class | created | src/Generated/Shared/Transfer/SalesOrderAmendmentDeleteCriteriaTransfer.php | +| SalesOrderAmendmentQuoteCollectionDeleteCriteria | class | created | src/Generated/Shared/Transfer/SalesOrderAmendmentQuoteCollectionDeleteCriteriaTransfer.php | +| SalesOrderAmendmentConditions | class | created | src/Generated/Shared/Transfer/SalesOrderAmendmentConditionsTransfer.php | +| SalesOrderAmendmentCollection | class | created | src/Generated/Shared/Transfer/SalesOrderAmendmentCollectionTransfer.php | +| SalesOrderAmendmentQuoteCollection | class | created | src/Generated/Shared/Transfer/SalesOrderAmendmentQuoteCollectionTransfer.php | +| SalesOrderAmendmentRequest | class | created | src/Generated/Shared/Transfer/SalesOrderAmendmentRequestTransfer.php | +| SalesOrderAmendmentQuoteCollectionRequest | class | created | src/Generated/Shared/Transfer/SalesOrderAmendmentQuoteCollectionRequestTransfer.php | +| SalesOrderAmendmentQuoteCollectionResponse | class | created | src/Generated/Shared/Transfer/SalesOrderAmendmentQuoteCollectionResponseTransfer.php | +| SalesOrderAmendmentResponse | class | created | src/Generated/Shared/Transfer/SalesOrderAmendmentResponseTransfer.php | +| SalesOrderAmendmentItemCollection | class | created | src/Generated/Shared/Transfer/SalesOrderAmendmentItemCollectionTransfer.php | +| Quote | class | updated | src/Generated/Shared/Transfer/QuoteTransfer.php | +| QuoteUpdateRequestAttributes | class | updated | src/Generated/Shared/Transfer/QuoteUpdateRequestAttributesTransfer.php | +| CartReorderRequest | class | updated | src/Generated/Shared/Transfer/CartReorderRequestTransfer.php | +| Order | class | updated | src/Generated/Shared/Transfer/OrderTransfer.php | +| Item | class | updated | src/Generated/Shared/Transfer/ItemTransfer.php | +| ErrorCollection | class | created | src/Generated/Shared/Transfer/ErrorCollectionTransfer.php | +| CartReorderResponse | class | created | src/Generated/Shared/Transfer/CartReorderResponseTransfer.php | +| CartReorder | class | created | src/Generated/Shared/Transfer/CartReorderTransfer.php | +| OrderConditions | class | created | src/Generated/Shared/Transfer/OrderConditionsTransfer.php | +| OrderCriteria | class | created | src/Generated/Shared/Transfer/OrderCriteriaTransfer.php | +| OrderCollection | class | created | src/Generated/Shared/Transfer/OrderCollectionTransfer.php | +| OrderItemFilter | class | created | src/Generated/Shared/Transfer/OrderItemFilterTransfer.php | +| CheckoutResponse | class | updated | src/Generated/Shared/Transfer/CheckoutResponseTransfer.php | +| OmsOrderItemState | class | created | src/Generated/Shared/Transfer/OmsOrderItemStateTransfer.php | +| RestCartsAttributes | class | created | src/Generated/Shared/Transfer/RestCartsAttributesTransfer.php | +| RestCartReorderRequestAttributes | class | created | src/Generated/Shared/Transfer/RestCartReorderRequestAttributesTransfer.php | +| RestOrderAmendmentsAttributes | class | created | src/Generated/Shared/Transfer/RestOrderAmendmentsAttributesTransfer.php | +| PriceProductResolveConditions | class | created | src/Generated/Shared/Transfer/PriceProductResolveConditionsTransfer.php | +| PriceProductFilter | class | updated | src/Generated/Shared/Transfer/PriceProductFilterTransfer.php | +| OriginalSalesOrderItem | class | updated | src/Generated/Shared/Transfer/OriginalSalesOrderItemTransfer.php | +| SellableItemsRequest | class | updated | src/Generated/Shared/Transfer/SellableItemsRequestTransfer.php | +| SellableItemRequest | class | updated | src/Generated/Shared/Transfer/SellableItemRequestTransfer.php | +| ProductAvailabilityCriteria | class | updated | src/Generated/Shared/Transfer/ProductAvailabilityCriteriaTransfer.php | +| SellableItemResponse | class | updated | src/Generated/Shared/Transfer/SellableItemResponseTransfer.php | +| SellableItemsResponse | class | updated | src/Generated/Shared/Transfer/SellableItemsResponseTransfer.php | + +{% endinfo_block %} + +### 4) Add translations + +1. Append glossary according to your language configuration: + +**src/data/import/glossary.csv** + +```yaml +sales_order_amendment_oms.validation.order_not_amendable,The order cannot be amended.,en_US +sales_order_amendment_oms.validation.order_not_amendable,Die Bestellung kann nicht geändert werden.,de_DE +sales_order_amendment_oms.validation.amended_order_does_not_exist,Order with reference %order_reference% could not be found.,en_US +sales_order_amendment_oms.validation.amended_order_does_not_exist,Bestellnummer %order_reference% konnte nicht gefunden werden.,de_DE +sales_order_amendment_oms.validation.amendment_order_does_not_exist,Order with reference %order_reference% could not be found.,en_US +sales_order_amendment_oms.validation.amendment_order_does_not_exist,Bestellnummer %order_reference% konnte nicht gefunden werden.,de_DE +sales_order_amendment.validation.sales_order_amendment_does_not_exist,Can not update the sales order amendment with ID %uuid%. Please check the ID.,en_US +sales_order_amendment.validation.sales_order_amendment_does_not_exist,Die Änderung der Bestellung mit der ID %uuid% kann nicht aktualisiert werden. Bitte überprüfen Sie die ID.,de_DE +sales_order_amendment.validation.order_amendment_duplicated,An amendment is already in progress for this order. Please complete or cancel it before starting a new one.,en_US +sales_order_amendment.validation.order_amendment_duplicated,"Für diese Bestellung ist bereits eine Änderung in Bearbeitung. Diese Änderung muss abgeschlossen oder storniert sein, damit Sie eine neue Änderung beginnen können.",de_DE +sales_order_amendment.validation.cart_reorder.order_reference_not_match,"Another order is currently being amended. Complete or cancel the previous amendment before making changes to this order.",en_US +sales_order_amendment.validation.cart_reorder.order_reference_not_match,"Eine andere Bestellung wird gerade geändert. Diese Änderung muss abgeschlossen oder storniert sein, bevor Sie Änderungen an dieser Bestellung vornehmen können.",de_DE +sales_order_amendment.validation.cart.cart_cant_be_amended,"Current cart cannot be amended.",en_US +sales_order_amendment.validation.cart.cart_cant_be_amended,"Der aktuelle Warenkorb kann nicht geändert werden.",de_DE +oms.state.order-amendment,Editing in Progress,en_US +oms.state.order-amendment,Bestelländerung in Bearbeitung,de_DE +sales_order_amendment_oms.validation.order_not_being_amended,This order cannot be edited because the time limit for changes has expired.,en_US +sales_order_amendment_oms.validation.order_not_being_amended,"Eine Bearbeitung dieser Bestellung ist nicht möglich, da die Änderungsfrist abgelaufen ist.",de_DE +sales_order_amendment.pre_check.cannot_change_currency,"Currency cannot be changed during order edit.",en_US +sales_order_amendment.pre_check.cannot_change_currency,"Währung kann während der Bearbeitung einer Bestellung nicht geändert werden.",de_DE +sales_order_amendment.pre_check.cannot_change_price_mode,"Price mode cannot be changed during order edit.",en_US +sales_order_amendment.pre_check.cannot_change_price_mode,"Preismodus kann während der Bearbeitung einer Bestellung nicht geändert werden.",de_DE +store.cart_reorder.error.store_mismatch,"This order was placed in a different store. This action cannot be performed.",en_US +store.cart_reorder.error.store_mismatch,"Diese Bestellung wurde in einem anderen Store getätigt. Aktion kann nicht ausgeführt werden.",de_DE +sales_order_amendment.quote_request.validation.error.forbidden,"Quote requests are unavailable during order amendment.",en_US +sales_order_amendment.quote_request.validation.error.forbidden,"Angebotsanfragen sind während der Bestelländerung nicht verfügbar.",de_DE +sales_order_amendment.order_amendment_after_rfq.validation.error.forbidden,"Amendments are not allowed for orders created from a quote.",en_US +sales_order_amendment.order_amendment_after_rfq.validation.error.forbidden,"Für Bestellungen, die aus einem Angebot erstellt wurden, sind keine Änderungen zulässig.",de_DE +``` + +2. Import data: + +```bash +console data:import glossary +``` + +{% info_block warningBox "Verification" %} + +Make sure that, in the database, the configured data has been added to the `spy_glossary` table. + +{% endinfo_block %} + +### 5) Set up behavior + +Enable the following behaviors by registering the plugins: + +| PLUGIN | SPECIFICATION | PREREQUISITES | NAMESPACE | +|------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------| +| OrderAmendmentCartReorderValidatorPlugin | Validates if quote amendment order reference matches `CartReorderTransfer.order.orderReference`. | | Spryker\Zed\SalesOrderAmendment\Communication\Plugin\CartReorder | +| OrderAmendmentQuoteProcessFlowExpanderCartPreReorderPlugin | Expands the quote process flow with the quote process flow name. | | Spryker\Zed\SalesOrderAmendment\Communication\Plugin\CartReorder | +| StartOrderAmendmentCartReorderPostCreatePlugin | Triggers the OMS event to start the order amendment process. | | Spryker\Zed\SalesOrderAmendmentOms\Communication\Plugin\CartReorder | +| IsAmendableOrderCartReorderRequestValidatorPlugin | Validates if all order items are in the order item state that has the `amendable` flag. | | Spryker\Zed\SalesOrderAmendmentOms\Communication\Plugin\CartReorder | +| AmendmentOrderReferenceCartPreReorderPlugin | Sets `CartReorderTransfer.quote.amendmentOrderReference` taken from `CartReorderRequestTransfer.orderReference`. | | Spryker\Zed\SalesOrderAmendment\Communication\Plugin\CartReorder | +| AmendmentQuoteNameCartPreReorderPlugin | Updates `CartReorderTransfer.quote.name` with a custom amendment quote name. | | Spryker\Zed\SalesOrderAmendment\Communication\Plugin\CartReorder | +| OriginalSalesOrderItemPriceCartPreReorderPlugin | Adds original sales order item unit prices to `CartReorderTransfer.quote.originalSalesOrderItemUnitPrices` with group keys as an array. | | Spryker\Zed\PriceProductSalesOrderAmendment\Communication\Plugin\CartReorder | +| OrderSalesOrderAmendmentValidatorRulePlugin | Validates if an order with provided original or amended order reference exists. | | Spryker\Zed\SalesOrderAmendmentOms\Communication\Plugin\SalesOrderAmendment | +| CartNoteSalesOrderItemCollectorPlugin | Iterates over `SalesOrderAmendmentItemCollectionTransfer.itemsToSkip` and compares an item's cart notes with the corresponding item's cart notes from `OrderTransfer.items`. | | Spryker\Zed\CartNote\Communication\Plugin\SalesOrderAmendment | +| ShipmentSalesOrderItemCollectorPlugin | Iterates over `SalesOrderAmendmentItemCollectionTransfer.itemsToSkip` and compares an item's shipments with the corresponding item's shipments from `OrderTransfer.items`. | | Spryker\Zed\Shipment\Communication\Plugin\SalesOrderAmendment | +| ConfigurableBundleNoteSalesOrderItemCollectorPlugin | Iterates over `SalesOrderAmendmentItemCollectionTransfer.itemsToSkip` and compares an item's configurable bundle notes with the corresponding item's configurable bundle notes from `OrderTransfer.items`. | | Spryker\Zed\ConfigurableBundleNote\Communication\Plugin\SalesOrderAmendment | +| SalesProductConfigurationSalesOrderItemCollectorPlugin | Iterates over `SalesOrderAmendmentItemCollectionTransfer.itemsToSkip` and compares an item's configurations with the corresponding item's configurations from `OrderTransfer.items`. | | Spryker\Zed\SalesProductConfiguration\Communication\Plugin\SalesOrderAmendment | +| SalesServicePointSalesOrderItemCollectorPlugin | Iterates over `SalesOrderAmendmentItemCollectionTransfer.itemsToSkip` and compares an item's service points with the corresponding item's service points from `OrderTransfer.items`. | | Spryker\Zed\SalesServicePoint\Communication\Plugin\SalesOrderAmendment | +| OrderAmendmentRestCartReorderAttributesMapperPlugin | Maps the `isAmendment` property from `RestCartReorderRequestAttributesTransfer` to `CartReorderRequestTransfer`. | | Spryker\Glue\OrderAmendmentsRestApi\Plugin\CartReorderRestApi | +| OrderAmendmentRestCartAttributesMapperPlugin | Maps the `amendmentOrderReference` field from `QuoteTransfer` to `RestCartsAttributesTransfer`. | | Spryker\Glue\OrderAmendmentsRestApi\Plugin\CartsRestApi | +| OrderAmendmentCheckoutPreCheckPlugin | Validates if an order is in a state that allows amendment. | | Spryker\Zed\SalesOrderAmendmentOms\Communication\Plugin\Checkout | +| CustomerOrderSavePlugin | Saves customer info to a sales related table. | | Spryker\Zed\Customer\Communication\Plugin\Checkout | +| UpdateOrderByQuoteCheckoutDoSaveOrderPlugin | Updates order billing address with billing address data from quote. | | Spryker\Zed\Sales\Communication\Plugin\Checkout | +| OrderTotalsSaverPlugin | Saves order totals. | | Spryker\Zed\Sales\Communication\Plugin\Checkout | +| ReleaseUsedCodesCheckoutDoSaveOrderPlugin | Decreases the number of uses of each of located discount codes by 1. | | Spryker\Zed\Discount\Communication\Plugin\Checkout | +| ShipmentTypeCheckoutDoSaveOrderPlugin | Creates or updates a sales shipment type entity. | Must be executed after `ReplaceSalesOrderShipmentCheckoutDoSaveOrderPlugin`. | Spryker\Zed\SalesShipmentType\Communication\Plugin\Checkout | +| UpdateCartNoteCheckoutDoSaveOrderPlugin | Updates an order's cart note with the cart note provided in `QuoteTransfer.cartNote`. | | Spryker\Zed\CartNote\Communication\Plugin\Checkout | +| ReplaceSalesOrderDiscountsCheckoutDoSaveOrderPlugin | Deletes sales discount and sales discount code entities related to a provided sales order ID. Iterates over `orderItems` and `orderExpenses` and creates sales discount entities for each item. | | Spryker\Zed\Discount\Communication\Plugin\Checkout | +| ReplaceSalesOrderShipmentCheckoutDoSaveOrderPlugin | Recreates new sales shipment expenses for each item level shipment. | | Spryker\Zed\Shipment\Communication\Plugin\Checkout | +| SalesOrderAmendmentItemsCheckoutDoSaveOrderPlugin | Replaces an order item during amendment process. | | Spryker\Zed\SalesOrderAmendment\Communication\Plugin\Checkout | +| ProductBundleOrderSaverPlugin | Saves order bundle items. | | Spryker\Zed\ProductBundle\Communication\Plugin\Checkout | +| ReplaceSalesOrderPaymentCheckoutDoSaveOrderPlugin | Saves order payments from `QuoteTransfer`. | | Spryker\Zed\SalesPayment\Communication\Plugin\Checkout | +| GiftCardPaymentCheckoutDoSaveOrderPlugin | Iterates over `QuoteTransfer.payments` and saves gift card related payments into the `spy_payment_gift_card` table. | | Spryker\Zed\GiftCard\Communication\Plugin\Checkout | +| ReplaceSalesOrderThresholdExpensesCheckoutDoSaveOrderPlugin | Iterates over `QuoteTransfer.expenses` and stores expenses of the type defined by `{@link \Spryker\Shared\SalesOrderThreshold\SalesOrderThresholdConfig::THRESHOLD_EXPENSE_TYPE}` in the database. | | Spryker\Zed\SalesOrderThreshold\Communication\Plugin\Checkout | +| FinishOrderAmendmentCheckoutPostSavePlugin | Triggers the OMS event defined in `{@link \Spryker\Zed\SalesOrderAmendmentOms\SalesOrderAmendmentOmsConfig::getFinishOrderAmendmentEvent()}` to finish the order amendment process. | | Spryker\Zed\SalesOrderAmendmentOms\Communication\Plugin\Checkout | +| DummyPaymentCheckoutPostSavePlugin | If `QuoteTransfer.billingAddress.lastName` is `Invalid`, adds the error into `CheckoutResponseTransfer`. | | Spryker\Zed\DummyPayment\Communication\Plugin\Checkout | +| CloseQuoteRequestCheckoutPostSaveHookPlugin | If quote contains a quote request version reference, marks the quote request as closed. | | Spryker\Zed\QuoteRequest\Communication\Plugin\Checkout | +| SendEmailToGiftCardUser | Sends an email to a Gift Card user. | | Spryker\Zed\GiftCardMailConnector\Communication\Plugin\Checkout | +| PaymentAuthorizationCheckoutPostSavePlugin | Checks whether the payment method selected for the given order requires authorization. | | Spryker\Zed\Payment\Communication\Plugin\Checkout | +| PaymentConfirmPreOrderPaymentCheckoutPostSavePlugin | Send a request to the used PSP App to confirm the preorder payment. | | Spryker\Zed\Payment\Communication\Plugin\Checkout | +| DisallowQuoteCheckoutPreSavePlugin | Disallows quote checkout for the configured amount of seconds. | | Spryker\Zed\QuoteCheckoutConnector\Communication\Plugin\Checkout | +| SalesOrderExpanderPlugin | Transforms the provided cart items according to the configured cart item transformer strategies. | | Spryker\Zed\Sales\Communication\Plugin\Checkout | +| OriginalOrderQuoteExpanderCheckoutPreSavePlugin | Sets `QuoteTransfer.originalOrder` with a found order entity. | | Spryker\Zed\SalesOrderAmendment\Communication\Plugin\Checkout | +| CancelOrderAmendmentQuoteDeleteAfterPlugin | Triggers the OMS event defined in `{@link \Spryker\Zed\SalesOrderAmendmentOms\SalesOrderAmendmentOmsConfig::getCancelOrderAmendmentEvent()}` to cancel the order amendment process. | | Spryker\Zed\SalesOrderAmendmentOms\Communication\Plugin\Quote | +| SalesOrderAmendmentOrderExpanderPlugin | Expands `OrderTransfer.salesOrderAmendment` with a found sales order amendment. | | Spryker\Zed\SalesOrderAmendment\Communication\Plugin\Sales | +| IsAmendableOrderExpanderPlugin | Checks if all order items are in the order item state that has a flag defined in `{@link \Spryker\Zed\SalesOrderAmendmentOms\SalesOrderAmendmentOmsConfig::getAmendableOmsFlag()}`. | | Spryker\Zed\SalesOrderAmendmentOms\Communication\Plugin\Sales | +| CreateSalesOrderAmendmentOrderPostSavePlugin | Persists a sales order amendment entity. | | Spryker\Zed\SalesOrderAmendment\Communication\Plugin\Sales | +| OrderAmendmentCartPreCheckPlugin | Validates if the customer order with a provided amendment order reference exists. | | Spryker\Zed\SalesOrderAmendment\Communication\Plugin\Cart | +| ResetAmendmentOrderReferencePreReloadItemsPlugin | Resets `QuoteTransfer.amendmentOrderReference` before reloading cart items. | | Spryker\Zed\SalesOrderAmendment\Communication\Plugin\Cart | +| ResetOriginalSalesOrderItemUnitPricesPreReloadItemsPlugin | Resets `QuoteTransfer.originalSalesOrderItemUnitPrices` before reloading cart items. | | Spryker\Zed\PriceProductSalesOrderAmendment\Communication\Plugin\Cart | +| ResetAmendmentQuoteProcessFlowQuotePostMergePlugin | If `PersistentQuoteTransfer.idQuote` is not equal to `CurrentQuoteTransfer.idQuote`, and `quoteProcessFlow` is set to `order-amendment`, resets `quoteProcessFlow`. | | Spryker\Zed\SalesOrderAmendment\Communication\Plugin\PersistentCart | +| DefaultQuoteCollectionFilterPlugin | Filters out non-default quotes. | | Spryker\Zed\MultiCart\Communication\Plugin\Quote | +| IsAmendableOrderSearchOrderExpanderPlugin | Expands the `OrderTransfer.isAmendable` property. | | Spryker\Zed\SalesOrderAmendmentOms\Communication\Plugin\Sales | +| OrderAmendmentDefaultOrderItemInitialStateProviderPlugin | Returns the initial OMS order item state for order items in the order amendment flow. | | Spryker\Zed\SalesOrderAmendmentOms\Communication\Plugin\Sales | +| OrderAmendmentsByOrderResourceRelationshipPlugin | Adds the `order-amendments` resource as relationship if `OrderTransfer` and `OrderTransfer.salesOrderAmendment` are provided as a payload. | | Spryker\Glue\OrderAmendmentsRestApi\Plugin\GlueApplication | +| CountriesCheckoutDataValidatorPlugin | Verifies if countries can be found by `countryIso2Codes` given in `CheckoutDataTransfer.shipments.shippingAddress`. | | Spryker\Zed\Country\Communication\Plugin\CheckoutRestApi | +| ShipmentMethodCheckoutDataValidatorPlugin | Verifies if a shipment method is valid. | | Spryker\Zed\ShipmentsRestApi\Communication\Plugin\CheckoutRestApi | +| ItemsCheckoutDataValidatorPlugin | Validates if `CheckoutDataTransfer` provides shipment data per item level. | | Spryker\Zed\ShipmentsRestApi\Communication\Plugin\CheckoutRestApi | +| CustomerAddressCheckoutDataValidatorPlugin | Checks if customer addresses exist. | | Spryker\Zed\CustomersRestApi\Communication\Plugin\CheckoutRestApi | +| CompanyBusinessUnitAddressCheckoutDataValidatorPlugin | Checks if company addresses exist. | | Spryker\Zed\CompanyBusinessUnitAddressesRestApi\Communication\Plugin\CheckoutRestApi | +| ShipmentTypeCheckoutDataValidatorPlugin | Validates whether a shipment type related to the shipment method is active and belongs to the quote store. | | Spryker\Zed\ShipmentTypesRestApi\Communication\Plugin\CheckoutRestApi | +| ClickAndCollectExampleReplaceCheckoutDataValidatorPlugin | Replaces filtered product offers with suitable product offers from Persistence. | | Spryker\Zed\ClickAndCollectExample\Communication\Plugin\CheckoutRestApi | +| SaveOrderCommentThreadOrderPostSavePlugin | Saves a comments thread after an order is saved. | | Spryker\Zed\CommentSalesConnector\Communication\Plugin\Sales | +| SaveCompanyBusinessUnitUuidOrderPostSavePlugin | Saves company business unit UUID to the order after it's saved. | | Spryker\Zed\CompanyBusinessUnitSalesConnector\Communication\Plugin\Sales | +| SaveCompanyUuidOrderPostSavePlugin | Saves company UUID to the order after it's saved. | | Spryker\Zed\CompanySalesConnector\Communication\Plugin\Sales | +| DiscountSalesOrderItemCollectionPreDeletePlugin | Deletes sales discount and sales discount code entities found by criteria. | | Spryker\Zed\Discount\Communication\Plugin\Sales | +| SalesDiscountSalesExpensePreDeletePlugin | Deletes sales discount entities related to provided expenses. | | Spryker\Zed\Discount\Communication\Plugin\Sales | +| GiftCardOrderItemsPostSavePlugin | Processes gift card order items after they're saved. | | Spryker\Zed\GiftCard\Communication\Plugin\Sales | +| GiftCardSalesOrderItemCollectionPreDeletePlugin | Deletes sales order item gift card entities found by criteria. | | Spryker\Zed\GiftCard\Communication\Plugin\Sales | +| NopaymentSalesOrderItemCollectionPreDeletePlugin | Deletes no-payment paid entities found by criteria. | | Spryker\Zed\Nopayment\Communication\Plugin\Sales | +| DefaultOrderItemInitialStateProviderPlugin | Sets the initial OMS state for order items. | | Spryker\Zed\Oms\Communication\Plugin\Sales | +| OmsItemHistorySalesOrderItemCollectionPreDeletePlugin | Deletes entities found by criteria. | | Spryker\Zed\Oms\Communication\Plugin\Sales | +| UpdateOrderCustomReferenceOrderPostSavePlugin | Updates custom order reference after an order is saved. | | Spryker\Zed\OrderCustomReference\Communication\Plugin\Sales | +| ProductOptionOrderItemsPostSavePlugin | Processes product option order items after they're saved. | | Spryker\Zed\ProductOption\Communication\Plugin\Sales | +| ProductOptionSalesOrderItemCollectionPostUpdatePlugin | Processes product options after an order items collection is updated. | | Spryker\Zed\ProductOption\Communication\Plugin\Sales | +| ProductOptionSalesOrderItemCollectionPreDeletePlugin | Deletes sales order item option entities. | | Spryker\Zed\ProductOption\Communication\Plugin\Sales | +| SalesConfigurableBundleSalesOrderItemCollectionPreDeletePlugin | Deletes sales order configured bundle item entities. | | Spryker\Zed\SalesConfigurableBundle\Communication\Plugin\Sales | +| SalesConfiguredBundlesSalesOrderItemCollectionPostUpdatePlugin | Processes configured bundles after an order items collection is updated. | | Spryker\Zed\SalesConfigurableBundle\Communication\Plugin\Sales | +| SalesProductConfigurationSalesOrderItemCollectionPostUpdatePlugin | Processes product configurations after an order items collection is updated. | | Spryker\Zed\SalesProductConfiguration\Communication\Plugin\Sales | +| SalesProductConfigurationSalesOrderItemCollectionPreDeletePlugin | Deletes sales order item configuration entities found by criteria. | | Spryker\Zed\SalesProductConfiguration\Communication\Plugin\Sales | +| ItemMetadataSalesOrderItemCollectionPostUpdatePlugin | Processes item metadata after an order items collection is updated. | | Spryker\Zed\SalesProductConnector\Communication\Plugin\Sales | +| ItemMetadataSalesOrderItemCollectionPreDeletePlugin | Deletes sales order item metadata entities found by criteria. | | Spryker\Zed\SalesProductConnector\Communication\Plugin\Sales | +| SalesReclamationSalesOrderItemCollectionPreDeletePlugin | Deletes sales reclamation item entities found by criteria. | | Spryker\Zed\SalesReclamation\Communication\Plugin\Sales | +| ServicePointSalesOrderItemCollectionPostUpdatePlugin | Processes service points after an order items collection is updated. | | Spryker\Zed\SalesServicePoint\Communication\Plugin\Sales | +| ServicePointSalesOrderItemCollectionPreDeletePlugin | Deletes sales order item service point entities found by criteria. | | Spryker\Zed\SalesServicePoint\Communication\Plugin\Sales | +| SalesOrderAmendmentCurrentCurrencyIsoCodePreCheckPlugin | Disallows changing the currency when an order is being edited. | | Spryker\Client\SalesOrderAmendment\Plugin\Currency | +| SalesOrderAmendmentCurrentPriceModePreCheckPlugin | Disallows changing the price mode when an order is being edited. | | Spryker\Client\SalesOrderAmendment\Plugin\Price | +| PriceItemExpanderPlugin | Adds product prices to item based on currency, price mode, and price type. Allows to expand items with nullable prices. | For Order amendment flow, should be executed instead of `{@link \Spryker\Zed\PriceCartConnector\Communication\Plugin\CartItemPricePlugin}`. | Spryker\Zed\PriceCartConnector\Communication\Plugin\Cart | +| OriginalSalesOrderItemPriceItemExpanderPlugin | Replaces an item's prices with the original sales order item's prices before adding or removing cart items to persistence. | Should be executed after `{@link \Spryker\Zed\PriceCartConnector\Communication\Plugin\PriceItemExpanderPlugin}`. | Spryker\Zed\PriceProductSalesOrderAmendment\Communication\Plugin\Cart | +| OriginalSalesOrderItemPriceProductPostResolvePlugin | Replaces an item's prices with the original sales order item's prices after resolving prices for the resulting `PriceProductTransfer`. | | Spryker\Client\PriceProductSalesOrderAmendment\Plugin\PriceProduct | +| OrderItemPriceProductResolveConditionsPriceProductFilterExpanderPlugin | Expands `PriceProductFilterTransfer` with `PriceProductResolveConditionsTransfer` from `ProductViewTransfer`. | | Spryker\Client\PriceProductSalesOrderAmendment\Plugin\PriceProductStorage | +| CurrentStoreCartReorderValidatorPlugin | Validates that the current store matches the store of the order and quote. | | Spryker\Zed\Store\Communication\Plugin\CartReorder | +| ProductOfferOriginalSalesOrderItemGroupKeyExpanderPlugin | Expands a provided group key with a product offer reference if `ItemTransfer.productOfferReference` is set. | | Spryker\Service\ProductOffer\Plugin\SalesOrderAmendment | +| ProductOfferOriginalSalesOrderItemPriceGroupKeyExpanderPlugin | Expands a provided price group key with a product offer reference if `ItemTransfer.productOfferReference` is set. | | Spryker\Service\ProductOffer\Plugin\SalesOrderAmendment | +| OrderAmendmentQuantityBatchAvailabilityStrategyPlugin | Calculates available quantity for each processed item. | | Spryker\Zed\SalesOrderAmendment\Communication\Plugin\Availability | +| OrderAmendmentProductApprovalCartPreCheckPlugin | Checks the approval status for products. Skips items that are part of the original order. | | Spryker\Zed\ProductApproval\Communication\Plugin\Cart | +| OrderAmendmentProductApprovalPreReloadItemsPlugin | Checks and removes unapproved product items from Quote transfer. Skips items that are part of the original order. | | Spryker\Zed\ProductApproval\Communication\Plugin\Cart | +| OrderAmendmentProductBundleAvailabilityCartPreCheckPlugin | Checks if product bundle items in `CartChangeTransfer` are available and active. Skips `isActive` validation for items with SKUs from `CartChangeTransfer.quote.originalSalesOrderItems`. | | Spryker\Zed\ProductBundle\Communication\Plugin\Cart | +| OrderAmendmentProductBundleStatusCartPreCheckPlugin | Checks if product bundle items in `CartChangeTransfer` are active. Skips validation for items with SKUs from `CartChangeTransfer.quote.originalSalesOrderItems`. | | Spryker\Zed\ProductBundle\Communication\Plugin\Cart | +| OrderAmendmentProductExistsCartPreCheckPlugin | Checks if the products added to cart exist. Skips items that are part of the original order. | | Spryker\Zed\ProductCartConnector\Communication\Plugin\Cart | +| OrderAmendmentRemoveInactiveItemsPreReloadPlugin | Removes inactive items from quote. Skips items that are part of the original order. | | Spryker\Zed\ProductCartConnector\Communication\Plugin\Cart | +| OrderAmendmentProductDiscontinuedCartPreCheckPlugin | Checks all item related products from a cart change request are not discontinued. Skips items that are part of the original order. | | Spryker\Zed\ProductDiscontinued\Communication\Plugin\Cart | +| OrderAmendmentFilterInactiveProductOfferPreReloadItemsPlugin | Checks and removes inactive product offers from cart. Skips inactive product offers that are part of the original order. | | Spryker\Zed\ProductOffer\Communication\Plugin\Cart | +| OrderAmendmentProductOfferCartPreCheckPlugin | Checks if a cart item product offer belongs to a product. Skips product offers that are part of the original order. | | Spryker\Zed\ProductOffer\Communication\Plugin\Cart | +| OriginalOrderBundleItemCartPreReorderPlugin | Expands `CartReorderTransfer.quote` with original sales order items from a provided `CartReorderTransfer.order.bundleItems`. | | Spryker\Zed\ProductBundle\Communication\Plugin\CartReorder | +| OriginalSalesOrderItemCartPreReorderPlugin | Expands `CartReorderTransfer.quote` with original sales order items from a provided `CartReorderTransfer.order.items`. | | Spryker\Zed\SalesOrderAmendment\Communication\Plugin\CartReorder | +| RemoveInactiveProductOptionItemsCartReorderPreAddToCartPlugin | Filters out items with inactive product options from `CartChangeTransfer`. | | Spryker\Zed\ProductOptionCartConnector\Communication\Plugin\CartReorder | +| OrderAmendmentProductApprovalCheckoutPreConditionPlugin | Returns `false` if at least one quote item transfer has items with unapproved product. Skips items that are part of the original order. | | Spryker\Zed\ProductApproval\Communication\Plugin\Checkout | +| OrderAmendmentProductBundleAvailabilityCheckoutPreConditionPlugin | Checks if the product bundle items in the `QuoteTransfer` are available and active. Skips `isActive` validation for items with SKUs from `QuoteTransfer.originalSalesOrderItems`. | | Spryker\Zed\ProductBundle\Communication\Plugin\Checkout | +| OrderAmendmentProductExistsCheckoutPreConditionPlugin | Validates if concrete products with the `QuoteTransfer.item.sku` SKU exist and are active. Skips items that are part of the original order. | | Spryker\Zed\ProductCartConnector\Communication\Plugin\Checkout | +| OrderAmendmentProductDiscontinuedCheckoutPreConditionPlugin | Checks if there are no discontinued products in checkout. Skips items that are part of the original order. | | Spryker\Zed\ProductDiscontinued\Communication\Plugin\Checkout | +| OrderAmendmentProductOfferCheckoutPreConditionPlugin | Returns `false` if at least one quote item transfer has items with inactive or unapproved `ProductOffer`. Skips product offers that are part of the original order. | | Spryker\Zed\ProductOffer\Communication\Plugin\Checkout | +| SalesOrderAmendmentQuoteCheckoutDoSaveOrderPlugin | Creates a new sales order amendment quote entity based on a provided `QuoteTransfer`. | | Spryker\Zed\SalesOrderAmendment\Communication\Plugin\Checkout | +| UpdateDeletedItemReservationCommandByOrderPlugin | Retrieves the sales order amendment quote collection by order reference. If the collection is not empty, updates the reservations of deleted items in the order. | | Spryker\Zed\SalesOrderAmendmentOms\Communication\Plugin\Oms | +| OriginalSalesOrderItemGroupKeyCartReorderItemHydratorPlugin | Hydrates `items.originalSalesOrderItemGroupKey` with the original sales order item group key. | | Spryker\Zed\SalesOrderAmendment\Communication\Plugin\CartReorder | + + + +
+ src/Pyz/Service/SalesOrderAmendment/SalesOrderAmendmentDependencyProvider.php + +```php + + */ + protected function getOriginalSalesOrderItemGroupKeyExpanderPlugins(): array + { + return [ + new ProductOfferOriginalSalesOrderItemGroupKeyExpanderPlugin(), + ]; + } +} +``` + +
+ +
+ src/Pyz/Service/PriceProductSalesOrderAmendment/PriceProductSalesOrderAmendmentDependencyProvider.php + +```php + + */ + protected function getOriginalSalesOrderItemPriceGroupKeyExpanderPlugins(): array + { + return [ + new ProductOfferOriginalSalesOrderItemPriceGroupKeyExpanderPlugin(), + ]; + } +} +``` + +
+ + +
+ src/Pyz/Zed/SalesOrderAmendment/SalesOrderAmendmentDependencyProvider.php + +```php + + */ + protected function getSalesOrderAmendmentCreateValidationRulePlugins(): array + { + return [ + new OrderSalesOrderAmendmentValidatorRulePlugin(), + ]; + } + + /** + * @return list<\Spryker\Zed\SalesOrderAmendmentExtension\Dependency\Plugin\SalesOrderItemCollectorPluginInterface> + */ + protected function getSalesOrderItemCollectorPlugins(): array + { + return [ + new CartNoteSalesOrderItemCollectorPlugin(), + new ShipmentSalesOrderItemCollectorPlugin(), + new ConfigurableBundleNoteSalesOrderItemCollectorPlugin(), + new SalesProductConfigurationSalesOrderItemCollectorPlugin(), + new SalesServicePointSalesOrderItemCollectorPlugin(), + ]; + } +} +``` + +
+ + +
+ src/Pyz/Zed/CartReorder/CartReorderDependencyProvider.php + +```php + + */ + protected function getCartReorderRequestValidatorPlugins(): array + { + return [ + new IsAmendableOrderCartReorderRequestValidatorPlugin(), + ]; + } + + /** + * @return list<\Spryker\Zed\CartReorderExtension\Dependency\Plugin\CartReorderValidatorPluginInterface> + */ + protected function getCartReorderValidatorPluginsForOrderAmendment(): array + { + return [ + new CurrentStoreCartReorderValidatorPlugin(), + new OrderAmendmentCartReorderValidatorPlugin(), + ]; + } + + /** + * @return list<\Spryker\Zed\CartReorderExtension\Dependency\Plugin\CartPreReorderPluginInterface> + */ + protected function getCartPreReorderPlugins(): array + { + return [ + new OrderAmendmentQuoteProcessFlowExpanderCartPreReorderPlugin(), + new AmendmentOrderReferenceCartPreReorderPlugin(), + new AmendmentQuoteNameCartPreReorderPlugin(), + new OriginalSalesOrderItemPriceCartPreReorderPlugin(), + ]; + } + + /** + * @return list<\Spryker\Zed\CartReorderExtension\Dependency\Plugin\CartReorderItemHydratorPluginInterface> + */ + protected function getCartReorderItemHydratorPlugins(): array + { + return [ + new OriginalSalesOrderItemGroupKeyCartReorderItemHydratorPlugin(), + ]; + } + + /** + * @return list<\Spryker\Zed\CartReorderExtension\Dependency\Plugin\CartPostReorderPluginInterface> + */ + protected function getCartPostReorderPlugins(): array + { + return [ + new StartOrderAmendmentCartReorderPostCreatePlugin(), + ]; + } +} +``` + +
+ +
+ src/Pyz/Glue/CartReorderRestApi/CartReorderRestApiDependencyProvider.php + + +```php + + */ + protected function getRestCartReorderAttributesMapperPlugins(): array + { + return [ + new OrderAmendmentRestCartReorderAttributesMapperPlugin(), + ]; + } +} +``` + +
+ +
+ src/Pyz/Glue/CartsRestApi/CartsRestApiDependencyProvider.php + + +```php + + */ + protected function getRestCartAttributesMapperPlugins(): array + { + return [ + new OrderAmendmentRestCartAttributesMapperPlugin(), + ]; + } +} +``` + + +
+ + +
+ src/Pyz/Zed/Checkout/CheckoutDependencyProvider.php + +```php + + */ + protected function getCheckoutPreConditionsForOrderAmendment(Container $container): array + { + return [ + new OrderAmendmentProductBundleAvailabilityCheckoutPreConditionPlugin(), + new OrderAmendmentProductDiscontinuedCheckoutPreConditionPlugin(), + new OrderAmendmentProductOfferCheckoutPreConditionPlugin(), + new OrderAmendmentProductExistsCheckoutPreConditionPlugin(), + new OrderAmendmentProductApprovalCheckoutPreConditionPlugin(), + new OrderAmendmentCheckoutPreCheckPlugin(), + ]; + } + + + /** + * @param \Spryker\Zed\Kernel\Container $container + * + * @return list<\Spryker\Zed\Checkout\Dependency\Plugin\CheckoutSaveOrderInterface|\Spryker\Zed\CheckoutExtension\Dependency\Plugin\CheckoutDoSaveOrderInterface> + */ + protected function getCheckoutOrderSaversForOrderAmendment(Container $container): array + { + return [ + new CustomerOrderSavePlugin(), + new UpdateOrderByQuoteCheckoutDoSaveOrderPlugin(), + new OrderTotalsSaverPlugin(), + new ReleaseUsedCodesCheckoutDoSaveOrderPlugin(), + new UpdateCartNoteCheckoutDoSaveOrderPlugin(), + new ReplaceSalesOrderDiscountsCheckoutDoSaveOrderPlugin(), + new ReplaceSalesOrderShipmentCheckoutDoSaveOrderPlugin(), + new ShipmentTypeCheckoutDoSaveOrderPlugin(), + new SalesOrderAmendmentItemsCheckoutDoSaveOrderPlugin(), + new ProductBundleOrderSaverPlugin(), + new ReplaceSalesOrderPaymentCheckoutDoSaveOrderPlugin(), + new SalesOrderAmendmentQuoteCheckoutDoSaveOrderPlugin(), + new GiftCardPaymentCheckoutDoSaveOrderPlugin(), + new ReplaceSalesOrderThresholdExpensesCheckoutDoSaveOrderPlugin(), + ]; + } + + /** + * @param \Spryker\Zed\Kernel\Container $container + * + * @return list<\Spryker\Zed\CheckoutExtension\Dependency\Plugin\CheckoutPostSaveInterface> + */ + protected function getCheckoutPostHooks(Container $container): array + { + return [ + new FinishOrderAmendmentCheckoutPostSavePlugin(), + ]; + } + + /** + * @param \Spryker\Zed\Kernel\Container $container + * + * @return list<\Spryker\Zed\CheckoutExtension\Dependency\Plugin\CheckoutPostSaveInterface> + */ + protected function getCheckoutPostHooksForOrderAmendment(Container $container): array + { + return [ + new DummyPaymentCheckoutPostSavePlugin(), + new CloseQuoteRequestCheckoutPostSaveHookPlugin(), + new SendEmailToGiftCardUser(), + new PaymentAuthorizationCheckoutPostSavePlugin(), + new PaymentConfirmPreOrderPaymentCheckoutPostSavePlugin(), + ]; + } + + /** + * @param \Spryker\Zed\Kernel\Container $container + * + * @return list<\Spryker\Zed\Checkout\Dependency\Plugin\CheckoutPreSaveHookInterface|\Spryker\Zed\Checkout\Dependency\Plugin\CheckoutPreSaveInterface|\Spryker\Zed\CheckoutExtension\Dependency\Plugin\CheckoutPreSavePluginInterface> + */ + protected function getCheckoutPreSaveHooksForOrderAmendment(Container $container): array + { + return [ + new DisallowQuoteCheckoutPreSavePlugin(), + new SalesOrderExpanderPlugin(), + new OriginalOrderQuoteExpanderCheckoutPreSavePlugin(), + new FilterOriginalOrderBundleItemCheckoutPreSavePlugin(), + ]; + } +} +``` + +
+ + + +
+ src/Pyz/Zed/Quote/QuoteDependencyProvider.php + + +```php + + */ + protected function getQuoteDeleteAfterPlugins(): array + { + return [ + new CancelOrderAmendmentQuoteDeleteAfterPlugin(), + ]; + } + + /** + * @return list<\Spryker\Zed\QuoteExtension\Dependency\Plugin\QuoteCollectionFilterPluginInterface> + */ + protected function getQuoteCollectionFilterPlugins(): array + { + return [ + new DefaultQuoteCollectionFilterPlugin(), + ]; + } +} +``` + +
+ + + +
+ src/Pyz/Zed/Sales/SalesDependencyProvider.php + + +```php + + */ + protected function getOrderHydrationPlugins(): array + { + return [ + new SalesOrderAmendmentOrderExpanderPlugin(), + new IsAmendableOrderExpanderPlugin(), + ]; + } + + /** + * @return list<\Spryker\Zed\SalesExtension\Dependency\Plugin\OrderPostSavePluginInterface> + */ + protected function getOrderPostSavePluginsForOrderAmendment(): array + { + return [ + new SaveOrderCommentThreadOrderPostSavePlugin(), + new UpdateOrderCustomReferenceOrderPostSavePlugin(), + new SaveCompanyBusinessUnitUuidOrderPostSavePlugin(), + new SaveCompanyUuidOrderPostSavePlugin(), + new CreateSalesOrderAmendmentOrderPostSavePlugin(), + ]; + } + + /** + * @return list<\Spryker\Zed\SalesExtension\Dependency\Plugin\SearchOrderExpanderPluginInterface> + */ + protected function getSearchOrderExpanderPlugins(): array + { + return [ + new IsAmendableOrderSearchOrderExpanderPlugin(), + ]; + } + + /** + * @return list<\Spryker\Zed\SalesExtension\Dependency\Plugin\OrderItemsPostSavePluginInterface> + */ + protected function getOrderItemsPostSavePlugins(): array + { + return [ + new GiftCardOrderItemsPostSavePlugin(), + new ProductOptionOrderItemsPostSavePlugin(), + ]; + } + + /** + * @return list<\Spryker\Zed\SalesExtension\Dependency\Plugin\SalesExpensePreDeletePluginInterface> + */ + protected function getSalesExpensePreDeletePlugins(): array + { + return [ + new SalesDiscountSalesExpensePreDeletePlugin(), + ]; + } + + /** + * @return list<\Spryker\Zed\SalesExtension\Dependency\Plugin\SalesOrderItemCollectionPreDeletePluginInterface> + */ + protected function getSalesOrderItemCollectionPreDeletePlugins(): array + { + return [ + new DiscountSalesOrderItemCollectionPreDeletePlugin(), + new ItemMetadataSalesOrderItemCollectionPreDeletePlugin(), + new OmsItemHistorySalesOrderItemCollectionPreDeletePlugin(), + new ProductOptionSalesOrderItemCollectionPreDeletePlugin(), + new ServicePointSalesOrderItemCollectionPreDeletePlugin(), + new SalesConfigurableBundleSalesOrderItemCollectionPreDeletePlugin(), + new SalesProductConfigurationSalesOrderItemCollectionPreDeletePlugin(), + new GiftCardSalesOrderItemCollectionPreDeletePlugin(), + new NopaymentSalesOrderItemCollectionPreDeletePlugin(), + new SalesReclamationSalesOrderItemCollectionPreDeletePlugin(), + ]; + } + + /** + * @return list<\Spryker\Zed\SalesExtension\Dependency\Plugin\SalesOrderItemCollectionPostUpdatePluginInterface> + */ + protected function getOrderItemCollectionPostUpdatePlugins(): array + { + return [ + new SalesConfiguredBundlesSalesOrderItemCollectionPostUpdatePlugin(), + new SalesProductConfigurationSalesOrderItemCollectionPostUpdatePlugin(), + new ItemMetadataSalesOrderItemCollectionPostUpdatePlugin(), + new ServicePointSalesOrderItemCollectionPostUpdatePlugin(), + new ProductOptionSalesOrderItemCollectionPostUpdatePlugin(), + ]; + } + + /** + * @return list<\Spryker\Zed\SalesExtension\Dependency\Plugin\OrderItemInitialStateProviderPluginInterface> + */ + protected function getOrderItemInitialStateProviderPlugins(): array + { + return [ + new DefaultOrderItemInitialStateProviderPlugin(), + ]; + } + + /** + * @return list<\Spryker\Zed\SalesExtension\Dependency\Plugin\OrderItemInitialStateProviderPluginInterface> + */ + protected function getOrderItemInitialStateProviderPluginsForOrderAmendment(): array + { + return [ + new OrderAmendmentDefaultOrderItemInitialStateProviderPlugin(), + ]; + } +} +``` + +
+ +
+ src/Pyz/Glue/GlueApplication/GlueApplicationDependencyProvider.php + +```php +addRelationship( + OrdersRestApiConfig::RESOURCE_ORDERS, + new OrderAmendmentsByOrderResourceRelationshipPlugin(), + ); + + return $resourceRelationshipCollection; + } +} +``` + + + +
+ + + +
+ src/Pyz/Zed/CheckoutRestApi/CheckoutRestApiDependencyProvider.php + + +```php + + */ + protected function getCheckoutDataValidatorPluginsForOrderAmendment(): array + { + return [ + new CountriesCheckoutDataValidatorPlugin(), + new ShipmentMethodCheckoutDataValidatorPlugin(), + new ItemsCheckoutDataValidatorPlugin(), + new CustomerAddressCheckoutDataValidatorPlugin(), + new CompanyBusinessUnitAddressCheckoutDataValidatorPlugin(), + new ShipmentTypeCheckoutDataValidatorPlugin(), + new ClickAndCollectExampleReplaceCheckoutDataValidatorPlugin(), + ]; + } +} +``` + +
+ +
+ src/Pyz/Zed/Availability/AvailabilityDependencyProvider.php + +```php + + */ + protected function getBatchAvailabilityStrategyPlugins(): array + { + return [ + /* + * OrderAmendmentQuantityBatchAvailabilityStrategyPlugin needs to be after all other implementations including ProductConcreteBatchAvailabilityStrategyPlugin. + */ + new OrderAmendmentQuantityBatchAvailabilityStrategyPlugin(), + ]; + } +} +``` + +
+ +
+ src/Pyz/Zed/Oms/OmsDependencyProvider.php + +```php +extend(self::COMMAND_PLUGINS, function (CommandCollectionInterface $commandCollection) { + $commandCollection->add(new UpdateDeletedItemReservationCommandByOrderPlugin(), 'OrderAmendment/UnreserveDeletedItems'); + $commandCollection->add(new DeleteOrderAmendmentQuoteCommandByOrderPlugin(), 'OrderAmendment/StartGracePeriod'); + + return $commandCollection; + }); + + return $container; + } +} +``` + +
+ +{% info_block warningBox "Verification" %} + +1. Place an order with different types of products–for example, physical or digital, and check if the order amendment is available. +2. Go to order detail and order list pages and check if the **edit order** button is displayed. +3. Deactivated and discontinue the products in the order. Make sure the order can be amended. + +{% endinfo_block %} + +**src/Pyz/Client/Currency/CurrencyDependencyProvider.php** + +```php + + */ + protected function getCurrentCurrencyIsoCodePreCheckPlugins(): array + { + return [ + new SalesOrderAmendmentCurrentCurrencyIsoCodePreCheckPlugin(), + ]; + } +} +``` + +**src/Pyz/Client/Price/PriceDependencyProvider.php** + +```php + + */ + protected function getCurrentPriceModePreCheckPlugins(): array + { + return [ + new SalesOrderAmendmentCurrentPriceModePreCheckPlugin(), + ]; + } +} +``` + +{% info_block warningBox "Verification" %} + +Make a Glue API call with a currency and price mode different from those in the cart when an order is being edited. For example: `htts://glue.mysprykershop.com/catalog-search?q=001¤cy=CHF&priceMode=NET_MODE`. Make sure the currency and price mode remain unchanged. + +{% endinfo_block %} + +
+ src/Pyz/Zed/Cart/CartDependencyProvider.php + +```php + + */ + protected function getExpanderPluginsForOrderAmendment(Container $container): array + { + return [ + new PriceItemExpanderPlugin(), + new OriginalSalesOrderItemPriceItemExpanderPlugin(), + ]; + } + + /** + * @return list<\Spryker\Zed\CartExtension\Dependency\Plugin\CartPreCheckPluginInterface> + */ + protected function getCartPreCheckPluginsForOrderAmendment(): array + { + return [ + new OrderAmendmentProductExistsCartPreCheckPlugin(), + new OrderAmendmentProductBundleAvailabilityCartPreCheckPlugin(), + new OrderAmendmentProductBundleStatusCartPreCheckPlugin(), + new OrderAmendmentProductDiscontinuedCartPreCheckPlugin(), + new OrderAmendmentProductOfferCartPreCheckPlugin(), + new OrderAmendmentProductApprovalCartPreCheckPlugin(), + // Plugins from getCartPreCheckPlugins() without CartItemPricePreCheckPlugin + new OrderAmendmentCartPreCheckPlugin(), + ]; + } + + /** + * @param \Spryker\Zed\Kernel\Container $container + * + * @return list<\Spryker\Zed\CartExtension\Dependency\Plugin\PreReloadItemsPluginInterface> + */ + protected function getPreReloadPlugins(Container $container): array + { + new ResetAmendmentOrderReferencePreReloadItemsPlugin(), + new ResetOriginalSalesOrderItemUnitPricesPreReloadItemsPlugin(), + } + + /** + * @param \Spryker\Zed\Kernel\Container $container + * + * @return list<\Spryker\Zed\CartExtension\Dependency\Plugin\PreReloadItemsPluginInterface> + */ + protected function getPreReloadPluginsForOrderAmendment(Container $container): array + { + return [ + new OrderAmendmentRemoveInactiveItemsPreReloadPlugin(), + new OrderAmendmentFilterInactiveProductOfferPreReloadItemsPlugin(), + new OrderAmendmentProductApprovalPreReloadItemsPlugin(), + // Plugins from getPreReloadPlugin() without FilterItemsWithoutPricePlugin + ]; + } +} +``` + +
+ +**src/Pyz/Zed/PersistentCart/PersistentCartDependencyProvider.php** + +```php + + */ + protected function getQuotePostMergePlugins(): array + { + return [ + new ResetAmendmentQuoteProcessFlowQuotePostMergePlugin(), + ]; + } +} +``` + +**src/Pyz/Client/PriceProduct/PriceProductDependencyProvider.php** + +```php + + */ + protected function getPriceProductPostResolvePlugins(): array + { + return [ + new OriginalSalesOrderItemPriceProductPostResolvePlugin(), + ]; + } +} +``` + +**src/Pyz/Client/PriceProductStorage/PriceProductStorageDependencyProvider.php** + +```php + + */ + protected function getPriceProductFilterExpanderPlugins(): array + { + return [ + new OrderItemPriceProductResolveConditionsPriceProductFilterExpanderPlugin(), + ]; + } +} +``` + +{% info_block warningBox "Verification" %} + +1. Place an order with a product. +2. Increase the price of the product from the order. +3. Start the order amendment process for the order you've placed. + Make sure the product still has the original price. +4. Go to the order details page and click the product to go to the product details page. + Make sure that, on the product details page, the product still has the original price. + + + +{% endinfo_block %} + +## Add the quotation process context + +Take the steps in the following sections to add the context for quote requests. + +### 1) Install the required modules + +Install the required modules using Composer: + +```bash +composer require spryker/sales-quote-request-connector: "^1.0.0" --update-with-dependencies +``` + +{% info_block warningBox "Verification" %} + +Make sure that the following modules have been installed: + +| MODULE | EXPECTED DIRECTORY | +|----------------------------|----------------------------------------------| +| SalesQuoteRequestConnector | vendor/spryker/sales-quote-request-connector | + +{% endinfo_block %} + +### 2) Set up behavior + +Enable the following behaviors by registering the plugins: + +| PLUGIN | SPECIFICATION | PREREQUISITES | NAMESPACE | +|-------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------|---------------|-------------------------------------------------------------------| +| QuoteRequestVersionReferenceOrderPostSavePlugin | Persists the `QuoteTransfer.quoteRequestVersionReference` transfer property in the `spy_sales_order` table. | | Spryker\Zed\SalesQuoteRequestConnector\Communication\Plugin\Sales | +| OrderAmendmentQuoteRequestQuoteCheckPlugin | Returns false if quote is in amendment process; otherwise, returns true. | | Spryker\Client\SalesOrderAmendment\Plugin\QuoteRequest | +| OrderAmendmentQuoteRequestValidatorPlugin | Prevents create and update of a quote request with quote in order amendment process. | | Spryker\Zed\SalesOrderAmendment\Communication\Plugin\QuoteRequest | +| OrderAmendmentQuoteRequestUserValidatorPlugin | Prevents create and update of a quote request with quote in order amendment process. | | Spryker\Zed\SalesOrderAmendment\Communication\Plugin\QuoteRequest | +| QuoteRequestVersionCartReorderValidatorPlugin | Returns `CartReorderResponseTransfer.errors` with error messages if `CartReorderTransfer.order.quoteRequestVersionReference` is set. | | Spryker\Zed\SalesOrderAmendment\Communication\Plugin\CartReorder | + +**src/Pyz/Zed/Sales/SalesDependencyProvider.php** + +```php + + */ + protected function getOrderPostSavePlugins(): array + { + return [ + new QuoteRequestVersionReferenceOrderPostSavePlugin(), + ]; + } +} +``` + +{% info_block warningBox "Verification" %} + +1. Create a request for quote. +2. As an agent, approve the quote request. +3. Place an order that was converted from request for quote. +Make sure the `quote_request_version_reference` column in the `spy_sales_order` table is populated with the correct value. + +{% endinfo_block %} + +**src/Pyz/Client/QuoteRequest/QuoteRequestDependencyProvider.php** + +```php + + */ + protected function getQuoteRequestQuoteCheckPlugins(): array + { + return [ + new OrderAmendmentQuoteRequestQuoteCheckPlugin(), + ]; + } +} +``` + +**src/Pyz/Zed/QuoteRequest/QuoteRequestDependencyProvider.php** + +```php + + */ + protected function getQuoteRequestValidatorPlugins(): array + { + return [ + new OrderAmendmentQuoteRequestValidatorPlugin(), + ]; + } + + /** + * @return list<\Spryker\Zed\QuoteRequestExtension\Dependency\Plugin\QuoteRequestUserValidatorPluginInterface> + */ + protected function getQuoteRequestUserValidatorPlugins(): array + { + return [ + new OrderAmendmentQuoteRequestUserValidatorPlugin(), + ]; + } +} +``` + +**src/Pyz/Zed/CartReorder/CartReorderDependencyProvider.php** + +```php + + */ + protected function getCartReorderValidatorPluginsForOrderAmendment(): array + { + return [ + new OriginalSalesOrderItemCartPreReorderPlugin(), + new QuoteRequestVersionCartReorderValidatorPlugin(), + ]; + } + + /** + * @return list<\Spryker\Zed\CartReorderExtension\Dependency\Plugin\CartReorderPreAddToCartPluginInterface> + */ + protected function getCartReorderPreAddToCartPluginsForOrderAmendment(): array + { + return [ + new RemoveInactiveProductOptionItemsCartReorderPreAddToCartPlugin(), + ]; + } +} +``` + +{% info_block warningBox "Verification" %} + +Verify that reordering is disabled for orders created from a quote request: + +1. Create a request for quote. +2. As an agent, approve the quote request. +3. Place an order that was converted from the request. +4. Try to reorder the order. + Make sure the error message is displayed: `You cannot reorder this order because it is in the amendment process.`. + +{% endinfo_block %} + +## Enable order editing by company users + +Take the steps in the following sections to enable order editing by company users. + +### 1) Install the required modules + +Install the required modules using Composer: + +```bash +composer require spryker/company-business-unit-sales-connector: "^1.3.0" spryker/company-sales-connector: "^1.3.0" --update-with-dependencies +``` + +{% info_block warningBox "Verification" %} + +Make sure that the following modules have been installed: + +| MODULE | EXPECTED DIRECTORY | +|-----------------------------------|------------------------------------------------------| +| CompanyBusinessUnitSalesConnector | vendor/spryker/company-business-unit-sales-connector | +| CompanySalesConnector | vendor/spryker/company-sales-connector | + +{% endinfo_block %} + +### 2) Add translations + +1. Append glossary according to your configuration: + + +**>src/data/import/glossary.csv** + +```yaml +permission.name.EditCompanyOrdersPermissionPlugin,Edit Company orders,en_US +permission.name.EditCompanyOrdersPermissionPlugin,Edit Company orders,de_DE +permission.name.EditBusinessUnitOrdersPermissionPlugin,Edit Business unit orders,en_US +permission.name.EditBusinessUnitOrdersPermissionPlugin,Edit Business unit orders,de_DE +``` + + + +2. Import data: + +```bash +console data:import glossary +``` + +### 3) Set up behavior + +Enable the following behaviors by registering the plugins: + +| PLUGIN | SPECIFICATION | PREREQUISITES | NAMESPACE | +|---------------------------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------|---------------|--------------------------------------------------------------------------------| +| EditCompanyOrdersPermissionPlugin | Adds a permission for company users to edit orders from the same company in the Client layer. | | Spryker\Client\CompanySalesConnector\Plugin\Permission | +| EditCompanyOrdersPermissionPlugin | Adds a permission for company users to edit orders from the same company in the Zed layer. | | Spryker\Zed\CompanySalesConnector\Communication\Plugin\Permission | +| EditBusinessUnitOrdersPermissionPlugin | Adds a permission for company users to edit orders from the same business unit in the Client layer. | | Spryker\Client\CompanyBusinessUnitSalesConnector\Plugin\Permission | +| EditBusinessUnitOrdersPermissionPlugin | Adds a permission for company users to edit orders from the same business unit in the Zed layer. | | Spryker\Zed\CompanyBusinessUnitSalesConnector\Communication\Plugin\Permission | +| EditCompanyOrderCartReorderOrderProviderPlugin | Provides an order if `CartReorderRequestTransfer.companyUserTransfer` has the permission to edit company orders. | | Spryker\Zed\CompanySalesConnector\Communication\Plugin\CartReorder | +| EditBusinessUnitOrderCartReorderOrderProviderPlugin | Provides an order if `CartReorderRequestTransfer.companyUserTransfer` has the permission to edit business unit orders. | | Spryker\Zed\CompanyBusinessUnitSalesConnector\Communication\Plugin\CartReorder | +| EditCompanyOrderQuoteExpanderCheckoutPreSavePlugin | Expands `QuoteTransfer` with original order if `QuoteTransfer.customer.companyUserTransfer` has the permission to edit company orders. | | Spryker\Zed\CompanySalesConnector\Communication\Plugin\Checkout | +| EditBusinessUnitOrderQuoteExpanderCheckoutPreSavePlugin | Expands `QuoteTransfer` with original order if `QuoteTransfer.customer.companyUserTransfer` has the permission to edit business unit orders. | | Spryker\Zed\CompanyBusinessUnitSalesConnector\Communication\Plugin\Checkout | + +**src/Pyz/Client/Permission/PermissionDependencyProvider.php** + +```php + + */ + protected function getPermissionPlugins(): array + { + return [ + new EditCompanyOrdersPermissionPlugin(), + new EditBusinessUnitOrdersPermissionPlugin(), + ]; + } +} +``` + +**src/Pyz/Zed/Permission/PermissionDependencyProvider.php** + +```php + + */ + protected function getPermissionPlugins(): array + { + return [ + new EditCompanyOrdersPermissionPlugin(), + new EditBusinessUnitOrdersPermissionPlugin(), + ]; + } +} +``` + +3. Execute registered installer: + + +```bash +console setup:init-db +``` + +{% info_block warningBox "Verification" %} + +1. Log in as a company admin. +2. Go to `https://www.mysprykershop.com/en/company/company-role`. +3. Click **Edit** next to a role. + Make sure you can assign the **Edit Company orders** and **Edit Business unit orders** permissions. + +{% endinfo_block %} + +**src/Pyz/Zed/CartReorder/CartReorderDependencyProvider.php** + +```php + + */ + protected function getCartReorderOrderProviderPlugins(): array + { + return [ + new EditCompanyOrderCartReorderOrderProviderPlugin(), + new EditBusinessUnitOrderCartReorderOrderProviderPlugin(), + ]; + } +} +``` + +**src/Pyz/Glue/CartReorderRestApi/CartReorderRestApiDependencyProvider.php** + +```php + + */ + protected function getCartReorderRequestExpanderPlugins(): array + { + return [ + new CompanyUserCompanyCartReorderRequestExpanderPlugin(), + new CompanyUserCompanyBusinessUnitCartReorderRequestExpanderPlugin(), + ]; + } +} +``` + +**src/Pyz/Zed/Checkout/CheckoutDependencyProvider.php** + +```php + + */ + protected function getCheckoutPreSaveHooksForOrderAmendment(Container $container): array + { + return [ + new EditCompanyOrderQuoteExpanderCheckoutPreSavePlugin(), + new EditBusinessUnitOrderQuoteExpanderCheckoutPreSavePlugin(), + ]; + } +} +``` + +{% info_block warningBox "Verification" %} + +1. Place an order as a company user. +3. Log in as a different company user from the same company and business unit. +4. Go to `https://www.mysprykershop.com/en/company/company-role`. +5. Click **Edit** next to a role for your user. +6. Assign the **Edit Company orders**, **Edit Business unit orders**, **View Company orders** and **View Business Unit orders** permissions to the role. +7. Re-login as the same user. +8. Go to `https://www.mysprykershop.com/en/customer/order`. +9. Click **Company orders**. +10. Click **Edit order** for an order from the same company or business unit. +Make sure the order amendment starts correctly. +11. Change the order. Make sure the order can be placed successfully. + +{% endinfo_block %} + +## Optionally: Enable order amendment in asynchronous mode + +Order amendment can be enabled in asynchronous mode to improve performance by offloading the most resource-intensive operations to the OMS. + +### 1) Install the required modules + +Some of the Async Order Amendment functionality is provided by an example module. You can install it to see how it works in practice and replace it with your own implementation if needed. + +Install the OrderAmendmentExample module using Composer: + +```bash +composer require spryker/order-amendment-example: "^0.3.0" --update-with-dependencies +``` + +{% info_block warningBox "Verification" %} + +Make sure that the following modules have been installed: + +| MODULE | EXPECTED DIRECTORY | +|-----------------------|----------------------------------------| +| OrderAmendmentExample | vendor/spryker/order-amendment-example | + +{% endinfo_block %} + +### 2) Set up configuration + +1. Add the following configuration: + +```php + + */ + public function getQuoteFieldsAllowedForSaving(): array + { + return array_merge(parent::getQuoteFieldsAllowedForSaving(), [ + QuoteTransfer::CUSTOMER, + QuoteTransfer::CUSTOMER_REFERENCE, + QuoteTransfer::STORE, + QuoteTransfer::PAYMENT, + QuoteTransfer::PAYMENTS, + QuoteTransfer::BILLING_ADDRESS, + QuoteTransfer::SHIPPING_ADDRESS, + QuoteTransfer::ORDER_CUSTOM_REFERENCE, + QuoteTransfer::SHIPMENT, + QuoteTransfer::ERRORS, + ]); + } +} +``` + +2. Remove the quote fields that are not relevant for your project. + +{% info_block warningBox "Verification" %} + +Make sure `SalesOrderAmendmentQuoteCheckoutDoSaveOrderPlugin` saves the specified fields to `spy_sales_order_amendment_quote`. + +{% endinfo_block %} + +#### Configure OMS + +1. Create the async Order amendment OMS subprocess file using the example: + +
+ config/Zed/oms/DummySubprocess/DummyOrderAmendmentAsync01.xml + +```xml + + + + + + + amendment in progress + + + + amendment in progress + + + + amendment in progress + + + + amendment in progress + + + + amendment in progress + + + + + + + order amendment draft pending + order amendment draft + + + + order amendment draft + order amendment draft applied + apply-order-amendment-draft + + + + order amendment draft applied + draft apply succeeded + + + + order amendment draft applied + draft apply failed + + + + draft apply succeeded + grace period pending + notify-order-amendment-applied + + + + draft apply failed + grace period pending + notify-order-amendment-failed + + + + order amendment + order amendment draft pending + start-order-amendment-draft + + + + + + + + + + + + + +``` + +
+ +2. Adjust your OMS state machine configuration according to your project's requirements. + +
config/Zed/oms/DummyPayment01.xml + +```xml + + + + + + DummyOrderAmendmentAsync + + + + + + + +``` + +
+ +{% info_block warningBox "Verification" %} + +1. In the Back Office, go to **Administration > OMS**. + +2. Select **DummyPayment01 [preview-version]** and make sure the `order amendment draft pending` state exists. + +{% endinfo_block %} + +### 3) Add translations + +1. Append glossary according to your configuration: + + +
src/data/import/glossary.csv + +```yaml +sales_order_amendment_oms.mail.order_amendment_applied.subject,Your order has been successfully updated,en_US +sales_order_amendment_oms.mail.order_amendment_applied.subject,Ihre Bestellung wurde erfolgreich aktualisiert,de_DE +sales_order_amendment_oms.mail.order_amendment_applied.salutation,Hello,en_US +sales_order_amendment_oms.mail.order_amendment_applied.salutation,Hallo,de_DE +sales_order_amendment_oms.mail.order_amendment_applied.title,Your order has been successfully updated,en_US +sales_order_amendment_oms.mail.order_amendment_applied.title,Ihre Bestellung wurde erfolgreich aktualisiert,de_DE +sales_order_amendment_oms.mail.order_amendment_applied.text.line_1,Thank you for shopping at Spryker Shop!,en_US +sales_order_amendment_oms.mail.order_amendment_applied.text.line_1,Danke für deine Bestellung beim Spryker Shop!,de_DE +sales_order_amendment_oms.mail.order_amendment_applied.text.line_2,We are writing to let you know that your order has been successfully updated as requested. You will receive a shipping confirmation by e-mail as soon as your updated order has been sent.,en_US +sales_order_amendment_oms.mail.order_amendment_applied.text.line_2,"Wir möchten Sie darüber informieren, dass Ihre Bestellung wie gewünscht erfolgreich aktualisiert wurde. Sobald Ihre aktualisierte Bestellung versendet wurde, erhalten Sie eine Versandbestätigung per E-Mail.",de_DE +sales_order_amendment_oms.mail.order_amendment_applied.text.line_3,"If you change your mind, you can return the items within 14 days after delivery. We hope you enjoy your purchase!",en_US +sales_order_amendment_oms.mail.order_amendment_applied.text.line_3,"Falls Sie es sich anders überlegen, können Sie die Artikel innerhalb von 14 Tagen nach Lieferung zurücksenden. Wir wünschen Ihnen viel Freude mit Ihrem Einkauf!",de_DE +sales_order_amendment_oms.mail.order_amendment_failed.subject,Order edit could not be saved,en_US +sales_order_amendment_oms.mail.order_amendment_failed.subject,Bestelländerung konnte nicht gespeichert werden,de_DE +sales_order_amendment_oms.mail.order_amendment_failed.salutation,Hello,en_US +sales_order_amendment_oms.mail.order_amendment_failed.salutation,Hallo,de_DE +sales_order_amendment_oms.mail.order_amendment_failed.title,Order edit could not be saved,en_US +sales_order_amendment_oms.mail.order_amendment_failed.title,Bestelländerung konnte nicht gespeichert werden,de_DE +sales_order_amendment_oms.mail.order_amendment_failed.text.line_1,Thank you for shopping at Spryker Shop!,en_US +sales_order_amendment_oms.mail.order_amendment_failed.text.line_1,Danke für deine Bestellung beim Spryker Shop!,de_DE +sales_order_amendment_oms.mail.order_amendment_failed.text.line_2,"We are writing to let you know that we tried to update your order as requested. Unfortunately, the changes could not be saved due to the following error:",en_US +sales_order_amendment_oms.mail.order_amendment_failed.text.line_2,"Wir möchten Sie darüber informieren, dass wir versucht haben, Ihre Bestellung wie gewünscht zu aktualisieren. Leider konnten die Änderungen aufgrund des folgenden Fehlers nicht gespeichert werden:",de_DE +sales_order_amendment_oms.mail.order_amendment_failed.text.line_3,"Your original order remains unchanged. If you need help or would like to try again, please contact our customer service team. We’re happy to assist you.",en_US +sales_order_amendment_oms.mail.order_amendment_failed.text.line_3,"Ihre ursprüngliche Bestellung bleibt unverändert. Wenn Sie Hilfe benötigen oder es erneut versuchen möchten, wenden Sie sich bitte an unser Kundenservice — wir helfen Ihnen gerne weiter.",de_DE +sales_order_amendment_oms.mail.footer.text.line_1,Viele Grüße,de_DE +sales_order_amendment_oms.mail.footer.text.line_1,Have a great day!,en_US +sales_order_amendment_oms.mail.footer.text.line_2,Dein Spryker Shop,de_DE +sales_order_amendment_oms.mail.footer.text.line_2,Your Spryker Shop,en_US +sales_order_amendment_oms.error.apply_order_amendment_draft_failed,We could not process your order edit.,en_US +sales_order_amendment_oms.error.apply_order_amendment_draft_failed,Ihre Bestelländerung konnte nicht bearbeitet werden.,de_DE +oms.state.order-amendment-draft-pending,Editing in Progress,en_US +oms.state.order-amendment-draft-pending,Bestelländerung in Bearbeitung,de_DE +oms.state.order-amendment-draft-applied,Editing in Progress,en_US +oms.state.order-amendment-draft-applied,Bestelländerung in Bearbeitung,de_DE +``` + +
+ + +2. Import data: + +```bash +console data:import glossary +``` + +{% info_block warningBox "Verification" %} + +Make sure that, in the database, the configured data has been added to the `spy_glossary` table. + +{% endinfo_block %} + +### 4) Set up behavior + +Enable the following behaviors by registering the plugins: + +| PLUGIN | SPECIFICATION | PREREQUISITES | NAMESPACE | +|---------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------|---------------|------------------------------------------------------------------| +| QuoteToSaveOrderMapperCheckoutDoSaveOrderPlugin | Maps an original order from `QuoteTransfer.originalOrder` to `SaveOrderTransfer`. | | Spryker\Zed\SalesOrderAmendment\Communication\Plugin\Checkout | +| StartOrderAmendmentDraftCheckoutPostSavePlugin | Triggers the OMS event to start the order amendment draft. | | Spryker\Zed\SalesOrderAmendmentOms\Communication\Plugin\Checkout | +| NotifyOrderAmendmentAppliedMailTypeBuilderPlugin | Builds `MailTransfer` with data for the `notify order amendment applied` email. | | Spryker\Zed\SalesOrderAmendmentOms\Communication\Plugin\Mail | +| NotifyOrderAmendmentFailedMailTypeBuilderPlugin | Builds `MailTransfer` with data for the `notify order amendment failed` email. | | Spryker\Zed\SalesOrderAmendmentOms\Communication\Plugin\Mail | +| ApplyOrderAmendmentDraftCommandByOrderPlugin | Places an order with a found sales order amendment quote and quote process flow set to `order-amendment`. | | Spryker\Zed\OrderAmendmentExample\Communication\Plugin\Oms | +| NotifyOrderAmendmentAppliedCommandPlugin | When a sales order amendment quote is found, sends an email notification about successfully applying order amendment. | | Spryker\Zed\SalesOrderAmendmentOms\Communication\Plugin\Oms | +| NotifyOrderAmendmentFailedCommandPlugin | If a sales order amendment quote is found, sends an email notification about failing order amendment. | | Spryker\Zed\SalesOrderAmendmentOms\Communication\Plugin\Oms | +| IsOrderAmendmentDraftSuccessfullyAppliedConditionPlugin | Returns `true` if the sales order amendment quote is not found; otherwise returns `false`. | | Spryker\Zed\SalesOrderAmendmentOms\Communication\Plugin\Oms | +| ShipmentGroupsSalesOrderAmendmentQuoteExpanderPlugin | Expands each `SalesOrderAmendmentQuoteTransfer` in `SalesOrderAmendmentQuoteCollectionTransfer.salesOrderAmendmentQuotes` with shipment groups data. | | Spryker\Zed\Shipment\Communication\Plugin\SalesOrderAmendment | + +
+ src/Pyz/Zed/Checkout/CheckoutDependencyProvider.php + +```php + + */ + protected function getCheckoutOrderSaversForOrderAmendmentAsync(Container $container): array // phpcs:ignore SlevomatCodingStandard.Functions.UnusedParameter + { + return [ + new QuoteToSaveOrderMapperCheckoutDoSaveOrderPlugin(), #Order Amendment Feature + new SalesOrderAmendmentQuoteCheckoutDoSaveOrderPlugin(), #Order Amendment Feature + ]; + } + + /** + * @param \Spryker\Zed\Kernel\Container $container + * + * @return list<\Spryker\Zed\CheckoutExtension\Dependency\Plugin\CheckoutPostSaveInterface> + */ + protected function getCheckoutPostHooksForOrderAmendmentAsync(Container $container): array // phpcs:ignore SlevomatCodingStandard.Functions.UnusedParameter + { + return [ + new StartOrderAmendmentDraftCheckoutPostSavePlugin(), #Order Amendment Feature + ]; + } +} +``` + +
+ +
+ src/Pyz/Zed/Mail/MailDependencyProvider.php + +```php + + */ + protected function getMailTypeBuilderPlugins(): array + { + return [ + new NotifyOrderAmendmentAppliedMailTypeBuilderPlugin(), + new NotifyOrderAmendmentFailedMailTypeBuilderPlugin(), + ]; + } +} +``` + +
+ +
+ src/Pyz/Zed/Oms/OmsDependencyProvider.php + +```php +extend(self::COMMAND_PLUGINS, function (CommandCollectionInterface $commandCollection) { + $commandCollection->add(new ApplyOrderAmendmentDraftCommandByOrderPlugin(), 'OrderAmendmentAsync/ApplyOrderAmendmentDraft'); + $commandCollection->add(new NotifyOrderAmendmentAppliedCommandPlugin(), 'OrderAmendmentAsync/NotifyOrderAmendmentApplied'); + $commandCollection->add(new NotifyOrderAmendmentFailedCommandPlugin(), 'OrderAmendmentAsync/NotifyOrderAmendmentFailed'); + + return $commandCollection; + }); + + return $container; + } + + /** + * @param \Spryker\Zed\Kernel\Container $container + * + * @return \Spryker\Zed\Kernel\Container + */ + protected function extendConditionPlugins(Container $container): Container // phpcs:ignore SlevomatCodingStandard.Functions.UnusedParameter + { + $container->extend(self::CONDITION_PLUGINS, function (ConditionCollectionInterface $conditionCollection) { + $conditionCollection + ->add(new IsOrderAmendmentDraftSuccessfullyAppliedConditionPlugin(), 'DummyOrderAmendmentAsync/IsSuccessfullyApplied'); + + return $conditionCollection; + }); +} +``` + +
+ +
+ src/Pyz/Zed/SalesOrderAmendment/SalesOrderAmendmentDependencyProvider.php + +```php + + */ + protected function getSalesOrderAmendmentQuoteExpanderPlugins(): array + { + return [ + new ShipmentGroupsSalesOrderAmendmentQuoteExpanderPlugin(), + ]; + } +} +``` + +
+ + +### Enable asynchronous order amendment + +You can set up asynchronous order amendment in two ways: + +1. Conditionally: The standard order amendment flow starts first, then switches to the asynchronous flow based on specific conditions. +2. Unconditionally: The asynchronous flow runs from the start. + +Follow the instructions in the following sections according to how you want to set it up. + +#### Option 1: Enable async order amendment conditionally + +The Example module lets you enable the asynchronous order amendment flow based on the selected payment method. To configure this behavior, follow the steps: + +1. Enable the following behaviors by registering the plugins: + +| PLUGIN | SPECIFICATION | PREREQUISITES | NAMESPACE | +|-------------------------------------------------------|------------------------------------------------------------------------------------------------------------------|---------------|-----------------------------------------------------------------| +| PaymentToAsyncOrderAmendmentFlowCheckoutPreSavePlugin | Sets `QuoteTransfer.quoteProcessFlow` to a new `QuoteProcessFlowTransfer` with the `order-amendment-async` name. | | Spryker\Zed\OrderAmendmentExample\Communication\Plugin\Checkout | + +**src/Pyz/Zed/Checkout/CheckoutDependencyProvider.php** + +```php + + */ + protected function getCheckoutPreSaveHooksForOrderAmendment(Container $container): array + { + return [ + new PaymentToAsyncOrderAmendmentFlowCheckoutPreSavePlugin(), + ]; + } +} +``` + + +2. Specify the payment methods to enable the asynchronous order amendment checkout process flow for: + +**src/Pyz/Zed/OrderAmendmentExample/OrderAmendmentExampleConfig.php** + +```php + + */ + protected const ASYNC_ORDER_AMENDMENT_PAYMENT_METHOD_NAMES = [ + 'dummyPaymentInvoice', + ]; +} +``` + +#### Option 2: Enable async order amendment unconditionally + +1. Specify the order amendment quote process flow: + +**src/Pyz/Zed/SalesOrderAmendment/SalesOrderAmendmentConfig.php** + +```php +setName(SalesOrderAmendmentExtensionContextsInterface::CONTEXT_ORDER_AMENDMENT_ASYNC); + } +} +``` + +2. Enable plugins for the asynchronous order amendment checkout process flow: + +Make sure all the needed plugins registered for the `order-amendment` checkout process flow are also registered for the `order-amendment-async` checkout process flow. + +Replace dependency provider methods postfixed with `ForOrderAmendment` with `ForOrderAmendmentAsync` methods in the following modules: +- `Cart` +- `CartReorder` +- `Checkout` +- `CheckoutRestApi` +- `Sales` + + +{% info_block warningBox "Verification" %} + +1. Place an order. +2. Initiate and finish order amendment. Make sure the following applies: +- The order doesn't show the changes you've submitted. +- The quote has been saved to the `spy_sales_order_amendment_quote` table. +- The order items are in the `order amendment draft pending` state. +3. Execute `console oms:check-condition` command. +- Make sure the order items are in the `order amendment draft applied` state. +- Make sure the changes made in the order have been applied to the order. +- Make sure an email notification about order amendment has been sent. + +{% endinfo_block %} + +#### Optional: Project level customizations + +- Display errors: Display errors appearing during the `ApplyOrderAmendmentDraftCommandByOrderPlugin` execution. If any errors occur, `ApplyOrderAmendmentDraftCommandByOrderPlugin` saves them to `spy_sales_order_amendment_quote` table to the `quote_data` with the other Quote data. You can obtain them from the Quote and display in the frontend. +- Customize email templates: Customize email templates for the order amendment applied and failed notifications by redefining Twig templates: + - `notify-order-amendment-applied.html.twig` + - `notify-order-amendment-applied.text.twig` + - `notify-order-amendment-failed.html.twig` + - `notify-order-amendment-failed.text.twig` +- Customize the OMS process: you can customize you OMS processes to add more states and transitions, for example, to add a state and transition to implement the retry logic for the order amendment draft applying in case of errors. + +## Install feature frontend + +Take the following steps to install the feature frontend. + +### Prerequisites + +Install the following required features: + +| NAME | VERSION | INSTALLATION GUIDE | +|------------------|------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| Spryker Core | {{page.release_tag}} | [Install the Spryker Core feature](/docs/pbc/all/miscellaneous/latest/install-and-upgrade/install-features/install-the-spryker-core-feature.html) | +| Order Management | {{page.release_tag}} | [Install the Order Management feature](/docs/pbc/all/order-management-system/latest/base-shop/install-and-upgrade/install-features/install-the-order-management-feature.html) | + +### 1) Install the required modules + +Install the required modules using Composer: + +```bash +composer require spryker-feature/order-amendment: "{{page.release_tag}}" --update-with-dependencies +``` + +{% info_block warningBox "Verification" %} + +Make sure the following modules have been installed: + +| MODULE | EXPECTED DIRECTORY | +|-------------------------------|--------------------------------------------------| +| SalesOrderAmendmentWidget | vendor/spryker-shop/sales-order-amendment-widget | + +{% endinfo_block %} + +### 2) Set up configuration + +Add the following configuration: + +| CONFIGURATION | SPECIFICATION | NAMESPACE | +|--------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|------------------------------------| +| SalesOrderAmendmentWidgetConfig::ORDER_AMENDMENT_CART_REORDER_STRATEGY | Defines the cart reorder strategy for order amendment, for example `replace`, `new`. The corresponding strategy plugin handling the specified value must be registered in the project. | Pyz\Yves\SalesOrderAmendmentWidget | +| SalesOrderAmendmentWidgetConfig::IS_ORDER_AMENDMENT_CONFIRMATION_ENABLED | Defines if the order amendment confirmation popup window is displayed. | Pyz\Yves\SalesOrderAmendmentWidget | + +**src/Pyz/Yves/SalesOrderAmendmentWidget/SalesOrderAmendmentWidgetConfig.php** + +```php + + */ + protected function getRouteProvider(): array + { + return [ + new SalesOrderAmendmentWidgetRouteProviderPlugin(), + ]; + } +} +``` + +{% info_block warningBox "Verification" %} + +Make sure order amendment is available on order details and orders pages. + +{% endinfo_block %} + +### 5) Set up widgets + +To enable widgets, register the following plugins: + +| PLUGIN | SPECIFICATION | PREREQUISITES | NAMESPACE | +|-------------------------------------------|---------------------------------------------------------------------|---------------|---------------------------------------------------| +| OrderAmendmentWidget | Enables customers to edit existing orders. | | SprykerShop\Yves\SalesOrderAmendmentWidget\Widget | +| CancelOrderAmendmentWidget | Enables customers to cancel order amendment requests. | | SprykerShop\Yves\SalesOrderAmendmentWidget\Widget | +| OrderAmendmentItemLinkWidget | Handles URL generation for deactivated products in order amendment. | | SprykerShop\Yves\SalesOrderAmendmentWidget\Widget | +| UpdateOrderCheckoutSubmitButtonTextWidget | Displays the text for the submit order update button. | | SprykerShop\Yves\SalesOrderAmendmentWidget\Widget | +| UpdateOrderCheckoutSuccessTitleWidget | Displays the title for the successful order update page. | | SprykerShop\Yves\SalesOrderAmendmentWidget\Widget | + +**src/Pyz/Yves/ShopApplication/ShopApplicationDependencyProvider.php** + +```php + + */ + protected function getGlobalWidgets(): array + { + return [ + OrderAmendmentWidget::class, + CancelOrderAmendmentWidget::class, + OrderAmendmentItemLinkWidget::class, + UpdateOrderCheckoutSubmitButtonTextWidget::class, + UpdateOrderCheckoutSuccessTitleWidget::class, + ]; + } +} +``` + +{% info_block warningBox "Widgets in Twig" %} + +If your project uses Twig templates, make sure the corresponding widgets are used in the redefined templates. + +{% endinfo_block %} + +{% info_block warningBox "Verification" %} + +Make sure the following widgets have been registered: + +| MODULE | TEST | +|-------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| OrderAmendmentWidget | Make sure the edit order button is displayed on the orders and order details pages. | +| CancelOrderAmendmentWidget | Make sure the cancel order amendment button is displayed on the Cart page. | +| OrderAmendmentItemLinkWidget | Make sure that, on the Cart page, product URLs are not displayed for deactivated products. | +| UpdateOrderCheckoutSubmitButtonTextWidget | Make sure that, on the Checkout summary page, the submit button text is displayed as configured for the `sales_order_amendment_widget.summary_step.update.order` glossary key. | +| UpdateOrderCheckoutSuccessTitleWidget | Make sure that, on the Successful order update page, the title is displayed as configured for the `sales_order_amendment_widget.success_step.update.success.title` glossary key. | + +{% endinfo_block %} + +{% info_block warningBox "Verification" %} + +- Make sure that after clicking the edit order button the specified reorder strategy for order amendment is applied (the current cart items are replaced by the amended order items in case the `replace` strategy is applied, new cart is created in case the `new` strategy is applied). + +- Ensure that clicking the "Edit Order" button applies the specified reorder strategy for order amendment: + - `replace` strategy: current cart items are replaced with amended order items + - `new` strategy: a new cart is created +- If the `IS_ORDER_AMENDMENT_CONFIRMATION_ENABLED` configuration is set to `true`, make sure that the order amendment confirmation popup window is displayed. + +{% endinfo_block %} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/fixtures/guides/ssp-asset-management.txt b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/fixtures/guides/ssp-asset-management.txt new file mode 100644 index 0000000..cfbd859 --- /dev/null +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/fixtures/guides/ssp-asset-management.txt @@ -0,0 +1,1448 @@ +This document describes how to install the Self-Service Portal (SSP) Asset Management feature. + +{% info_block warningBox "Install all SSP features" %} + +For the Self-Service Portal to work correctly, you must install all SSP features. Each feature depends on the others for proper functionality. + +{% endinfo_block %} + +## Features SSP Asset Management depends on + +- [Install the SSP Dashboard Management feature](/docs/pbc/all/self-service-portal/latest/install/install-the-ssp-dashboard-management-feature.html) +- [Install the SSP File Management feature](/docs/pbc/all/self-service-portal/latest/install/install-the-ssp-file-management-feature.html) +- [Install the SSP Inquiry Management feature](/docs/pbc/all/self-service-portal/latest/install/install-the-ssp-inquiry-management-feature.html) +- [Install the SSP Model Management feature](/docs/pbc/all/self-service-portal/latest/install/install-the-ssp-model-management-feature.html) +- [Install the SSP Service Management feature](/docs/pbc/all/self-service-portal/latest/install/install-the-ssp-service-management-feature.html) +- [Install the Asset-Based Catalog feature](/docs/pbc/all/self-service-portal/latest/install/install-the-ssp-asset-based-catalog-feature.html) + +## Prerequisites + +| FEATURE | VERSION | INSTALLATION GUIDE | +|--------------|----------| ------------------ | +| Spryker Core | {{page.release_tag}} | [Install the Spryker Core feature](/docs/pbc/all/miscellaneous/latest/install-and-upgrade/install-features/install-the-spryker-core-feature.html) | +| Self-Service Portal | {{page.release_tag}} | [Install Self-Service Portal](/docs/pbc/all/self-service-portal/latest/install/install-self-service-portal) | + +## Install the required modules + +Install the required modules using Composer: + +```bash +composer require spryker-feature/self-service-portal:"^{{page.release_tag}}" --update-with-dependencies +``` + +{% info_block warningBox "Verification" %} + +Make sure the following packages are now listed in `composer.lock`: + +| MODULE | EXPECTED DIRECTORY | +|-------------------|--------------------------------------------| +| SelfServicePortal | vendor/spryker-feature/self-service-portal | + +{% endinfo_block %} + +## Set up configuration + +| CONFIGURATION | SPECIFICATION | NAMESPACE | +|------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------| +| FileSystemConstants::FILESYSTEM_SERVICE | Defines the Flysystem service configuration for handling asset file storage. This configuration specifies the adapter, such as local or S3, and the root path for storing asset files, ensuring they're managed securely and efficiently. | Spryker\Shared\FileSystem | +| SelfServicePortalConstants::BASE_URL_YVES | Specifies the base URL for the Yves frontend. This URL is used to generate absolute links to asset-related pages on the Storefront, ensuring correct navigation and resource loading. | SprykerFeature\Shared\SelfServicePortal | +| SelfServicePortalConstants::ASSET_STORAGE_NAME | Defines the unique identifier for the Flysystem storage instance used for SSP assets. This name links the asset management feature to the specific filesystem configuration defined in `FileSystemConstants::FILESYSTEM_SERVICE`. | SprykerFeature\Zed\SelfServicePortal | +| SelfServicePortalConstants::DEFAULT_FILE_MAX_SIZE | Defines the default file max size per file upload during ssp asset creation and update. | SprykerFeature\Zed\SelfServicePortal | +| KernelConstants::CORE_NAMESPACES | Defines the core namespaces. | Spryker\Shared\Kerne | +| SelfServicePortalConfig::getAssetStatusClassMap() | Defines a map that associates asset status values, such as `pending` or `approved`, with their corresponding CSS class names. This is used in the Back Office and Storefront to visually represent the status of each asset, for example, with colored labels. | SprykerFeature\Zed\SelfServicePortal | +| SelfServicePortalConfig::QUEUE_NAME_SYNC_STORAGE_SSP_ASSET | Defines queue name as used for processing SSP asset storage messages. | SprykerFeature\Shared\SelfServicePortal | +| SelfServicePortalConfig::QUEUE_NAME_SYNC_SEARCH_SSP_ASSET | Defines queue name as used for processing ssp asset search synchronization. | SprykerFeature\Shared\SelfServicePortal | + +**config/Shared/config_default.php** + +To enable an IAM role configuration, use `IamAws3v3FilesystemBuilderPlugin`: + +```php +use Spryker\Shared\FileSystem\FileSystemConstants; +use SprykerFeature\Shared\SelfServicePortal\SelfServicePortalConstants; +use Spryker\Service\FlysystemAws3v3FileSystem\Plugin\Flysystem\IamAws3v3FilesystemBuilderPlugin; + +$config[FileSystemConstants::FILESYSTEM_SERVICE] = [ + 'ssp-asset-image' => [ + 'sprykerAdapterClass' => IamAws3v3FilesystemBuilderPlugin::class, + 'bucket' => getenv('SPRYKER_S3_SSP_ASSETS_BUCKET') ?: '', + 'region' => getenv('AWS_REGION') ?: '', + 'path' => '/ssp-asset-image', + ], +]; + +$config[SelfServicePortalConstants::BASE_URL_YVES] = 'https://your-yves-url'; +$config[SelfServicePortalConstants::ASSET_STORAGE_NAME] = 'ssp-asset-image'; +$config[SelfServicePortalConstants::DEFAULT_FILE_MAX_SIZE] = getenv('SPRYKER_SSP_DEFAULT_FILE_MAX_SIZE') ?: '10M'; + +$config[KernelConstants::CORE_NAMESPACES] = [ + ... + 'SprykerFeature', +]; +``` + +{% info_block warningBox "IAM authentication required" %} + +These buckets authenticate through the IAM role attached to the workload. Access keys (`key` and `secret`) are not supported. If your project was set up from older documentation using access keys, migrate to this configuration. For more details, see [AWS S3 filesystem builder plugins](/docs/dg/dev/backend-development/data-manipulation/data-ingestion/structural-preparations/flysystem.html#aws-s3-filesystem-builder-plugins). + +{% endinfo_block %} + +{% info_block infoBox "Cloud environment variables" %} + +In cloud environments, set the following environment variables: + +- `SPRYKER_S3_SSP_ASSETS_BUCKET` - AWS S3 bucket name for SSP assets storage +- `AWS_REGION` - AWS region +- `SPRYKER_SSP_DEFAULT_FILE_MAX_SIZE` - Maximum file size for SSP asset uploads (defaults to `10M` if not set) + +{% endinfo_block %} + +**src/Pyz/Zed/SelfServicePortal/SelfServicePortalConfig.php** + +```php + + */ + public function getAssetStatusClassMap(): array + { + return [ + 'pending' => 'label-warning', + 'in_review' => 'label-primary', + 'approved' => 'label-success', + 'deactivated' => 'label-danger', + ]; + } + + + /** + * @return string|null + */ + public function getSspAssetSearchSynchronizationPoolName(): ?string + { + return SynchronizationConfig::DEFAULT_SYNCHRONIZATION_POOL_NAME; + } +} +``` + +## Configure synchronization queues + +**src/Pyz/Client/RabbitMq/RabbitMqConfig.php** + +```php + + */ + protected function getSynchronizationQueueConfiguration(): array + { + return [ + SelfServicePortalConfig::QUEUE_NAME_SYNC_STORAGE_SSP_ASSET, + SelfServicePortalConfig::QUEUE_NAME_SYNC_SEARCH_SSP_ASSET, + ]; + } +} +``` + + +**src/Pyz/Zed/Queue/QueueDependencyProvider.php** + +```php + + */ + protected function getProcessorMessagePlugins(Container $container): array + { + return [ + SelfServicePortalConfig::QUEUE_NAME_SYNC_STORAGE_SSP_ASSET => new SynchronizationStorageQueueMessageProcessorPlugin(), + SelfServicePortalConfig::QUEUE_NAME_SYNC_SEARCH_SSP_ASSET => new SynchronizationSearchQueueMessageProcessorPlugin(), + ]; + } +} +``` + +Set up the queue infrastructure: + +```bash +vendor/bin/console queue:setup +``` + +{% info_block warningBox "Verification" %} +Make sure that, in the RabbitMQ management interface, the following queues are available: +- `sync.search.ssp_asset` +- `sync.search.ssp_asset.error` +- `sync.storage.ssp_asset` +- `sync.storage.ssp_asset.error` +{% endinfo_block %} + +## Configure ElasticSearch supported source indexes + +**src/Pyz/Shared/SearchElasticsearch/SearchElasticsearchConfig.php** + +```php + + */ + protected const SUPPORTED_SOURCE_IDENTIFIERS = [ + 'ssp_asset', + ]; +} +``` + +**src/Pyz/Zed/SearchElasticsearch/SearchElasticsearchConfig.php** + +```php + + */ + public function getJsonSchemaDefinitionDirectories(): array + { + $directories = parent::getJsonSchemaDefinitionDirectories(); + + $directory = sprintf('%s/vendor/spryker-feature/*/src/*/Shared/*/Schema/', APPLICATION_ROOT_DIR); + if (glob($directory, GLOB_NOSORT | GLOB_ONLYDIR)) { + $directories[] = $directory; + } + + $directories[] = sprintf('%s/src/Pyz/Shared/*/Schema/', APPLICATION_ROOT_DIR); + + return $directories; + } +} +``` + +**src/Pyz/Client/SelfServicePortal/SelfServicePortalDependencyProvider.php** + +```php + + */ + protected function getSspAssetSearchResultFormatterPlugins(): array + { + return [ + new SspAssetSearchResultFormatterPlugin(), + ]; + } + + /** + * @return list<\Spryker\Client\SearchExtension\Dependency\Plugin\QueryExpanderPluginInterface> + */ + protected function getSspAssetSearchQueryExpanderPlugins(): array + { + return [ + new SspAssetSearchQueryExpanderPlugin(), + ]; + } +} + +``` + +## Configure the event triggering for the Asset entity + +**src/Pyz/Zed/SelfServicePortal/Persistence/Propel/Schema/spy_ssp_asset.schema.xml** + +```xml + + + + + + + +
+ + + + + +
+ +
+``` + +## Set up database schema + +Apply schema updates: + +```bash +console propel:install +``` + +{% info_block warningBox "Verification" %} +Make sure the following tables have been created in the database: + +- `spy_ssp_asset` +- `spy_ssp_asset_file` +- `spy_ssp_asset_to_company_business_unit` +- `spy_sales_order_item_ssp_asset` +- `spy_ssp_asset_storage` +- `spy_ssp_asset_search` + +{% endinfo_block %} + +## Set up transfer objects + +Generate transfer classes: + +```bash +console transfer:generate +``` + +## Configure navigation + +Add the `Assets` section to `navigation.xml`: + +**config/Zed/navigation.xml** + +```xml + + + + + Customer Portal + fa-id-badge + + + + Assets + self-service-portal + list-asset + index + + + + +``` + +Generate routers and navigation cache: + +```bash +console router:cache:warm-up:backoffice +console navigation:build-cache +``` + +{% info_block warningBox "Verification" %} + +Make sure that, in the Back Office, the **Customer portal** > **Assets** section is available. + +{% endinfo_block %} + +## Set up behavior + +| PLUGIN | SPECIFICATION | PREREQUISITES | NAMESPACE | +|-------------------------------------------------------------|---------------------------------------------------------------------------------------------------------|---------------|-------------------------------------------------------------------------------------------| +| ViewCompanySspAssetPermissionPlugin | Grants permission to view assets of an entire company. | | SprykerFeature\Shared\SelfServicePortal\Plugin\Permission | +| ViewBusinessUnitSspAssetPermissionPlugin | Grants permission to view assets within the user's business unit. | | SprykerFeature\Shared\SelfServicePortal\Plugin\Permission | +| CreateSspAssetPermissionPlugin | Grants permission to create assets. | | SprykerFeature\Shared\SelfServicePortal\Plugin\Permission | +| UpdateSspAssetPermissionPlugin | Grants permission to update assets. | | SprykerFeature\Shared\SelfServicePortal\Plugin\Permission | +| UnassignSspAssetPermissionPlugin | Grants permission to unassign assets from business units. | | SprykerFeature\Shared\SelfServicePortal\Plugin\Permission | +| SelfServicePortalPageRouteProviderPlugin | Provides routes for the SSP asset management pages on the Storefront. | | SprykerFeature\Yves\SelfServicePortal\Plugin\Router | +| FileSizeFormatterTwigPlugin | Adds a Twig filter to format file sizes into a human-readable format. | | SprykerFeature\Yves\SelfServicePortal\Plugin\Twig | +| SspAssetPreAddToCartPlugin | When a product is added to cart, maps the asset reference from the request to the item transfer object. | | SprykerFeature\Yves\SelfServicePortal\Plugin\CartPage | +| SspAssetItemExpanderPlugin | Expands cart items with asset data. | | SprykerFeature\Zed\SelfServicePortal\Communication\Plugin\Cart | +| SspAssetOrderExpanderPlugin | Expands an order with asset data for all its items. | | SprykerFeature\Zed\SelfServicePortal\Communication\Plugin\Sales | +| SspAssetOrderItemsPostSavePlugin | After an order is placed, saves the relations between order items and assets. | | SprykerFeature\Zed\SelfServicePortal\Communication\Plugin\Sales | +| SspAssetOrderItemExpanderPlugin | Expands individual order items with asset data. | | SprykerFeature\Zed\SelfServicePortal\Communication\Plugin\Sales | +| SspAssetPublisherTriggerPlugin | Retrieves SSP assets by offset and limit. | | SprykerFeature\Zed\SelfServicePortal\Communication\Plugin\Publisher | +| SspAssetQueryExpanderPlugin | Expands search query with asset-specific product filtering based on SSP asset reference. | | SprykerFeature\Client\SelfServicePortal\Plugin\Catalog | +| SspAssetWritePublisherPlugin | Publishes SSP asset data by `SpySspAsset` entity events to the storage. | | SprykerFeature\Zed\SelfServicePortal\Communication\Plugin\Publisher\SspAsset\Search | +| SspAssetToCompanyBusinessUnitWritePublisherPlugin | Publishes SSP asset data by `SpySspAssetToCompanyBusinessUnit` entity events to the storage. | | SprykerFeature\Zed\SelfServicePortal\Communication\Plugin\Publisher\SspAsset\Search | +| SspAssetWritePublisherPlugin | Publishes SSP asset data by `SpySspAsset` entity events to the search engine. | | SprykerFeature\Zed\SelfServicePortal\Communication\Plugin\Publisher\SspAsset\Storage | +| SearchSspAssetToCompanyBusinessUnitWritePublisherPlugin | Publishes SSP asset data by `SpySspAssetToCompanyBusinessUnit` entity events to the search engine. | | SprykerFeature\Zed\SelfServicePortal\Communication\Plugin\Publisher\SspAsset\Storage | +| SspAssetListSynchronizationDataBulkRepositoryPlugin | Retrieves SSP assets by offset and limit for synchronization to a storage. | | SprykerFeature\Zed\SelfServicePortal\Communication\Plugin\Synchronization\Storage | +| SearchSspAssetListSynchronizationDataBulkRepositoryPlugin | Retrieves SSP assets by offset and limit for synchronization to a search engine. | | SprykerFeature\Zed\SelfServicePortal\Communication\Plugin\Synchronization\SspAsset\Search | + +**src/Pyz/Zed/Permission/PermissionDependencyProvider.php** + +```php + + */ + protected function getPermissionPlugins(): array + { + return [ + new ViewCompanySspAssetPermissionPlugin(), + new ViewBusinessUnitSspAssetPermissionPlugin(), + new UpdateSspAssetPermissionPlugin(), + new UnassignSspAssetPermissionPlugin(), + new CreateSspAssetPermissionPlugin(), + ]; + } +} +``` + +**src/Pyz/Client/Permission/PermissionDependencyProvider.php** + +```php + + */ + protected function getPermissionPlugins(): array + { + return [ + new ViewCompanySspAssetPermissionPlugin(), + new ViewBusinessUnitSspAssetPermissionPlugin(), + new UpdateSspAssetPermissionPlugin(), + new UnassignSspAssetPermissionPlugin(), + new CreateSspAssetPermissionPlugin(), + ]; + } +} +``` + +Enable new permission plugins + +```bash +console setup:init-db +``` + +**src/Pyz/Yves/Router/RouterDependencyProvider.php** + +```php + + */ + protected function getRouteProvider(): array + { + return [ + new SelfServicePortalPageRouteProviderPlugin(), + ]; + } +} +``` + +**src/Pyz/Yves/Twig/TwigDependencyProvider.php** + +```php + + */ + protected function getTwigPlugins(): array + { + return [ + new FileSizeFormatterTwigPlugin(), + ]; + } +} +``` + +**src/Pyz/Yves/CartPage/CartPageDependencyProvider.php** + +```php + + */ + protected function getPreAddToCartPlugins(): array + { + return [ + new SspAssetPreAddToCartPlugin(), + ]; + } +} +``` + +**src/Pyz/Zed/Cart/CartDependencyProvider.php** + +```php + + */ + protected function getExpanderPlugins(Container $container): array + { + return [ + new SspAssetItemExpanderPlugin(), + ]; + } +} +``` + +**src/Pyz/Zed/Sales/SalesDependencyProvider.php** + +```php + + */ + protected function getOrderHydrationPlugins(): array + { + return [ + new SspAssetOrderExpanderPlugin(), + ]; + } + + /** + * @return array<\Spryker\Zed\SalesExtension\Dependency\Plugin\OrderItemsPostSavePluginInterface> + */ + protected function getOrderItemsPostSavePlugins(): array + { + return [ + new SspAssetOrderItemsPostSavePlugin(), + ]; + } + + /** + * @return array<\Spryker\Zed\SalesExtension\Dependency\Plugin\OrderItemExpanderPluginInterface> + */ + protected function getOrderItemExpanderPlugins(): array + { + return [ + new SspAssetOrderItemExpanderPlugin(), + ]; + } +} +``` + +**src/Pyz/Zed/Publisher/PublisherDependencyProvider.php** + +```php +|array> + */ + protected function getPublisherPlugins(): array + { + return array_merge( + $this->getSspAssetStoragePlugins(), + $this->getSspAssetSearchPlugins(), + ); + } + + /** + * @return array<\Spryker\Zed\PublisherExtension\Dependency\Plugin\PublisherTriggerPluginInterface> + */ + protected function getPublisherTriggerPlugins(): array + { + return [ + new SspAssetPublisherTriggerPlugin(), + ]; + } + + /** + * @return array<\Spryker\Zed\PublisherExtension\Dependency\Plugin\PublisherPluginInterface> + */ + protected function getSspAssetStoragePlugins(): array + { + return [ + new SspAssetWritePublisherPlugin(), + new SspAssetToCompanyBusinessUnitWritePublisherPlugin(), + ]; + } + + /** + * @return array<\Spryker\Zed\PublisherExtension\Dependency\Plugin\PublisherPluginInterface> + */ + protected function getSspAssetSearchPlugins(): array + { + return [ + new SearchSspAssetWritePublisherPlugin(), + new SearchSspAssetToCompanyBusinessUnitWritePublisherPlugin(), + ]; + } +} +``` + + +**src/Pyz/Client/Catalog/CatalogDependencyProvider.php** + +```php +|array<\Spryker\Client\Search\Dependency\Plugin\QueryExpanderPluginInterface> + */ + protected function createCatalogSearchQueryExpanderPlugins(): array + { + return [ + new SspAssetQueryExpanderPlugin(), + ]; + } +} +``` + +**src/Pyz/Zed/Synchronization/SynchronizationDependencyProvider.php** + +```php + + */ + protected function getSynchronizationDataPlugins(): array + { + return [ + new SspAssetListSynchronizationDataBulkRepositoryPlugin(), + new SearchSspAssetListSynchronizationDataBulkRepositoryPlugin(), + ]; + } +} +``` + +Setup search updates + +```bash +console search:setup +``` + +### Set up widgets + +| PLUGIN | SPECIFICATION | PREREQUISITES | NAMESPACE | +|----------------------------|-----------------------------------------------------------------------------------------|---------------|----------------------------------------------| +| SspAssetListWidget | Renders a list of assets on the **My Assets** page in the Customer Account. | | SprykerFeature\Yves\SelfServicePortal\Widget | +| SspAssetMenuItemWidget | Renders the **My Assets** menu item in the Customer Account side menu. | | SprykerFeature\Yves\SelfServicePortal\Widget | +| SspItemAssetSelectorWidget | On the product details page, renders an autocomplete form field for selecting an asset. | | SprykerFeature\Yves\SelfServicePortal\Widget | +| SspListMenuItemWidget | Renders the menu item in the Customer Account side menu. | | SprykerFeature\Yves\SelfServicePortal\Widget | + +**src/Pyz/Yves/ShopApplication/ShopApplicationDependencyProvider.php** + +```php + + */ + protected function getGlobalWidgets(): array + { + return [ + SspAssetListWidget::class, + SspAssetMenuItemWidget::class, + SspListMenuItemWidget::class, + ]; + } +} +``` + +### Add translations + +[Here you can find how to import translations for Self-Service Portal feature](/docs/pbc/all/self-service-portal/latest/install/ssp-glossary-data-import.html) + +Import translations: + +```bash +console data:import glossary +``` + +{% info_block warningBox "Verification" %} + +1. In the Back Office, go to **Customers** > **Company Roles**. +2. Click **Add Company User Role**. +3. Select a company. +4. Enter a name for the role. +5. In **Unassigned Permissions**, enable the following permissions: + - **View company assets** + - **View business unit assets** + - **Update assets** + - **Unassign business unit ssp assets** + - **Create assets** +6. Click **Submit**. +7. Go to **Customers** > **Company Users**. +8. Click **Edit** next to a user. +9. Assign the role you've just created to the user. + +{% endinfo_block %} + +{% info_block warningBox "Verification" %} + +1. On the Storefront, log in with the company user you've assigned the role to. + Make sure the **Assets** menu item is displayed. +2. Go to **Customer Account** > **Assets**. +3. Click **Create Asset**. +4. Upload an image and fill in the required fields. +5. Click **Save**. + Make sure the asset gets saved and this opens the asset details page. +6. Go to **Customer Account** > **Assets**. + Make sure the the asset you've created is displayed in the list. +7. Go to **Customer Account** > **Dashboard**. + Make sure the **Assets** widget displays the asset you've created. +8. Log out and log in with a company user without the role you've created. + Make sure the **Assets** menu item is not displayed, and you can't access the **Assets** page. + +{% endinfo_block %} + +## Enable the Backend API endpoints + +| PLUGIN | SPECIFICATION | PREREQUISITES | NAMESPACE | +|-------------------------------------|-------------------------------------------------------------|---------------|------------------------------------------------------------------------------| +| SspAssetsBackendResourcePlugin | Provides the GET, POST and PATCH endpoints for SSP assets. | | SprykerFeature\Glue\SelfServicePortal\Plugin\GlueBackendApiApplication | +| SspAssetSearchResultFormatterPlugin | Formats search ssp asset search result. | | SprykerFeature\Client\SelfServicePortal\Plugin\Elasticsearch\ResultFormatter | +| SspAssetSearchQueryExpanderPlugin | Expands SSP asset search query with permissions, sorting and search criterias. | | SprykerFeature\Client\SelfServicePortal\Plugin\Elasticsearch\Query | + +**src/Pyz/Client/SelfServicePortal/SelfServicePortalDependencyProvider.php** + +```php + + */ + protected function getSspAssetSearchResultFormatterPlugins(): array + { + return [ + new SspAssetSearchResultFormatterPlugin(), + ]; + } + + /** + * @return array<\Spryker\Client\SearchExtension\Dependency\Plugin\QueryExpanderPluginInterface> + */ + protected function getSspAssetSearchQueryExpanderPlugins(): array + { + return [ + new SspAssetSearchQueryExpanderPlugin(), + ]; + } +} +``` + +**src/Pyz/Glue/GlueBackendApiApplication/GlueBackendApiApplicationDependencyProvider.php** + +```php + + */ + protected function getResourcePlugins(): array + { + return [ + new SspAssetsBackendResourcePlugin(), + ]; + } +} +``` + +{% info_block warningBox "Verification" %} + +Make sure that you can manage `ssp-assets` resources as a Back Office user: + + +1. Get the access token by sending a `POST` request to the token endpoint with back office user credentials: + +`POST https://glue-backend.mysprykershop.com/token` + +```http +POST https://glue-backend.mysprykershop.com/token HTTP/2.0 +Host: glue-backend.mysprykershop.com +Content-Type: application/x-www-form-urlencoded +Accept: application/json +Content-Length: 1051 + +grant_type=password&username={username}&password={password} +``` + +2. Use the access token to access the `ssp-assets` backend endpoint: + +
+ GET https://glue-backend.mysprykershop.com/ssp-assets + +```json +{ + "data": [ + { + "id": "AST--1", + "type": "ssp-assets", + "attributes": { + "reference": "AST--1", + "name": "DemoBrand Print Pro 2100", + "serialNumber": "PRNT000014", + "status": "pending", + "note": "The DemoBrand Print Pro 2100 is a compact, high-speed monochrome LaserJet printer designed for home offices and small workgroups. It delivers crisp text and sharp graphics with a print speed of up to 24 pages per minute. Featuring wireless connectivity, auto-duplex printing, and a user-friendly control panel, the BlazeJet 2100 ensures professional output with minimal maintenance. Compatible with Windows, macOS, and mobile devices via Wi-Fi.", + "createdDate": "2025-09-23 10:37:21", + "externalImageUrl": "https://d2s0ynfc62ej12.cloudfront.net/image/Demo_Printer.jpeg", + "companyBusinessUnitOwnerUuid": "5b9c6fc4-bf5d-5b53-9ca9-1916657e6fb2" + }, + "links": { + "self": "http://glue-backend.eu.spryker.local/ssp-assets/AST--1" + } + }, + { + "id": "AST--2", + "type": "ssp-assets", + "attributes": { + "reference": "AST--2", + "name": "DemoHaul Titan X9", + "serialNumber": "TRK1200027", + "status": "pending", + "note": "The DemoHaul Titan X9 is a high-performance heavy-duty truck engineered for demanding transport operations. Built with a reinforced steel chassis and a turbocharged diesel engine, the Titan X9 delivers exceptional hauling power, fuel efficiency, and long-distance reliability. Its ergonomic cabin features advanced driver-assist technology, real-time load monitoring, and a fully digital dashboard for enhanced control. With a payload capacity of up to 18 tons and rugged off-road capability, the Titan X9 is the ultimate solution for logistics professionals and fleet operators.", + "createdDate": "2025-09-23 10:37:21", + "externalImageUrl": "https://d2s0ynfc62ej12.cloudfront.net/image/Demo_Truck.png", + "companyBusinessUnitOwnerUuid": "5860fdd0-21fc-5389-87c9-5f1507d1ef3e" + }, + "links": { + "self": "http://glue-backend.eu.spryker.local/ssp-assets/AST--2" + } + }, + { + "id": "AST--3", + "type": "ssp-assets", + "attributes": { + "reference": "AST--3", + "name": "OfficeJet Pro 9025e All-in-One Printer", + "serialNumber": "CN1234ABCD", + "status": "pending", + "note": "The OfficeJet Pro 9025e is a high-performance multifunctional printer designed for modern office environments. It offers fast printing, scanning, copying, and faxing capabilities with automatic duplex printing. With built-in Wi-Fi and mobile printing options, this all-in-one device enhances workplace efficiency.", + "createdDate": "2025-09-23 10:37:21", + "externalImageUrl": "https://d2s0ynfc62ej12.cloudfront.net/image/AdobeStock_125577546.jpeg", + "companyBusinessUnitOwnerUuid": "5b9c6fc4-bf5d-5b53-9ca9-1916657e6fb2" + }, + "links": { + "self": "http://glue-backend.eu.spryker.local/ssp-assets/AST--3" + } + }, + { + "id": "AST--4", + "type": "ssp-assets", + "attributes": { + "reference": "AST--4", + "name": "Logistic Casa F-08", + "serialNumber": "", + "status": "pending", + "note": "1FUJGLDR5KL123456", + "createdDate": "2025-09-23 10:37:21", + "externalImageUrl": "https://d2s0ynfc62ej12.cloudfront.net/image/AdobeStock_223498915.jpeg", + "companyBusinessUnitOwnerUuid": "5b9c6fc4-bf5d-5b53-9ca9-1916657e6fb2" + }, + "links": { + "self": "http://glue-backend.eu.spryker.local/ssp-assets/AST--4" + } + }, + { + "id": "AST--5", + "type": "ssp-assets", + "attributes": { + "reference": "AST--5", + "name": "AssetName1", + "serialNumber": "serialNumberAsset1API", + "status": "pending", + "note": "noteAsset", + "createdDate": "2025-09-23 12:50:06", + "externalImageUrl": "http://emaple.com", + "companyBusinessUnitOwnerUuid": "5b9c6fc4-bf5d-5b53-9ca9-1916657e6fb2" + }, + "links": { + "self": "http://glue-backend.eu.spryker.local/ssp-assets/AST--5" + } + } + ], + "links": { + "self": "http://glue-backend.eu.spryker.local/ssp-assets" + } +} +``` + +
+ +3. To get the particular asset, use the access token to send a `GET` request to the `ssp-assets` endpoint with the asset ID: + +`GET https://glue-backend.mysprykershop.com/ssp-assets/AST--1` + +```json +{ + "data": { + "id": "AST--1", + "type": "ssp-assets", + "attributes": { + "reference": "AST--1", + "name": "DemoBrand Print Pro 2100", + "serialNumber": "PRNT000014", + "status": "pending", + "note": "The DemoBrand Print Pro 2100 is a compact, high-speed monochrome LaserJet printer designed for home offices and small workgroups. It delivers crisp text and sharp graphics with a print speed of up to 24 pages per minute. Featuring wireless connectivity, auto-duplex printing, and a user-friendly control panel, the BlazeJet 2100 ensures professional output with minimal maintenance. Compatible with Windows, macOS, and mobile devices via Wi-Fi.", + "createdDate": "2025-09-23 10:37:21", + "externalImageUrl": "https://d2s0ynfc62ej12.cloudfront.net/image/Demo_Printer.jpeg", + "companyBusinessUnitOwnerUuid": "5b9c6fc4-bf5d-5b53-9ca9-1916657e6fb2" + }, + "links": { + "self": "http://glue-backend.eu.spryker.local/ssp-assets/AST--1" + } + } +} +``` + +4. Use the access token to create the `ssp-assets` resource: +`POST https://glue-backend.mysprykershop.com/ssp-assets` + +```json +{ + "data": { + "type": "ssp-assets", + "attributes": + { + "name": {% raw %}{{{% endraw %}Asset name{% raw %}}}{% endraw %}, + "serialNumber": {% raw %}{{{% endraw %}Serial number{% raw %}}}{% endraw %}", + "status": {% raw %}{{{% endraw %}One of the following statuses: pending, in_review, approved and deactivated{% raw %}}}{% endraw %}, + "note":{% raw %}{{{% endraw %}Note{% raw %}}}{% endraw %}, + "externalImageUrl": {% raw %}{{{% endraw %}URL to an image{% raw %}}}{% endraw %}, + "companyBusinessUnitOwnerUuid": {% raw %}{{{% endraw %}The UUID of the company business unit{% raw %}}}{% endraw %} + } + } +} +``` + +Example of a successful response: + +```json +{ + "data": { + "id": "AST--6", + "type": "ssp-assets", + "attributes": { + "reference": "AST--6", + "name": "Test Asset for CRUD TEST", + "serialNumber": "CRUD-TEST-YYYYY", + "status": "pending", + "note": "This asset will be used for testing all CRUD operations!!!!!", + "createdDate": "2025-09-23 13:59:35", + "externalImageUrl": "https://example.com/asset-image_1.jpg", + "companyBusinessUnitOwnerUuid": "5860fdd0-21fc-5389-87c9-5f1507d1ef3e" + }, + "links": { + "self": "http://glue-backend.eu.spryker.local/ssp-assets/AST--6" + } + } +} +``` + +5. For updating the particular asset, use the access token to send a `PATCH` request to the `ssp-assets` endpoint with the asset ID: + +`PATCH https://glue-backend.mysprykershop.com/ssp-assets/AST--6` + +```json +{ + "data": { + "type": "ssp-assets", + "attributes": + { + "name": {% raw %}{{{% endraw %}Asset name{% raw %}}}{% endraw %}, + "serialNumber": {% raw %}{{{% endraw %}Serial number{% raw %}}}{% endraw %}", + "status": {% raw %}{{{% endraw %}One of the following statuses: pending, in_review, approved and deactivated{% raw %}}}{% endraw %}, + "note":{% raw %}{{{% endraw %}Note{% raw %}}}{% endraw %}, + "externalImageUrl": {% raw %}{{{% endraw %}URL to an image{% raw %}}}{% endraw %}, + "companyBusinessUnitOwnerUuid": {% raw %}{{{% endraw %}The UUID of the company business unit{% raw %}}}{% endraw %}, + } + } +} +``` + +Example of a successful response: + +```json +{ + "data": { + "id": "AST--6", + "type": "ssp-assets", + "attributes": { + "reference": "AST--6", + "name": "Test Asset for CRUD TEST", + "serialNumber": "CRUD-TEST-XXXX", + "status": "pending", + "note": "This asset will be used for testing all CRUD operations!!!!!", + "createdDate": "2025-09-23 13:59:35", + "externalImageUrl": "https://example.com/asset-image_1.jpg", + "companyBusinessUnitOwnerUuid": "5860fdd0-21fc-5389-87c9-5f1507d1ef3e" + }, + "links": { + "self": "http://glue-backend.eu.spryker.local/ssp-assets/AST--6" + } + } +} +``` + +{% endinfo_block %} + +## Enable Storefront API endpoints + +| PLUGIN | SPECIFICATION | PREREQUISITES | NAMESPACE | +|------------------------------|---------------------------------------------------------|---------------|--------------------------------------------------------------| +| SspAssetsResourceRoutePlugin | Provides the GET and POST endpoints for the SSP assets. | | SprykerFeature\Glue\SelfServicePortal\Plugin\GlueApplication | + +**src/Pyz/Glue/GlueApplication/GlueApplicationDependencyProvider.php** + +```php + + */ + protected function getResourceRoutePlugins(): array + { + return [ + new SspAssetsResourceRoutePlugin(), + ]; + } +} +``` + +{% info_block warningBox "Verification" %} + +Make sure that you can manage `ssp-assets` resources for the company user: + +0. Prerequisites: +- You have a company user +- You have company user credentials: username and password +- Assets are assigned to the business unit of the company user +- You have imported assets as described in data import section + +1. Get the access token by sending a `POST` request to the token endpoint with the company user credentials. + `POST https://glue.mysprykershop.com/access-tokens` + +```json +{ + "data": { + "type": "access-tokens", + "attributes": { + "username": {username}, + "password": {password} + } + } +} +``` + +2. Use the access token to access the `ssp-assets` endpoint: + + +
+ GET https://glue.mysprykershop.com/ssp-assets + +```json +{ + "data": [ + { + "type": "ssp-assets", + "id": "AST--1", + "attributes": { + "reference": "AST--1", + "name": "DemoBrand Print Pro 2100", + "serialNumber": "PRNT000014", + "note": "The DemoBrand Print Pro 2100 is a compact, high-speed monochrome LaserJet printer designed for home offices and small workgroups. It delivers crisp text and sharp graphics with a print speed of up to 24 pages per minute. Featuring wireless connectivity, auto-duplex printing, and a user-friendly control panel, the BlazeJet 2100 ensures professional output with minimal maintenance. Compatible with Windows, macOS, and mobile devices via Wi-Fi.", + "externalImageUrl": "https://d2s0ynfc62ej12.cloudfront.net/image/Demo_Printer.jpeg" + }, + "links": { + "self": "http://glue.eu.spryker.local/ssp-assets/AST--1" + } + }, + { + "type": "ssp-assets", + "id": "AST--2", + "attributes": { + "reference": "AST--2", + "name": "DemoHaul Titan X9", + "serialNumber": "TRK1200027", + "note": "The DemoHaul Titan X9 is a high-performance heavy-duty truck engineered for demanding transport operations. Built with a reinforced steel chassis and a turbocharged diesel engine, the Titan X9 delivers exceptional hauling power, fuel efficiency, and long-distance reliability. Its ergonomic cabin features advanced driver-assist technology, real-time load monitoring, and a fully digital dashboard for enhanced control. With a payload capacity of up to 18 tons and rugged off-road capability, the Titan X9 is the ultimate solution for logistics professionals and fleet operators.", + "externalImageUrl": "https://d2s0ynfc62ej12.cloudfront.net/image/Demo_Truck.png" + }, + "links": { + "self": "http://glue.eu.spryker.local/ssp-assets/AST--2" + } + }, + { + "type": "ssp-assets", + "id": "AST--3", + "attributes": { + "reference": "AST--3", + "name": "OfficeJet Pro 9025e All-in-One Printer", + "serialNumber": "CN1234ABCD", + "note": "The OfficeJet Pro 9025e is a high-performance multifunctional printer designed for modern office environments. It offers fast printing, scanning, copying, and faxing capabilities with automatic duplex printing. With built-in Wi-Fi and mobile printing options, this all-in-one device enhances workplace efficiency.", + "externalImageUrl": "https://d2s0ynfc62ej12.cloudfront.net/image/AdobeStock_125577546.jpeg" + }, + "links": { + "self": "http://glue.eu.spryker.local/ssp-assets/AST--3" + } + }, + { + "type": "ssp-assets", + "id": "AST--4", + "attributes": { + "reference": "AST--4", + "name": "Logistic Casa F-08", + "serialNumber": "", + "note": "1FUJGLDR5KL123456", + "externalImageUrl": "https://d2s0ynfc62ej12.cloudfront.net/image/AdobeStock_223498915.jpeg" + }, + "links": { + "self": "http://glue.eu.spryker.local/ssp-assets/AST--4" + } + } + ], + "links": { + "self": "http://glue.eu.spryker.local/ssp-assets" + } +} +``` + +
+ +3. To get the particular asset, use the access token to send a `GET` request to the `ssp-assets` endpoint with the asset ID: + +`GET https://glue.mysprykershop.com/ssp-assets/AST--1` + +```json +{ + "data": { + "type": "ssp-assets", + "id": "AST--1", + "attributes": { + "reference": "AST--1", + "name": "DemoBrand Print Pro 2100", + "serialNumber": "PRNT000014", + "note": "The DemoBrand Print Pro 2100 is a compact, high-speed monochrome LaserJet printer designed for home offices and small workgroups. It delivers crisp text and sharp graphics with a print speed of up to 24 pages per minute. Featuring wireless connectivity, auto-duplex printing, and a user-friendly control panel, the BlazeJet 2100 ensures professional output with minimal maintenance. Compatible with Windows, macOS, and mobile devices via Wi-Fi.", + "externalImageUrl": "https://d2s0ynfc62ej12.cloudfront.net/image/Demo_Printer.jpeg" + }, + "links": { + "self": "http://glue.eu.spryker.local/ssp-assets/AST--1" + } + } +} +``` + +4. Use the access token to create the `ssp-assets` resource: + +`POST https://glue.mysprykershop.com/ssp-assets` + +```json +{ + "data": { + "type": "ssp-assets", + "attributes": { + "name": {Asset name}, + "serialNumber": {Serial number}, + "note": {Note}, + "externalImageUrl": {URL} + } + } +} +``` + +Example of a successful response: + +```json +{ + "data": { + "type": "ssp-assets", + "id": "AST--5", + "attributes": { + "reference": "AST--5", + "name": "AssetName1", + "serialNumber": "serialNumberAsset1API", + "note": "noteAsset", + "externalImageUrl": "http://emaple.com" + }, + "links": { + "self": "http://glue.eu.spryker.local/ssp-assets/AST--5" + } + } +} +``` + +{% endinfo_block %} + + +## Demo data for EU region / DE store + +### Add asset demo data + +Prepare your data according to your requirements using our demo data: + +**data/import/common/common/ssp_asset.csv** + +```csv +reference,name,serial_number,note,external_image_url,business_unit_key,assigned_business_unit_keys +AST--1,DemoBrand Print Pro 2100,PRNT000014,"The DemoBrand Print Pro 2100 is a compact, high-speed monochrome LaserJet printer designed for home offices and small workgroups. It delivers crisp text and sharp graphics with a print speed of up to 24 pages per minute. Featuring wireless connectivity, auto-duplex printing, and a user-friendly control panel, the BlazeJet 2100 ensures professional output with minimal maintenance. Compatible with Windows, macOS, and mobile devices via Wi-Fi.",https://d2s0ynfc62ej12.cloudfront.net/image/Demo_Printer.jpeg,spryker_systems_HR,"spryker_systems_HR" +AST--2,DemoHaul Titan X9,TRK1200027,"The DemoHaul Titan X9 is a high-performance heavy-duty truck engineered for demanding transport operations. Built with a reinforced steel chassis and a turbocharged diesel engine, the Titan X9 delivers exceptional hauling power, fuel efficiency, and long-distance reliability. Its ergonomic cabin features advanced driver-assist technology, real-time load monitoring, and a fully digital dashboard for enhanced control. With a payload capacity of up to 18 tons and rugged off-road capability, the Titan X9 is the ultimate solution for logistics professionals and fleet operators.",https://d2s0ynfc62ej12.cloudfront.net/image/Demo_Truck.png,spryker_systems_Zurich,spryker_systems_Zurich +AST--3,OfficeJet Pro 9025e All-in-One Printer,CN1234ABCD,"The OfficeJet Pro 9025e is a high-performance multifunctional printer designed for modern office environments. It offers fast printing, scanning, copying, and faxing capabilities with automatic duplex printing. With built-in Wi-Fi and mobile printing options, this all-in-one device enhances workplace efficiency.",https://d2s0ynfc62ej12.cloudfront.net/image/AdobeStock_125577546.jpeg,spryker_systems_HR,spryker_systems_HR +AST--4,Logistic Casa F-08,,1FUJGLDR5KL123456,https://d2s0ynfc62ej12.cloudfront.net/image/AdobeStock_223498915.jpeg,spryker_systems_HR,spryker_systems_HR +``` + +| COLUMN | REQUIRED | DATA TYPE | DATA EXAMPLE | DATA EXPLANATION | +|-----------------------------|----------|-----------|----------------------------------------------------------------|---------------------------------------------------------------------------| +| reference | ✓ | string | AST--1 | Unique identifier for the asset used as a reference in the system. | +| name | ✓ | string | DemoBrand Print Pro 2100 | The display name of the asset. | +| serial_number | x | string | PRNT000014 | The serial number of the asset for identification purposes. | +| note | x | string | The DemoBrand Print Pro 2100... | Detailed description or notes about the asset. | +| external_image_url | x | string | `https://d2s0ynfc62ej12.cloudfront.net/image/Demo_Printer.jpeg` | URL to an external image of the asset. | +| business_unit_key | x | string | spryker_systems_HR | The key of the business unit that owns the asset. | +| assigned_business_unit_keys | x | string | spryker_systems_HR | Comma-separated list of business unit keys that have access to the asset. | + +#### Extend the data import configuration + +**/data/import/local/full_EU.yml** + +```yaml +# ... + +# SelfServicePortal +- data_entity: ssp-asset + source: data/import/common/common/ssp_asset.csv +``` + +### Register the following data import plugins + +| PLUGIN | SPECIFICATION | PREREQUISITES | NAMESPACE | +|--------------------------|---------------------------------------|---------------|----------------------------------------------------------------------| +| SspAssetDataImportPlugin | Imports a ssp asset into persistence. | | SprykerFeature\Zed\SelfServicePortal\Communication\Plugin\DataImport | + +**src/Pyz/Zed/DataImport/DataImportDependencyProvider.php** + +```php + + */ + protected function getDataImporterPlugins(): array + { + return [ + new SspAssetDataImportPlugin(), + ]; + } +} +``` + +Enable the behaviors by registering the console commands: + +**src/Pyz/Zed/Console/ConsoleDependencyProvider.php** + +```php + + */ + protected function getConsoleCommands(Container $container) + { + $commands = [ + new DataImportConsole(DataImportConsole::DEFAULT_NAME . static::COMMAND_SEPARATOR . SelfServicePortalConfig::IMPORT_TYPE_SSP_ASSET), + ]; + + return $commands; + } +} +``` + + +### Import the data + +```bash +console data:import:ssp-asset +``` + +{% info_block warningBox "Verification" %} + +Make sure the configured data has been added to the following database tables: + +- `spy_asset` +- `spy_ssp_asset_to_company_business_unit` +- `spy_ssp_asset_storage` +- `spy_ssp_asset_search` + {% endinfo_block %} + +## Set up frontend templates + +For information about setting up frontend templates, see [Set up SSP frontend templates](/docs/pbc/all/self-service-portal/latest/install/ssp-frontend-templates.html). diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/lib.php b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/lib.php new file mode 100644 index 0000000..08d4a41 --- /dev/null +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/lib.php @@ -0,0 +1,100 @@ +|null + */ +function fi_load_checklist(string $path): ?array +{ + if (!is_file($path)) { + return null; + } + $checklist = json_decode((string)file_get_contents($path), true); + + return is_array($checklist) && isset($checklist['rows']) && is_array($checklist['rows']) ? $checklist : null; +} + +function fi_save_checklist(string $path, array $checklist): void +{ + file_put_contents($path, json_encode($checklist, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) . "\n"); +} + +function fi_is_skip(?string $decision): bool +{ + return is_string($decision) && str_starts_with($decision, 'skip:'); +} + +/** + * The console command a shell line runs: `vendor/bin/console data:import glossary` → `data:import`. + * Environment prefixes (`GLUE_APPLICATION=X vendor/bin/glue cache:warmup`) are ignored. + */ +function fi_command_name(string $command): string +{ + if (preg_match('/(?:^|\s)(?:vendor\/bin\/)?(?:console|glue)\s+([a-z0-9:\-]+)/', $command, $m)) { + return $m[1]; + } + + return strtok(trim($command), ' ') ?: trim($command); +} + +/** + * The full console invocation without the binary and flags: `console data:import glossary -vvv` + * → `data:import glossary`. Two calls of one command with other arguments are other steps. + */ +function fi_command_signature(string $command): string +{ + if (!preg_match('/(?:^|\s)(?:vendor\/bin\/)?(?:console|glue)\s+(.+)$/', trim($command), $m)) { + return trim($command); + } + $parts = array_filter(preg_split('/\s+/', $m[1]) ?: [], static fn (string $p): bool => !preg_match('/^-(v+|-no-ansi|-no-interaction|n)$/', $p)); + + return implode(' ', $parts); +} + +function fi_short_name(string $class): string +{ + $parts = explode('\\', $class); + + return (string)end($parts); +} + +/** + * @return array> package name => lock entry + */ +function fi_lock_packages(string $lockFile): array +{ + $lock = json_decode((string)@file_get_contents($lockFile), true); + $packages = []; + foreach (['packages', 'packages-dev'] as $key) { + foreach ($lock[$key] ?? [] as $package) { + if (isset($package['name'])) { + $packages[strtolower($package['name'])] = $package; + } + } + } + + return $packages; +} diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/parse-integration-guide.php b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/parse-integration-guide.php new file mode 100644 index 0000000..c87afa7 --- /dev/null +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/parse-integration-guide.php @@ -0,0 +1,608 @@ +... --out [--release ] + * [--docs-root ] [--append] [--force] + * + * --release replaces {{page.release_tag}}; default: release_version from /_config.yml + * --append adds the guides to an existing checklist; a guide already in it is skipped + * --force overwrites an existing checklist (its decisions are lost) + * + * Exit codes: 0 parsed, every row classified; 1 parsed with `unknown` rows or an unresolved release + * placeholder (the checklist is written; the rows need a manual decision); 2 usage or input error. + */ + +declare(strict_types=1); + +require_once __DIR__ . '/lib.php'; + +const PIG_SCHEMA_VERSION = 1; + +/** Commands a local install runs that a deploy recipe usually does not. */ +const PIG_FRESH_INSTALL_COMMANDS = [ + 'setup:init-db', + 'propel:install', + 'data:import', + 'publish:trigger-events', + 'sync:data', + 'search:setup', + 'acl-entity:synchronize', +]; + +const PIG_OPTIONAL_HEADING = '/^(add the |enable |optional|integrate |install .*\(optional\))/i'; + +/** + * @return list + */ +function pig_load_lines(string $path, ?string $docsRoot, array &$errors, int $depth = 0): array +{ + $raw = @file_get_contents($path); + if ($raw === false) { + $errors[] = "cannot read $path"; + + return []; + } + $raw = (string)preg_replace('/\A---\n.*?\n---\n/s', '', $raw); + $lines = []; + $inFence = false; + foreach (explode("\n", $raw) as $index => $text) { + if (preg_match('/^\s*```/', $text)) { + $inFence = !$inFence; + } + if (!$inFence && preg_match('/^\s*\{%\s*include\s+(\S+\.md)\s*%\}/', $text, $m)) { + $target = $docsRoot !== null ? rtrim($docsRoot, '/') . '/_includes/' . $m[1] : null; + if ($target !== null && is_file($target) && $depth < 5) { + array_push($lines, ...pig_load_lines($target, $docsRoot, $errors, $depth + 1)); + + continue; + } + $errors[] = "unresolved include {$m[1]} at " . basename($path) . ':' . ($index + 1); + } + $lines[] = ['text' => $text, 'file' => $path, 'line' => $index + 1]; + } + + return $lines; +} + +function pig_release_from_docs(?string $docsRoot): ?string +{ + if ($docsRoot === null || !is_file($docsRoot . '/_config.yml')) { + return null; + } + $config = (string)file_get_contents($docsRoot . '/_config.yml'); + + return preg_match('/^release_version:\s*"?([0-9.]+)"?/m', $config, $m) ? $m[1] : null; +} + +function pig_substitute_release(string $text, ?string $release): string +{ + if ($release === null) { + return $text; + } + + return (string)preg_replace('/\{\{\s*page\.release_tag\s*\}\}/', $release, $text); +} + +function pig_clean_heading(string $heading): array +{ + $heading = trim(strip_tags($heading)); + $numbered = (bool)preg_match('/^\d+[.)]\s+/', $heading); + $heading = trim((string)preg_replace('/^\d+[.)]\s+/', '', $heading)); + + return [$heading, $numbered]; +} + +/** + * A path-like header right above a code block: `**src/Pyz/...**`, `config/...`. + */ +function pig_header_path(string $line): ?string +{ + $line = trim($line); + if (preg_match('/^\*\*\s*>?\s*(\/?[A-Za-z0-9_.\-\/]+)\s*\*\*:?$/', $line, $m) + || preg_match('/\s*(\/?[A-Za-z0-9_.\-\/]+)\s*(<\/summary>)?\s*$/', $line, $m)) { + return pig_normalize_path($m[1]); + } + + return null; +} + +function pig_normalize_path(string $path): ?string +{ + $path = ltrim(trim($path), '/>'); + $path = (string)preg_replace('#^src/data/#', 'data/', $path); + if (!str_contains($path, '/') && !preg_match('/\.(json|yml|yaml|xml|php)$/', $path)) { + return null; + } + + return $path; +} + +/** + * A code block with no header: derive the file from the namespace and the class it declares, from + * `$config[...]` assignments (the config files), from `key,text,locale` lines (the glossary), or + * from deploy-file top-level keys. A guide that names no deploy file means every deploy file the + * project has: `deploy.*.yml`. + */ +function pig_infer_path(string $code, string $lang): ?string +{ + if ($lang === 'php' && preg_match('/^namespace\s+([A-Za-z0-9_\\\\]+);/m', $code, $ns) + && preg_match('/^(?:abstract\s+|final\s+)?(?:class|interface)\s+(\w+)/m', $code, $cl)) { + return 'src/' . str_replace('\\', '/', $ns[1]) . '/' . $cl[1] . '.php'; + } + if ($lang === 'php' && preg_match('/^\s*\$config\[/m', $code)) { + return 'config/Shared/config_default.php'; + } + if (in_array($lang, ['csv', 'yaml', 'yml', 'text', ''], true) && preg_match('/^[a-z0-9_.\-]+,.+,[a-z]{2}_[A-Z]{2}\s*$/m', $code)) { + return 'data/import/glossary.csv'; + } + if (in_array($lang, ['yaml', 'yml'], true) && preg_match('/^(image|regions|groups|services|docker|environment):/m', $code)) { + return 'deploy.*.yml'; + } + + return null; +} + +function pig_classify_path(string $path, string $code): string +{ + $file = basename($path); + $rules = [ + ['/\.transfer\.xml$/', 'transfer'], + ['/\.schema\.xml$/', str_contains($code, 'name="event"') ? 'event' : 'schema'], + ['#(^|/)config/Zed/(oms|StateMachine)/#', 'oms'], + ['/navigation\.xml$/', 'navigation'], + ['/glossary\.csv$/', 'glossary'], + ['#(^|/)data/import/.*\.csv$#', 'data-row'], + ['#(^|/)data/import/.*\.ya?ml$#', 'data-import'], + ['#^config/install/#', 'recipe'], + ['/^deploy[^\/]*\.ya?ml$/', 'deploy'], + ['/RouterDependencyProvider\.php$/', 'route'], + ['/ShopApplicationDependencyProvider\.php$/', 'widget'], + ['/(QueueDependencyProvider|RabbitMqConfig)\.php$/', 'queue'], + ['/DependencyProvider\.php$/', 'plugin'], + ['#SearchElasticsearch|/Search/Schema/|\.index\.json$|\.map\.json$#', 'search-index'], + ['#(Config|Constants)\.php$|^config/Shared/#', 'config'], + ['#\.(twig|ts|js|scss|css|html)$|^frontend/|(^|/)package\.json$|tsconfig.*\.json$#', 'frontend'], + ['/\.php$/', 'code'], + ]; + foreach ($rules as [$pattern, $kind]) { + if (preg_match($pattern, $path) || preg_match($pattern, $file)) { + return $kind; + } + } + + return 'unknown'; +} + +const PIG_WIRED_CLASS = '/\bnew\s+(\w+(?:Plugin|Widget|Console|Subscriber))\s*\(|\b(\w+(?:Plugin|Widget|Console|Subscriber))::class/'; + +/** + * @return array{plugins: list, names: list} the fully-qualified classes a + * DependencyProvider snippet wires, and every short name they go by (class and alias) + */ +function pig_plugins_in(string $code): array +{ + $uses = []; + if (preg_match_all('/^use\s+([A-Za-z0-9_\\\\]+?\\\\(\w+))(?:\s+as\s+(\w+))?;/m', $code, $m, PREG_SET_ORDER)) { + foreach ($m as $use) { + $uses[($use[3] ?? '') !== '' ? $use[3] : $use[2]] = $use[1]; + } + } + $plugins = []; + $names = []; + if (preg_match_all('/\bnew\s+(\w+)\s*\(|\b(\w+)::class/', $code, $m, PREG_SET_ORDER)) { + foreach ($m as $hit) { + $short = $hit[1] !== '' ? $hit[1] : $hit[2]; + if (!isset($uses[$short]) && !preg_match(PIG_WIRED_CLASS, 'new ' . $short . '(')) { + continue; + } + $fqcn = $uses[$short] ?? $short; + $plugins[] = $fqcn; + $names[] = $short; + $names[] = fi_short_name($fqcn); + } + } + + return ['plugins' => array_values(array_unique($plugins)), 'names' => array_values(array_unique($names))]; +} + +/** + * @return array package => constraint, from one `composer require` line + */ +function pig_composer_packages(string $command): array +{ + $args = trim((string)preg_replace('/^.*?composer\s+require\s+/', '', $command)); + $args = (string)preg_replace('/(\S+\/\S+?):\s+("[^"]*"|\S+)/', '$1:$2', $args); + $packages = []; + foreach (preg_split('/\s+/', $args) ?: [] as $token) { + if ($token === '' || str_starts_with($token, '-')) { + continue; + } + if (preg_match('/^([a-z0-9_.\-]+\/[a-z0-9_.\-]+)(?::(.*))?$/', $token, $m)) { + $packages[$m[1]] = trim($m[2] ?? '', '"\''); + } + } + + return $packages; +} + +function pig_section_tag(array $stack): string +{ + foreach ($stack as $heading) { + if (preg_match('/demo data/i', $heading['title'])) { + return 'demo-data'; + } + } + $top = $stack[0] ?? null; + if ($top !== null && !$top['numbered'] && preg_match(PIG_OPTIONAL_HEADING, $top['title'])) { + return 'optional-scenario:' . trim((string)preg_replace('/[^a-z0-9]+/', '-', strtolower($top['title'])), '-'); + } + + return 'required'; +} + +/** + * Translations and import configuration are what a feature needs to work; a demo-data section + * holds sample rows. Any other data row is a project decision the parser cannot make: null. + */ +function pig_data_class(string $kind, string $sectionTag): ?string +{ + return match (true) { + $sectionTag === 'demo-data' => 'demo-data', + $kind === 'glossary', $kind === 'data-import' => 'feature-data', + default => null, + }; +} + +function pig_kind_tag(string $kind, string $sectionTag, string $target): string +{ + if ($sectionTag !== 'required') { + return $sectionTag; + } + + return match (true) { + $kind === 'console' && in_array(fi_command_name($target), PIG_FRESH_INSTALL_COMMANDS, true), + $kind === 'console' && str_starts_with(fi_command_name($target), 'data:import') => 'fresh-install-only', + default => 'required', + }; +} + +/** + * @return list, rows: list>}> + */ +function pig_parse_table(array $tableLines): array +{ + $cells = static fn (string $line): array => array_map( + static fn (string $cell): string => trim(html_entity_decode($cell, ENT_QUOTES | ENT_HTML5)), + explode('|', trim(trim($line), '|')) + ); + $header = array_map('strtoupper', $cells($tableLines[0])); + $rows = []; + foreach (array_slice($tableLines, 1) as $line) { + if (preg_match('/^\s*\|?[\s:\-|]+\|?\s*$/', $line)) { + continue; + } + $rows[] = $cells($line); + } + + return ['header' => $header, 'rows' => $rows]; +} + +function pig_link(string $cell): array +{ + return preg_match('/\[([^\]]+)\]\(([^)]+)\)/', $cell, $m) ? [$m[1], $m[2]] : [trim($cell), null]; +} + +/** + * Parse one guide into its metadata and rows. Row ids are assigned by the caller. + * + * @return array{guide: array, rows: list>, errors: list} + */ +function pig_parse_guide(string $path, ?string $docsRoot, ?string $release): array +{ + $errors = []; + $lines = pig_load_lines($path, $docsRoot, $errors); + $guideName = basename($path); + $guide = ['file' => $guideName, 'prerequisites' => [], 'modules' => [], 'plugin_tables' => [], 'env' => []]; + $rows = []; + $stack = []; + $fence = null; + $info = null; + $lastText = ''; + $table = []; + $tableStart = 0; + $tablePlugins = []; + $linkedGuides = []; + + $addRow = static function (array $row) use (&$rows, &$stack, $guideName): void { + $sectionTag = pig_section_tag($stack); + $row = ['guide' => $guideName, 'section' => implode(' > ', array_column($stack, 'title'))] + $row; + $row['tag'] = pig_kind_tag($row['kind'], $sectionTag, (string)$row['target']); + if (in_array($row['kind'], FI_DATA_KINDS, true)) { + $row['data_class'] = pig_data_class($row['kind'], $sectionTag); + } + $rows[] = $row + ['source' => 'guide', 'reference' => null, 'decision' => null, 'status' => 'open']; + }; + + $flushTable = static function () use (&$table, &$tableStart, &$guide, &$stack, &$tablePlugins): void { + if (count($table) < 2) { + $table = []; + + return; + } + $parsed = pig_parse_table($table); + $header = $parsed['header']; + $section = implode(' > ', array_column($stack, 'title')); + if (($header[0] ?? '') === 'MODULE' && in_array('EXPECTED DIRECTORY', $header, true)) { + foreach ($parsed['rows'] as $cells) { + $guide['modules'][] = ['module' => $cells[0] ?? '', 'directory' => trim($cells[1] ?? '', '` ')]; + } + } elseif (in_array($header[0] ?? '', ['NAME', 'FEATURE'], true) && in_array('INSTALLATION GUIDE', $header, true)) { + foreach ($parsed['rows'] as $cells) { + [$linkText, $url] = pig_link($cells[2] ?? ''); + $guide['prerequisites'][] = ['name' => $cells[0] ?? '', 'version' => $cells[1] ?? '', 'guide' => $linkText, 'url' => $url]; + } + } elseif (($header[0] ?? '') === 'PLUGIN' && in_array('NAMESPACE', $header, true)) { + $nsColumn = (int)array_search('NAMESPACE', $header, true); + foreach ($parsed['rows'] as $cells) { + $class = trim(trim($cells[0] ?? ''), '`'); + $namespace = trim(trim($cells[$nsColumn] ?? ''), '`\\'); + $fqcn = $namespace !== '' ? $namespace . '\\' . $class : $class; + $guide['plugin_tables'][] = ['plugin' => $fqcn, 'section' => $section]; + $tablePlugins[$fqcn] = ['line' => $tableStart, 'stack' => $stack]; + } + } + $table = []; + }; + + foreach ($lines as $entry) { + $text = pig_substitute_release($entry['text'], $release); + $lineNo = $entry['line']; + + if ($fence !== null) { + if (preg_match('/^\s*```/', $text)) { + $code = implode("\n", $fence['body']); + $lang = $fence['lang']; + $span = [$fence['start'], $lineNo]; + if ($info !== null && $info['verification']) { + $info['text'] .= ' [' . ($lang !== '' ? $lang : 'code') . ' block]'; + } elseif (in_array($lang, ['bash', 'shell', 'sh', 'console'], true)) { + foreach ($fence['body'] as $offset => $commandLine) { + $command = trim((string)preg_replace('/^\$\s*/', '', trim($commandLine))); + if ($command === '' || str_starts_with($command, '#')) { + continue; + } + $at = $fence['start'] + 1 + $offset; + if (preg_match('/\bcomposer\s+require\b/', $command)) { + $addRow(['lines' => [$at, $at], 'kind' => 'composer', 'target' => $command, 'packages' => pig_composer_packages($command)]); + } else { + $addRow(['lines' => [$at, $at], 'kind' => 'console', 'target' => $command]); + } + } + } elseif (in_array($lang, ['json', 'http'], true) || preg_match('/^`?(GET|POST|PATCH|PUT|DELETE)\s/', $fence['header_text'])) { + // an API request or response example, not a step + } else { + $targetPath = $fence['header'] ?? pig_infer_path($code, $lang); + $kind = $targetPath !== null ? pig_classify_path($targetPath, $code) : 'unknown'; + $row = ['lines' => $span, 'kind' => $kind, 'target' => $targetPath ?? '(no file named above the block)']; + if ($fence['header'] === null && $targetPath !== null) { + $row['inferred_target'] = true; + } + if (in_array($kind, ['plugin', 'route', 'widget', 'queue'], true)) { + $wired = pig_plugins_in($code); + $row['plugins'] = $wired['plugins']; + foreach (array_keys($tablePlugins) as $listed) { + if (in_array(fi_short_name($listed), $wired['names'], true)) { + unset($tablePlugins[$listed]); + } + } + } + if (preg_match_all("/getenv\\(\\s*'([A-Z0-9_]+)'/", $code, $env)) { + $row['env'] = array_values(array_unique($env[1])); + $guide['env'] = array_values(array_unique(array_merge($guide['env'], $row['env']))); + } + $addRow($row); + } + $fence = null; + continue; + } + $fence['body'][] = $text; + continue; + } + + if (preg_match('/^\s*\|/', $text)) { + if ($table === []) { + $tableStart = $lineNo; + } + $table[] = $text; + continue; + } + if ($table !== []) { + $flushTable(); + } + + if (preg_match('/^\s*```\s*([a-zA-Z]*)/', $text, $m)) { + $fence = [ + 'lang' => strtolower($m[1]), + 'start' => $lineNo, + 'body' => [], + 'header' => pig_header_path($lastText), + 'header_text' => trim($lastText), + ]; + continue; + } + if (preg_match('/\{%\s*info_block\s+\w+\s+"([^"]*)"\s*%\}/', $text, $m)) { + $info = ['title' => $m[1], 'verification' => stripos($m[1], 'verification') !== false, 'start' => $lineNo, 'text' => '']; + continue; + } + if (preg_match('/\{%\s*endinfo_block\s*%\}/', $text)) { + if ($info !== null && $info['verification']) { + $summary = trim((string)preg_replace('/\s+/', ' ', strip_tags($info['text']))); + $addRow(['lines' => [$info['start'], $lineNo], 'kind' => 'verification', 'target' => mb_substr($summary, 0, 300)]); + } + $info = null; + continue; + } + if ($info === null && preg_match('/^(#{2,4})\s+(.+)$/', $text, $m)) { + [$title, $numbered] = pig_clean_heading($m[2]); + $level = strlen($m[1]); + $stack = array_values(array_filter($stack, static fn (array $h): bool => $h['level'] < $level)); + $stack[] = ['level' => $level, 'title' => $title, 'numbered' => $numbered]; + $lastText = ''; + continue; + } + if ($info !== null) { + $info['text'] .= ' ' . trim($text); + } + $inPrerequisites = $stack !== [] && preg_match('/^(prerequisites|features .* depends on|install the required features)/i', end($stack)['title']); + if (($info === null || !$info['verification']) && !$inPrerequisites + && preg_match_all('/\[([^\]]+)\]\((\/docs\/[^)#\s]+\.html)(?:#[^)]*)?\)/', $text, $links, PREG_SET_ORDER)) { + foreach ($links as $link) { + if (!in_array($link[2], $linkedGuides, true)) { + $linkedGuides[] = $link[2]; + $addRow(['lines' => [$lineNo, $lineNo], 'kind' => 'linked-guide', 'target' => $link[2], 'note' => $link[1]]); + } + } + } + if (trim($text) !== '') { + $lastText = $text; + } + } + if ($table !== []) { + $flushTable(); + } + + foreach ($tablePlugins as $plugin => $origin) { + $saved = $stack; + $stack = $origin['stack']; + $addRow(['lines' => [$origin['line'], $origin['line']], 'kind' => 'plugin', 'target' => $plugin, 'plugins' => [$plugin], 'note' => 'listed in a plugin table; no wiring snippet in the guide']); + $stack = $saved; + } + + return ['guide' => $guide, 'rows' => $rows, 'errors' => $errors]; +} + +/** + * @return array{schema: int, release: ?string, guides: list>, rows: list>} + */ +function pig_build_checklist(array $guidePaths, ?string $docsRoot, ?string $release, ?array $existing, array &$errors): array +{ + $checklist = $existing ?? ['schema' => PIG_SCHEMA_VERSION, 'release' => $release, 'guides' => [], 'rows' => []]; + $known = array_column($checklist['guides'], 'file'); + $next = count($checklist['rows']) + 1; + foreach ($guidePaths as $path) { + if (in_array(basename($path), $known, true)) { + $errors[] = 'skipped ' . basename($path) . ': already in the checklist'; + continue; + } + $parsed = pig_parse_guide($path, $docsRoot, $release); + array_push($errors, ...$parsed['errors']); + $checklist['guides'][] = $parsed['guide']; + foreach ($parsed['rows'] as $row) { + $checklist['rows'][] = ['id' => sprintf('R%03d', $next++)] + $row; + } + } + + return $checklist; +} + +/** + * @return array> + */ +function pig_summary(array $checklist): array +{ + $byKind = []; + $byTag = []; + foreach ($checklist['rows'] as $row) { + $byKind[$row['kind']] = ($byKind[$row['kind']] ?? 0) + 1; + $byTag[$row['tag']] = ($byTag[$row['tag']] ?? 0) + 1; + } + ksort($byKind); + ksort($byTag); + + return ['kind' => $byKind, 'tag' => $byTag]; +} + +function pig_main(array $argv): int +{ + $guides = []; + $options = ['out' => null, 'release' => null, 'docs-root' => null, 'append' => false, 'force' => false]; + for ($i = 1; $i < count($argv); $i++) { + $arg = $argv[$i]; + if (in_array($arg, ['--append', '--force'], true)) { + $options[substr($arg, 2)] = true; + } elseif (in_array($arg, ['--out', '--release', '--docs-root'], true)) { + $options[substr($arg, 2)] = $argv[++$i] ?? null; + } elseif (str_starts_with($arg, '--')) { + fwrite(STDERR, "unknown option $arg\n"); + + return 2; + } else { + $guides[] = $arg; + } + } + if ($guides === [] || $options['out'] === null) { + fwrite(STDERR, "usage: php parse-integration-guide.php ... --out [--release ] [--docs-root ] [--append] [--force]\n"); + + return 2; + } + $existing = null; + if (is_file($options['out'])) { + if ($options['append']) { + $existing = json_decode((string)file_get_contents($options['out']), true); + if (!is_array($existing) || !isset($existing['rows'])) { + fwrite(STDERR, "{$options['out']} is not a checklist\n"); + + return 2; + } + } elseif (!$options['force']) { + fwrite(STDERR, "{$options['out']} exists: pass --append to add guides, or --force to overwrite it and lose its decisions\n"); + + return 2; + } + } + $release = $options['release'] ?? $existing['release'] ?? pig_release_from_docs($options['docs-root']); + $errors = []; + $checklist = pig_build_checklist($guides, $options['docs-root'], $release, $existing, $errors); + $checklist['release'] = $release; + if (!is_dir(dirname($options['out']))) { + mkdir(dirname($options['out']), 0777, true); + } + file_put_contents($options['out'], json_encode($checklist, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) . "\n"); + + $summary = pig_summary($checklist); + fwrite(STDOUT, sprintf("%d rows from %d guide(s) -> %s\n", count($checklist['rows']), count($checklist['guides']), $options['out'])); + foreach ($summary as $axis => $counts) { + fwrite(STDOUT, sprintf(" %-5s %s\n", $axis, implode(', ', array_map(static fn ($k, $v) => "$k $v", array_keys($counts), $counts)))); + } + foreach ($errors as $error) { + fwrite(STDOUT, " note $error\n"); + } + $unknown = $summary['kind']['unknown'] ?? 0; + $placeholder = str_contains((string)file_get_contents($options['out']), 'release_tag'); + if ($release === null || $placeholder) { + fwrite(STDOUT, " {{page.release_tag}} is not resolved: pass --release or --docs-root\n"); + } + if ($unknown > 0) { + fwrite(STDOUT, " $unknown unknown row(s): read the guide at the row's lines and set kind and decision by hand\n"); + } + + return ($unknown > 0 || $release === null || $placeholder) ? 1 : 0; +} + +if (realpath($argv[0] ?? '') === __FILE__) { + exit(pig_main($argv)); +} diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/SKILL.md b/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/SKILL.md index 1e9c53b..ea88c85 100644 --- a/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/SKILL.md +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-upgrade/SKILL.md @@ -472,9 +472,9 @@ Two kinds of "new" need this gate, and only the first is visible in the lock dif `class_exists` branch (matrix #64), a new extension point (performance fixes: Phase 6.2, not here). Fetch each description (`composer show ` + release notes) and ask the user a structured question (use your harness's question tool if it has one, otherwise ask in chat and wait) -(multiSelect): integrate now / defer / never. Nothing new is wired without an explicit yes; each -accepted feature follows its integration guide, in its own commit (the `spryker-feature-install` skill -runs a guide end to end, including its optional storefront placement step). REMOVED packages: explain each. +(multiSelect): integrate now / defer / never. Nothing new is wired in the upgrade branch: each accepted +feature goes to `spryker-feature-install` after the upgrade pull request, one feature per run, on its +own branch (it includes the optional storefront placement step). REMOVED packages: explain each. ## Phase 6.1 — Storefront placement (optional, suggested) From a21ab540a3de05e05c89c2f73d260e1d6fe5d83a Mon Sep 17 00:00:00 2001 From: Veronika Golska Date: Tue, 17 Nov 2026 16:31:00 +0100 Subject: [PATCH 09/18] spryker-feature-install: use the capability search script as the fallback The install skill told the agent to fetch .md when the capability tools are missing, so it guessed slugs and package names. It now tells a missing MCP registration from a lost connection, as find-existing-capability does, and runs find-existing-capability/scripts/capability-search.php by feature name and synonyms. Never guess a slug or a package name. --- .../skills/spryker-feature-install/SKILL.md | 26 +++++++++++++++---- 1 file changed, 21 insertions(+), 5 deletions(-) diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/SKILL.md b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/SKILL.md index 1869999..48e688a 100644 --- a/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/SKILL.md +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/SKILL.md @@ -75,10 +75,26 @@ Match tools by **tool name** (server names vary by install; some clients namespa | `getSprykerModules`, `getSprykerModuleMap` | What the project has now; exact plugin interfaces. | | `getTransferStructureByName` | Transfer fields before a transfer XML edit. | -If the capability tools are not connected, start the MCP server and ask for a reload as -`find-existing-capability` describes. After two failed reconnects, take the feature name and guide -URL from the developer, or fetch `https://spryker-capability-map.s3.eu-central-1.amazonaws.com/.md` -and compare its packages with `composer.lock` by hand; the install status is then unverified. +**If the capability tools are not available**, tell the two causes apart, as `find-existing-capability` +describes: + +- **Not registered** (no `ai-dev:mcp-server` entry in `.mcp.json` or `.vscode/mcp.json`, and the + harness's MCP server list does not show it): go straight to the script below. There is nothing to + reconnect. +- **Registered but not connected:** start the server and ask the developer for a reload. After two + failed reconnects, use the script. + +The script searches the same capability map and reads `composer.lock`. Run it from the project root, +one quoted argument per query (the feature name and its synonyms): + +```bash +php /../find-existing-capability/scripts/capability-search.php "recurring orders" "subscription order" "scheduled reorder" +``` + +Per hit it prints `slug`, `installStatus`, `features`, `missingPackages`, `composerRequire` and +`url`. In place of `getSprykerCapability`, fetch the hit's `url`: it is the card. Without PHP or +network, use the web fallback of `find-existing-capability` (`INDEX.md`). **Never guess a card slug +or a package name.** Record in `state.md` that the search ran through a fallback. ## Phase 0 — Preflight and baselines @@ -107,7 +123,7 @@ and compare its packages with `composer.lock` by hand; the install status is the ## Phase 1 — Resolve the feature and its release 1. **The feature.** From a card: `getSprykerCapability(slug)`. From a name: `searchSprykerCapabilities` - with the name and its synonyms, then open the best card. Its Install section lists the + (or the search script, § Tools) with the name and its synonyms, then open the best card. Its Install section lists the `spryker-feature/` package and guide URL, `Requires features:`, the Glue API guide and the Storefront API packages. A card with several features offers alternatives: take the one that matches the project. From 214dd13366d646402047678467c944ced8b4b93f Mon Sep 17 00:00:00 2001 From: Veronika Golska Date: Tue, 17 Nov 2026 16:45:12 +0100 Subject: [PATCH 10/18] spryker-feature-install: cover the installed feature with tests - Phase 6b ports the reference demo shop's tests for the feature and adds functional, Glue API or Cypress tests, only for the suites the project already runs, after verification passes. - find-feature-change.php adds the reference change's tests as rows of kind test instead of listing them as not a step. - check-checklist.php --phase report fails when no test row is done, unless tests_waived holds the developer's reason. - The confirmation block names the planned tests; the report lists them. --- .../skills/spryker-feature-install/README.md | 8 ++-- .../skills/spryker-feature-install/SKILL.md | 41 ++++++++++++++++++- .../references/release-steps.md | 9 ++-- .../references/sources.md | 2 +- .../scripts/check-checklist.php | 14 ++++++- .../scripts/feature-install.test.php | 18 +++++--- .../scripts/find-feature-change.php | 9 ++-- .../scripts/parse-integration-guide.php | 1 + 8 files changed, 81 insertions(+), 21 deletions(-) diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/README.md b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/README.md index f49c59e..085906a 100644 --- a/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/README.md +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/README.md @@ -30,7 +30,8 @@ flowchart TD R --> I["5 - Install
composer, check-lock-diff, override checks
one guide section at a time, spryker-refresher
gate: check-feature-installed --wiring"] I --> Y["5b - Storefront placement
yves-integration-scan suggestions
yves-twig-integration on the developer's pick"] Y --> V["6 - Verify
auth precondition, spryker-verifier per
Verification row, baselines compared"] - V --> RS["7 - Release steps
diff-release-steps, prove with
deployed vs fresh comparison"] + V --> T["6b - Tests
port the reference tests, add functional,
API or Cypress tests the project runs"] + T --> RS["7 - Release steps
diff-release-steps, prove with
deployed vs fresh comparison"] RS --> RP(["8 - Report
gate: check-checklist report"]) ``` @@ -44,7 +45,7 @@ flowchart TD | `parse-integration-guide.php` | 3 | which steps does the guide have, of which kind, in which scenario? | | `check-feature-installed.php` | 3 (`--mark`), 5 (`--wiring`) | which modules and wiring does the project have already; is the decided wiring in place; which plugins belong to modules the project does not install? | | `find-feature-change.php` | 4 | which pull request brought the feature into the reference demo shop, and which of its files does no row name? | -| `check-checklist.php` | 4 (`--phase decide`), 8 (`--phase report`) | is every row decided; is every row done and every verification passed? | +| `check-checklist.php` | 4 (`--phase decide`), 8 (`--phase report`) | is every row decided; is every row done, every verification passed, and the feature covered by a passing test? | | `check-lock-diff.php` | 5 | which packages did the install move outside the feature's dependency tree; does a required package have a dev constraint? | | `glossary-key-check.php` | 5 | which translation keys of the feature's Yves modules have no glossary row? | | `diff-release-steps.php` | 7 | which commands, imports, republishes and variables does the deploy recipe not cover? | @@ -75,7 +76,7 @@ Everything a run writes is in the project, under `.ai-dev/feature-install/`, `demo-data`, `fresh-install-only` | | `data_class` | Data rows only: `feature-data`, `project-content`, `demo-data`, or null until decided | | `target` | The file, the command, the plugin class, or the linked page | @@ -102,6 +103,7 @@ wiring snippet in the guide: the guide lists the plugin and shows nowhere how to another feature package or a third-party root pin means an upgrade. - **The guide is the source of truth for steps; the installed code for names.** - **Project layer only.** Never `vendor/`, `src/Generated/` or `src/Orm/`. +- **The feature is covered by tests** in the suites the project runs; only the developer can waive it. - **Release steps are proven.** A command the guide runs locally is a release step until a recipe covers it. - **Blocked is not failed.** A failed fixture login makes logged-in checks BLOCKED (environment). diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/SKILL.md b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/SKILL.md index 48e688a..c884a67 100644 --- a/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/SKILL.md +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/SKILL.md @@ -42,7 +42,10 @@ extended, not rebuilt. Typical entry: `find-existing-capability` returned `not_i offers) is not a step. 6. **Data rows go to `project-data`.** This skill writes no row in `data/import/**`. 7. **A command the guide runs locally is a release step until a recipe covers it** (Phase 7). -8. **Project layer only, and no shortcuts:** never `vendor/`, `src/Generated/`, `src/Orm/` or a +8. **The installed feature is covered by tests** in the suites the project runs (Phase 6b). Without + them, the next upgrade has nothing that notices the feature stopped working. Only the developer + can waive this, with a reason. +9. **Project layer only, and no shortcuts:** never `vendor/`, `src/Generated/`, `src/Orm/` or a hand-edited `composer.lock`; never `dev-*` constraints or `--ignore-platform-reqs`; never a suppression; never `docker/sdk reset` or `clean-data`; never a commit or push without the developer's yes. @@ -177,6 +180,8 @@ was not found. - that storefront placement comes after the backend steps, as a suggestion list; - the environment: a bootstrap when the preflight found the stack down; any pre-existing issue; - the branch: `ai-feature/` from `HEAD` when `git status` is clean; else ask first; + - the tests that will cover the feature (Phase 6b): the suites the project has, and the + reference tests to port; - commits: one per guide section (recommended), or none until the report. Set `skip:` on every row of a block the developer did not choose. @@ -259,6 +264,37 @@ widgets; every vendor template the project overrides has lost the vendor's calls BLOCKED that stays goes to the developer: fix it, or accept it (`verdict: ACCEPTED` with a `verdict_note`: who and why). +## Phase 6b — Cover the feature with tests + +The tests pin what Phase 6 verified, so the next upgrade notices when the feature stops working. +Write them after Phase 6 passes, never before: a test written on a broken install pins the damage. + +1. **Find what the project runs.** Functional tests: `codeception.yml` and suites under + `tests/Test/` (Zed, Client, Yves, Glue). E2E tests: `cypress.config.*` or a + `tests/cypress*` directory. Use only the kinds the project already has; do not introduce a + framework. +2. **Start from the reference.** The `test` rows that `find-feature-change.php` added are the + reference demo shop's tests for the feature. Port each one into the project's namespace, fixtures + and data, or skip it with the reason (a scenario the developer declined, a capability the project + lacks). +3. **Cover what the reference does not.** One test per behaviour the feature adds, not per class: + - backend behaviour (a Verification row with a Back Office, API or database result, a plugin + stack the feature extends): a functional test through the Facade or the public Client or + Service, written with `codecept-functional`; + - an API block the developer chose: a Glue API test in the project's Glue suite; + - a storefront or Back Office flow, when the project has Cypress: an E2E test with + `cypress-tests`. + + The rules of [../spryker-upgrade/references/testing.md](../spryker-upgrade/references/testing.md) + apply: no tests for `*Factory`, `*Config` or `*DependencyProvider` classes, no getter or wiring + tests, no mocks of the feature's own modules. +4. **Each test is a checklist row** of kind `test`, with the test file as its `target`. Set + `status: done` only after it passes in the booted environment. Run the project's suite again: the + new tests must not turn an existing test red. +5. **A project without any test suite:** ask the developer. Only their answer can set + `tests_waived` in `checklist.json` (who and why); the report then names the feature as not + covered by tests. + ## Phase 7 — Release steps Do [references/release-steps.md](references/release-steps.md) exactly, in its order: list the @@ -271,7 +307,8 @@ proven. 1. Gate: `php $FI/check-checklist.php $STATE/checklist.json --phase report` exits 0. 2. Write `$STATE/report.md` in the shape that [references/release-steps.md](references/release-steps.md) § The report gives: installed, - differences from the guide, data, storefront placement, verification, release steps, not verified. + differences from the guide, data, storefront placement, verification, tests, release steps, not + verified. 3. Leave uncommitted changes unstaged for review. Stage only the files you changed, by path, and commit or push only on the developer's yes. diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/references/release-steps.md b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/references/release-steps.md index 0fb1104..bf77a63 100644 --- a/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/references/release-steps.md +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/references/release-steps.md @@ -109,10 +109,13 @@ the file that reads it, and what it holds. 4. **Data** — the hand-offs, per `data_class`, and the placeholders listed for `curate-golive-data`. 5. **Storefront placement** — the placements applied (widget, project file), declined, or the suggestion table as a follow-up; "no Yves code" when the step did not apply. -6. **Verification** — each `verification` row: PASS, or ACCEPTED with its note. The baseline +6. **Tests** — each `test` row: the test file, what behaviour it pins, ported from the reference or + new, and its suite. Or the `tests_waived` reason, with the line "the feature is not covered by + tests". +7. **Verification** — each `verification` row: PASS, or ACCEPTED with its note. The baseline comparison: PHPStan, sniffer, tests, Back Office crawl, storage and search counts. -7. **Release steps** — staging first, production after the check on staging passes. Per step: the +8. **Release steps** — staging first, production after the check on staging passes. Per step: the command, the reason, recipe entry or one-time job, and `verified` or `to verify`. -8. **Not verified** — every check that did not run, and what it would have found. +9. **Not verified** — every check that did not run, and what it would have found. Use only `verified` steps as instructions; list the `to verify` steps under their own heading. diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/references/sources.md b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/references/sources.md index 48c5e02..4f0d739 100644 --- a/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/references/sources.md +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/references/sources.md @@ -88,7 +88,7 @@ A full bare clone: a shallow or blob-filtered clone cannot search the history. `find-feature-change.php` uses it in Phase 4. It takes the first commit that added the feature package to `composer.json`, and the merge that brought that commit into the default branch. That merge is the reference change: every file it changed is named by a checklist row, added as a -`reference-only` row, or listed as not a step (tests, generated code, lock files). +`reference-only` row (its tests as `test` rows), or listed as not a step (generated code, lock files, CI). No label or link convention ties a pull request to a feature, so a title search can find nothing or the wrong pull request. A feature that came through a long-lived branch is found at its merge diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/check-checklist.php b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/check-checklist.php index 4f95503..f5433ac 100644 --- a/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/check-checklist.php +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/check-checklist.php @@ -10,11 +10,14 @@ * --phase decide after reconcile, before the install: every row has a valid decision, no row * is `unknown`, every data row that is not skipped has a `data_class` * --phase report (default) before the report: the decide checks, plus every row is `done` or - * `skipped`, and every verified row has a passing verdict + * `skipped`, every verified row has a passing verdict, and at least one `test` + * row is `done` * * A row's `decision` is one of apply-guide, apply-reference, merge, already-present or * skip:. A `verification` row that is not skipped needs `verdict` PASS, or ACCEPTED with a - * `verdict_note` that names who accepted it and why. + * `verdict_note` that names who accepted it and why. A feature without a passing test is only + * accepted when the checklist's `tests_waived` holds the developer's reason: the next upgrade has + * nothing else that notices the feature stopped working. * * Exit codes: 0 clean; 1 problems (listed by row); 2 usage or unreadable checklist. */ @@ -76,6 +79,13 @@ function cc_problems(array $checklist, string $phase): array } } + if ($phase === 'report') { + $coveringTests = array_filter($checklist['rows'], static fn (array $row): bool => ($row['kind'] ?? '') === 'test' && ($row['status'] ?? '') === 'done'); + if ($coveringTests === [] && trim((string)($checklist['tests_waived'] ?? '')) === '') { + $problems[] = 'no test covers the feature: add `test` rows and make them pass (Phase 6b), or set `tests_waived` to the developer\'s reason'; + } + } + return $problems; } diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/feature-install.test.php b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/feature-install.test.php index e4d21f5..4bf9467 100644 --- a/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/feature-install.test.php +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/feature-install.test.php @@ -156,17 +156,22 @@ function decided_row(array $overrides): array echo "check-checklist\n"; $undecided = parse_fixture('multiple-carts-glue-api'); check('a fresh checklist fails decide: no decisions', in_array(true, array_map(static fn (string $p): bool => str_contains($p, 'no decision'), cc_problems($undecided, 'decide')), true)); -$clean = ['rows' => [decided_row([]), decided_row(['id' => 'R002', 'kind' => 'verification', 'verdict' => 'PASS'])]]; -check('a decided, done, verified checklist passes report', cc_problems($clean, 'report') === []); +$testRow = decided_row(['id' => 'R099', 'kind' => 'test', 'target' => 'tests/PyzTest/Zed/X/Business/XFacadeTest.php', 'source' => 'reference-only']); +$clean = ['rows' => [decided_row([]), decided_row(['id' => 'R002', 'kind' => 'verification', 'verdict' => 'PASS']), $testRow]]; +check('a decided, done, verified and tested checklist passes report', cc_problems($clean, 'report') === []); +check('a checklist with no passing test fails report', in_array(true, array_map(static fn (string $p): bool => str_contains($p, 'no test covers the feature'), cc_problems(['rows' => [decided_row([])]], 'report')), true)); +check('an open test row does not count', cc_problems(['rows' => [decided_row([]), decided_row(['kind' => 'test', 'status' => 'open'])]], 'report') !== []); +check('a waiver with the developer\'s reason passes report', cc_problems(['rows' => [decided_row([])], 'tests_waived' => 'developer: covered by the existing Cypress suite'], 'report') === []); +check('the test gate does not apply at decide', cc_problems(['rows' => [decided_row([])]], 'decide') === []); check('skip without a reason fails', cc_problems(['rows' => [decided_row(['decision' => 'skip:', 'status' => 'skipped'])]], 'decide') !== []); check('apply-reference without a reference fails', cc_problems(['rows' => [decided_row(['decision' => 'apply-reference'])]], 'decide') !== []); check('a data row without data_class fails', cc_problems(['rows' => [decided_row(['kind' => 'data-row', 'target' => 'data/import/x.csv'])]], 'decide') !== []); -check('a skipped data row needs no data_class', cc_problems(['rows' => [decided_row(['kind' => 'data-row', 'decision' => 'skip:demo data declined', 'status' => 'skipped'])]], 'report') === []); +check('a skipped data row needs no data_class', cc_problems(['rows' => [decided_row(['kind' => 'data-row', 'decision' => 'skip:demo data declined', 'status' => 'skipped']), $testRow]], 'report') === []); check('an unknown kind fails', cc_problems(['rows' => [decided_row(['kind' => 'unknown', 'lines' => [3, 9]])]], 'decide') !== []); check('an open row passes decide but fails report', cc_problems(['rows' => [decided_row(['status' => 'open'])]], 'decide') === [] && cc_problems(['rows' => [decided_row(['status' => 'open'])]], 'report') !== []); check('a verification row without a verdict fails report', cc_problems(['rows' => [decided_row(['kind' => 'verification'])]], 'report') !== []); check('ACCEPTED without a verdict_note fails', cc_problems(['rows' => [decided_row(['kind' => 'verification', 'verdict' => 'ACCEPTED'])]], 'report') !== []); -check('ACCEPTED with a verdict_note passes', cc_problems(['rows' => [decided_row(['kind' => 'verification', 'verdict' => 'ACCEPTED', 'verdict_note' => 'developer: covered by the API test'])]], 'report') === []); +check('ACCEPTED with a verdict_note passes', cc_problems(['rows' => [decided_row(['kind' => 'verification', 'verdict' => 'ACCEPTED', 'verdict_note' => 'developer: covered by the API test']), $testRow]], 'report') === []); echo "check-lock-diff\n"; $lockDir = temp_dir('lock'); @@ -283,9 +288,10 @@ function decided_row(array $overrides): array [$exit, $output] = run_script('find-feature-change.php', ['--repo', $repo, '--package', 'spryker-feature/x', '--checklist', $refPath, '--add-rows'], $repo); $withRef = fi_load_checklist($refPath); check('the merge of the first commit that required the package is found', $exit === 0 && str_contains($output, 'Merge pull request #12') && ($withRef['reference_change']['pr'] ?? null) === 12); -check('a changed file no row names becomes a reference-only row', array_column(rows_where($withRef, static fn (array $r): bool => $r['source'] === 'reference-only'), 'target') === ['src/Pyz/Yves/CartPage/Theme/default/views/cart/cart.twig']); +check('a changed file no row names becomes a reference-only row', array_column(rows_where($withRef, static fn (array $r): bool => $r['source'] === 'reference-only'), 'target') === ['src/Pyz/Yves/CartPage/Theme/default/views/cart/cart.twig', 'tests/PyzTest/Zed/Cart/CartTest.php']); check('a reference-only row is classified and undecided', ($withRef['rows'][1]['kind'] ?? '') === 'frontend' && $withRef['rows'][1]['decision'] === null); -check('tests and composer files are not steps', str_contains($output, '2 not a step')); +check('a test of the reference change is a test row', ($withRef['rows'][2]['kind'] ?? '') === 'test'); +check('composer files are not steps', str_contains($output, '1 not a step')); [$exit] = run_script('find-feature-change.php', ['--repo', $repo, '--package', 'spryker-feature/never'], $repo); check('a package the reference never required exits 1', $exit === 1); diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/find-feature-change.php b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/find-feature-change.php index e879d8a..df19804 100644 --- a/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/find-feature-change.php +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/find-feature-change.php @@ -5,8 +5,9 @@ * and the files it changed that no guide row names. * * A guide names the wiring and the config, but the reference change also carries templates, - * DependencyProviders of neighbouring modules, OMS processes for its own payment methods, and data - * files. Those files reach the checklist only through the reference change. The finder needs no + * DependencyProviders of neighbouring modules, OMS processes for its own payment methods, data files + * and the tests that cover the feature (rows of kind `test`, ported in Phase 6b). Those files reach + * the checklist only through the reference change. The finder needs no * title search: the first commit that added the feature package to composer.json leads to the * merge that brought it into the branch. * @@ -27,7 +28,7 @@ require_once __DIR__ . '/parse-integration-guide.php'; /** Files a reference change carries that are never a step for the project. */ -const FFC_NOT_A_STEP = '#^(tests/|src/Orm/|src/Generated/|composer\.(json|lock)$|package-lock\.json$|\.github/|codeception|phpstan|architecture-baseline)#'; +const FFC_NOT_A_STEP = '#^(src/Orm/|src/Generated/|composer\.(json|lock)$|package-lock\.json$|\.github/|codeception|phpstan|architecture-baseline)#'; /** * @return array{0: int, 1: string} @@ -181,7 +182,7 @@ function ffc_main(array $argv): int $result = ffc_add_rows($checklist, $files, $merge); $checklist['reference_change'] = ['package' => $options['package'], 'pr' => $merge['pr'], 'merge' => $merge['merge'], 'via' => $merge['via']]; fi_save_checklist((string)$options['checklist'], $checklist); - fwrite(STDOUT, sprintf(" %d named by a row already, %d not a step (tests, generated code, lock files), %d reference-only row(s) added.\n", count($result['covered']), count($result['not_a_step']), count($result['added']))); + fwrite(STDOUT, sprintf(" %d named by a row already, %d not a step (generated code, lock files, CI), %d reference-only row(s) added.\n", count($result['covered']), count($result['not_a_step']), count($result['added']))); foreach ($result['added'] as $file) { fwrite(STDOUT, " + $file\n"); } diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/parse-integration-guide.php b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/parse-integration-guide.php index c87afa7..540b4ed 100644 --- a/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/parse-integration-guide.php +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/parse-integration-guide.php @@ -160,6 +160,7 @@ function pig_classify_path(string $path, string $code): string { $file = basename($path); $rules = [ + ['#^tests/#', 'test'], ['/\.transfer\.xml$/', 'transfer'], ['/\.schema\.xml$/', str_contains($code, 'name="event"') ? 'event' : 'schema'], ['#(^|/)config/Zed/(oms|StateMachine)/#', 'oms'], From 2f34495440d9351743dcde12afd3beaf0be6281f Mon Sep 17 00:00:00 2001 From: Veronika Golska Date: Tue, 17 Nov 2026 16:56:26 +0100 Subject: [PATCH 11/18] spryker-feature-install: always dry-run composer, mark optional prerequisites - Phase 1 dry-runs the composer require at every install release, with -w and -W, and shows the developer every update, major bump and removal of both. A feature at the project's own release can still move many modules. - The parser marks a prerequisite optional when the table says (optional) or the text below the table (an info box included) calls it optional. Phase 1 asks about a missing optional prerequisite instead of installing it first, and skips the rows that need it when declined. - New fixture: the Recurring Orders guide (two optional prerequisites). --- .../skills/spryker-feature-install/SKILL.md | 39 +- .../scripts/feature-install.test.php | 16 + .../fixtures/guides/recurring-orders.txt | 1797 +++++++++++++++++ .../scripts/parse-integration-guide.php | 27 +- 4 files changed, 1866 insertions(+), 13 deletions(-) create mode 100644 plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/fixtures/guides/recurring-orders.txt diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/SKILL.md b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/SKILL.md index c884a67..5d6ae36 100644 --- a/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/SKILL.md +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/SKILL.md @@ -132,23 +132,36 @@ or a package name.** Record in `state.md` that the search ran through a fallback matches the project. 2. **What is there.** `installed` → nothing to install: hand back to `find-existing-capability` (extend it). `partially_installed` → install only `missingPackages`. -3. **Required features first.** Check each one against `composer.lock`. Each one that is missing is - its own run, before this one; offer it. +3. **Required features first.** The candidates are the card's `Requires features:` and the guide's + Prerequisites table. A prerequisite is **optional** when the guide says so (`(optional)` in the + table, or the text below the table; the parser records it as `optional: true` in Phase 3) or when + the feature package's `composer.json` does not require it. Check each one against + `composer.lock`: + - a missing required one is its own run, before this one: offer it; + - a missing optional one: ask whether to install it first. When the developer declines, the + guide rows that need it are `skip: not installed`; `check-feature-installed.php` + reports their classes as not in `vendor/`. 4. **The project type** in `state.md`: B2B or B2C, with or without marketplace. Phase 4 uses it. 5. **The install release.** Read the project's release (`spryker-feature/spryker-core` in - `composer.lock`) and the releases of the feature (`composer show -a spryker-feature/`): - - The feature exists at the project's release → install at that release. - - The feature first exists in a later release → dry-run in the container: - `composer require spryker-feature/:^ -W --dry-run`. A conflict that names - a `spryker/*` module and a minimum version → add `spryker/:^` to the same - `require` and dry-run again, until it resolves. Each major bump among the moved modules needs - its migration guide, as `spryker-upgrade` Lane 0 describes. + `composer.lock`) and the releases of the feature (`composer show -a spryker-feature/`). The + feature exists at the project's release → that is the install release. The feature first exists + in a later release → that first release is the install release. +6. **Dry-run the install, always, in the container**, also at the project's own release: the + project's modules are often older than the versions the feature needs, so the require moves + modules even then. Run it twice and compare: + `composer require spryker-feature/:^ -w --dry-run` (direct dependencies only) + and the same with `-W` (all dependencies). + - A conflict that names a `spryker/*` module and a minimum version → add + `spryker/:^` to the same `require` and dry-run again, until it resolves. + - Show the developer the result of both: how many packages each installs, updates and removes, + every major bump, and every removal. Recommend the one that moves less, unless it does not + resolve. Each major bump needs its migration guide, as `spryker-upgrade` Lane 0 describes. - Stop and offer `spryker-upgrade` (`/spryker-upgrade`, or `/spryker-ai-dev-sdk:spryker-upgrade` on a plugin install) when another `spryker-feature/*` package must move, a conflict names a package that is not a `spryker/*` module (a root pin of a Symfony or other third-party package), the same package comes back in a later round, or nothing resolves. Name the blocking packages from the composer output. - Record the install release and the added modules in `state.md`. + Record in `state.md` the install release, the added modules, and both dry-run results. ## Phase 2 — Collect the sources @@ -173,6 +186,8 @@ was not found. in chat). It carries: - the feature, the packages `composer require` adds, the install release, the modules Phase 1 added, and required features to install first; + - the update mode, `-w` or `-W`, with the moves of each from the Phase 1 dry runs; + - each missing optional prerequisite: install it first, or skip the rows that need it; - the version constraint in the project's style (`^` for features, `^x.y.z` for modules); - the optional blocks, one choice each: every `optional-scenario:*` tag, the Glue, Storefront and @@ -202,8 +217,8 @@ Read [references/reconcile.md](references/reconcile.md) on entry. ## Phase 5 — Install -1. Run the `composer` rows in the container, with the install release and the modules Phase 1 - added. On a conflict, report it and stop. Then: +1. Run the `composer` rows in the container, with the install release, the modules Phase 1 added, + and the update mode the developer chose. On a conflict, report it and stop. Then: ```bash php $FI/check-lock-diff.php --before $STATE/composer.lock.before --checklist $STATE/checklist.json ``` diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/feature-install.test.php b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/feature-install.test.php index 4bf9467..5e6c104 100644 --- a/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/feature-install.test.php +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/feature-install.test.php @@ -124,6 +124,22 @@ function decided_row(array $overrides): array check('three prerequisites', count($glue['guides'][0]['prerequisites']) === 3); check(' header names the file', rows_where($glue, static fn (array $r): bool => $r['kind'] === 'plugin')[0]['target'] === 'src/Pyz/Zed/CartsRestApi/CartsRestApiDependencyProvider.php'); +echo "parse-integration-guide: optional prerequisites (Recurring Orders)\n"; +$ro = parse_fixture('recurring-orders'); +$prerequisiteState = array_column(array_map(static fn (array $p): array => [$p['name'], $p['optional']], $ro['guides'][0]['prerequisites']), 1, 0); +check('prerequisites the info box calls optional are optional', $prerequisiteState['Purchasing Control'] === true && $prerequisiteState['SSP Service Management'] === true); +check('the other prerequisites stay required', $prerequisiteState['Spryker Core'] === false && $prerequisiteState['Company Account'] === false && $prerequisiteState['Checkout'] === false); +check('no fixture guide gets a false optional prerequisite', array_filter(array_merge($oa['guides'][0]['prerequisites'], $ssp['guides'][0]['prerequisites'], $glue['guides'][0]['prerequisites']), static fn (array $p): bool => $p['optional']) === []); +$marked = [['name' => 'Cart', 'optional' => false], ['name' => 'Product', 'optional' => false]]; +pig_mark_optional_prerequisites($marked, 'Install Cart first; it is required.'); +check('a line without "optional" marks nothing', $marked[0]['optional'] === false); +pig_mark_optional_prerequisites($marked, 'The Product feature is optional.'); +check('a line with "optional" marks only the prerequisites it names', $marked[0]['optional'] === false && $marked[1]['optional'] === true); +$tableDir = temp_dir('optional-cell'); +write_file($tableDir . '/guide.md', "## Install feature core\n\n### Prerequisites\n\n| NAME | VERSION | INSTALLATION GUIDE |\n| --- | --- | --- |\n| Glue API (optional) | 202608.0 | [Install](/docs/x.html) |\n"); +$cellParsed = pig_parse_guide($tableDir . '/guide.md', null, '202608.0'); +check('"(optional)" in the name cell marks it and is removed from the name', $cellParsed['guide']['prerequisites'][0] === ['name' => 'Glue API', 'version' => '202608.0', 'guide' => 'Install', 'url' => '/docs/x.html', 'optional' => true]); + echo "parse-integration-guide: units\n"; check('header **path**', pig_header_path('**src/Pyz/Zed/Sales/SalesDependencyProvider.php**') === 'src/Pyz/Zed/Sales/SalesDependencyProvider.php'); check('header with a stray > and leading slash', pig_header_path('**>/data/import/local/full_EU.yml**') === 'data/import/local/full_EU.yml'); diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/fixtures/guides/recurring-orders.txt b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/fixtures/guides/recurring-orders.txt new file mode 100644 index 0000000..f45105c --- /dev/null +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/fixtures/guides/recurring-orders.txt @@ -0,0 +1,1797 @@ +--- +title: Install the Recurring Orders feature +description: Learn how to install the Recurring Orders feature into your Spryker project. +last_updated: Aug 17, 2026 +template: feature-integration-guide-template +related: + - title: Recurring Orders feature overview + link: docs/pbc/all/order-experience-management/latest/base-shop/feature-overviews/recurring-orders-feature-overview.html +--- + +This document describes how to install the Recurring Orders feature. + +## Install feature core + +Follow the steps below to install the Recurring Orders feature core. + +### Prerequisites + +To start feature integration, review and install the necessary features: + +| NAME | VERSION | INSTALLATION GUIDE | +| --- | --- | --- | +| Spryker Core | {{page.release_tag}} | [Install the Spryker Core feature](/docs/pbc/all/miscellaneous/latest/install-and-upgrade/install-features/install-the-spryker-core-feature.html) | +| Company Account | {{page.release_tag}} | [Install the Company Account feature](/docs/pbc/all/customer-relationship-management/latest/base-shop/install-and-upgrade/install-features/install-the-company-account-feature.html) | +| Checkout | {{page.release_tag}} | [Install the Checkout feature](/docs/pbc/all/cart-and-checkout/latest/base-shop/install-and-upgrade/install-features/install-the-checkout-feature.html) | +| Purchasing Control | {{page.release_tag}} | [Install the Purchasing Control feature](/docs/pbc/all/cart-and-checkout/latest/base-shop/install-and-upgrade/install-features/install-the-purchasing-control-feature.html) | +| SSP Service Management | {{page.release_tag}} | [Install the SSP Service Management feature](/docs/pbc/all/self-service-portal/latest/install/install-the-ssp-service-management-feature.html) | + +{% info_block infoBox "Optional features" %} + +Both Purchasing Control and SSP Service Management are optional: + +- Install Purchasing Control if you want buyers to assign a cost center and budget to a recurring order. Without it, the cost center and budget fields are not rendered on the recurring order forms. +- Install SSP Service Management if your catalog contains service products. It restricts which service products buyers can add to a recurring schedule on the **Review Required** page. Without it, no service-specific restriction is applied. + +{% endinfo_block %} + +### 1) Install the required modules + +{% info_block infoBox "Required modules" %} + +```bash +composer require spryker-feature/order-experience-management:"^1.0.0" --update-with-dependencies +composer update \ + spryker/availability:"^9.32.0" \ + spryker/merchant:"^3.20.0" \ + spryker/merchant-product:"^1.3.0" \ + spryker/merchant-product-option:"^1.4.0" \ + spryker/merchant-storage:"^1.0.0" \ + spryker/merchant-switcher:"^0.6.8" \ + spryker/product-alternative-storage:"^1.15.0" \ + spryker/product-approval:"^1.5.0" \ + spryker/product-bundle:"^7.28.0" \ + spryker/product-cart-connector:"^4.15.0" \ + spryker/product-configuration-cart:"^1.1.0" \ + spryker/product-discontinued:"^1.15.0" \ + spryker/product-measurement-unit:"^5.0.0" \ + spryker/product-offer:"^1.18.0" \ + spryker/product-offer-storage:"^1.0.0" \ + spryker/product-packaging-unit:"^4.14.0" \ + spryker/product-packaging-unit-storage:"^5.5.0" \ + spryker/product-quantity:"^3.8.0" \ + spryker/shipment-type-storage:"^1.0.0" \ + spryker-feature/purchasing-control:"^1.1.1" \ + spryker-shop/checkout-page:"^3.42.0" \ + spryker-shop/customer-page:"^2.80.0" \ + spryker-shop/merchant-product-offer-widget:"^2.0.0" \ + spryker-shop/product-search-widget:"^3.9.0" \ + spryker-shop/shop-ui:"^2.0.0" \ + --with-dependencies +``` + +{% endinfo_block %} + +{% info_block infoBox "Modules required by the add-product flow" %} + +The **Review Required** page lets buyers add products to the order being placed. That flow pulls in the following modules, so install them even if your project does not use the corresponding functionality elsewhere: + +| MODULE | PURPOSE | +| --- | --- | +| `spryker-shop/product-search-widget` | Provides `ProductConcreteSearchWidget` and the `products-list` molecule that the add-product search bar reuses. | +| `spryker-shop/merchant-product-offer-widget` | Backs the merchant offer selector rendered for an added product in a marketplace setup. | +| `spryker-shop/shop-ui` | Provides the `Component` base class, `AjaxProvider`, and app registry used by the recurring order web components. | +| `spryker/product-alternative-storage` | Provides the alternative products offered as substitutes for discontinued and substituted items. | +| `spryker/shipment-type-storage` | Resolves the shipment types of an added product to decide whether a recurring order can serve it. | +| `spryker/product-measurement-unit`, `spryker/product-packaging-unit-storage` | Detect products sold in measurement or packaging units so they can be excluded from the add-product picker. | + +{% endinfo_block %} + +{% info_block infoBox "Merchant Switcher" %} + +`spryker/merchant-switcher` is not a dependency of the feature. Include it in the `composer update` command only if your project uses Merchant Switcher. Its checkout error type is one of the types mapped to a review reason group, so a project without the module simply never produces that error. + +{% endinfo_block %} + +### 2) Set up database schema and transfer objects + +Apply database changes and generate entity and transfer changes: + +```bash +console propel:install +console transfer:generate +``` + +{% info_block warningBox "Verification" %} + +Make sure the following changes have been applied in the database: + +| DATABASE ENTITY | TYPE | EVENT | +| --- | --- | --- | +| spy_recurring_schedule | table | created | +| spy_recurring_schedule_item | table | created | +| spy_recurring_schedule_history | table | created | +| spy_recurring_schedule_forecast | table | created | + +Make sure the following changes have been applied in transfer objects: + +| TRANSFER | TYPE | EVENT | PATH | +| --- | --- | --- | --- | +| RecurringSchedule | class | created | src/Generated/Shared/Transfer/RecurringScheduleTransfer.php | +| RecurringScheduleCollection | class | created | src/Generated/Shared/Transfer/RecurringScheduleCollectionTransfer.php | +| RecurringScheduleCriteria | class | created | src/Generated/Shared/Transfer/RecurringScheduleCriteriaTransfer.php | +| RecurringScheduleConditions | class | created | src/Generated/Shared/Transfer/RecurringScheduleConditionsTransfer.php | +| RecurringScheduleCollectionRequest | class | created | src/Generated/Shared/Transfer/RecurringScheduleCollectionRequestTransfer.php | +| RecurringScheduleCollectionResponse | class | created | src/Generated/Shared/Transfer/RecurringScheduleCollectionResponseTransfer.php | +| RecurringScheduleItem | class | created | src/Generated/Shared/Transfer/RecurringScheduleItemTransfer.php | +| RecurringScheduleItemAddition | class | created | src/Generated/Shared/Transfer/RecurringScheduleItemAdditionTransfer.php | +| RecurringScheduleHistory | class | created | src/Generated/Shared/Transfer/RecurringScheduleHistoryTransfer.php | +| RecurringScheduleValidationResult | class | created | src/Generated/Shared/Transfer/RecurringScheduleValidationResultTransfer.php | +| RecurringScheduleItemReview | class | created | src/Generated/Shared/Transfer/RecurringScheduleItemReviewTransfer.php | +| RecurringScheduleSubstituteOption | class | created | src/Generated/Shared/Transfer/RecurringScheduleSubstituteOptionTransfer.php | +| RecurringScheduleShippingAddressChoice | class | created | src/Generated/Shared/Transfer/RecurringScheduleShippingAddressChoiceTransfer.php | +| RecurringScheduleReviewResponse | class | created | src/Generated/Shared/Transfer/RecurringScheduleReviewResponseTransfer.php | +| RecurringScheduleEventRequest | class | created | src/Generated/Shared/Transfer/RecurringScheduleEventRequestTransfer.php | +| RecurringScheduleEventResponse | class | created | src/Generated/Shared/Transfer/RecurringScheduleEventResponseTransfer.php | +| RecurringScheduleStatusCount | class | created | src/Generated/Shared/Transfer/RecurringScheduleStatusCountTransfer.php | +| RecurringScheduleStatusCountCollection | class | created | src/Generated/Shared/Transfer/RecurringScheduleStatusCountCollectionTransfer.php | +| RecurringScheduleForecast | class | created | src/Generated/Shared/Transfer/RecurringScheduleForecastTransfer.php | +| RecurringScheduleForecastCollection | class | created | src/Generated/Shared/Transfer/RecurringScheduleForecastCollectionTransfer.php | +| RecurringScheduleForecastSnapshot | class | created | src/Generated/Shared/Transfer/RecurringScheduleForecastSnapshotTransfer.php | +| RecurringScheduleTableFilter | class | created | src/Generated/Shared/Transfer/RecurringScheduleTableFilterTransfer.php | +| RecurringScheduleDueData | class | created | src/Generated/Shared/Transfer/RecurringScheduleDueDataTransfer.php | +| RecurringScheduleError | class | created | src/Generated/Shared/Transfer/RecurringScheduleErrorTransfer.php | +| RecurringOrderSettings | class | created | src/Generated/Shared/Transfer/RecurringOrderSettingsTransfer.php | +| RecurringOrderQuoteUpdateRequest | class | created | src/Generated/Shared/Transfer/RecurringOrderQuoteUpdateRequestTransfer.php | +| RecurringOrderQuoteUpdateResponse | class | created | src/Generated/Shared/Transfer/RecurringOrderQuoteUpdateResponseTransfer.php | +| RecurringOrderReloadResult | class | created | src/Generated/Shared/Transfer/RecurringOrderReloadResultTransfer.php | +| Quote.recurringOrderSettings | property | created | src/Generated/Shared/Transfer/QuoteTransfer.php | + +{% endinfo_block %} + +### 3) Set up data import + +Import the CMS blocks that provide the HTML and text templates for recurring order notification emails. + +The CMS block definitions are provided in the module at `src/SprykerFeature/OrderExperienceManagement/data/import/cms_block.csv`. Copy the contents of that file and add them to **data/import/common/common/cms_block.csv**. + +For each store you want to enable the email notifications in, add the corresponding block keys to **data/import/common/{store}/cms_block_store.csv**. + +Import the data: + +```bash +console data:import:cms-block +console data:import:cms-block-store +``` + +{% info_block warningBox "Verification" %} + +In the Back Office, under **Content > Blocks**, make sure the CMS blocks from the module file are present and active. + +{% endinfo_block %} + +### 4) Set up behavior + +Enable the following behaviors by registering the plugins. + +#### Set up Checkout plugins + +| PLUGIN | SPECIFICATION | PREREQUISITES | NAMESPACE | +| --- | --- | --- | --- | +| RecurringOrderCheckoutPreConditionPlugin | Validates the quote is eligible for a recurring order before checkout proceeds. Checks that the quote is not locked, not from an RFQ, not a guest session, the payment method is invoice-based, and the cadence type is registered and valid. Also runs the registered recurring order checkout validator plugins. Does nothing when `recurringOrderSettings` is not set on the quote. | None | SprykerFeature\Zed\OrderExperienceManagement\Communication\Plugin\Checkout | +| RecurringOrdersCheckoutPostSavePlugin | Creates a recurring schedule and registers it with the state machine after the order is successfully saved. Does nothing when `recurringOrderSettings` is not set on the quote. | None | SprykerFeature\Zed\OrderExperienceManagement\Communication\Plugin\Checkout | + +**src/Pyz/Zed/Checkout/CheckoutDependencyProvider.php** + +```php + + */ + protected function getCheckoutPreConditions(Container $container): array + { + return [ + // ... + new RecurringOrderCheckoutPreConditionPlugin(), #RecurringOrdersFeature + ]; + } + + /** + * @param \Spryker\Zed\Kernel\Container $container + * + * @return list<\Spryker\Zed\CheckoutExtension\Dependency\Plugin\CheckoutPostSaveInterface> + */ + protected function getCheckoutPostHooks(Container $container): array + { + return [ + // ... + new RecurringOrdersCheckoutPostSavePlugin(), #RecurringOrdersFeature + ]; + } +} +``` + +{% info_block warningBox "Verification" %} + +1. Add a product to the cart, set a recurring order cadence on the quote, and complete checkout. Make sure a recurring schedule is created in `spy_recurring_schedule`. +2. Attempt to place a recurring order with a non-invoice payment method. Make sure checkout is blocked. +3. Attempt to place a recurring order with an invalid cadence type. Make sure checkout is blocked. + +{% endinfo_block %} + +#### Set up cadence type and schedule validator plugins + +Register the built-in cadence type and schedule validator plugins: + +| PLUGIN | SPECIFICATION | PREREQUISITES | NAMESPACE | +| --- | --- | --- | --- | +| WeeklyCadenceTypePlugin | Calculates the next trigger date 7 days after the current trigger date. | None | SprykerFeature\Zed\OrderExperienceManagement\Communication\Plugin\Cadence | +| BiWeeklyCadenceTypePlugin | Calculates the next trigger date 14 days after the current trigger date. | None | SprykerFeature\Zed\OrderExperienceManagement\Communication\Plugin\Cadence | +| MonthlyCadenceTypePlugin | Calculates the next trigger date on the same day of the following month. | None | SprykerFeature\Zed\OrderExperienceManagement\Communication\Plugin\Cadence | +| EveryNWeeksCadenceTypePlugin | Calculates the next trigger date every N weeks. Requires `cadenceValue` to be set on the schedule. | None | SprykerFeature\Zed\OrderExperienceManagement\Communication\Plugin\Cadence | +| PriceScheduleValidatorPlugin | Detects price increases on recurring schedule items compared to their stored reference prices before order placement. | None | SprykerFeature\Zed\OrderExperienceManagement\Communication\Plugin\ScheduleValidator | +| CheckoutPlaceabilityScheduleValidatorPlugin | Simulates a checkout to detect availability, discontinuation, or product approval issues on recurring schedule items before order placement. | None | SprykerFeature\Zed\OrderExperienceManagement\Communication\Plugin\ScheduleValidator | + +**src/Pyz/Zed/OrderExperienceManagement/OrderExperienceManagementDependencyProvider.php** + +```php + + */ + protected function getCadenceTypePlugins(): array + { + return [ + new WeeklyCadenceTypePlugin(), #RecurringOrdersFeature + new BiWeeklyCadenceTypePlugin(), #RecurringOrdersFeature + new MonthlyCadenceTypePlugin(), #RecurringOrdersFeature + new EveryNWeeksCadenceTypePlugin(), #RecurringOrdersFeature + ]; + } + + /** + * @return array<\SprykerFeature\Zed\OrderExperienceManagement\Dependency\Plugin\ScheduleValidatorPluginInterface> + */ + protected function getScheduleValidatorPlugins(): array + { + return [ + new PriceScheduleValidatorPlugin(), #RecurringOrdersFeature + new CheckoutPlaceabilityScheduleValidatorPlugin(), #RecurringOrdersFeature + ]; + } +} +``` + +{% info_block warningBox "Verification" %} + +Make sure all four cadence types (weekly, bi-weekly, monthly, every N weeks) are available when setting up a recurring order on the storefront. + +{% endinfo_block %} + +#### Set up recurring order checkout validator plugins + +Recurring order checkout validator plugins reject a quote that must not be checked out as a recurring order. `RecurringOrderCheckoutPreConditionPlugin` runs them after its own eligibility checks, and only when `QuoteTransfer.recurringOrderSettings` is set—a regular checkout is never affected. + +| PLUGIN | SPECIFICATION | PREREQUISITES | NAMESPACE | +| --- | --- | --- | --- | +| BudgetApprovalRuleRecurringOrderCheckoutValidatorPlugin | Blocks checkout when the budget selected on the quote uses the `require_approval` enforcement rule. A recurring order places its follow-up orders unattended, so no approval can be granted for them upfront. Applies regardless of the quote grand total and the remaining budget amount. Passes when no budget is selected or the budget uses another enforcement rule. | Purchasing Control feature | SprykerFeature\Zed\PurchasingControl\Communication\Plugin\OrderExperienceManagement | + +**src/Pyz/Zed/OrderExperienceManagement/OrderExperienceManagementDependencyProvider.php** + +```php + + */ + protected function getRecurringOrderCheckoutValidatorPlugins(): array + { + return [ + new BudgetApprovalRuleRecurringOrderCheckoutValidatorPlugin(), #RecurringOrdersFeature + ]; + } +} +``` + +{% info_block infoBox "Custom checkout validators" %} + +To block a recurring order checkout for a project-specific reason, implement `SprykerFeature\Zed\OrderExperienceManagement\Dependency\Plugin\RecurringOrderCheckoutValidatorPluginInterface`. Return a `CheckoutErrorTransfer` whose `message` is your own glossary key—and whose `parameters` are set when the message is parameterized—to reject the quote, or `null` when your check passes. + +Use this extension point for rules that apply to the recurring order as a whole at checkout time. To reject an individual product a buyer adds later on the **Review Required** page, use [AddedItemValidatorPluginInterface](#set-up-added-item-validator-plugins) instead. + +{% endinfo_block %} + +{% info_block warningBox "Verification" %} + +Set a budget's enforcement rule to **Require approval** in the Back Office, assign it to a cart, and set up that cart as a recurring order at checkout. Make sure checkout is blocked with a message stating that the selected budget requires approval and cannot be used for a recurring order. + +{% endinfo_block %} + +#### Set up added item validator plugins + +Added item validator plugins reject a product the buyer added on the **Review Required** page. They run after the item is resolved through the cart, so they see the resolved price, shipment, and any data the cart item expanders added. They also run after the module's own availability, price, and shipment checks, so they are only reached when those pass. + +| PLUGIN | SPECIFICATION | PREREQUISITES | NAMESPACE | +| --- | --- | --- | --- | +| ServiceProductAddedItemValidatorPlugin | Rejects a service item whose resolved shipment method is not one a recurring order can serve. A service fulfilled on site or in a service center needs an appointment, which a recurring order places unattended and therefore cannot book. | SSP Service Management feature | SprykerFeature\Zed\SelfServicePortal\Communication\Plugin\OrderExperienceManagement | + +**src/Pyz/Zed/OrderExperienceManagement/OrderExperienceManagementDependencyProvider.php** + +```php + + */ + protected function getAddedItemValidatorPlugins(): array + { + return [ + new ServiceProductAddedItemValidatorPlugin(), #RecurringOrdersFeature + ]; + } +} +``` + +`ServiceProductAddedItemValidatorPlugin` reads the accepted shipment type keys from `SelfServicePortalConfig`. The module default is an empty list, which accepts service products with any shipment type. Define the shipment types your project can serve unattended by overriding the constant in the shared config, which applies it in Yves and Zed at once: + +**src/Pyz/Shared/SelfServicePortal/SelfServicePortalConfig.php** + +```php + + */ + public const RECURRING_ORDER_SERVICE_SHIPMENT_TYPE_KEYS = [ + self::SHIPMENT_TYPE_DELIVERY, + ]; +} +``` + +| CONFIGURATION CONSTANT | DEFAULT | DESCRIPTION | +| --- | --- | --- | +| `RECURRING_ORDER_SERVICE_SHIPMENT_TYPE_KEYS` | `[]` | Shipment type keys a service product must support to be part of a recurring order. An empty list accepts service products with any shipment type. `getRecurringOrderServiceShipmentTypeKeys()` returns this constant, so overriding the constant is enough. | + +{% info_block infoBox "Configure the constant once" %} + +If your project follows [Install the SSP Service Management feature](/docs/pbc/all/self-service-portal/latest/install/install-the-ssp-service-management-feature.html), the constant is already defined in `src/Pyz/Shared/SelfServicePortal/SelfServicePortalConfig.php`. Define it in one place only. + +{% endinfo_block %} + +{% info_block infoBox "Custom added item validators" %} + +To reject added products for a project-specific reason, implement `SprykerFeature\Zed\OrderExperienceManagement\Dependency\Plugin\AddedItemValidatorPluginInterface`. Return an `ErrorTransfer` carrying your own glossary key to reject the addition, or `null` to accept it. Pair it with an `AddedProductConcreteRestrictionPluginInterface` implementation in Yves so the product is hidden from the picker as well as rejected on approval. + +{% endinfo_block %} + +{% info_block warningBox "Verification" %} + +Open the **Review Required** page for a schedule and add a service product whose shipment type is not in `RECURRING_ORDER_SERVICE_SHIPMENT_TYPE_KEYS`. Make sure the approval is rejected with an error message naming the product SKU. + +{% endinfo_block %} + +#### Set up the state machine handler + +Register the recurring orders state machine handler: + +| PLUGIN | SPECIFICATION | PREREQUISITES | NAMESPACE | +| --- | --- | --- | --- | +| RecurringOrdersStateMachineHandlerPlugin | Registers the `RecurringOrder` state machine process, maps commands and conditions to plugins, updates the state machine item state on each transition, and returns schedule items by state IDs. | None | SprykerFeature\Zed\OrderExperienceManagement\Communication\Plugin\StateMachine | + +**src/Pyz/Zed/StateMachine/StateMachineDependencyProvider.php** + +```php + + */ + protected function getStateMachineHandlers(): array + { + return [ + // ... + new RecurringOrdersStateMachineHandlerPlugin(), #RecurringOrdersFeature + ]; + } +} +``` + +Copy the state machine process XML from the module into your project. The example file is located at `src/SprykerFeature/OrderExperienceManagement/config/Zed/StateMachine/RecurringOrder/RecurringOrderStateMachine.xml` in the module. Add it to your project at the following path: + +**config/Zed/StateMachine/RecurringOrder/RecurringOrderStateMachine.xml** + +The handler plugin registers the following commands and conditions, so you do not need to register them individually. Reference them by name if you extend the process XML: + +| TYPE | NAME | SPECIFICATION | +| --- | --- | --- | +| Condition | RecurringOrders/IsScheduleDue | Checks whether the schedule has entered its notification window. | +| Condition | RecurringOrders/IsPlacementDue | Checks whether the trigger date has been reached. | +| Condition | RecurringOrders/IsScheduleValid | Runs the registered schedule validator plugins and reports whether the schedule can be placed. | +| Condition | RecurringOrders/IsOrderPlaced | Checks whether the sales order has been created successfully. | +| Command | RecurringOrders/NotifyBuyer | Sends the pre-trigger notification email. | +| Command | RecurringOrders/PlaceOrder | Places the order from the stored quote data. | +| Command | RecurringOrders/CompletePlacement | Writes the placement result to the schedule history. | +| Command | RecurringOrders/AdvanceSchedule | Calculates and stores the next trigger date using the registered cadence type plugin. | + +The process XML resolves the `confirm` event out of `review_required` into two transitions, so the target depends on when the buyer approves the review: + +```xml + + review_required + confirmed + confirm + + + + review_required + active + confirm + +``` + +- The buyer approves on or after the trigger date: `RecurringOrders/IsPlacementDue` evaluates to `true`, the schedule moves to `confirmed`, and the order is placed in this cycle. +- The buyer approves before the trigger date: the condition evaluates to `false`, and the schedule returns to `active`. Nothing is placed yet, and the schedule waits for its trigger date. + +{% info_block warningBox "Transition order" %} + +The conditional transition must precede the unconditional one. The state machine evaluates transitions in document order and takes the first match, so an unconditional transition placed first makes every `confirm` event resolve to `active` and no order is ever placed. Keep this order if you extend the process XML. + +{% endinfo_block %} + +{% info_block warningBox "Verification" %} + +1. In the Back Office, under **Maintenance > State Machine**, make sure the `RecurringOrderStateMachine` process is listed and the diagram renders correctly. +2. Approve a review for a schedule whose trigger date is still in the future. Make sure the schedule status returns to **Active** and no order is placed. +3. Approve a review for a schedule whose trigger date has been reached. Make sure the schedule status becomes **Confirmed** and the order is placed. + +{% endinfo_block %} + +#### Set up Mail plugins + +Register the following mail type builder plugins: + +| PLUGIN | SPECIFICATION | PREREQUISITES | NAMESPACE | +| --- | --- | --- | --- | +| RecurringOrderUpcomingNotificationMailTypeBuilderPlugin | Builds the pre-trigger notification email sent to the buyer a configurable number of hours before the scheduled order is placed. | None | SprykerFeature\Zed\OrderExperienceManagement\Communication\Plugin\Mail | +| RecurringOrderValidationFailedMailTypeBuilderPlugin | Builds the review-required notification email sent to the buyer when a price increase or product availability issue is detected. | None | SprykerFeature\Zed\OrderExperienceManagement\Communication\Plugin\Mail | +| RecurringOrderFailureMailTypeBuilderPlugin | Builds the order placement failure notification email sent to the buyer when order placement fails. | None | SprykerFeature\Zed\OrderExperienceManagement\Communication\Plugin\Mail | + +**src/Pyz/Zed/Mail/MailDependencyProvider.php** + +```php + + */ + protected function getMailTypeBuilderPlugins(): array + { + return [ + // ... + new RecurringOrderUpcomingNotificationMailTypeBuilderPlugin(), #RecurringOrdersFeature + new RecurringOrderValidationFailedMailTypeBuilderPlugin(), #RecurringOrdersFeature + new RecurringOrderFailureMailTypeBuilderPlugin(), #RecurringOrdersFeature + ]; + } +} +``` + +{% info_block warningBox "Verification" %} + +Trigger a recurring order cycle and verify the following: +- A pre-trigger notification email is sent to the buyer within the configured notification window hours. +- When a price increase or product availability issue is detected, a review-required email is sent. +- When order placement fails, a failure notification email is sent. + +{% endinfo_block %} + +#### Set up permissions + +By default, a company user can only see their own recurring orders. To allow users to view recurring orders across their company or business unit, register the following permission plugins: + +| PLUGIN | SPECIFICATION | PREREQUISITES | NAMESPACE | +| --- | --- | --- | --- | +| SeeCompanyOrdersPermissionPlugin | Grants permission to view all recurring orders within the company. Assign to company roles that should have company-wide visibility. | None | Spryker\Zed\CompanySalesConnector\Communication\Plugin\Permission | +| SeeBusinessUnitOrdersPermissionPlugin | Grants permission to view all recurring orders within the company business unit. Assign to company roles that should have business-unit-wide visibility. | None | Spryker\Zed\CompanyBusinessUnitSalesConnector\Communication\Plugin\Permission | + +**src/Pyz/Zed/Permission/PermissionDependencyProvider.php** + +```php + + */ + protected function getPermissionPlugins(): array + { + return [ + // ... + new SeeCompanyOrdersPermissionPlugin(), #RecurringOrdersFeature + new SeeBusinessUnitOrdersPermissionPlugin(), #RecurringOrdersFeature + ]; + } +} +``` + +**src/Pyz/Client/Permission/PermissionDependencyProvider.php** + +```php + + */ + protected function getPermissionPlugins(): array + { + return [ + // ... + new SeeCompanyOrdersPermissionPlugin(), #RecurringOrdersFeature + new SeeBusinessUnitOrdersPermissionPlugin(), #RecurringOrdersFeature + ]; + } +} +``` + +{% info_block warningBox "Verification" %} + +In the Back Office, under **Customers > Company Roles**, assign `SeeCompanyOrdersPermissionPlugin` to a company role. Make sure company users with that role can see all recurring orders within their company on the storefront. + +Assign `SeeBusinessUnitOrdersPermissionPlugin` to a role. Make sure users with that role can see all recurring orders within their business unit. + +{% endinfo_block %} + +#### Set up console commands + +Register the following console commands: + +| COMMAND | CONSOLE CLASS | SPECIFICATION | NAMESPACE | +| --- | --- | --- | --- | +| `recurring-orders:forecast:refresh` | RecurringOrderForecastRefreshConsole | Recalculates the monthly recurring volume forecast—orders already placed plus schedules still due—and stores it as a snapshot in `spy_recurring_schedule_forecast`. The Back Office **Recurring Order Schedules** page reads the stored snapshot instead of recalculating on each request. | SprykerFeature\Zed\OrderExperienceManagement\Communication\Console | +| `recurring-orders:trigger-placement` | RecurringOrderTriggerConsole | Manually triggers order placement for a specific recurring schedule. Optional—intended for development and debugging. | SprykerFeature\Zed\OrderExperienceManagement\Communication\Console | + +**src/Pyz/Zed/Console/ConsoleDependencyProvider.php** + +```php + + */ + protected function getConsoleCommands(Container $container): array + { + return [ + // ... + new RecurringOrderForecastRefreshConsole(), #RecurringOrdersFeature + new RecurringOrderTriggerConsole(), #RecurringOrdersFeature + ]; + } +} +``` + +`RecurringOrderTriggerConsole` runs the same placement logic as the state machine `PlaceOrder` command, which makes it useful for development, debugging, and one-off operational tasks: + +```bash +# Trigger placement by numeric ID +console recurring-orders:trigger-placement 42 + +# Trigger placement by UUID +console recurring-orders:trigger-placement 550e8400-e29b-41d4-a716-446655440000 + +# Run pre-placement validation first; aborts if validation fails +console recurring-orders:trigger-placement 42 --validate +``` + +The `--validate` flag runs all registered `ScheduleValidatorPlugin` implementations (for example, `PriceScheduleValidatorPlugin` and `CheckoutPlaceabilityScheduleValidatorPlugin`) before attempting placement. If any validator reports a failure, the command exits with an error and does not place the order. + +{% info_block warningBox "Development use only" %} + +`recurring-orders:trigger-placement` is intended for development and debugging. Do not use it in production automated pipelines—the state machine cron job is the intended trigger for production order placement. + +{% endinfo_block %} + +{% info_block warningBox "Verification" %} + +Run `console recurring-orders:forecast:refresh`. Make sure the command completes successfully and a row with `forecast_key` set to `monthly` is created in `spy_recurring_schedule_forecast`. + +{% endinfo_block %} + +#### Set up cron jobs + +The recurring orders state machine relies on a cron job to evaluate condition transitions, and the Back Office forecast relies on a cron job to refresh its snapshot. Register the jobs in your Jenkins configuration: + +**config/Zed/cronjobs/jenkins.php** + +```php +/* RecurringOrder StateMachine */ +$jobs[] = [ + 'name' => 'recurring-order-check-conditions', + 'command' => '$PHP_BIN vendor/bin/console state-machine:check-condition RecurringOrder', + 'schedule' => '* * * * *', + 'enable' => true, +]; + +/* RecurringOrder forecast */ +$jobs[] = [ + 'name' => 'recurring-order-forecast-refresh', + 'command' => '$PHP_BIN vendor/bin/console recurring-orders:forecast:refresh', + 'schedule' => '0 * * * *', + 'enable' => true, +]; +``` + +{% info_block infoBox "Scheduling recommendation" %} + +To have recurring orders placed before the business day starts, set trigger dates to an early morning time (for example, 01:00) and configure the schedule grace period to `18` hours or more. With an 18-hour window, the pre-trigger notification is sent the previous afternoon (after 12:00), allowing the buyer to review or skip before the order is placed overnight. + +{% endinfo_block %} + +If your project uses Symfony Scheduler instead of Jenkins, register the equivalent jobs in your scheduler config: + +**src/Pyz/Zed/SymfonyScheduler/SymfonySchedulerConfig.php** + +```php +'recurring-orders-check-condition' => [ + 'command' => '$PHP_BIN vendor/bin/console state-machine:check-condition RecurringOrder', + 'schedule' => '* * * * *', +], +'recurring-orders-clear-locks' => [ + 'command' => '$PHP_BIN vendor/bin/console state-machine:clear-locks', + 'schedule' => '0 6 * * *', +], +'recurring-orders-forecast-refresh' => [ + 'command' => '$PHP_BIN vendor/bin/console recurring-orders:forecast:refresh', + 'schedule' => '0 * * * *', +], +``` + +{% info_block warningBox "Verification" %} + +1. Activate a recurring schedule. Make sure the state machine condition check job runs and the schedule transitions from `draft` to `active` within one minute. +2. Make sure the forecast refresh job runs hourly and updates `calculated_at` in `spy_recurring_schedule_forecast`. + +{% endinfo_block %} + +#### Set up the Back Office navigation + +To make the recurring order schedules list available in the Back Office, add the navigation entry to the `` element of the `` node in your project navigation: + +**config/Zed/navigation.xml** + +```xml + + + + + + + Recurring Order Schedules + order-experience-management + recurring-schedule + index + 1 + + + +``` + +Rebuild the navigation cache: + +```bash +console navigation:build-cache +``` + +{% info_block warningBox "Verification" %} + +In the Back Office, go to **Sales > Recurring Order Schedules**. Make sure the list of recurring order schedules is displayed with the status and cadence filters, and that the **Total Committed Recurring Volume** widget shows the already-placed and still-planned breakdown. Open a schedule and make sure the detail view renders the schedule items with their merchant and configurable bundle names, the customer, and a link to the source order. + +{% endinfo_block %} + +#### Configure product bundle field copying + +{% info_block infoBox "Product Bundles feature" %} + +This step is only required if your project uses the [Product Bundles feature](/docs/pbc/all/product-information-management/latest/base-shop/feature-overviews/product-bundles-feature-overview.html). + +{% endinfo_block %} + +Override the allowed fields to copy so that shipment information is preserved when recurring orders re-create bundle items: + +| CONFIGURATION METHOD | SPECIFICATION | PREREQUISITES | NAMESPACE | +| --- | --- | --- | --- | +| `getAllowedBundleItemFieldsToCopy()` | Returns the list of `ItemTransfer` fields copied from bundle items when they are duplicated during order re-creation. Adding `ItemTransfer::SHIPMENT` ensures the shipment is preserved on each recurring order placement. | None | Pyz\Zed\ProductBundle | + +**src/Pyz/Zed/ProductBundle/ProductBundleConfig.php** + +```php + + */ + public function getAllowedBundleItemFieldsToCopy(): array + { + return [ + ItemTransfer::SHIPMENT, + ]; + } +} +``` + +{% info_block warningBox "Verification" %} + +Add a product bundle to the cart, set up a recurring order, and complete checkout. On the next scheduled order placement, make sure the bundle items are re-created with the correct shipment assignment. + +{% endinfo_block %} + +### 5) Configure module behavior + +Override the following configuration methods in your project (if needed) to adjust the default behavior: + +**src/Pyz/Zed/OrderExperienceManagement/OrderExperienceManagementConfig.php** + +```php + Recurring Order Schedules**. Make sure the column headers, filter labels, and status badges are translated instead of showing raw glossary keys. + +{% endinfo_block %} + +## Install feature frontend + +Follow the steps below to install the Recurring Orders feature frontend. + +### 1) Set up routes + +Register the following route provider plugin: + +| PLUGIN | SPECIFICATION | PREREQUISITES | NAMESPACE | +| --- | --- | --- | --- | +| RecurringOrderRouteProviderPlugin | Adds the storefront routes for the recurring order list, detail, edit, review, product search, product offer selection, shipment method, and schedule action pages. | None | SprykerFeature\Yves\OrderExperienceManagement\Plugin\Router | + +**src/Pyz/Yves/Router/RouterDependencyProvider.php** + +```php + + */ + protected function getRouteProvider(): array + { + return [ + // ... + new RecurringOrderRouteProviderPlugin(), #RecurringOrdersFeature + ]; + } +} +``` + +After registering the plugin, warm up the router caches: + +```bash +vendor/bin/yves router:cache:warm-up +vendor/bin/console router:cache:warm-up +vendor/bin/console router:cache:warm-up:backend-gateway +``` + +{% info_block warningBox "Verification" %} + +Make sure the following storefront routes are accessible: + +| ROUTE NAME | PATTERN | PURPOSE | +| --- | --- | --- | +| recurring-orders | `/recurring-orders` | Recurring order list page. | +| recurring-orders/detail | `/recurring-orders/{uuid}` | Recurring order detail page. | +| recurring-orders/review-required | `/recurring-orders/{uuid}/review-required` | Review required page. | +| recurring-order/edit | `/recurring-order/{uuid}/edit` | Recurring schedule edit form. | +| recurring-order/form | `/recurring-order-form` | Recurring order setup form rendered at checkout. | +| recurring-order/save | `/recurring-order/save` | Saves recurring order settings on the quote. | +| recurring-order/clear | `/recurring-order/clear` | Removes recurring order settings from the quote. | +| recurring-order/pause | `/recurring-order/{uuid}/pause` | Pauses a schedule. | +| recurring-order/resume | `/recurring-order/{uuid}/resume` | Resumes a paused schedule. | +| recurring-order/skip | `/recurring-order/{uuid}/skip` | Skips the next placement. | +| recurring-order/cancel | `/recurring-order/{uuid}/cancel` | Cancels a schedule. | +| recurring-order/confirm | `/recurring-order/{uuid}/confirm` | Confirms a reviewed schedule. | +| recurring-order/retry | `/recurring-order/{uuid}/retry` | Retries a failed placement. | +| recurring-orders/shipment-methods | `/recurring-orders/{uuid}/shipment-methods` | Returns the shipment methods available for an added item. | +| recurring-orders/product-price | `/recurring-orders/{uuid}/product-price` | Returns the current price of an added item. | +| recurring-orders/product-concrete-search | `/recurring-orders/{uuid}/product-concrete-search` | Backs the add-product search bar on the review page. | +| recurring-order/product-offer-select | `/recurring-order/product-offer-select` | Renders the merchant offer selector for an added item. | + +{% endinfo_block %} + +### 2) Set up widgets + +Register the following global widgets: + +| WIDGET | DESCRIPTION | NAMESPACE | +| --- | --- | --- | +| RecurringOrderSelectorWidget | Renders the recurring order setup form at checkout. Visible only when the quote is eligible for a recurring order (invoice payment, not locked, not from RFQ, not guest). | SprykerFeature\Yves\OrderExperienceManagement\Widget | +| RecurringOrderMenuItemWidget | Renders the **Recurring Orders** navigation menu item in the storefront customer account menu. | SprykerFeature\Yves\OrderExperienceManagement\Widget | +| ProductConcreteSearchWidget | Backs the add-product search bar on the **Review Required** page. Also provides the `products-list` molecule the search results view reuses. | SprykerShop\Yves\ProductSearchWidget\Widget | +| CostCenterDetailWidget | Displays the selected cost center and budget in the recurring order detail sidebar, which is its only caller. Takes a `QuoteTransfer` and an optional flag that adds a budget usage summary. Only active cost centers are resolved, so a deactivated cost center makes the widget render nothing. Requires the [Purchasing Control feature](/docs/pbc/all/cart-and-checkout/latest/base-shop/install-and-upgrade/install-features/install-the-purchasing-control-feature.html). | SprykerFeature\Yves\PurchasingControl\Widget | + +**src/Pyz/Yves/ShopApplication/ShopApplicationDependencyProvider.php** + +```php + + */ + protected function getGlobalWidgets(): array + { + return [ + // ... + RecurringOrderSelectorWidget::class, #RecurringOrdersFeature + RecurringOrderMenuItemWidget::class, #RecurringOrdersFeature + ProductConcreteSearchWidget::class, #RecurringOrdersFeature + CostCenterDetailWidget::class, #RecurringOrdersFeature + ]; + } +} +``` + +{% info_block warningBox "Verification" %} + +1. On the checkout summary page with an invoice-based payment method, make sure the recurring order selector is displayed. +2. In the customer account, make sure the **Recurring Orders** menu item is displayed. +3. On the **Review Required** page, open the add-product search bar and make sure product suggestions are returned. +4. On the recurring order detail page, make sure the selected cost center and budget names are displayed in the sidebar. + +{% endinfo_block %} + +### 3) Set up storefront plugins + +{% info_block infoBox "Optional features" %} + +Each plugin in this step comes from an optional feature. Register only the plugins whose feature your project uses. + +{% endinfo_block %} + +Register the following plugins to let buyers select a cost center and budget on the recurring order forms, and to restrict which products they can add on the **Review Required** page: + +| PLUGIN | SPECIFICATION | PREREQUISITES | NAMESPACE | +| --- | --- | --- | --- | +| CostCenterRecurringOrderApproveFormExpanderPlugin | Adds cost center and budget dropdowns to the review approve form and validates the selected pair server-side. Only active cost centers of the buyer's company business unit in the currency of the recurring order are offered. | Purchasing Control feature | SprykerFeature\Yves\PurchasingControl\Plugin\OrderExperienceManagement | +| CostCenterRecurringScheduleEditFormExpanderPlugin | Adds cost center and budget dropdowns to the recurring schedule edit form and validates the selected pair server-side. Only active cost centers of the buyer's company business unit in the currency of the recurring order are offered. | Purchasing Control feature | SprykerFeature\Yves\PurchasingControl\Plugin\OrderExperienceManagement | +| ServiceProductAddedProductConcreteRestrictionPlugin | Hides a service product from the add-product search bar and the offer selector when its shipment types do not include one a recurring order can serve. | SSP Service Management feature | SprykerFeature\Yves\SelfServicePortal\Plugin\OrderExperienceManagement | + +**src/Pyz/Yves/OrderExperienceManagement/OrderExperienceManagementDependencyProvider.php** + +```php + + */ + protected function getRecurringOrderApproveFormExpanderPlugins(): array + { + return [ + new CostCenterRecurringOrderApproveFormExpanderPlugin(), #RecurringOrdersFeature + ]; + } + + /** + * @return array<\SprykerFeature\Yves\OrderExperienceManagement\Dependency\Plugin\RecurringScheduleEditFormExpanderPluginInterface> + */ + protected function getRecurringScheduleEditFormExpanderPlugins(): array + { + return [ + new CostCenterRecurringScheduleEditFormExpanderPlugin(), #RecurringOrdersFeature + ]; + } + + /** + * @return array<\SprykerFeature\Yves\OrderExperienceManagement\Dependency\Plugin\AddedProductConcreteRestrictionPluginInterface> + */ + protected function getAddedProductConcreteRestrictionPlugins(): array + { + return [ + new ServiceProductAddedProductConcreteRestrictionPlugin(), #RecurringOrdersFeature + ]; + } +} +``` + +{% info_block infoBox "Custom product restrictions" %} + +To hide additional products from the add-product picker, implement `SprykerFeature\Yves\OrderExperienceManagement\Dependency\Plugin\AddedProductConcreteRestrictionPluginInterface`. The plugin receives a `ProductViewTransfer` resolved from product storage with all view expanders applied, so it can rely on the data your own module publishes there. Returning `true` removes the product from the search results and makes the offer selector return no choices for it. + +A storefront restriction only hides the product. To also reject a crafted request, register a matching `AddedItemValidatorPluginInterface` implementation in Zed—see [Set up added item validator plugins](#set-up-added-item-validator-plugins). + +{% endinfo_block %} + +Both cost center plugins offer only budgets whose enforcement rule is listed in `getRecurringOrderSelectableBudgetEnforcementRules()`. Budgets that require approval when the budget is exceeded are hidden, because a recurring order is placed unattended and cannot wait for an approval decision. To change which enforcement rules qualify, override the method in your project: + +**src/Pyz/Yves/PurchasingControl/PurchasingControlConfig.php** + +```php + + */ + public function getRecurringOrderSelectableBudgetEnforcementRules(): array + { + return [ + SharedPurchasingControlConfig::ENFORCEMENT_RULE_BLOCK, + SharedPurchasingControlConfig::ENFORCEMENT_RULE_WARN, + ]; + } +} +``` + +| CONFIGURATION METHOD | DEFAULT | DESCRIPTION | +| --- | --- | --- | +| `getRecurringOrderSelectableBudgetEnforcementRules()` | `[ENFORCEMENT_RULE_BLOCK, ENFORCEMENT_RULE_WARN]` | Budget enforcement rules that can be selected on the recurring order forms. Budgets bound to any other rule—`ENFORCEMENT_RULE_REQUIRE_APPROVAL` in particular—are hidden from the budget selector. | + +{% info_block warningBox "Verification" %} + +1. Open the **Review Required** page for a schedule and make sure the **Cost Center** and **Budget** dropdowns are displayed on the approve form. +2. Open the recurring schedule edit form and make sure the same dropdowns are displayed. +3. Submit the form with a budget that does not belong to the selected cost center. Make sure the form is rejected with a validation error. +4. Set a budget's enforcement rule to **Require approval** in the Back Office. Make sure the budget is no longer offered in the recurring order budget selector. +5. On the **Review Required** page, search for a service product whose shipment type is not in `RECURRING_ORDER_SERVICE_SHIPMENT_TYPE_KEYS`. Make sure the product is not offered in the add-product search results. + +{% endinfo_block %} + +### 4) Add the recurring order selector to the checkout summary page + +`spryker-shop/checkout-page` calls `RecurringOrderSelectorWidget` from its checkout summary template, so no change is required if your project uses the module template as is. + +If your project overrides the checkout summary template, call the widget explicitly. Add it after any cost center or voucher sections, before the order form. + +**src/Pyz/Yves/CheckoutPage/Theme/default/views/summary/summary.twig** + +```twig +{% raw %}{% widget 'RecurringOrderSelectorWidget' args [data.cart] only %}{% endwidget %}{% endraw %} +``` + +{% info_block warningBox "Verification" %} + +On the checkout summary page with an invoice-based payment method, make sure the **Set up as recurring order** checkbox and description are displayed. + +{% endinfo_block %} + +### 5) Add the menu item to the customer navigation sidebar + +`spryker-shop/customer-page` calls `RecurringOrderMenuItemWidget` from the `customer-navigation` molecule, so no change is required if your project uses the module template as is. + +If your project overrides the `customer-navigation` molecule, call the widget from the same position—directly after the **Order History** item. The widget renders an `
  • ` element and must be placed inside a `
      ` context. + +**src/Pyz/Yves/CustomerPage/Theme/default/components/molecules/customer-navigation/customer-navigation.twig** + +```twig +{% raw %} +{% widget 'RecurringOrderMenuItemWidget' args [data.activePage] only %}{% endwidget %} +{% endraw %} +``` + +{% info_block infoBox "Alternative: plain menu item" %} + +If your sidebar template is built from a plain `data.items` array instead of widget calls, add the entry directly. Place it after the Order History item: + +```twig +{% raw %} +{ + name: 'recurring-orders', + url: path('recurring-orders'), + label: 'recurring_orders.menu_item' | trans, + icon: 'calendar', +}, +{% endraw %} +``` + +{% endinfo_block %} + +{% info_block warningBox "Verification" %} + +In the storefront customer account, make sure the **Recurring Orders** menu item is displayed directly below **Order History** in the left sidebar navigation and links to `/recurring-orders`. + +{% endinfo_block %} + +### 6) Configure the storefront behavior + +Override the following configuration methods in your project (if needed) to adjust the storefront behavior: + +**src/Pyz/Yves/OrderExperienceManagement/OrderExperienceManagementConfig.php** + +```php + cadence value]`. Extend it when you register a custom cadence type plugin. | +| `getCadenceTypeEveryNWeeks()` | `every_n_weeks` | Cadence type that requires an additional numeric interval. | +| `getInvoicePaymentMethodKeys()` | `[invoice, purchaseOnAccount, dummyMarketplacePaymentInvoice]` | Payment method keys that qualify as invoice-based. Only quotes with a matching payment method can generate a recurring schedule. Override this in the shared config to apply it in Yves and Zed at once. | +| `getBusinessUnitChoicesLimit()` | `100` | Maximum number of company business units loaded into the recurring order search scope dropdown. Projects with more business units should raise this value or switch to an async autocomplete widget. | +| `getRecurringScheduleListItemsPerPage()` | `10` | Number of recurring schedules shown per page on the list page. | +| `getRecurringScheduleHistoryItemsPerPage()` | `10` | Number of execution history entries shown per page on the detail page. | +| `getSupportedAddedItemShipmentTypeKeys()` | `[delivery, on-site-service]` | Shipment type keys supported for products added on the **Review Required** page. | +| `getSubstitutableReviewReasons()` | `[discontinued, substituted]` | Review reason groups for which a **Choose a substitute** action is offered. | +| `getPriceChangeReviewReasons()` | `[price_increased]` | Review reason groups whose lines are marked as price changes the buyer accepts by confirming the order. | +| `isUnavailableProductsExcludedFromAddProductSearch()` | `true` | When enabled, concrete products and merchant offers without availability are hidden from the add-product search bar and the offer selector. | +| `isMeasurementUnitProductAdditionRestricted()` | `true` | When enabled, products sold in measurement units are hidden from the add-product picker. Reads the value from the shared config. | +| `isPackagingUnitProductAdditionRestricted()` | `true` | When enabled, products sold in packaging units are hidden from the add-product picker. Reads the value from the shared config. | +| `getStatusBadgeClassMap()`, `getStatusIconMap()`, `getHistoryEventTypeBadgeClassMap()`, `getReviewReasonLabelMap()`, `getReviewReasonBadgeMap()`, `getItemFlagLabelMap()`, `getItemFlagBadgeMap()` | See `OrderExperienceManagementConfig` | Presentation maps for statuses, history events, review reasons, and item flags. Extend them when you introduce custom statuses or review reasons. | +| `getErrorBannerStatuses()`, `getAttentionBannerStatuses()` | See `OrderExperienceManagementConfig` | Statuses that render the error banner and the attention banner on the list and detail pages. | +| `getRecurringScheduleStatusChoices()`, `getReviewScopeChoices()` | See `OrderExperienceManagementConfig` | Choices offered in the storefront status filter and the review scope selector. | + +{% info_block infoBox "Overriding storefront molecules" %} + +The module ships its storefront UI as molecules under `src/SprykerFeature/OrderExperienceManagement/src/SprykerFeature/Yves/OrderExperienceManagement/Theme/default/components/molecules`. To adjust the markup, override the molecule in your project at the same relative path under `src/Pyz/Yves/OrderExperienceManagement/Theme/default/components/molecules`. The most commonly customized molecules are `recurring-order-selector`, `recurring-order-list`, `schedule-detail`, `schedule-detail-sidebar`, `schedule-review`, and `recurring-order-edit-form`. + +The **Review Required** page is composed of the `review-` molecules: `review-flagged-items`, `review-unchanged-items`, `review-quantity-control`, `review-substitute`, `review-add-product`, `review-add-product-picker`, `review-shipment-selection`, `review-scope-selector`, `review-change-summary`, `review-summary-banner`, `review-blocking-errors`, and `review-footer`. + +The `schedule-detail-sidebar`, `schedule-review`, and `recurring-order-edit-form` molecules embed the `cost-center-detail`, `recurring-order-cost-center-budget`, and `recurring-order-budget-summary` molecules from the `PurchasingControl` module. If your project does not use the Purchasing Control feature, these embeds resolve to nothing and the surrounding markup remains valid. + +{% endinfo_block %} + +### 7) Build the frontend + +After making changes to Twig templates and registering new widgets, rebuild the Yves frontend assets: + +```bash +npm run yves +``` + +{% info_block warningBox "Verification" %} + +Reload the checkout summary page and make sure the recurring order selector renders without console errors. + +{% endinfo_block %} + +### 8) Import glossary data + +Import the following glossary keys for Storefront translations: + +**data/import/common/common/glossary.csv** + +```csv +recurring_orders.attention_banner.link.failed,View Failed,en_US +recurring_orders.attention_banner.link.failed,Fehlgeschlagene anzeigen,de_DE +recurring_orders.attention_banner.link.paused,View Paused,en_US +recurring_orders.attention_banner.link.paused,Pausierte anzeigen,de_DE +recurring_orders.attention_banner.link.review_required,View Review Required,en_US +recurring_orders.attention_banner.link.review_required,Zu prüfende anzeigen,de_DE +recurring_orders.attention_banner.message,You have %count% recurring schedule(s) that require your attention.,en_US +recurring_orders.attention_banner.message,"Sie haben %count% wiederkehrende(n) Zeitplan/Zeitpläne, die Ihre Aufmerksamkeit erfordern.",de_DE +recurring_orders.cadence.bi_weekly,Bi-weekly,en_US +recurring_orders.cadence.bi_weekly,Zweiwöchentlich,de_DE +recurring_orders.cadence.every_n_weeks,Every N weeks,en_US +recurring_orders.cadence.every_n_weeks,Alle N Wochen,de_DE +recurring_orders.cadence.monthly,Monthly,en_US +recurring_orders.cadence.monthly,Monatlich,de_DE +recurring_orders.cadence.weekly,Weekly,en_US +recurring_orders.cadence.weekly,Wöchentlich,de_DE +recurring_orders.checkout.cadence_label,Frequency,en_US +recurring_orders.checkout.cadence_label,Häufigkeit,de_DE +recurring_orders.checkout.cadence_placeholder,Select frequency,en_US +recurring_orders.checkout.cadence_placeholder,Häufigkeit auswählen,de_DE +recurring_orders.checkout.cadence_value_label,Interval (weeks),en_US +recurring_orders.checkout.cadence_value_label,Intervall (Wochen),de_DE +recurring_orders.checkout.confirm_button,Confirm,en_US +recurring_orders.checkout.confirm_button,Bestätigen,de_DE +recurring_orders.checkout.enable_description,"Get this order delivered automatically on your schedule. Skip and cancel anytime.",en_US +recurring_orders.checkout.enable_description,"Lassen Sie sich diese Bestellung automatisch nach Ihrem Zeitplan liefern. Jederzeit überspringen und stornieren.",de_DE +recurring_orders.checkout.enable_label,Set up as recurring order,en_US +recurring_orders.checkout.enable_label,Als wiederkehrende Bestellung einrichten,de_DE +recurring_orders.checkout.remove_button,Remove,en_US +recurring_orders.checkout.remove_button,Entfernen,de_DE +recurring_orders.checkout.schedule_name_label,Schedule name,en_US +recurring_orders.checkout.schedule_name_label,Name des Zeitplans,de_DE +recurring_orders.checkout.section_title,Recurring Order,en_US +recurring_orders.checkout.section_title,Wiederkehrende Bestellung,de_DE +recurring_orders.checkout.start_date_label,Start date,en_US +recurring_orders.checkout.start_date_label,Startdatum,de_DE +recurring_orders.checkout.start_date_tooltip,"The date your first recurring delivery is placed. Today's order is placed as normal, recurring deliveries then repeat on your selected frequency from this date.",en_US +recurring_orders.checkout.start_date_tooltip,"Das Datum, an dem Ihre erste wiederkehrende Lieferung erfolgt. Die heutige Bestellung wird wie gewohnt aufgegeben, wiederkehrende Lieferungen wiederholen sich danach ab diesem Datum in der von Ihnen gewählten Häufigkeit.",de_DE +recurring_orders.checkout.start_date_tooltip_label,More information about the start date,en_US +recurring_orders.checkout.start_date_tooltip_label,Weitere Informationen zum Startdatum,de_DE +recurring_orders.checkout.first_order_notice,Your first recurring order starts on %date%,en_US +recurring_orders.checkout.first_order_notice,Ihre erste wiederkehrende Bestellung beginnt am %date%,de_DE +recurring_orders.checkout.validation.start_date_required,Please choose a start date.,en_US +recurring_orders.checkout.validation.start_date_required,Bitte wählen Sie ein Startdatum aus.,de_DE +recurring_orders.checkout.validation.start_date_in_past,The start date cannot be in the past.,en_US +recurring_orders.checkout.validation.start_date_in_past,Das Startdatum darf nicht in der Vergangenheit liegen.,de_DE +recurring_orders.checkout.error.start_date_in_past,The recurring order start date cannot be in the past.,en_US +recurring_orders.checkout.error.start_date_in_past,Das Startdatum der wiederkehrenden Bestellung darf nicht in der Vergangenheit liegen.,de_DE +recurring_orders.checkout.error.start_date_required,Please choose a start date for the recurring order.,en_US +recurring_orders.checkout.error.start_date_required,Bitte wählen Sie ein Startdatum für die wiederkehrende Bestellung aus.,de_DE +recurring_orders.detail.access_denied,You do not have access to this recurring order.,en_US +recurring_orders.detail.access_denied,Sie haben keinen Zugriff auf diese wiederkehrende Bestellung.,de_DE +recurring_orders.detail.action.error,An error occurred while processing the action. Please try again.,en_US +recurring_orders.detail.action.error,Bei der Verarbeitung der Aktion ist ein Fehler aufgetreten. Bitte versuchen Sie es erneut.,de_DE +recurring_orders.detail.actions.cancel,Cancel Schedule,en_US +recurring_orders.detail.actions.cancel,Zeitplan abbrechen,de_DE +recurring_orders.detail.actions.pause,Pause,en_US +recurring_orders.detail.actions.pause,Pausieren,de_DE +recurring_orders.detail.actions.resume,Resume,en_US +recurring_orders.detail.actions.resume,Fortsetzen,de_DE +recurring_orders.detail.actions.retry,Retry Again,en_US +recurring_orders.detail.actions.retry,Erneut versuchen,de_DE +recurring_orders.detail.actions.review,Review,en_US +recurring_orders.detail.actions.review,Überprüfen,de_DE +recurring_orders.detail.actions.skip,Skip This Execution,en_US +recurring_orders.detail.actions.skip,Diese Ausführung überspringen,de_DE +recurring_orders.detail.cancel.modal.title,Cancel Schedule?,en_US +recurring_orders.detail.cancel.modal.title,Zeitplan abbrechen?,de_DE +recurring_orders.detail.cancel.modal.warning,This action is permanent. The schedule will stop immediately and cannot be reactivated.,en_US +recurring_orders.detail.cancel.modal.warning,Diese Aktion ist dauerhaft. Der Zeitplan wird sofort gestoppt und kann nicht reaktiviert werden.,de_DE +recurring_orders.detail.error.failed.title,The last order attempt failed for the following reasons:,en_US +recurring_orders.detail.error.failed.title,Der letzte Bestellversuch ist aus den folgenden Gründen fehlgeschlagen:,de_DE +recurring_orders.detail.estimated_total.info,Estimated Grand Total displays the sum of order items excl. shipping costs or discounts.,en_US +recurring_orders.detail.estimated_total.info,Der geschätzte Gesamtbetrag enthält die Summe der Artikel ohne Versandkosten oder Rabatte.,de_DE +recurring_orders.detail.estimated_total.label,Estimated Total,en_US +recurring_orders.detail.estimated_total.label,Geschätzter Gesamtbetrag,de_DE +recurring_orders.detail.skip.modal.title,Skip this execution?,en_US +recurring_orders.detail.skip.modal.title,Diese Ausführung überspringen?,de_DE +recurring_orders.detail.skip.modal.execution_being_skipped,Execution being skipped,en_US +recurring_orders.detail.skip.modal.execution_being_skipped,Übersprungene Ausführung,de_DE +recurring_orders.detail.skip.modal.next_scheduled_execution,Next scheduled execution,en_US +recurring_orders.detail.skip.modal.next_scheduled_execution,Nächste geplante Ausführung,de_DE +recurring_orders.detail.skip.modal.summary,The %skippedDate% order will not be placed. The schedule will continue and trigger next on %nextDate%.,en_US +recurring_orders.detail.skip.modal.summary,Die Bestellung vom %skippedDate% wird nicht aufgegeben. Der Zeitplan läuft weiter und wird als Nächstes am %nextDate% ausgelöst.,de_DE +recurring_orders.detail.skip.modal.confirm,Skip this execution,en_US +recurring_orders.detail.skip.modal.confirm,Diese Ausführung überspringen,de_DE +recurring_orders.detail.history.description,View all past and upcoming executions for this schedule,en_US +recurring_orders.detail.history.description,Alle vergangenen und bevorstehenden Ausführungen für diesen Zeitplan anzeigen,de_DE +recurring_orders.detail.history.actions,Actions,en_US +recurring_orders.detail.history.actions,Aktionen,de_DE +recurring_orders.detail.history.date,Date,en_US +recurring_orders.detail.history.date,Datum,de_DE +recurring_orders.detail.history.empty,No execution history yet.,en_US +recurring_orders.detail.history.empty,Noch kein Ausführungsverlauf vorhanden.,de_DE +recurring_orders.detail.history.order_reference,Order Reference,en_US +recurring_orders.detail.history.order_reference,Bestellreferenz,de_DE +recurring_orders.detail.history.status,Status,en_US +recurring_orders.detail.history.status,Status,de_DE +recurring_orders.detail.history.title,Past scheduled orders,en_US +recurring_orders.detail.history.title,Ausführungsverlauf,de_DE +recurring_orders.detail.history.view_order,View Order,en_US +recurring_orders.detail.history.view_order,Bestellung anzeigen,de_DE +recurring_orders.detail.next_execution.paused,Schedule is paused. Resume to set next execution date.,en_US +recurring_orders.detail.next_execution.paused,"Zeitplan ist pausiert. Setzen Sie ihn fort, um das nächste Ausführungsdatum festzulegen.",de_DE +recurring_orders.detail.next_execution.title,Next Scheduled Execution,en_US +recurring_orders.detail.next_execution.title,Nächste geplante Ausführung,de_DE +recurring_orders.detail.order_items.column.product,Product,en_US +recurring_orders.detail.order_items.column.product,Produkt,de_DE +recurring_orders.detail.order_items.column.quantity,Qty,en_US +recurring_orders.detail.order_items.column.quantity,Menge,de_DE +recurring_orders.detail.order_items.column.total,Total,en_US +recurring_orders.detail.order_items.column.total,Gesamt,de_DE +recurring_orders.detail.order_items.empty,No items found.,en_US +recurring_orders.detail.order_items.empty,Keine Artikel gefunden.,de_DE +recurring_orders.detail.order_items.label,Order Items,en_US +recurring_orders.detail.order_items.label,Bestellartikel,de_DE +recurring_orders.detail.order_items.not_in_next_order_label,Not in next order,en_US +recurring_orders.detail.order_items.not_in_next_order_label,Nicht in nächster Bestellung,de_DE +recurring_orders.detail.order_items.one_time_label,Just this order,en_US +recurring_orders.detail.order_items.one_time_label,Nur diese Bestellung,de_DE +recurring_orders.detail.order_items.recurring_quantity_label,Recurring: %quantity%,en_US +recurring_orders.detail.order_items.recurring_quantity_label,Wiederkehrend: %quantity%,de_DE +recurring_orders.detail.pause.modal.title,Pause Schedule?,en_US +recurring_orders.detail.pause.modal.title,Pausenplan?,de_DE +recurring_orders.detail.pause.modal.warning,Do you want to pause the schedule now?,en_US +recurring_orders.detail.pause.modal.warning,Möchten Sie den Zeitplan jetzt pausieren?,de_DE +recurring_orders.detail.resume.modal.title,Resume schedule,en_US +recurring_orders.detail.resume.modal.title,Zeitplan fortsetzen,de_DE +recurring_orders.detail.edit.title,Edit schedule,en_US +recurring_orders.detail.edit.title,Zeitplan bearbeiten,de_DE +recurring_orders.detail.edit.actions.save,Save changes,en_US +recurring_orders.detail.edit.actions.save,Änderungen speichern,de_DE +recurring_orders.detail.edit.success,Recurring order updated.,en_US +recurring_orders.detail.edit.success,Wiederkehrende Bestellung aktualisiert.,de_DE +recurring_orders.detail.edit.error,Recurring order could not be updated.,en_US +recurring_orders.detail.edit.error,Wiederkehrende Bestellung konnte nicht aktualisiert werden.,de_DE +recurring_orders.detail.edit.error.schedule_not_found,Recurring order %uuid% not found or access denied.,en_US +recurring_orders.detail.edit.error.schedule_not_found,Wiederkehrende Bestellung %uuid% nicht gefunden oder Zugriff verweigert.,de_DE +recurring_orders.detail.edit.name_label,Name,en_US +recurring_orders.detail.edit.name_label,Name,de_DE +recurring_orders.detail.edit.frequency_label,Frequency,en_US +recurring_orders.detail.edit.frequency_label,Häufigkeit,de_DE +recurring_orders.detail.edit.cadence_value_label,Interval,en_US +recurring_orders.detail.edit.cadence_value_label,Intervall,de_DE +recurring_orders.detail.edit.starting_date_label,Next Execution Date,en_US +recurring_orders.detail.edit.starting_date_label,Nächstes Ausführungsdatum,de_DE +recurring_orders.detail.edit.validation.name_required,Please enter a name.,en_US +recurring_orders.detail.edit.validation.name_required,Bitte geben Sie einen Namen ein.,de_DE +recurring_orders.detail.edit.validation.starting_date_required,Please select a starting date.,en_US +recurring_orders.detail.edit.validation.starting_date_required,Bitte wählen Sie ein Startdatum.,de_DE +recurring_orders.detail.edit.validation.starting_date_in_past,The starting date cannot be in the past.,en_US +recurring_orders.detail.edit.validation.starting_date_in_past,Das Startdatum darf nicht in der Vergangenheit liegen.,de_DE +recurring_orders.detail.resume.date_label,Next execution date,en_US +recurring_orders.detail.resume.date_label,Datum der nächsten Ausführung,de_DE +recurring_orders.detail.review_required.attention,Recurring order could not be processed automatically and requires your attention.,en_US +recurring_orders.detail.review_required.attention,Der wiederkehrende Auftrag konnte nicht automatisch verarbeitet werden und erfordert Ihre Aufmerksamkeit.,de_DE +recurring_orders.detail.sidebar.cadence,Cadence,en_US +recurring_orders.detail.sidebar.cadence,Häufigkeit,de_DE +recurring_orders.detail.sidebar.created,Created,en_US +recurring_orders.detail.sidebar.created,Erstellt,de_DE +recurring_orders.detail.sidebar.created_by,Created By,en_US +recurring_orders.detail.sidebar.created_by,Erstellt von,de_DE +recurring_orders.detail.sidebar.status,Status,en_US +recurring_orders.detail.sidebar.status,Status,de_DE +recurring_orders.detail.sidebar.title,Schedule Details,en_US +recurring_orders.detail.sidebar.title,Zeitplandetails,de_DE +recurring_orders.detail.source_order,Original order,en_US +recurring_orders.detail.source_order,Ursprüngliche Bestellung,de_DE +recurring_orders.detail.title,Recurring Order Details,en_US +recurring_orders.detail.title,Wiederkehrende Bestellung – Details,de_DE +recurring_orders.error.items_not_purchasable,The following items can no longer be purchased and the recurring order was not placed: %skus%,en_US +recurring_orders.error.items_not_purchasable,"Die folgenden Artikel können nicht mehr gekauft werden, und die wiederkehrende Bestellung wurde nicht aufgegeben: %skus%",de_DE +recurring_orders.history.errors.show,Show errors,en_US +recurring_orders.history.errors.show,Fehler anzeigen,de_DE +recurring_orders.history.event.cancelled,Cancelled,en_US +recurring_orders.history.event.cancelled,Abgebrochen,de_DE +recurring_orders.history.event.failed,Failed,en_US +recurring_orders.history.event.failed,Fehlgeschlagen,de_DE +recurring_orders.history.event.paused,Paused,en_US +recurring_orders.history.event.paused,Pausiert,de_DE +recurring_orders.history.event.placed,Completed,en_US +recurring_orders.history.event.placed,Abgeschlossen,de_DE +recurring_orders.history.event.resumed,Resumed,en_US +recurring_orders.history.event.resumed,Fortgesetzt,de_DE +recurring_orders.history.event.skipped,Skipped,en_US +recurring_orders.history.event.skipped,Übersprungen,de_DE +recurring_orders.item.configurable_bundle_label,Bundle: %name%,en_US +recurring_orders.item.configurable_bundle_label,Bundle: %name%,de_DE +recurring_orders.list.column.actions,Actions,en_US +recurring_orders.list.column.actions,Aktionen,de_DE +recurring_orders.list.column.frequency,Frequency,en_US +recurring_orders.list.column.frequency,Häufigkeit,de_DE +recurring_orders.list.column.name,Schedule Name,en_US +recurring_orders.list.column.name,Zeitplanname,de_DE +recurring_orders.list.column.next_order_date,Next Order Date,en_US +recurring_orders.list.column.next_order_date,Nächstes Bestelldatum,de_DE +recurring_orders.list.column.status,Status,en_US +recurring_orders.list.column.status,Status,de_DE +recurring_orders.list.empty,No recurring orders found.,en_US +recurring_orders.list.empty,Keine wiederkehrenden Bestellungen gefunden.,de_DE +recurring_orders.list.form.scope,Show schedules for,en_US +recurring_orders.list.form.scope,Zeitpläne anzeigen für,de_DE +recurring_orders.list.form.search,Search,en_US +recurring_orders.list.form.search,Suche,de_DE +recurring_orders.list.form.search_placeholder,Search schedules...,en_US +recurring_orders.list.form.search_placeholder,Zeitpläne suchen...,de_DE +recurring_orders.list.form.status,Status,en_US +recurring_orders.list.form.status,Status,de_DE +recurring_orders.list.form.status.all,All statuses,en_US +recurring_orders.list.form.status.all,Alle Status,de_DE +recurring_orders.list.scope.company,All Company Schedules,en_US +recurring_orders.list.scope.company,Alle Unternehmensbestellungen,de_DE +recurring_orders.list.scope.my_business_unit,My Business Unit,en_US +recurring_orders.list.scope.my_business_unit,Meine Geschäftseinheit,de_DE +recurring_orders.list.scope.my_schedules,My Schedules,en_US +recurring_orders.list.scope.my_schedules,Meine Zeitpläne,de_DE +recurring_orders.list.title,Recurring Orders,en_US +recurring_orders.list.title,Wiederkehrende Bestellungen,de_DE +recurring_orders.mail.notify_buyer_placement_failure.body.cta,Review Order,en_US +recurring_orders.mail.notify_buyer_placement_failure.body.cta,Bestellung prüfen,de_DE +recurring_orders.mail.notify_buyer_placement_failure.body.detail,Please review the order details and failure reason in your recurring orders dashboard.,en_US +recurring_orders.mail.notify_buyer_placement_failure.body.detail,Bitte überprüfen Sie die Bestelldetails und den Fehlergrund in Ihrem Dashboard für Folgebestellungen.,de_DE +recurring_orders.mail.notify_buyer_placement_failure.body.intro,"We were unable to place your recurring order ""%schedule_name%"" automatically.",en_US +recurring_orders.mail.notify_buyer_placement_failure.body.intro,"Ihre Folgebestellung ""%schedule_name%"" konnte nicht automatisch aufgegeben werden.",de_DE +recurring_orders.mail.notify_buyer_placement_failure.body.sign_off,Best regards,en_US +recurring_orders.mail.notify_buyer_placement_failure.body.sign_off,Mit freundlichen Grüßen,de_DE +recurring_orders.mail.notify_buyer_placement_failure.salutation,Hello,en_US +recurring_orders.mail.notify_buyer_placement_failure.salutation,Hallo,de_DE +recurring_orders.mail.notify_buyer_placement_failure.subject,"Recurring order ""%schedule_name%"" could not be placed",en_US +recurring_orders.mail.notify_buyer_placement_failure.subject,"Folgebestellung ""%schedule_name%"" konnte nicht aufgegeben werden",de_DE +recurring_orders.mail.notify_buyer_upcoming_order.body.cta,View Order,en_US +recurring_orders.mail.notify_buyer_upcoming_order.body.cta,Bestellung ansehen,de_DE +recurring_orders.mail.notify_buyer_upcoming_order.body.intro,"Your recurring order ""%schedule_name%"" is scheduled for %execution_date%. We will process it automatically on that date.",en_US +recurring_orders.mail.notify_buyer_upcoming_order.body.intro,"Ihre wiederkehrende Bestellung ""%schedule_name%"" ist für %execution_date% geplant. Wir werden sie automatisch an diesem Datum verarbeiten.",de_DE +recurring_orders.mail.notify_buyer_upcoming_order.body.review,"If you need to make changes, please review and update your order before %expiry_date%.",en_US +recurring_orders.mail.notify_buyer_upcoming_order.body.review,"Wenn Sie Änderungen vornehmen möchten, überprüfen und aktualisieren Sie bitte Ihre Bestellung vor dem %expiry_date%.",de_DE +recurring_orders.mail.notify_buyer_upcoming_order.salutation,Hello,en_US +recurring_orders.mail.notify_buyer_upcoming_order.salutation,Hallo,de_DE +recurring_orders.mail.notify_buyer_upcoming_order.subject,"Upcoming recurring order: ""%schedule_name%"" on %execution_date%",en_US +recurring_orders.mail.notify_buyer_upcoming_order.subject,"Bevorstehende Folgebestellung: ""%schedule_name%"" am %execution_date%",de_DE +recurring_orders.mail.notify_buyer_validation_failed.body.cta,Review Order,en_US +recurring_orders.mail.notify_buyer_validation_failed.body.cta,Bestellung überprüfen,de_DE +recurring_orders.mail.notify_buyer_validation_failed.body.detail,Please review your order details and make any necessary adjustments before the scheduled date.,en_US +recurring_orders.mail.notify_buyer_validation_failed.body.detail,Bitte überprüfen Sie Ihre Bestelldetails und nehmen Sie gegebenenfalls Anpassungen vor dem geplanten Datum vor.,de_DE +recurring_orders.mail.notify_buyer_validation_failed.body.intro,"Your recurring order ""%schedule_name%"", scheduled for %execution_date%, could not be processed automatically and requires your attention.",en_US +recurring_orders.mail.notify_buyer_validation_failed.body.intro,"Ihre wiederkehrende Bestellung ""%schedule_name%"", geplant für %execution_date%, konnte nicht automatisch verarbeitet werden und erfordert Ihre Aufmerksamkeit.",de_DE +recurring_orders.mail.notify_buyer_validation_failed.salutation,Hello,en_US +recurring_orders.mail.notify_buyer_validation_failed.salutation,Hallo,de_DE +recurring_orders.mail.notify_buyer_validation_failed.subject,"Action Required: ""%schedule_name%"" — your order needs attention",en_US +recurring_orders.mail.notify_buyer_validation_failed.subject,"Handlung erforderlich: ""%schedule_name%"" – Ihre Bestellung erfordert Aufmerksamkeit",de_DE +recurring_orders.menu_item,Recurring Orders,en_US +recurring_orders.menu_item,Wiederkehrende Bestellungen,de_DE +recurring_orders.review_details,Review recurring order,en_US +recurring_orders.review_details,Wiederkehrende Bestellung prüfen,de_DE +recurring_orders.sku,SKU: %sku%,en_US +recurring_orders.sku,SKU: %sku%,de_DE +recurring_orders.summary_of_changes,Summary of changes,en_US +recurring_orders.summary_of_changes,Zusammenfassung der Änderungen,de_DE +recurring_orders.view_details,Schedule Details,en_US +recurring_orders.view_details,Zeitplandetails,de_DE +recurring_orders.review.all_items_removed,The order cannot be placed - all items are unavailable and the schedule cannot be executed without items.,en_US +recurring_orders.review.all_items_removed,Die Bestellung kann nicht aufgegeben werden - alle Artikel sind nicht verfügbar und der Zeitplan kann ohne Artikel nicht ausgeführt werden.,de_DE +recurring_orders.review.approve_error,The changes could not be applied. Please try again.,en_US +recurring_orders.review.approve_error,Die Änderungen konnten nicht übernommen werden. Bitte versuchen Sie es erneut.,de_DE +recurring_orders.review.add_product.error.no_price,No price is available for product %sku%. Please remove it or choose a different product.,en_US +recurring_orders.review.add_product.error.no_price,Für das Produkt %sku% ist kein Preis verfügbar. Bitte entfernen Sie es oder wählen Sie ein anderes Produkt.,de_DE +recurring_orders.review.add_product.error.not_available,Product %sku% is not available. Please remove it or choose a different product.,en_US +recurring_orders.review.add_product.error.not_available,Das Produkt %sku% ist nicht verfügbar. Bitte entfernen Sie es oder wählen Sie ein anderes Produkt.,de_DE +recurring_orders.review.add_product.error.shipment_unavailable,No shipment method is available for product %sku%. Please remove it or choose a different product.,en_US +recurring_orders.review.add_product.error.shipment_unavailable,Für das Produkt %sku% ist keine Versandart verfügbar. Bitte entfernen Sie es oder wählen Sie ein anderes Produkt.,de_DE +recurring_orders.review.add_product.error.measurement_unit_not_supported,Product %sku% is sold in measurement units and cannot be added here. Please choose a different product.,en_US +recurring_orders.review.add_product.error.measurement_unit_not_supported,Das Produkt %sku% wird in Maßeinheiten verkauft und kann hier nicht hinzugefügt werden. Bitte wählen Sie ein anderes Produkt.,de_DE +recurring_orders.review.add_product.error.packaging_unit_not_supported,Product %sku% is sold in packaging units and cannot be added here. Please choose a different product.,en_US +recurring_orders.review.add_product.error.packaging_unit_not_supported,Das Produkt %sku% wird in Verpackungseinheiten verkauft und kann hier nicht hinzugefügt werden. Bitte wählen Sie ein anderes Produkt.,de_DE +recurring_orders.review.add_product.error.not_placeable,The added products cannot be scheduled. Please review your selection and try again.,en_US +recurring_orders.review.add_product.error.not_placeable,Die hinzugefügten Produkte können nicht eingeplant werden. Bitte überprüfen Sie Ihre Auswahl und versuchen Sie es erneut.,de_DE +recurring_orders.review.approve_failed,The changes could not be applied.,en_US +recurring_orders.review.approve_failed,Die Änderungen konnten nicht übernommen werden.,de_DE +recurring_orders.review.approve_success,Your changes were applied and the order was placed.,en_US +recurring_orders.review.approve_success,Ihre Änderungen wurden übernommen und die Bestellung wurde aufgegeben.,de_DE +recurring_orders.review.back_to_detail,Back to schedule detail,en_US +recurring_orders.review.back_to_detail,Zurück zur Zeitplanübersicht,de_DE +recurring_orders.review.banner.price_change,%count% price change,en_US +recurring_orders.review.banner.price_change,%count% Preisänderung,de_DE +recurring_orders.review.banner.substituted,%count% product substituted,en_US +recurring_orders.review.banner.substituted,%count% Produkt ersetzt,de_DE +recurring_orders.review.banner.unavailable,%count% unavailable,en_US +recurring_orders.review.banner.unavailable,%count% nicht verfügbar,de_DE +recurring_orders.review.blocking.title,Cannot proceed — blocking issues,en_US +recurring_orders.review.blocking.title,Kann nicht fortfahren — blockierende Probleme,de_DE +recurring_orders.review.column.current_price,Current price,en_US +recurring_orders.review.column.current_price,Aktueller Preis,de_DE +recurring_orders.review.column.previous_price,Previous price,en_US +recurring_orders.review.column.previous_price,Vorheriger Preis,de_DE +recurring_orders.review.column.reason,Reason,en_US +recurring_orders.review.column.reason,Grund,de_DE +recurring_orders.review.cta.accept_and_place,Accept & place order,en_US +recurring_orders.review.cta.accept_and_place,Bestellung annehmen und aufgeben,de_DE +recurring_orders.review.execution_scheduled,Execution scheduled for %date%,en_US +recurring_orders.review.execution_scheduled,Ausführung geplant für %date%,de_DE +recurring_orders.review.flagged.title,Items requiring your review,en_US +recurring_orders.review.flagged.title,Zu überprüfende Artikel,de_DE +recurring_orders.review.footer.helper,Accepting these changes will update this order and future executions of the schedule.,en_US +recurring_orders.review.footer.helper,"Wenn Sie diese Änderungen akzeptieren, werden diese Bestellung und zukünftige Ausführungen des Zeitplans aktualisiert.",de_DE +recurring_orders.review.footer.new_total,New total,en_US +recurring_orders.review.footer.new_total,Neue Summe,de_DE +recurring_orders.review.footer.summary,Removed products: %removed%,en_US +recurring_orders.review.footer.summary,Entfernte Produkte: %removed%,de_DE +recurring_orders.review.invalid_form,The request could not be processed. Please review and try again.,en_US +recurring_orders.review.invalid_form,Die Anfrage konnte nicht verarbeitet werden. Bitte überprüfen Sie sie und versuchen Sie es erneut.,de_DE +recurring_orders.review.modal.accepted_prices,Accepted price changes,en_US +recurring_orders.review.modal.accepted_prices,Akzeptierte Preisänderungen,de_DE +recurring_orders.review.modal.body,Removing unavailable items and accepting updated prices will affect this order and all future executions of this schedule. These changes will become the new reference state for the recurring order going forward.,en_US +recurring_orders.review.modal.body,Das Entfernen nicht verfügbarer Artikel und das Akzeptieren aktualisierter Preise wirken sich auf diese Bestellung und alle zukünftigen Ausführungen dieses Zeitplans aus. Diese Änderungen werden zum neuen Referenzzustand der wiederkehrenden Bestellung.,de_DE +recurring_orders.review.modal.headline,Confirm order and apply changes,en_US +recurring_orders.review.modal.headline,Bestellung bestätigen und Änderungen übernehmen,de_DE +recurring_orders.review.modal.new_total,New order total,en_US +recurring_orders.review.modal.new_total,Neue Bestellsumme,de_DE +recurring_orders.review.modal.original_total,Original order total,en_US +recurring_orders.review.modal.original_total,Ursprüngliche Bestellsumme,de_DE +recurring_orders.review.modal.removed_items,Removed products,en_US +recurring_orders.review.modal.removed_items,Entfernte Produkte,de_DE +recurring_orders.review.modal.substituted_items,Substituted products,en_US +recurring_orders.review.modal.substituted_items,Ersetzte Produkte,de_DE +recurring_orders.review.modal.added_products,Added products,en_US +recurring_orders.review.modal.added_products,Hinzugefügte Produkte,de_DE +recurring_orders.review.quantity_label,Quantity (every future order),en_US +recurring_orders.review.quantity_label,Menge (jede zukünftige Bestellung),de_DE +recurring_orders.review.scope.label,Apply these changes to,en_US +recurring_orders.review.scope.label,Diese Änderungen anwenden auf,de_DE +recurring_orders.review.scope.this_order,This order only,en_US +recurring_orders.review.scope.this_order,Nur diese Bestellung,de_DE +recurring_orders.review.scope.every_future,Update schedule permanently,en_US +recurring_orders.review.scope.every_future,Zeitplan dauerhaft aktualisieren,de_DE +recurring_orders.review-scope-selector-option.occurrence.note,"Apply to the %date% execution. Your recurring schedule stays unchanged.",en_US +recurring_orders.review-scope-selector-option.occurrence.note,"Auf die Ausführung am %date% anwenden. Ihr wiederkehrender Zeitplan bleibt unverändert.",de_DE +recurring_orders.review-scope-selector-option.standing.note,"Apply to this and all future executions, and update reference prices.",en_US +recurring_orders.review-scope-selector-option.standing.note,"Wenden Sie dies auf diese und alle zukünftigen Ausführungen an und aktualisieren Sie die Referenzpreise.",de_DE +recurring_orders.review.remove.label,Remove from schedule,en_US +recurring_orders.review.remove.label,Aus Zeitplan entfernen,de_DE +recurring_orders.review.remove.undo,Undo removal,en_US +recurring_orders.review.remove.undo,Entfernen rückgängig machen,de_DE +recurring_orders.review.quantity.decrease,Decrease quantity,en_US +recurring_orders.review.quantity.decrease,Menge verringern,de_DE +recurring_orders.review.quantity.increase,Increase quantity,en_US +recurring_orders.review.quantity.increase,Menge erhöhen,de_DE +recurring_orders.review.scope_required,Please choose whether each quantity change applies to just this order or every future order.,en_US +recurring_orders.review.scope_required,Bitte wählen Sie ob jede Mengenänderung nur für diese Bestellung oder für jede zukünftige Bestellung gilt.,de_DE +recurring_orders.review.quantity_invalid,Please enter a quantity of at least 1. To drop an item use the remove action instead.,en_US +recurring_orders.review.quantity_invalid,Bitte geben Sie eine Menge von mindestens 1 ein. Verwenden Sie zum Entfernen eines Artikels die Entfernen-Aktion.,de_DE +recurring_orders.review.not_available,This schedule does not require review.,en_US +recurring_orders.review.not_available,Dieser Zeitplan erfordert keine Überprüfung.,de_DE +recurring_orders.review.currency_mismatch,This recurring order can only be reviewed in its own currency. Please switch back to it to make changes.,en_US +recurring_orders.review.currency_mismatch,"Diese wiederkehrende Bestellung kann nur in ihrer eigenen Währung überprüft werden. Bitte wechseln Sie zurück, um Änderungen vorzunehmen.",de_DE +recurring_orders.review.price_mode_mismatch,This recurring order can only be reviewed in its own price mode (gross/net). Please switch back to it to make changes.,en_US +recurring_orders.review.price_mode_mismatch,"Diese wiederkehrende Bestellung kann nur in ihrem eigenen Preismodus (brutto/netto) überprüft werden. Bitte wechseln Sie zurück, um Änderungen vorzunehmen.",de_DE +recurring_orders.review.prices_changed,Prices changed again since you reviewed. Please review the updated order before approving.,en_US +recurring_orders.review.prices_changed,Die Preise haben sich seit Ihrer Überprüfung erneut geändert. Bitte überprüfen Sie die aktualisierte Bestellung vor der Genehmigung.,de_DE +recurring_orders.review.reason.discontinued,Discontinued,en_US +recurring_orders.review.reason.discontinued,Eingestellt,de_DE +recurring_orders.review.reason.not_approved,Not approved,en_US +recurring_orders.review.reason.not_approved,Nicht genehmigt,de_DE +recurring_orders.review.reason.price_increased,Price increased,en_US +recurring_orders.review.reason.price_increased,Preis erhöht,de_DE +recurring_orders.review.reason.price_unavailable,Price unavailable,en_US +recurring_orders.review.reason.price_unavailable,Preis nicht verfügbar,de_DE +recurring_orders.review.reason.substituted,Substituted,en_US +recurring_orders.review.reason.substituted,Ersetzt,de_DE +recurring_orders.review.substitute.label,Substitute,en_US +recurring_orders.review.substitute.label,Ersatzprodukt,de_DE +recurring_orders.review.substitute.select,Select Substitute,en_US +recurring_orders.review.substitute.select,Ersatzprodukt auswählen,de_DE +recurring_orders.review.substitute.change,Change,en_US +recurring_orders.review.substitute.change,Ändern,de_DE +recurring_orders.review.substitute.remove,Remove,en_US +recurring_orders.review.substitute.remove,Entfernen,de_DE +recurring_orders.review.reason.unavailable,Unavailable,en_US +recurring_orders.review.reason.unavailable,Nicht verfügbar,de_DE +recurring_orders.review.reason.out_of_stock,Out Of Stock,en_US +recurring_orders.review.reason.out_of_stock,Nicht auf Lager,de_DE +recurring_orders.review.title,Review Required — %name%,en_US +recurring_orders.review.title,Überprüfung erforderlich — %name%,de_DE +recurring_orders.review.unchanged.title,Unchanged items (%count%),en_US +recurring_orders.review.unchanged.title,Unveränderte Artikel (%count%),de_DE +recurring_orders.review.unchanged.title.plural,%count% unchanged items,en_US +recurring_orders.review.unchanged.title.plural,%count% unveränderte Artikel,de_DE +recurring_orders.status.active,Active,en_US +recurring_orders.status.active,Aktiv,de_DE +recurring_orders.status.cancelled,Cancelled,en_US +recurring_orders.status.cancelled,Abgebrochen,de_DE +recurring_orders.status.draft,Draft,en_US +recurring_orders.status.draft,Entwurf,de_DE +recurring_orders.status.failed,Failed,en_US +recurring_orders.status.failed,Fehlgeschlagen,de_DE +recurring_orders.status.paused,Paused,en_US +recurring_orders.status.paused,Pausiert,de_DE +recurring_orders.status.review_required,Review Required,en_US +recurring_orders.status.review_required,Überprüfung erforderlich,de_DE +recurring_orders.checkout.validation.cadence_required,Please select a frequency.,en_US +recurring_orders.checkout.validation.cadence_required,Bitte wählen Sie eine Häufigkeit aus.,de_DE +recurring_orders.checkout.validation.settings_not_confirmed,Please confirm your recurring order settings before submitting.,en_US +recurring_orders.checkout.validation.settings_not_confirmed,Bitte bestätigen Sie Ihre Einstellungen für die wiederkehrende Bestellung vor dem Absenden.,de_DE +recurring_orders.detail.resume.validation.date_required,Please select a resume date.,en_US +recurring_orders.detail.resume.validation.date_required,Bitte wählen Sie ein Fortsetzungsdatum aus.,de_DE +recurring_orders.detail.resume.validation.date_in_past,The resume date must be in the future.,en_US +recurring_orders.detail.resume.validation.date_in_past,Das Fortsetzungsdatum muss in der Zukunft liegen.,de_DE +recurring_orders.scheduled.order.errors.title,Recurring order not placed,en_US +recurring_orders.scheduled.order.errors.title,Wiederkehrende Bestellung nicht aufgegeben,de_DE +recurring_orders.review.add_product.add,Add,en_US +recurring_orders.review.add_product.add,Hinzufügen,de_DE +recurring_orders.review.add_product.clear,Clear,en_US +recurring_orders.review.add_product.clear,Zurücksetzen,de_DE +recurring_orders.review.add_product.label,Add a product — name or SKU,en_US +recurring_orders.review.add_product.label,Produkt hinzufügen — Name oder SKU,de_DE +recurring_orders.review.add_product.modal.title,Add a product,en_US +recurring_orders.review.add_product.modal.title,Produkt hinzufügen,de_DE +recurring_orders.review.add_product.open_modal,Add product,en_US +recurring_orders.review.add_product.open_modal,Produkt hinzufügen,de_DE +recurring_orders.review.add_product.price,Price,en_US +recurring_orders.review.add_product.price,Preis,de_DE +recurring_orders.review.add_product.quantity,Quantity,en_US +recurring_orders.review.add_product.quantity,Menge,de_DE +recurring_orders.review.add_product.remove,Remove,en_US +recurring_orders.review.add_product.remove,Entfernen,de_DE +recurring_orders.review.add_product.shipment_address,Delivery address,en_US +recurring_orders.review.add_product.shipment_address,Lieferadresse,de_DE +recurring_orders.review.add_product.shipment_address.group.company_unit_address,Business unit addresses,en_US +recurring_orders.review.add_product.shipment_address.group.company_unit_address,Adressen der Geschäftseinheit,de_DE +recurring_orders.review.add_product.shipment_address.group.schedule,Saved with this schedule,en_US +recurring_orders.review.add_product.shipment_address.group.schedule,Mit diesem Zeitplan gespeichert,de_DE +recurring_orders.review.add_product.shipment_address.placeholder,Select a delivery address,en_US +recurring_orders.review.add_product.shipment_address.placeholder,Lieferadresse auswählen,de_DE +recurring_orders.review.add_product.shipment_method,Shipment method,en_US +recurring_orders.review.add_product.shipment_method,Versandart,de_DE +recurring_orders.review.add_product.shipment_method.none,No shipment methods available for this address.,en_US +recurring_orders.review.add_product.shipment_method.none,Für diese Adresse sind keine Versandarten verfügbar.,de_DE +recurring_orders.review.add_product.shipment_method.placeholder,Select a shipment method,en_US +recurring_orders.review.add_product.shipment_method.placeholder,Versandart auswählen,de_DE +recurring_orders.review.add_product.title,Added products (%count%),en_US +recurring_orders.review.add_product.title,Hinzugefügte Produkte (%count%),de_DE +recurring_orders.review.add_product.title.singular,Added product (%count%),en_US +recurring_orders.review.add_product.title.singular,Hinzugefügtes Produkt (%count%),de_DE +recurring_orders.review.substitute.delta_higher,Higher price,en_US +recurring_orders.review.substitute.delta_higher,Höherer Preis,de_DE +recurring_orders.review.substitute.delta_lower,Lower price,en_US +recurring_orders.review.substitute.delta_lower,Niedrigerer Preis,de_DE +recurring_orders.review.substitute.delta_same,Same price,en_US +recurring_orders.review.substitute.delta_same,Gleicher Preis,de_DE +recurring_orders.review.substitute.modal.confirm,Use this substitute,en_US +recurring_orders.review.substitute.modal.confirm,Diesen Ersatz verwenden,de_DE +recurring_orders.review.substitute.modal.description,%product% is no longer available. Select a replacement to use for this order.,en_US +recurring_orders.review.substitute.modal.description,%product% ist nicht mehr verfügbar. Wählen Sie einen Ersatz für diese Bestellung.,de_DE +recurring_orders.review.substitute.modal.title,Choose a substitute,en_US +recurring_orders.review.substitute.modal.title,Ersatzprodukt wählen,de_DE +recurring_orders.review.substitute.recommended,recommended,en_US +recurring_orders.review.substitute.recommended,empfohlen,de_DE +recurring_orders.review.substitute.removed,Removed,en_US +recurring_orders.review.substitute.removed,Entfernt,de_DE +recurring_orders.review.substitute.unavailable,unavailable,en_US +recurring_orders.review.substitute.unavailable,nicht verfügbar,de_DE +recurring_orders.checkout.error.not_eligible,This cart cannot be placed as a recurring order.,en_US +recurring_orders.checkout.error.not_eligible,Dieser Warenkorb kann nicht als wiederkehrende Bestellung aufgegeben werden.,de_DE +recurring_orders.checkout.error.cadence_value_required,Please choose an interval for the recurring order.,en_US +recurring_orders.checkout.error.cadence_value_required,Bitte wählen Sie ein Intervall für die wiederkehrende Bestellung aus.,de_DE +recurring_orders.error.quote_not_found,The cart could not be found or access was denied.,en_US +recurring_orders.error.quote_not_found,Der Warenkorb wurde nicht gefunden oder der Zugriff wurde verweigert.,de_DE +recurring_orders.review.reason.configurable_bundle_unavailable,Configurable bundle unavailable,en_US +recurring_orders.review.reason.configurable_bundle_unavailable,Konfigurierbares Bundle nicht verfügbar,de_DE +recurring_orders.review.product-discontinued.message,"This product is discontinued. Choose a replacement to keep it in your order.",en_US +recurring_orders.review.product-discontinued.message,"Dieses Produkt wurde eingestellt. Wählen Sie einen Ersatz aus, damit es in Ihrer Bestellung bleibt.",de_DE +recurring_orders.review.substitute.sold-by,Sold by,en_US +recurring_orders.review.substitute.sold-by,Verkauft durch,de_DE +``` + +Import data: + +```bash +console data:import:glossary +``` + +{% info_block warningBox "Verification" %} + +Make sure that, in the database, the configured data has been added to the `spy_glossary_key` and `spy_glossary_translation` tables. + +{% endinfo_block %} + +### 9) Configure the Back Office settings + +Sync the recurring orders configuration settings to the database to make them editable in the Back Office: + +```bash +console configuration:sync +``` + +{% info_block warningBox "Verification" %} + +In the Back Office, go to **Configuration > Recurring Orders > General > Schedule**. Make sure the **Schedule Grace Period** field is displayed with a default value of `48`. + +{% endinfo_block %} + +{% info_block infoBox "Configurable settings" %} + +| SETTING | KEY | DEFAULT | CONSTRAINTS | DESCRIPTION | +| --- | --- | --- | --- | --- | +| Schedule Grace Period | `grace_period_hours` | `48` | Required, between 1 and 720 | Number of hours before the trigger date when the pre-trigger notification email is sent to the buyer. Per-schedule overrides stored in `spy_recurring_schedule.notification_window_hours` take precedence over this global value. | + +The setting is defined at `src/SprykerFeature/OrderExperienceManagement/resources/configuration/recurring_orders.configuration.yml` and applies globally—it has no per-store scope. + +{% endinfo_block %} diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/parse-integration-guide.php b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/parse-integration-guide.php index 540b4ed..6462930 100644 --- a/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/parse-integration-guide.php +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/parse-integration-guide.php @@ -302,6 +302,25 @@ function pig_parse_table(array $tableLines): array return ['header' => $header, 'rows' => $rows]; } +/** + * A prerequisites table lists every feature a guide touches; the text below it can say that some of + * them are optional ("Both Purchasing Control and SSP Service Management are optional"). A line that + * says "optional" marks every prerequisite it names. Without this, an optional feature would be + * installed first as a requirement. + */ +function pig_mark_optional_prerequisites(array &$prerequisites, string $line): void +{ + if (!preg_match('/\boptional\b/i', $line) || preg_match('/^\s*\|/', $line)) { + return; + } + foreach ($prerequisites as $index => $prerequisite) { + $name = (string)$prerequisite['name']; + if ($name !== '' && preg_match('/\b' . preg_quote($name, '/') . '\b/i', $line)) { + $prerequisites[$index]['optional'] = true; + } + } +} + function pig_link(string $cell): array { return preg_match('/\[([^\]]+)\]\(([^)]+)\)/', $cell, $m) ? [$m[1], $m[2]] : [trim($cell), null]; @@ -354,7 +373,10 @@ function pig_parse_guide(string $path, ?string $docsRoot, ?string $release): arr } elseif (in_array($header[0] ?? '', ['NAME', 'FEATURE'], true) && in_array('INSTALLATION GUIDE', $header, true)) { foreach ($parsed['rows'] as $cells) { [$linkText, $url] = pig_link($cells[2] ?? ''); - $guide['prerequisites'][] = ['name' => $cells[0] ?? '', 'version' => $cells[1] ?? '', 'guide' => $linkText, 'url' => $url]; + $name = $cells[0] ?? ''; + $optional = (bool)preg_match('/\(\s*optional\s*\)/i', $name); + $name = trim((string)preg_replace('/\(\s*optional\s*\)/i', '', $name)); + $guide['prerequisites'][] = ['name' => $name, 'version' => $cells[1] ?? '', 'guide' => $linkText, 'url' => $url, 'optional' => $optional]; } } elseif (($header[0] ?? '') === 'PLUGIN' && in_array('NAMESPACE', $header, true)) { $nsColumn = (int)array_search('NAMESPACE', $header, true); @@ -469,6 +491,9 @@ function pig_parse_guide(string $path, ?string $docsRoot, ?string $release): arr $info['text'] .= ' ' . trim($text); } $inPrerequisites = $stack !== [] && preg_match('/^(prerequisites|features .* depends on|install the required features)/i', end($stack)['title']); + if ($inPrerequisites && ($info === null || !$info['verification'])) { + pig_mark_optional_prerequisites($guide['prerequisites'], $text); + } if (($info === null || !$info['verification']) && !$inPrerequisites && preg_match_all('/\[([^\]]+)\]\((\/docs\/[^)#\s]+\.html)(?:#[^)]*)?\)/', $text, $links, PREG_SET_ORDER)) { foreach ($links as $link) { From cab81b2ed753dc4f377d7f560dee66a8fe06d23b Mon Sep 17 00:00:00 2001 From: Veronika Golska Date: Wed, 18 Nov 2026 08:56:20 +0100 Subject: [PATCH 12/18] spryker-feature-install: Definition of Done and blocker rule - check-dod.php decides DONE or NOT DONE from evidence in the state dir: scope, valid baselines, module moves with reasons, the checklist, the wiring, after-install checks and builds, verifications, tests, approved agent-written content, and proven release steps. Ten items, each met or not, with the reasons. - dod.json records the evidence no script can measure; only the developer's answer can waive an item. - The report's first line is check-dod.php's first line. While it says NOT DONE, the run is not described as installed, working or done. - A blocker stops the run in the phase where it is found, and the developer decides: fix, waive with a reason, or stop. - Phase 5 moves back modules the feature does not need unless the developer gives a reason; content the agent writes needs approval. --- .../skills/spryker-feature-install/README.md | 5 +- .../skills/spryker-feature-install/SKILL.md | 89 +++++-- .../references/release-steps.md | 3 +- .../scripts/check-checklist.php | 25 +- .../scripts/check-dod.php | 224 ++++++++++++++++++ .../scripts/feature-install.test.php | 75 ++++++ 6 files changed, 401 insertions(+), 20 deletions(-) create mode 100644 plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/check-dod.php diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/README.md b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/README.md index 085906a..832adff 100644 --- a/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/README.md +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/README.md @@ -32,7 +32,7 @@ flowchart TD Y --> V["6 - Verify
      auth precondition, spryker-verifier per
      Verification row, baselines compared"] V --> T["6b - Tests
      port the reference tests, add functional,
      API or Cypress tests the project runs"] T --> RS["7 - Release steps
      diff-release-steps, prove with
      deployed vs fresh comparison"] - RS --> RP(["8 - Report
      gate: check-checklist report"]) + RS --> RP(["8 - Report
      status: check-dod DONE or NOT DONE"]) ``` ## Scripts @@ -49,6 +49,7 @@ flowchart TD | `check-lock-diff.php` | 5 | which packages did the install move outside the feature's dependency tree; does a required package have a dev constraint? | | `glossary-key-check.php` | 5 | which translation keys of the feature's Yves modules have no glossary row? | | `diff-release-steps.php` | 7 | which commands, imports, republishes and variables does the deploy recipe not cover? | +| `check-dod.php` | 8 | is the integration DONE? Each of the ten Definition of Done items, met or not, from the evidence in the state directory | `lib.php` is the shared library. `feature-install.test.php` is the maintainer test suite (`php $FI/feature-install.test.php`); its guide fixtures in `fixtures/guides/` are copies of real @@ -65,6 +66,7 @@ Everything a run writes is in the project, under `.ai-dev/feature-install/.md` | The fixed row lists for `project-data` | @@ -92,6 +94,7 @@ wiring snippet in the guide: the guide lists the plugin and shows nowhere how to ## Design decisions baked in +- **The status comes from the Definition of Done.** `check-dod.php` decides DONE or NOT DONE; a blocker stops the run when it is found. - **Confirm before changing.** Nothing is required or edited before the developer agrees to the feature, release, constraint and optional integrations. - **Every step is a row; every row is decided.** The checklist gates block the install and the diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/SKILL.md b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/SKILL.md index 5d6ae36..417975d 100644 --- a/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/SKILL.md +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/SKILL.md @@ -48,7 +48,49 @@ extended, not rebuilt. Typical entry: `find-existing-capability` returned `not_i 9. **Project layer only, and no shortcuts:** never `vendor/`, `src/Generated/`, `src/Orm/` or a hand-edited `composer.lock`; never `dev-*` constraints or `--ignore-platform-reqs`; never a suppression; never `docker/sdk reset` or `clean-data`; never a commit or push without the - developer's yes. + developer's yes. Ask first before you write to a database by hand, change a user account, or + write content yourself (translations, CMS text). +10. **The status is `check-dod.php`'s, never yours** (§ Definition of Done). A blocker stops the run + when you find it (§ Blockers). + +## Definition of Done + +A feature integration is **DONE** only when all ten items hold, each one with its evidence in +`$STATE`. `php $FI/check-dod.php $STATE` decides it from that evidence. + +| # | Item | Evidence | +|---|---|---| +| 1 | The developer confirmed the scope: feature, install release, update mode, branch. | `dod.json` `scope` (Phase 3) | +| 2 | Every baseline ran and is valid: PHPStan, sniffer, tests, Back Office crawl, storage and search counts. | `dod.json` `baselines` (Phase 0) | +| 3 | Only modules the feature needs moved; every other move has a recorded reason. | `composer.lock.before` vs `composer.lock`; `dod.json` `accepted_moves` (Phase 5) | +| 4 | Every checklist row is decided, and done or skipped with a reason. | `checklist.json` | +| 5 | The decided wiring is in place. | `checklist.json` and the project's DependencyProviders | +| 6 | No regression against the baselines, and the Yves, Zed and Merchant Portal builds pass. | `dod.json` `checks` (Phase 6) | +| 7 | Every verification passed. BLOCKED and FAIL are not done; ACCEPTED counts with the developer's note. | `checklist.json` verdicts (Phase 6) | +| 8 | Passing tests cover the feature, or the developer waived them with a reason. | `checklist.json` `test` rows, `tests_waived` (Phase 6b) | +| 9 | Every text you wrote (translations, CMS text) is approved by the developer. | `dod.json` `authored_content` (Phase 5) | +| 10 | Every release step is verified, or the developer accepted shipping it unproven. | `release-steps.md`; `dod.json` `release_steps_accepted` (Phase 7) | + +`dod.json` holds what no script can measure. Its format is in the header of +`scripts/check-dod.php`. A baseline is `valid`, a check is `pass`; `blocked: ` records a +blocker; only the developer's answer can make a value `waived: `. + +**The report's first line is `check-dod.php`'s first line, word for word.** While it says +`NOT DONE`, the report opens with the unmet items, and the words "installed", "works", "done" or +"ready" do not describe the run. + +## Blockers + +A blocker is anything that stops a Definition of Done item from being met and that the install +itself cannot fix: a login that fails, a baseline that cannot run, a missing frontend dependency +tree, a check that needs a decision or data only the developer has. + +1. **Stop when you find it**, in the phase where you find it. Do not continue with the next phase + and report it at the end. +2. Record it in `dod.json` (`blocked: `) and in `state.md`. +3. Ask the developer, in one question: what blocks which item, and the options — fix it (with what + you need from them), waive the item with their reason, or stop the run. +4. Continue only on their answer. **Plan tracking is mandatory.** After Phase 0, create one task per phase in your harness's task list, and keep the phase table in `$STATE/state.md`: it survives a compaction. @@ -120,8 +162,11 @@ or a package name.** Record in `state.md` that the search ran through a fallback SPRYKER_UPGRADE_STATE_DIR=$STATE/baseline SPRYKER_BACKOFFICE_USER= SPRYKER_BACKOFFICE_PASSWORD= php $UP/backoffice-smoke.php --url --baseline ``` For the storage and search counts, copy `$UP/storage-search-counts.php` into `$STATE/baseline/` - and run it in the container with `--snapshot before`. A red baseline is not this run's damage: - record it in `state.md`. + and run it in the container with `--snapshot before`. +4. Record each baseline in `$STATE/dod.json` `baselines`. Red tests and existing findings are a + **valid** baseline: they are what the project had before. A baseline that did not run, or whose + result an environment problem distorts (a failed login makes the crawl and the logged-in tests + fail), is `blocked: ` — a blocker: stop and ask now (§ Blockers). ## Phase 1 — Resolve the feature and its release @@ -199,7 +244,9 @@ was not found. reference tests to port; - commits: one per guide section (recommended), or none until the report. - Set `skip:` on every row of a block the developer did not choose. + Set `skip:` on every row of a block the developer did not choose. Record the answer in + `dod.json` `scope` (`feature`, `install_release`, `update_mode`, `branch`, and `confirmed`: the + developer's answer in their words). ## Phase 4 — Reconcile @@ -223,7 +270,10 @@ Read [references/reconcile.md](references/reconcile.md) on entry. php $FI/check-lock-diff.php --before $STATE/composer.lock.before --checklist $STATE/checklist.json ``` Exit 1 lists packages that moved outside the feature's dependency tree (a module Phase 1 added is - expected), or a dev constraint. The developer accepts each move, or you narrow the update. + expected), or a dev constraint. Move each one back to its version in `composer.lock.before` + (`composer require spryker/: --update-with-dependencies`, then restore the + constraint), unless the feature needs it. A move that stays needs the developer's reason in + `dod.json` `accepted_moves`. Accepting the update mode at gate #1 is not a reason for each move. 2. When any module moved, check the project's customisations against it: ```bash SPRYKER_UPGRADE_STATE_DIR=$STATE/baseline php $UP/check-typed-members.php @@ -236,7 +286,11 @@ Read [references/reconcile.md](references/reconcile.md) on entry. [references/apply-steps.md](references/apply-steps.md): - apply the section's rows by their decision; set `status: done` or `failed` on each; - hand the section's data rows to `project-data` (the hand-off format in - [references/data-classes.md](references/data-classes.md)); + [references/data-classes.md](references/data-classes.md)), into the files the project's import + manifests read for every environment; + - text the guide or the module does not ship (a translation for a project locale, CMS text) is + content: ask the developer first (or hand it to `translate-content`), and record it in + `dod.json` `authored_content` with their approval; - schema rows: run `propel:diff` and show the migration before `propel:migrate`; the guide's `propel:install` is for a fresh local database only; - codegen and setup: `spryker-refresher` with the changed files, then the section's own setup @@ -271,8 +325,9 @@ widgets; every vendor template the project overrides has lost the vendor's calls evidence path. Weigh a FAIL as a hypothesis before acting: browser problems look like feature failures. 3. Run PHPStan, the sniffer, the tests, the Back Office crawl and the storage and search counts - (`--snapshot after`, then `--compare before after`) again, each against its baseline. A new - failure is this run's damage. + (`--snapshot after`, then `--compare before after`) again, each against its baseline, and the + Yves, Zed and Merchant Portal builds. A new failure is this run's damage. Record each result in + `dod.json` `checks` (`pass`, or `fail: `; `frontend-build` covers all builds). 4. `getSprykerCapability(slug)` shows `installed` (or `partially_installed` for API packages skipped on purpose). 5. A FAIL goes to `spryker-issue-diagnoser`; fix its root cause as a checklist row. A FAIL or @@ -315,16 +370,20 @@ Write them after Phase 6 passes, never before: a test written on a broken instal Do [references/release-steps.md](references/release-steps.md) exactly, in its order: list the candidates with `php $FI/diff-release-steps.php $STATE/checklist.json`, write each uncovered one into `$STATE/release-steps.md`, and prove the log with the comparison procedure, or record why it was not -proven. +proven. Each log row ends with its status: `verified`, `not needed`, `covered by recipe`, or +`to verify`. When the developer does not allow the proof, ask whether they accept shipping the +unproven steps, and record their reason in `dod.json` `release_steps_accepted`. ## Phase 8 — Report -1. Gate: `php $FI/check-checklist.php $STATE/checklist.json --phase report` exits 0. -2. Write `$STATE/report.md` in the shape that - [references/release-steps.md](references/release-steps.md) § The report gives: installed, - differences from the guide, data, storefront placement, verification, tests, release steps, not - verified. -3. Leave uncommitted changes unstaged for review. Stage only the files you changed, by path, and +1. Run `php $FI/check-dod.php $STATE`. Its first line is the run's status. +2. **NOT DONE:** the report opens with that line and the unmet items, each with what the + developer can do (fix, waive with a reason, accept). Then stop and ask. Do not describe the run + as installed, working, done or ready. +3. **DONE:** write `$STATE/report.md` in the shape that + [references/release-steps.md](references/release-steps.md) § The report gives. Its first line is + `check-dod.php`'s first line, word for word. +4. Leave uncommitted changes unstaged for review. Stage only the files you changed, by path, and commit or push only on the developer's yes. ## Hard rules diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/references/release-steps.md b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/references/release-steps.md index bf77a63..55a0194 100644 --- a/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/references/release-steps.md +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/references/release-steps.md @@ -100,7 +100,8 @@ the file that reads it, and what it holds. ## The report -`$STATE/report.md`, in this order: +`$STATE/report.md`, in this order. Its first line is the first line of `check-dod.php`, word for +word. A report is written only when that line says `DONE` (SKILL.md Phase 8). 1. **Feature and release** — the feature, the release, the guides used (with their source URLs). 2. **Installed** — per guide section: the rows applied, with their decision. diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/check-checklist.php b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/check-checklist.php index f5433ac..53b2c95 100644 --- a/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/check-checklist.php +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/check-checklist.php @@ -31,8 +31,20 @@ */ function cc_problems(array $checklist, string $phase): array { - $problems = []; + return array_merge(...array_values(cc_problems_by_item($checklist, $phase))); +} + +/** + * The problems grouped as the Definition of Done counts them: rows (decisions and status), + * verification (verdicts) and tests (coverage). + * + * @return array{rows: list, verification: list, tests: list} + */ +function cc_problems_by_item(array $checklist, string $phase): array +{ + $byItem = ['rows' => [], 'verification' => [], 'tests' => []]; foreach ($checklist['rows'] as $row) { + $problems = []; $id = (string)($row['id'] ?? '?'); $where = sprintf('%s %s %s', $id, $row['kind'] ?? '?', $row['target'] ?? ''); $decision = $row['decision'] ?? null; @@ -60,6 +72,7 @@ function cc_problems(array $checklist, string $phase): array } if ($phase !== 'report') { + $byItem['rows'] = array_merge($byItem['rows'], $problems); continue; } if ($status === 'failed') { @@ -77,16 +90,22 @@ function cc_problems(array $checklist, string $phase): array $problems[] = "$where: ACCEPTED without a verdict_note"; } } + $item = match ($row['kind'] ?? '') { + 'verification' => 'verification', + 'test' => 'tests', + default => 'rows', + }; + $byItem[$item] = array_merge($byItem[$item], $problems); } if ($phase === 'report') { $coveringTests = array_filter($checklist['rows'], static fn (array $row): bool => ($row['kind'] ?? '') === 'test' && ($row['status'] ?? '') === 'done'); if ($coveringTests === [] && trim((string)($checklist['tests_waived'] ?? '')) === '') { - $problems[] = 'no test covers the feature: add `test` rows and make them pass (Phase 6b), or set `tests_waived` to the developer\'s reason'; + $byItem['tests'][] = 'no test covers the feature: add `test` rows and make them pass (Phase 6b), or set `tests_waived` to the developer\'s reason'; } } - return $problems; + return $byItem; } function cc_main(array $argv): int diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/check-dod.php b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/check-dod.php new file mode 100644 index 0000000..cb19e1f --- /dev/null +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/check-dod.php @@ -0,0 +1,224 @@ + e.g. .ai-dev/feature-install/recurring-orders + * + * Evidence it reads from the state dir: + * checklist.json rows, verdicts, `test` rows, `tests_waived` (items 4, 5, 7, 8, 9) + * dod.json scope, baselines, accepted module moves, after-install checks, authored + * content, accepted unproven release steps (items 1, 2, 3, 6, 9, 10) + * composer.lock.before with the project's composer.lock and composer.json (item 3) + * release-steps.md the release-steps log (item 10): a row is met when its status starts + * with `verified`, `not needed` or `covered` + * + * dod.json: + * { + * "scope": {"feature": "...", "install_release": "...", "update_mode": "-w", "branch": "...", + * "confirmed": ""}, + * "baselines": {"phpstan": "valid", "sniffer": "valid", "tests": "valid", + * "backoffice-crawl": "valid", "storage-counts": "valid"}, + * "accepted_moves": {"spryker/": ""}, + * "checks": {"phpstan": "pass", "sniffer": "pass", "tests": "pass", "backoffice-crawl": "pass", + * "storage-counts": "pass", "frontend-build": "pass"}, + * "authored_content": [{"file": "...", "what": "...", "approved": ""}], + * "release_steps_accepted": "" + * } + * A baseline is `valid`; a check is `pass`. Anything else is unmet, except `waived: `. `blocked: ` records a blocker, and a blocker is unmet. + * + * Exit codes: 0 DONE; 1 NOT DONE (each unmet item listed); 2 usage or unreadable state. + */ + +declare(strict_types=1); + +require_once __DIR__ . '/lib.php'; +require_once __DIR__ . '/check-checklist.php'; +require_once __DIR__ . '/check-lock-diff.php'; +require_once __DIR__ . '/check-feature-installed.php'; + +const DOD_BASELINES = ['phpstan', 'sniffer', 'tests', 'backoffice-crawl', 'storage-counts']; +const DOD_CHECKS = ['phpstan', 'sniffer', 'tests', 'backoffice-crawl', 'storage-counts', 'frontend-build']; + +const DOD_ITEMS = [ + 1 => 'the developer confirmed the scope', + 2 => 'every baseline ran and is valid', + 3 => 'only modules the feature needs moved; every other move has a reason', + 4 => 'every checklist row is decided, and done or skipped with a reason', + 5 => 'the decided wiring is in place', + 6 => 'no regression against the baselines, and the frontend builds pass', + 7 => 'every verification passed', + 8 => 'passing tests cover the feature', + 9 => 'every text the agent wrote is approved', + 10 => 'the release steps are proven', +]; + +function dod_waived(string $value): bool +{ + return (bool)preg_match('/^waived:\s*\S/', $value); +} + +/** + * @return list unmet entries of a baselines or checks map + */ +function dod_unmet_map(array $map, array $required, string $passValue): array +{ + $unmet = []; + foreach ($required as $name) { + $value = trim((string)($map[$name] ?? '')); + if ($value === '') { + $unmet[] = "$name: not recorded"; + } elseif ($value !== $passValue && !dod_waived($value)) { + $unmet[] = "$name: $value"; + } + } + + return $unmet; +} + +/** + * @return list release-steps log rows whose status is not verified or not needed + */ +function dod_unproven_release_steps(string $file): array +{ + if (!is_file($file)) { + return ['release-steps.md is missing']; + } + $unproven = []; + $inTable = false; + foreach (file($file, FILE_IGNORE_NEW_LINES) ?: [] as $line) { + if (!preg_match('/^\s*\|/', $line)) { + $inTable = false; + continue; + } + $isHeader = !$inTable; + $inTable = true; + if ($isHeader || preg_match('/^\s*\|?[\s:\-|]+\|?\s*$/', $line)) { + continue; + } + $cells = array_map('trim', explode('|', trim(trim($line), '|'))); + $status = strtolower((string)end($cells)); + if (!preg_match('/^(verified|not needed|covered)\b/', $status)) { + $unproven[] = $cells[0] . ': ' . ($status !== '' ? $status : 'no status'); + } + } + + return $unproven; +} + +/** + * @return array> item number => unmet reasons (empty list = met) + */ +function dod_evaluate(string $root, string $stateDir): array +{ + $checklist = fi_load_checklist($stateDir . '/checklist.json'); + $dod = json_decode((string)@file_get_contents($stateDir . '/dod.json'), true); + $dod = is_array($dod) ? $dod : []; + $result = array_fill_keys(array_keys(DOD_ITEMS), []); + + $scope = $dod['scope'] ?? []; + foreach (['feature', 'install_release', 'update_mode', 'branch', 'confirmed'] as $field) { + if (trim((string)($scope[$field] ?? '')) === '') { + $result[1][] = "scope.$field is not recorded"; + } + } + + $result[2] = dod_unmet_map($dod['baselines'] ?? [], DOD_BASELINES, 'valid'); + + $before = $stateDir . '/composer.lock.before'; + if ($checklist === null || !is_file($before) || !is_file($root . '/composer.lock')) { + $result[3][] = 'cannot compare: checklist.json, composer.lock.before or composer.lock is missing'; + } else { + $after = fi_lock_packages($root . '/composer.lock'); + $features = cld_features_from_checklist($checklist); + $outside = array_diff_key(cld_moved(fi_lock_packages($before), $after), cld_tree($after, $features)); + foreach ($outside as $package => $versions) { + if (trim((string)($dod['accepted_moves'][$package] ?? '')) === '') { + $result[3][] = sprintf('%s %s -> %s moved outside the feature tree with no reason', $package, $versions['before'] ?? '(new)', $versions['after'] ?? '(removed)'); + } + } + $composerJson = (array)json_decode((string)@file_get_contents($root . '/composer.json'), true); + foreach (cld_dev_constraints($composerJson) as $package => $constraint) { + if (in_array(strtolower($package), array_map('strtolower', $features), true)) { + $result[3][] = "$package has the dev constraint $constraint"; + } + } + } + + if ($checklist === null) { + $result[4][] = 'checklist.json is missing or unreadable'; + $result[7][] = 'checklist.json is missing or unreadable'; + $result[8][] = 'checklist.json is missing or unreadable'; + } else { + $byItem = cc_problems_by_item($checklist, 'report'); + $result[4] = $byItem['rows']; + $result[7] = $byItem['verification']; + $result[8] = $byItem['tests']; + + $namespaces = cfi_project_namespaces($root); + $providers = cfi_dependency_providers($root, $namespaces); + foreach ($checklist['rows'] as $row) { + $decision = $row['decision'] ?? null; + if (!in_array($row['kind'] ?? '', CFI_WIRING_KINDS, true) || $decision === null || fi_is_skip($decision)) { + continue; + } + $state = cfi_wiring_state($root, $row, $namespaces, $providers); + if (!in_array($state['state'], ['present', 'file-present'], true)) { + $result[5][] = sprintf('%s %s: %s', $row['id'] ?? '?', $row['target'] ?? '', $state['state']); + } + } + } + + $result[6] = dod_unmet_map($dod['checks'] ?? [], DOD_CHECKS, 'pass'); + + foreach ($dod['authored_content'] ?? [] as $content) { + if (trim((string)($content['approved'] ?? '')) === '') { + $result[9][] = sprintf('%s (%s) is not approved', $content['file'] ?? '?', $content['what'] ?? 'text the agent wrote'); + } + } + + if (trim((string)($dod['release_steps_accepted'] ?? '')) === '') { + $result[10] = dod_unproven_release_steps($stateDir . '/release-steps.md'); + } + + return $result; +} + +function dod_main(array $argv): int +{ + $stateDir = $argv[1] ?? null; + if ($stateDir === null || !is_dir($stateDir)) { + fwrite(STDERR, "usage: php check-dod.php (for example .ai-dev/feature-install/)\n"); + + return 2; + } + $result = dod_evaluate(fi_project_root(), rtrim($stateDir, '/')); + $unmet = array_filter($result, static fn (array $reasons): bool => $reasons !== []); + + fwrite(STDOUT, $unmet === [] + ? "DONE — all 10 Definition of Done items are met.\n" + : sprintf("NOT DONE — %d of 10 Definition of Done items are not met: %s.\n", count($unmet), implode(', ', array_keys($unmet)))); + foreach (DOD_ITEMS as $number => $label) { + $reasons = $result[$number]; + fwrite(STDOUT, sprintf(" [%s] %2d %s\n", $reasons === [] ? 'x' : ' ', $number, $label)); + foreach (array_slice($reasons, 0, 8) as $reason) { + fwrite(STDOUT, ' - ' . (mb_strlen($reason) > 160 ? mb_substr($reason, 0, 120) . ' … ' . mb_substr($reason, -36) : $reason) . "\n"); + } + if (count($reasons) > 8) { + fwrite(STDOUT, sprintf(" - and %d more\n", count($reasons) - 8)); + } + } + + return $unmet === [] ? 0 : 1; +} + +if (realpath($argv[0] ?? '') === __FILE__) { + exit(dod_main($argv)); +} diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/feature-install.test.php b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/feature-install.test.php index 5e6c104..9fe8f39 100644 --- a/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/feature-install.test.php +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/feature-install.test.php @@ -10,6 +10,7 @@ require __DIR__ . '/check-feature-installed.php'; require __DIR__ . '/diff-release-steps.php'; require __DIR__ . '/find-feature-change.php'; +require __DIR__ . '/check-dod.php'; $failures = 0; $count = 0; @@ -311,5 +312,79 @@ function decided_row(array $overrides): array [$exit] = run_script('find-feature-change.php', ['--repo', $repo, '--package', 'spryker-feature/never'], $repo); check('a package the reference never required exits 1', $exit === 1); +echo "check-dod\n"; +$dodProject = temp_dir('dod'); +$dodState = $dodProject . '/.ai-dev/feature-install/x'; +$dodLock = static fn (array $packages): string => json_encode(['packages' => array_map(static fn (string $n, array $p): array => ['name' => $n] + $p, array_keys($packages), $packages)]); +write_file($dodProject . '/composer.json', json_encode(['require' => ['spryker-feature/x' => '^202608.0'], 'autoload' => ['psr-4' => ['Pyz\\' => 'src/Pyz/']]])); +write_file($dodState . '/composer.lock.before', $dodLock(['spryker/kernel' => ['version' => '3.70.0'], 'spryker/unrelated' => ['version' => '1.0.0']])); +write_file($dodProject . '/composer.lock', $dodLock([ + 'spryker-feature/x' => ['version' => '202608.0', 'require' => ['spryker/kernel' => '^3.70']], + 'spryker/kernel' => ['version' => '3.71.0'], + 'spryker/unrelated' => ['version' => '1.0.0'], +])); +write_file($dodProject . '/src/Pyz/Zed/Cart/CartDependencyProvider.php', " 1, 'release' => '202608.0', 'guides' => [], 'rows' => [ + decided_row(['id' => 'R001', 'kind' => 'composer', 'target' => 'composer require spryker-feature/x', 'packages' => ['spryker-feature/x' => '^202608.0']]), + decided_row(['id' => 'R002', 'kind' => 'plugin', 'target' => 'src/Pyz/Zed/Cart/CartDependencyProvider.php', 'plugins' => ['Spryker\Zed\X\XPlugin']]), + decided_row(['id' => 'R003', 'kind' => 'verification', 'verdict' => 'PASS']), + decided_row(['id' => 'R004', 'kind' => 'test', 'target' => 'tests/PyzTest/Zed/X/XFacadeTest.php']), +]]; +$dodEvidence = [ + 'scope' => ['feature' => 'spryker-feature/x', 'install_release' => '202608.0', 'update_mode' => '-w', 'branch' => 'ai-feature/x', 'confirmed' => 'developer: yes, -w, skip demo data'], + 'baselines' => array_fill_keys(DOD_BASELINES, 'valid'), + 'checks' => array_fill_keys(DOD_CHECKS, 'pass'), + 'authored_content' => [], +]; +$writeDod = static function (array $checklist, array $evidence, string $releaseSteps) use ($dodState): void { + fi_save_checklist($dodState . '/checklist.json', $checklist); + write_file($dodState . '/dod.json', json_encode($evidence)); + write_file($dodState . '/release-steps.md', $releaseSteps); +}; +$provenSteps = "| action | why | rows | status |\n|---|---|---|---|\n| data:import glossary | feature-data | R010 | verified |\n| queue:setup | new queue | R011 | covered by recipe |\n"; +$unmetItems = static fn (): array => array_keys(array_filter(dod_evaluate($dodProject, $dodState), static fn (array $r): bool => $r !== [])); +$writeDod($dodChecklist, $dodEvidence, $provenSteps); +[$exit, $output] = run_script('check-dod.php', ['.ai-dev/feature-install/x'], $dodProject); +check('complete evidence is DONE, exit 0', $exit === 0 && str_starts_with($output, 'DONE')); +$writeDod($dodChecklist, ['scope' => ['feature' => 'spryker-feature/x']] + $dodEvidence, $provenSteps); +check('an unconfirmed scope fails item 1', $unmetItems() === [1]); +$writeDod($dodChecklist, ['baselines' => ['backoffice-crawl' => 'blocked: admin login fails'] + $dodEvidence['baselines']] + $dodEvidence, $provenSteps); +check('a blocked baseline fails item 2', $unmetItems() === [2]); +$writeDod($dodChecklist, ['baselines' => ['backoffice-crawl' => 'waived: developer, no Back Office in this project'] + $dodEvidence['baselines']] + $dodEvidence, $provenSteps); +check('a baseline waived with a reason is met', $unmetItems() === []); +write_file($dodProject . '/composer.lock', $dodLock(['spryker-feature/x' => ['version' => '202608.0', 'require' => ['spryker/kernel' => '^3.70']], 'spryker/kernel' => ['version' => '3.71.0'], 'spryker/unrelated' => ['version' => '1.1.0']])); +$writeDod($dodChecklist, $dodEvidence, $provenSteps); +check('a module moved outside the feature tree with no reason fails item 3', $unmetItems() === [3]); +$writeDod($dodChecklist, ['accepted_moves' => ['spryker/unrelated' => 'developer: required by the -w update, patch only']] + $dodEvidence, $provenSteps); +check('a move with a recorded reason is met', $unmetItems() === []); +$open = $dodChecklist; +$open['rows'][0]['status'] = 'open'; +$writeDod($open, ['accepted_moves' => ['spryker/unrelated' => 'patch only']] + $dodEvidence, $provenSteps); +check('an open row fails item 4', $unmetItems() === [4]); +write_file($dodProject . '/src/Pyz/Zed/Cart/CartDependencyProvider.php', " ['spryker/unrelated' => 'patch only']] + $dodEvidence, $provenSteps); +check('missing wiring fails item 5', $unmetItems() === [5]); +write_file($dodProject . '/src/Pyz/Zed/Cart/CartDependencyProvider.php', " ['spryker/unrelated' => 'patch only'], 'checks' => ['frontend-build' => 'fail: Zed webpack error'] + $dodEvidence['checks']] + $dodEvidence, $provenSteps); +check('a failed frontend build fails item 6', $unmetItems() === [6]); +$blocked = $dodChecklist; +$blocked['rows'][2]['verdict'] = 'BLOCKED'; +$writeDod($blocked, ['accepted_moves' => ['spryker/unrelated' => 'patch only']] + $dodEvidence, $provenSteps); +check('a BLOCKED verification fails item 7, and only item 7', $unmetItems() === [7]); +$untested = $dodChecklist; +unset($untested['rows'][3]); +$untested['rows'] = array_values($untested['rows']); +$writeDod($untested, ['accepted_moves' => ['spryker/unrelated' => 'patch only']] + $dodEvidence, $provenSteps); +check('no passing test fails item 8', $unmetItems() === [8]); +$writeDod($dodChecklist, ['accepted_moves' => ['spryker/unrelated' => 'patch only'], 'authored_content' => [['file' => 'data/import/local/common/partial_glossary.csv', 'what' => 'fr_FR translations']]] + $dodEvidence, $provenSteps); +check('text the agent wrote without approval fails item 9', $unmetItems() === [9]); +$unproven = "| action | why | rows | status |\n|---|---|---|---|\n| data:import glossary | feature-data | R010 | to verify |\n"; +$writeDod($dodChecklist, ['accepted_moves' => ['spryker/unrelated' => 'patch only']] + $dodEvidence, $unproven); +check('an unproven release step fails item 10', $unmetItems() === [10]); +$writeDod($dodChecklist, ['accepted_moves' => ['spryker/unrelated' => 'patch only'], 'release_steps_accepted' => 'developer: proven on staging instead'] + $dodEvidence, $unproven); +check('unproven release steps the developer accepted are met', $unmetItems() === []); +[$exit, $output] = run_script('check-dod.php', ['.ai-dev/feature-install/missing'], $dodProject); +check('a missing state dir exits 2', $exit === 2); + echo "\n$count checks, $failures failed\n"; exit($failures === 0 ? 0 : 1); From 82a54ae1910b134219a0a33d47ed990b257b46ad Mon Sep 17 00:00:00 2001 From: Veronika Golska Date: Wed, 18 Nov 2026 09:32:49 +0100 Subject: [PATCH 13/18] Move the feature-install tests and guide fixtures out of the plugin The test suite and its four guide fixtures (360 KB of copied integration guides) are maintainer tooling, so they no longer ship with the plugin. They now live in tests/scripts/feature-install/, and CI runs them in the plugins job. --- .github/workflows/ci.yml | 3 +++ .../skills/spryker-feature-install/README.md | 9 +++---- .../feature-install}/feature-install.test.php | 25 ++++++++++++------- .../guides/multiple-carts-glue-api.txt | 0 .../fixtures/guides/order-amendment.txt | 0 .../fixtures/guides/recurring-orders.txt | 0 .../fixtures/guides/ssp-asset-management.txt | 0 7 files changed, 23 insertions(+), 14 deletions(-) rename {plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts => tests/scripts/feature-install}/feature-install.test.php (97%) rename {plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts => tests/scripts/feature-install}/fixtures/guides/multiple-carts-glue-api.txt (100%) rename {plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts => tests/scripts/feature-install}/fixtures/guides/order-amendment.txt (100%) rename {plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts => tests/scripts/feature-install}/fixtures/guides/recurring-orders.txt (100%) rename {plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts => tests/scripts/feature-install}/fixtures/guides/ssp-asset-management.txt (100%) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 467f6b8..e0344c0 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -63,6 +63,9 @@ jobs: - name: Rule sync script run: bash tests/scripts/test-sync-rules.sh + - name: Feature install scripts + run: php tests/scripts/feature-install/feature-install.test.php + - name: Stop guard, under both harnesses run: php plugins/spryker-ai-dev-sdk/hooks/hooks.test.php diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/README.md b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/README.md index 832adff..7d024ea 100644 --- a/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/README.md +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/README.md @@ -51,11 +51,10 @@ flowchart TD | `diff-release-steps.php` | 7 | which commands, imports, republishes and variables does the deploy recipe not cover? | | `check-dod.php` | 8 | is the integration DONE? Each of the ten Definition of Done items, met or not, from the evidence in the state directory | -`lib.php` is the shared library. `feature-install.test.php` is the maintainer test suite -(`php $FI/feature-install.test.php`); its guide fixtures in `fixtures/guides/` are copies of real -integration guides in both guide styles. It is not part of an install run. The baselines and the -override checks reuse `../spryker-upgrade/scripts/`; storefront placement uses -`../yves-twig-integration/scripts/`. +`lib.php` is the shared library. The baselines and the override checks reuse +`../spryker-upgrade/scripts/`; storefront placement uses `../yves-twig-integration/scripts/`. The +maintainer test suite is not part of the plugin: it lives in the plugin repository, in +`tests/scripts/feature-install/`. ## State diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/feature-install.test.php b/tests/scripts/feature-install/feature-install.test.php similarity index 97% rename from plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/feature-install.test.php rename to tests/scripts/feature-install/feature-install.test.php index 9fe8f39..2be5b1c 100644 --- a/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/feature-install.test.php +++ b/tests/scripts/feature-install/feature-install.test.php @@ -2,15 +2,22 @@ declare(strict_types=1); -/** Zero-dependency tests for the spryker-feature-install scripts. Run: php scripts/feature-install.test.php */ +/** + * Zero-dependency tests for the spryker-feature-install scripts. Maintainer tooling: it stays out of + * the plugin. The guide fixtures are copies of real integration guides. + * + * Run from the repository root: php tests/scripts/feature-install/feature-install.test.php + */ + +const FI_SCRIPTS = __DIR__ . '/../../../plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts'; -require __DIR__ . '/parse-integration-guide.php'; -require __DIR__ . '/check-checklist.php'; -require __DIR__ . '/check-lock-diff.php'; -require __DIR__ . '/check-feature-installed.php'; -require __DIR__ . '/diff-release-steps.php'; -require __DIR__ . '/find-feature-change.php'; -require __DIR__ . '/check-dod.php'; +require FI_SCRIPTS . '/parse-integration-guide.php'; +require FI_SCRIPTS . '/check-checklist.php'; +require FI_SCRIPTS . '/check-lock-diff.php'; +require FI_SCRIPTS . '/check-feature-installed.php'; +require FI_SCRIPTS . '/diff-release-steps.php'; +require FI_SCRIPTS . '/find-feature-change.php'; +require FI_SCRIPTS . '/check-dod.php'; $failures = 0; $count = 0; @@ -30,7 +37,7 @@ function check(string $name, bool $ok): void function run_script(string $script, array $args, string $projectDir): array { $process = proc_open( - array_merge([PHP_BINARY, __DIR__ . '/' . $script], $args), + array_merge([PHP_BINARY, FI_SCRIPTS . '/' . $script], $args), [1 => ['pipe', 'w'], 2 => ['pipe', 'w']], $pipes, $projectDir, diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/fixtures/guides/multiple-carts-glue-api.txt b/tests/scripts/feature-install/fixtures/guides/multiple-carts-glue-api.txt similarity index 100% rename from plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/fixtures/guides/multiple-carts-glue-api.txt rename to tests/scripts/feature-install/fixtures/guides/multiple-carts-glue-api.txt diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/fixtures/guides/order-amendment.txt b/tests/scripts/feature-install/fixtures/guides/order-amendment.txt similarity index 100% rename from plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/fixtures/guides/order-amendment.txt rename to tests/scripts/feature-install/fixtures/guides/order-amendment.txt diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/fixtures/guides/recurring-orders.txt b/tests/scripts/feature-install/fixtures/guides/recurring-orders.txt similarity index 100% rename from plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/fixtures/guides/recurring-orders.txt rename to tests/scripts/feature-install/fixtures/guides/recurring-orders.txt diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/fixtures/guides/ssp-asset-management.txt b/tests/scripts/feature-install/fixtures/guides/ssp-asset-management.txt similarity index 100% rename from plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/fixtures/guides/ssp-asset-management.txt rename to tests/scripts/feature-install/fixtures/guides/ssp-asset-management.txt From 382315e2194b301deb76e449b3e07b32716afe48 Mon Sep 17 00:00:00 2001 From: Veronika Golska Date: Wed, 18 Nov 2026 14:36:04 +0100 Subject: [PATCH 14/18] spryker-feature-install: install report format references/report.md holds the report developers share with colleagues: versions table (releases only, never package version tags), what was done, branch and pull request, steps after the deploy, the guide link pinned to the version followed, the guide steps not installed and why, what was validated and how, and what upgrading the project to the latest release would add. It is written only when check-dod.php says DONE; project problems the install did not cause go to the developer as ticket candidates, not into the report. --- .../skills/spryker-feature-install/README.md | 2 +- .../skills/spryker-feature-install/SKILL.md | 13 +-- .../references/release-steps.md | 27 +----- .../references/report.md | 96 +++++++++++++++++++ 4 files changed, 109 insertions(+), 29 deletions(-) create mode 100644 plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/references/report.md diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/README.md b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/README.md index 7d024ea..cd43653 100644 --- a/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/README.md +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/README.md @@ -70,7 +70,7 @@ Everything a run writes is in the project, under `.ai-dev/feature-install/.md` | The fixed row lists for `project-data` | | `release-steps.md` | The release-steps log | -| `report.md` | The report | +| `report.md` | The install report for colleagues, written only when `check-dod.php` says DONE (`references/report.md`) | ## The checklist row diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/SKILL.md b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/SKILL.md index 417975d..fb80c75 100644 --- a/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/SKILL.md +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/SKILL.md @@ -75,9 +75,10 @@ A feature integration is **DONE** only when all ten items hold, each one with it `scripts/check-dod.php`. A baseline is `valid`, a check is `pass`; `blocked: ` records a blocker; only the developer's answer can make a value `waived: `. -**The report's first line is `check-dod.php`'s first line, word for word.** While it says -`NOT DONE`, the report opens with the unmet items, and the words "installed", "works", "done" or -"ready" do not describe the run. +**The status is `check-dod.php`'s first line.** While it says `NOT DONE`, every message to the +developer opens with that line and the unmet items, the words "installed", "works", "done" or +"ready" do not describe the run, and nothing is offered for review. The install report +([references/report.md](references/report.md)) is written only after `DONE`. ## Blockers @@ -380,9 +381,9 @@ unproven steps, and record their reason in `dod.json` `release_steps_accepted`. 2. **NOT DONE:** the report opens with that line and the unmet items, each with what the developer can do (fix, waive with a reason, accept). Then stop and ask. Do not describe the run as installed, working, done or ready. -3. **DONE:** write `$STATE/report.md` in the shape that - [references/release-steps.md](references/release-steps.md) § The report gives. Its first line is - `check-dod.php`'s first line, word for word. +3. **DONE:** write `$STATE/report.md` with the template and rules in + [references/report.md](references/report.md). Problems found in the project that this install + did not cause go to the developer as ticket candidates, not into the report. 4. Leave uncommitted changes unstaged for review. Stage only the files you changed, by path, and commit or push only on the developer's yes. diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/references/release-steps.md b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/references/release-steps.md index 55a0194..cbec9d0 100644 --- a/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/references/release-steps.md +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/references/release-steps.md @@ -98,25 +98,8 @@ For each verified step, recommend one of these: Environment variables: the team sets them in each environment before the deploy. Name the variable, the file that reads it, and what it holds. -## The report - -`$STATE/report.md`, in this order. Its first line is the first line of `check-dod.php`, word for -word. A report is written only when that line says `DONE` (SKILL.md Phase 8). - -1. **Feature and release** — the feature, the release, the guides used (with their source URLs). -2. **Installed** — per guide section: the rows applied, with their decision. -3. **Differences from the guide** — every row with `apply-reference`, `merge` or `skip:`, - with the reason. -4. **Data** — the hand-offs, per `data_class`, and the placeholders listed for `curate-golive-data`. -5. **Storefront placement** — the placements applied (widget, project file), declined, or the - suggestion table as a follow-up; "no Yves code" when the step did not apply. -6. **Tests** — each `test` row: the test file, what behaviour it pins, ported from the reference or - new, and its suite. Or the `tests_waived` reason, with the line "the feature is not covered by - tests". -7. **Verification** — each `verification` row: PASS, or ACCEPTED with its note. The baseline - comparison: PHPStan, sniffer, tests, Back Office crawl, storage and search counts. -8. **Release steps** — staging first, production after the check on staging passes. Per step: the - command, the reason, recipe entry or one-time job, and `verified` or `to verify`. -9. **Not verified** — every check that did not run, and what it would have found. - -Use only `verified` steps as instructions; list the `to verify` steps under their own heading. +## In the report + +The report ([report.md](report.md)) lists only `verified` steps, under "Steps after the deploy". +A run with steps still `to verify` is not DONE, unless the developer accepted them +(`dod.json` `release_steps_accepted`). diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/references/report.md b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/references/report.md new file mode 100644 index 0000000..2734d81 --- /dev/null +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/references/report.md @@ -0,0 +1,96 @@ +# The install report + +Write `$STATE/report.md` only when `check-dod.php` says `DONE` (SKILL.md Phase 8). It is the report +the developer shares with colleagues: short, for readers who did not follow the run. Working detail +(checklist, decisions per row, evidence files, baselines) stays in `$STATE`. + +## Rules + +- **Releases, not package versions.** Name the project and the feature by their release number + (`202608.0`). Never by a package's own version tag (`4.0.0`). +- **The guide link is the guide that was followed.** When the install release is older than the + release the docs site shows, link the guide file in `spryker/spryker-docs` pinned to the commit + that was used, and say which release it matches. The docs site and its archive show only the + latest guide. +- **Every claim is measured.** "No new failures" only for a check that has a baseline; a check that + could not run is not in this report, because the run is not DONE. +- **No internal working detail:** no commands that were tried, no files not to commit, no account + names or passwords. +- **Problems found in the project that this install did not cause** are not in the report. List + them for the developer as ticket candidates. + +## Template + +````markdown +# — install report + +The feature is installed in the project at release [, the same release as +the rest of the project]. + +| Version | Release | +| --- | --- | +| Project (all Spryker features) | | +| feature, installed | | +| feature, latest available | | + +## What was done + + + +- +- +- + +## Branch and pull request + +Branch: ``. | The change is not committed yet, so there is no pull request for it.> + +## Steps after the deploy + +On each existing environment, run once after the deploy: + +1. `` + + + +## Integration guide + +[Install the feature, version used for this install]() (, matching release ). + +## Not installed + +The install guide also contains steps that connect with other Spryker features. These steps +are needed only when the project uses those features. This project does not use them, so the +following steps were not installed: + +| Part of the guide | Reason | +| --- | --- | +| | | + + + +## What was validated and how + +| What | How | Result | +| --- | --- | --- | +| All applicable checks of the guide | run on the local shop: | pass | +| | new tests | pass | +| Code quality | PHPStan level , code sniffer | no new findings | +| Existing behaviour | compared with a run before the install; crawl of Back Office pages | no new failures | +| Steps after the deploy | local comparison of a deployed environment with a fresh install | equal after the steps above | +| | | approved | + +## Upgrading the project to release + + + +The project runs Spryker release . The latest available release is . Upgrading the project to makes the latest version of +available, which adds these capabilities: + +| Capability | What it gives | +| --- | --- | +| | | + +Sources: [release notes ](), [module release notes](). +```` From ada596f96882b0dd36ed94353cae486bcbbe9d16 Mon Sep 17 00:00:00 2001 From: Veronika Golska Date: Wed, 18 Nov 2026 14:40:18 +0100 Subject: [PATCH 15/18] spryker-feature-install: report template follows the shared Recurring Orders report The template now has the same sections, headings and fixed sentences as the report shared with the team, including the date and author line, and the report itself is the worked example. --- .../references/report.md | 163 +++++++++++++----- 1 file changed, 117 insertions(+), 46 deletions(-) diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/references/report.md b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/references/report.md index 2734d81..286f96f 100644 --- a/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/references/report.md +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/references/report.md @@ -1,31 +1,27 @@ # The install report -Write `$STATE/report.md` only when `check-dod.php` says `DONE` (SKILL.md Phase 8). It is the report -the developer shares with colleagues: short, for readers who did not follow the run. Working detail -(checklist, decisions per row, evidence files, baselines) stays in `$STATE`. - -## Rules - -- **Releases, not package versions.** Name the project and the feature by their release number - (`202608.0`). Never by a package's own version tag (`4.0.0`). -- **The guide link is the guide that was followed.** When the install release is older than the - release the docs site shows, link the guide file in `spryker/spryker-docs` pinned to the commit - that was used, and say which release it matches. The docs site and its archive show only the - latest guide. -- **Every claim is measured.** "No new failures" only for a check that has a baseline; a check that - could not run is not in this report, because the run is not DONE. -- **No internal working detail:** no commands that were tried, no files not to commit, no account - names or passwords. -- **Problems found in the project that this install did not cause** are not in the report. List - them for the developer as ticket candidates. +Write `$STATE/report.md` only when `check-dod.php` says `DONE` (SKILL.md Phase 8), in exactly the +format below: the same sections, in the same order, with the same headings and fixed sentences. It +is the report the developer shares with colleagues. Offer to publish it as a shared document; working +detail (checklist, decisions per row, evidence, baselines) stays in `$STATE`. + +- Name the project and the feature by release number only (`202608.0`), never by a package's own + version tag. +- The guide link points to the guide that was followed: when the install release is older than the + release the docs site shows, the guide file in `spryker/spryker-docs` pinned to the commit used. +- A section with nothing in it keeps its heading and says so in one line ("None."). +- Leave out "Upgrading the project to release …" when the installed release is the latest. +- Problems in the project that this install did not cause are not in the report: list them for the + developer as ticket candidates. ## Template -````markdown +```markdown # — install report -The feature is installed in the project at release [, the same release as -the rest of the project]. + · + +The feature is installed in the project at release , the same release as the rest of the project. | Version | Release | | --- | --- | @@ -37,60 +33,135 @@ the rest of the project]. -- -- -- +- +- +- ## Branch and pull request -Branch: ``. | The change is not committed yet, so there is no pull request for it.> +Branch: ``. . | The change is not committed yet, so there is no pull request for it.> ## Steps after the deploy -On each existing environment, run once after the deploy: +On each existing environment, run once after the deploy (the deploy itself does not import data): 1. `` - - ## Integration guide -[Install the feature, version used for this install]() (, matching release ). +[Install the feature, version used for this install]() (spryker-docs, state of , matching release ). ## Not installed -The install guide also contains steps that connect with other Spryker features. These steps -are needed only when the project uses those features. This project does not use them, so the -following steps were not installed: +The install guide also contains steps that connect with other Spryker features. These steps are needed only when the project uses those features. This project does not use them, so the following steps were not installed: | Part of the guide | Reason | | --- | --- | -| | | - - +| | is not in the project | ## What was validated and how | What | How | Result | | --- | --- | --- | | All applicable checks of the guide | run on the local shop: | pass | -| | new tests | pass | +| | new | pass, twice in a row on a fresh install | | Code quality | PHPStan level , code sniffer | no new findings | -| Existing behaviour | compared with a run before the install; crawl of Back Office pages | no new failures | -| Steps after the deploy | local comparison of a deployed environment with a fresh install | equal after the steps above | -| | | approved | +| Existing behaviour | full Codecept suite (compared with a run before the install); crawl of Back Office pages | no new test failures | +| Steps after the deploy | local comparison of a deployed environment with a fresh install | equal after the imports | +| | | | ## Upgrading the project to release - - -The project runs Spryker release . The latest available release is . Upgrading the project to makes the latest version of -available, which adds these capabilities: +The project runs Spryker release . The latest available release is . Upgrading the project to makes the latest version of available, which adds these capabilities: | Capability | What it gives | | --- | --- | -| | | +| | | Sources: [release notes ](), [module release notes](). -```` +``` + +## Example + +The Recurring Orders report, as shared with the team: + +```markdown +# Recurring Orders — install report + +2026-11-18 · Veronika + +The Recurring Orders feature is installed in the project at release 202608.0, the same release as the rest of the project. + +| Version | Release | +| --- | --- | +| Project (all Spryker features) | 202608 | +| Recurring Orders feature, installed | 202608.0 | +| Recurring Orders feature, latest available | 202610.0 | + +## What was done + +A business customer can now turn an order into a schedule that the shop places again on a fixed rhythm. + +- Checkout option "Set up as recurring order" (weekly, every two weeks, monthly, every N weeks) +- Recurring Orders page in the customer account (details, history, pause, skip, cancel) +- Automatic placement and reminder e-mails through two Jenkins jobs +- Back Office overview of all recurring orders (Sales > Recurring Order Schedules) +- French translations added for all new storefront and e-mail texts +- All shop e-mails now sent with Symfony Mailer, so that e-mail subjects are translated +- `spryker/gui`, `spryker/cms`, `spryker/customer` and `spryker/mail` stay at their current versions, because their newer versions are not compatible with the project's Back Office build, customer override and e-mail setup + +## Branch and pull request + +Branch: `ai-dev-sdk-integration`. The change is not committed yet, so there is no pull request for it. + +## Steps after the deploy + +On each existing environment, run once after the deploy (the deploy itself does not import data): + +1. `vendor/bin/console data:import:glossary` +2. `vendor/bin/console data:import:cms-block` +3. `vendor/bin/console data:import:cms-block-store` + +## Integration guide + +[Install the Recurring Orders feature, version used for this install](https://github.com/spryker/spryker-docs/blob/693430ceea/docs/pbc/all/order-experience-management/latest/base-shop/install-and-upgrade/install-features/install-the-recurring-orders-feature.md) (spryker-docs, state of 17 August 2026, matching release 202608). + +## Not installed + +The install guide also contains steps that connect Recurring Orders with other Spryker features. These steps are needed only when the project uses those features. This project does not use them, so the following steps were not installed: + +| Part of the guide | Reason | +| --- | --- | +| Cost center and budget on recurring orders | Purchasing Control is not in the project | +| Restrictions for service products | Self-Service Portal is not in the project | +| Back Office setting "Schedule Grace Period" | the Configuration feature is not in the project; the default of 48 hours applies | +| Shipment copy for product bundles | the shop sells no product bundles | + +## What was validated and how + +| What | How | Result | +| --- | --- | --- | +| All 17 applicable checks of the guide | run on the local shop: checkout, customer account, Back Office, database, e-mails in the mail catcher, Jenkins jobs | pass | +| Checkout to customer account, and the Back Office list | 2 new Cypress journeys | pass, twice in a row on a fresh install | +| Code quality | PHPStan level 6, code sniffer | no new findings | +| Existing behaviour | full Codecept suite (compared with a run before the install); crawl of 77 Back Office pages | no new test failures; 1 crawl error, in a module this change did not touch | +| Steps after the deploy | local comparison of a deployed environment with a fresh install | equal after the 3 imports | +| French texts | not validated | need a review by a French speaker | + +## Upgrading the project to release 202610 + +The project runs Spryker release 202608. The latest available release is 202610. Upgrading the project to 202610 makes the latest version of Recurring Orders available, which adds these capabilities: + +| Capability | What it gives | +| --- | --- | +| Multi-day schedules | one recurring order can deliver on several days, for example every Tuesday and Thursday | +| Price tolerances | buyers set an accepted price increase for the order total and for single products; small price changes no longer stop the schedule for review | +| Price tolerances in the Back Office | tolerance column, filter and details on the schedules list and detail page | +| "Processing" status | a schedule shows "processing" while its order is being placed, and buyer actions are hidden during that time | +| Recovery of stuck schedules | a console command restarts schedules stuck in the state machine and reports the others | +| Orders Backend API | read, list and create orders, trigger order state transitions and add order comments, for example for an ERP integration | +| Fixes | schedules no longer get stuck in validation; a price accepted for "just this order" no longer replaces the regular price; a price change with a budget warning goes to review instead of being placed | +| Experience | a more consistent design across checkout, order review and the customer account | + +Sources: [release notes 202610.0](https://docs.spryker.com/docs/about/all/releases/release-notes-202610.0.html), [module release notes](https://github.com/spryker-feature/order-experience-management/releases). +``` From bd28ef4128981caa2d6b6518977860ab4736931f Mon Sep 17 00:00:00 2001 From: Veronika Golska Date: Wed, 18 Nov 2026 17:25:32 +0100 Subject: [PATCH 16/18] spryker-feature-install: measured checks for moves, baselines, data, glossary and release steps - check-needed-moves.php judges every moved package: needed (a requirer or a conflict rules out the old version), not needed (the old version satisfies every requirer) or unknown. Not-needed moves go back unless the developer gives a reason. Composer constraint matching is in lib.php. - compare-baselines.php checks that each baseline holds a result and compares PHPStan, sniffer, tests (by failing test), Back Office crawl, storage counts and frontend builds after the install with it. Baseline files use the names spryker-upgrade's check-baselines.php validates. - check-data-manifests.php checks that every data file the install wrote is imported by a manifest a deploy recipe runs. - glossary-key-check.php also reads keys from PHP (mail subjects through constants, messages), keys a package ships, files like partial_glossary.csv, and takes --locales. - dump-state.php dumps tables and search indices without ids and timestamps and compares a deployed environment with a fresh install. - check-dod.php measures items 2, 3, 6, 8 and 9 from these files; dod.json keeps only scope, reasons, approvals, data files and waivers. --- .../skills/spryker-feature-install/README.md | 11 +- .../skills/spryker-feature-install/SKILL.md | 64 +++-- .../references/apply-steps.md | 2 +- .../references/release-steps.md | 6 +- .../scripts/check-data-manifests.php | 136 ++++++++++ .../scripts/check-dod.php | 110 +++++---- .../scripts/check-needed-moves.php | 149 +++++++++++ .../scripts/compare-baselines.php | 207 ++++++++++++++++ .../scripts/dump-state.php | 233 ++++++++++++++++++ .../scripts/glossary-key-check.php | 146 +++++++++-- .../spryker-feature-install/scripts/lib.php | 135 ++++++++++ .../feature-install/feature-install.test.php | 196 ++++++++++++--- 12 files changed, 1250 insertions(+), 145 deletions(-) create mode 100644 plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/check-data-manifests.php create mode 100644 plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/check-needed-moves.php create mode 100644 plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/compare-baselines.php create mode 100644 plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/dump-state.php diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/README.md b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/README.md index cd43653..3ee5df5 100644 --- a/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/README.md +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/README.md @@ -46,9 +46,13 @@ flowchart TD | `check-feature-installed.php` | 3 (`--mark`), 5 (`--wiring`) | which modules and wiring does the project have already; is the decided wiring in place; which plugins belong to modules the project does not install? | | `find-feature-change.php` | 4 | which pull request brought the feature into the reference demo shop, and which of its files does no row name? | | `check-checklist.php` | 4 (`--phase decide`), 8 (`--phase report`) | is every row decided; is every row done, every verification passed, and the feature covered by a passing test? | -| `check-lock-diff.php` | 5 | which packages did the install move outside the feature's dependency tree; does a required package have a dev constraint? | -| `glossary-key-check.php` | 5 | which translation keys of the feature's Yves modules have no glossary row? | +| `check-needed-moves.php` | 5 | which moved packages does the feature need, and which only moved because composer could move them? | +| `check-lock-diff.php` | 5 | which packages moved outside the feature's dependency tree; does a required package have a dev constraint? | +| `glossary-key-check.php` | 5 | which translation keys the feature uses (Twig, PHP mail subjects and messages) or ships have no glossary row for a project locale? | +| `check-data-manifests.php` | 5 | is every data file the install wrote imported by a manifest a deploy recipe runs? | +| `compare-baselines.php` | 0, 6 | does every baseline hold a result; did PHPStan, the sniffer, the tests, the Back Office crawl, the storage counts or a frontend build regress? | | `diff-release-steps.php` | 7 | which commands, imports, republishes and variables does the deploy recipe not cover? | +| `dump-state.php` | 7 | is a deployed environment the same as a fresh install? Dumps tables and search indices without ids and timestamps, and compares two dumps | | `check-dod.php` | 8 | is the integration DONE? Each of the ten Definition of Done items, met or not, from the evidence in the state directory | `lib.php` is the shared library. The baselines and the override checks reuse @@ -67,7 +71,8 @@ Everything a run writes is in the project, under `.ai-dev/feature-install/.md` | The fixed row lists for `project-data` | | `release-steps.md` | The release-steps log | | `report.md` | The install report for colleagues, written only when `check-dod.php` says DONE (`references/report.md`) | diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/SKILL.md b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/SKILL.md index fb80c75..4b7c3c7 100644 --- a/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/SKILL.md +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/SKILL.md @@ -61,19 +61,21 @@ A feature integration is **DONE** only when all ten items hold, each one with it | # | Item | Evidence | |---|---|---| | 1 | The developer confirmed the scope: feature, install release, update mode, branch. | `dod.json` `scope` (Phase 3) | -| 2 | Every baseline ran and is valid: PHPStan, sniffer, tests, Back Office crawl, storage and search counts. | `dod.json` `baselines` (Phase 0) | -| 3 | Only modules the feature needs moved; every other move has a recorded reason. | `composer.lock.before` vs `composer.lock`; `dod.json` `accepted_moves` (Phase 5) | +| 2 | Every baseline ran and holds a result: PHPStan, sniffer, tests, Back Office crawl, storage and search counts. | `baseline/` tool output, `compare-baselines.php` (Phase 0) | +| 3 | Only modules the feature needs moved; every other move has the developer's reason. | `composer.lock.before` vs `composer.lock`, `check-needed-moves.php`; `dod.json` `accepted_moves` (Phase 5) | | 4 | Every checklist row is decided, and done or skipped with a reason. | `checklist.json` | | 5 | The decided wiring is in place. | `checklist.json` and the project's DependencyProviders | -| 6 | No regression against the baselines, and the Yves, Zed and Merchant Portal builds pass. | `dod.json` `checks` (Phase 6) | +| 6 | No regression against the baselines, and the Yves, Zed and Merchant Portal builds pass. | `after/` tool output, `compare-baselines.php` (Phase 6) | | 7 | Every verification passed. BLOCKED and FAIL are not done; ACCEPTED counts with the developer's note. | `checklist.json` verdicts (Phase 6) | -| 8 | Passing tests cover the feature, or the developer waived them with a reason. | `checklist.json` `test` rows, `tests_waived` (Phase 6b) | -| 9 | Every text you wrote (translations, CMS text) is approved by the developer. | `dod.json` `authored_content` (Phase 5) | +| 8 | Passing tests cover the feature, or the developer waived them with a reason. | `checklist.json` `test` rows and their files, `tests_waived` (Phase 6b) | +| 9 | Every data file the install wrote is imported by a manifest a recipe runs, and every text you wrote is approved. | `dod.json` `data_files`, `check-data-manifests.php`; `dod.json` `authored_content` (Phase 5) | | 10 | Every release step is verified, or the developer accepted shipping it unproven. | `release-steps.md`; `dod.json` `release_steps_accepted` (Phase 7) | -`dod.json` holds what no script can measure. Its format is in the header of -`scripts/check-dod.php`. A baseline is `valid`, a check is `pass`; `blocked: ` records a -blocker; only the developer's answer can make a value `waived: `. +Items 2, 3, 5, 6, 8 and 9 are measured from files, not from what you write down. `dod.json` holds +only what no file shows: the scope, the developer's reasons and approvals, the data files the +hand-off wrote, and waivers (`"waived": {"baseline:": ""}`, `"check:"`). Its +format is in the header of `scripts/check-dod.php`. Only the developer's answer can make a waiver or +a reason. **The status is `check-dod.php`'s first line.** While it says `NOT DONE`, every message to the developer opens with that line and the unmet items, the words "installed", "works", "done" or @@ -157,17 +159,17 @@ or a package name.** Record in `state.md` that the search ran through a fallback SPRYKER_UPGRADE_STATE_DIR=$STATE/baseline php $UP/check-config-constants.php || true SPRYKER_UPGRADE_STATE_DIR=$STATE/baseline php $UP/check-dead-overrides.php snapshot SPRYKER_UPGRADE_STATE_DIR=$STATE/baseline php $UP/twig-shadow-map.php snapshot - script -q /dev/null docker/sdk cli php -d memory_limit=2048M vendor/bin/phpstan analyze -c phpstan.neon src/ -l 6 2>&1 | tee $STATE/baseline/phpstan.txt - script -q /dev/null docker/sdk cli vendor/bin/console code:sniff:style 2>&1 | tee $STATE/baseline/sniff.txt - script -q /dev/null docker/sdk testing codecept run --no-exit 2>&1 | tee $STATE/baseline/codecept.txt + script -q /dev/null docker/sdk cli php -d memory_limit=2048M vendor/bin/phpstan analyze -c phpstan.neon src/ -l 6 2>&1 | tee $STATE/baseline/phpstan-baseline-run.txt + script -q /dev/null docker/sdk cli vendor/bin/console code:sniff:style 2>&1 | tee $STATE/baseline/sniff-baseline.txt + script -q /dev/null docker/sdk testing codecept run --no-exit 2>&1 | tee $STATE/baseline/codecept-baseline.txt SPRYKER_UPGRADE_STATE_DIR=$STATE/baseline SPRYKER_BACKOFFICE_USER= SPRYKER_BACKOFFICE_PASSWORD= php $UP/backoffice-smoke.php --url --baseline ``` For the storage and search counts, copy `$UP/storage-search-counts.php` into `$STATE/baseline/` and run it in the container with `--snapshot before`. -4. Record each baseline in `$STATE/dod.json` `baselines`. Red tests and existing findings are a - **valid** baseline: they are what the project had before. A baseline that did not run, or whose - result an environment problem distorts (a failed login makes the crawl and the logged-in tests - fail), is `blocked: ` — a blocker: stop and ask now (§ Blockers). +4. Check the baselines: `php $FI/compare-baselines.php $STATE` — every line under "Baselines" is + `ok`. Red tests and existing findings are a valid baseline: they are what the project had before. + A baseline that did not run, or that an environment problem made fail (a failed login writes no + crawl baseline), is a blocker: stop and ask now (§ Blockers). Only the developer can waive it. ## Phase 1 — Resolve the feature and its release @@ -268,13 +270,14 @@ Read [references/reconcile.md](references/reconcile.md) on entry. 1. Run the `composer` rows in the container, with the install release, the modules Phase 1 added, and the update mode the developer chose. On a conflict, report it and stop. Then: ```bash - php $FI/check-lock-diff.php --before $STATE/composer.lock.before --checklist $STATE/checklist.json + php $FI/check-needed-moves.php --before $STATE/composer.lock.before --accepted $STATE/dod.json ``` - Exit 1 lists packages that moved outside the feature's dependency tree (a module Phase 1 added is - expected), or a dev constraint. Move each one back to its version in `composer.lock.before` - (`composer require spryker/: --update-with-dependencies`, then restore the - constraint), unless the feature needs it. A move that stays needs the developer's reason in - `dod.json` `accepted_moves`. Accepting the update mode at gate #1 is not a reason for each move. + It judges every moved package: `needed` (a requirer or a conflict rules out its old version), + `not needed` (its old version satisfies every requirer), or `unknown`. Move each `not needed` + package back to its version in `composer.lock.before` (`composer require :`, + then restore the constraint), and run the check again until only `needed` moves are left. A move + that stays without being needed needs the developer's reason in `dod.json` `accepted_moves`; + accepting the update mode at gate #1 is not a reason for each move. 2. When any module moved, check the project's customisations against it: ```bash SPRYKER_UPGRADE_STATE_DIR=$STATE/baseline php $UP/check-typed-members.php @@ -287,8 +290,11 @@ Read [references/reconcile.md](references/reconcile.md) on entry. [references/apply-steps.md](references/apply-steps.md): - apply the section's rows by their decision; set `status: done` or `failed` on each; - hand the section's data rows to `project-data` (the hand-off format in - [references/data-classes.md](references/data-classes.md)), into the files the project's import - manifests read for every environment; + [references/data-classes.md](references/data-classes.md)). Record the files it wrote in + `dod.json` `data_files`, then `php $FI/check-data-manifests.php ...`: each file must be + imported by a manifest that a deploy recipe runs, for every environment that needs the rows; + - glossary: `php $FI/glossary-key-check.php --package= --locales=` lists the keys the feature uses or ships that have no row for a project locale; - text the guide or the module does not ship (a translation for a project locale, CMS text) is content: ask the developer first (or hand it to `translate-content`), and record it in `dod.json` `authored_content` with their approval; @@ -325,10 +331,14 @@ widgets; every vendor template the project overrides has lost the vendor's calls acceptance criterion, in the guide's words. Record `verdict` PASS, FAIL or BLOCKED with the evidence path. Weigh a FAIL as a hypothesis before acting: browser problems look like feature failures. -3. Run PHPStan, the sniffer, the tests, the Back Office crawl and the storage and search counts - (`--snapshot after`, then `--compare before after`) again, each against its baseline, and the - Yves, Zed and Merchant Portal builds. A new failure is this run's damage. Record each result in - `dod.json` `checks` (`pass`, or `fail: `; `frontend-build` covers all builds). +3. Run the baseline tools again, into `$STATE/after/` with the same commands as in Phase 0: + `phpstan-after.txt`, `sniff-after.txt`, `codecept-after.txt`; the Back Office crawl without + `--baseline` (same `SPRYKER_UPGRADE_STATE_DIR`: it marks each failure that is in the baseline); + the storage and search counts with `--snapshot after`, then `--compare before after`. Run each + frontend build the project has into `after/yves-build.txt`, `after/zed-build.txt`, + `after/mp-build.txt`, each ending with its exit code + (`… 2>&1 | tee ; echo "exit ${PIPESTATUS[0]}" >> `). Then + `php $FI/compare-baselines.php $STATE`: every line is `ok`. A new failure is this run's damage. 4. `getSprykerCapability(slug)` shows `installed` (or `partially_installed` for API packages skipped on purpose). 5. A FAIL goes to `spryker-issue-diagnoser`; fix its root cause as a checklist row. A FAIL or diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/references/apply-steps.md b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/references/apply-steps.md index 0deddb9..e63088c 100644 --- a/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/references/apply-steps.md +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/references/apply-steps.md @@ -18,7 +18,7 @@ files (plugins, dependency providers, transfers) define the conventions. | `transfer` | Project layer; check fields with `getTransferStructureByName`. | | `schema`, `event` | Project layer; follow the `propel-schema` conventions. | | `navigation`, `route` | Add the entry; do not reorder existing ones. | -| `glossary` | Add the keys for every configured locale (through the `project-data` hand-off). Guides often have no glossary step, so also run `php $FI/glossary-key-check.php --module=`: it lists the `'key' \| trans` keys of those modules that no `data/import/**/glossary*.csv` row defines, per locale. Add a `glossary` row with `data_class: feature-data` for each missing key; a missing key renders raw on the page. | +| `glossary` | Add the keys for every configured locale (through the `project-data` hand-off). Guides often have no glossary step, so also run `php $FI/glossary-key-check.php --package= --locales=`: it lists the keys the feature uses (Twig, PHP mail subjects and messages) or ships that no glossary row of the project defines, per locale. Add a `glossary` row with `data_class: feature-data` for each missing key; a missing key renders raw on the page. | | `data-row`, `data-import` | Through the `project-data` hand-off ([data-classes.md](data-classes.md)). The importer plugin and console command registration stays here. | | `deploy` | A new service or environment variable in a deploy file usually needs `docker/sdk up`, which is a rebuild: ask the developer. Never `docker/sdk reset` or `clean-data`. | | `console` | Through `spryker-refresher` and the guide's own setup commands (below). | diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/references/release-steps.md b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/references/release-steps.md index cbec9d0..38a8172 100644 --- a/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/references/release-steps.md +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/references/release-steps.md @@ -61,10 +61,10 @@ are empty after each reset and after the deployment. | 2 | `docker/sdk reset` | production today | | 3 | Check out the feature branch. | | | 4 | Build the images and assets as the pipeline does, without data: `docker/sdk up --build --assets`. Then run only the normal deployment commands. | | -| 5 | Dump the database, Redis and the search engine (documents, mappings, index settings). | **deployed** | +| 5 | Copy `$FI/dump-state.php` into `$STATE/`, then `docker/sdk cli php $STATE/dump-state.php --dump deployed`: every table (row count and content, without ids and timestamps) and every search index (document count). | **deployed** | | 6 | `docker/sdk reset` | | -| 7 | Dump the same set as in step 5. | **fresh** | -| 8 | Compare **deployed** with **fresh**. Ignore IDs, UUIDs and timestamps. | | +| 7 | `docker/sdk cli php $STATE/dump-state.php --dump fresh` | **fresh** | +| 8 | `php $STATE/dump-state.php --compare deployed fresh`: `EQUAL`, or each table and index that differs. | | **For each difference:** diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/check-data-manifests.php b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/check-data-manifests.php new file mode 100644 index 0000000..f171aba --- /dev/null +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/check-data-manifests.php @@ -0,0 +1,136 @@ +.yml` in `config/install/**`, with + * `${SPRYKER_REGION}` and similar variables matched against the files that exist. Each manifest's + * `source:` entries are the files it imports. + * + * Usage (from the project root, or set SPRYKER_PROJECT_ROOT): + * php check-data-manifests.php [...] + * + * without files: the CSV files under data/import that differ from HEAD (changed or new) + * + * Exit codes: 0 every file is imported by at least one recipe's manifest; 1 a file no recipe + * imports (listed); 2 usage, or no manifest found. + */ + +declare(strict_types=1); + +require_once __DIR__ . '/lib.php'; + +/** + * @return list manifest paths relative to the project root, from the install recipes + */ +function cdm_manifests(string $root): array +{ + $manifests = []; + $recipes = array_merge(glob($root . '/config/install/*.yml') ?: [], glob($root . '/config/install/*/*.yml') ?: []); + foreach ($recipes as $recipe) { + if (!preg_match_all('/--config[= ]([^\s\'"]+\.ya?ml)/', (string)file_get_contents($recipe), $m)) { + continue; + } + foreach ($m[1] as $config) { + $pattern = (string)preg_replace('/\$\{?[A-Z_]+\}?/', '*', $config); + foreach (glob($root . '/' . ltrim($pattern, '/')) ?: [] as $file) { + $manifests[] = substr($file, strlen($root) + 1); + } + } + } + $manifests = array_values(array_unique($manifests)); + sort($manifests); + + return $manifests; +} + +/** + * @return list the files a manifest imports, relative to the project root + */ +function cdm_sources(string $root, string $manifest): array +{ + $sources = []; + if (!preg_match_all('/^\s*-?\s*source:\s*[\'"]?([^\s\'"#]+)/m', (string)@file_get_contents($root . '/' . $manifest), $m)) { + return []; + } + foreach ($m[1] as $source) { + $source = ltrim((string)preg_replace('#^\./#', '', $source), '/'); + $sources[] = is_file($root . '/' . $source) || !is_file($root . '/' . dirname($manifest) . '/' . $source) + ? $source + : dirname($manifest) . '/' . $source; + } + + return $sources; +} + +/** + * @return list + */ +function cdm_changed_files(string $root): array +{ + $files = []; + foreach ([['diff', '--name-only', 'HEAD', '--', 'data/import'], ['ls-files', '--others', '--exclude-standard', '--', 'data/import']] as $args) { + $command = 'git -C ' . escapeshellarg($root) . ' ' . implode(' ', array_map('escapeshellarg', $args)) . ' 2>/dev/null'; + foreach (explode("\n", (string)shell_exec($command)) as $file) { + if (str_ends_with($file, '.csv') && is_file($root . '/' . $file)) { + $files[] = $file; + } + } + } + + return array_values(array_unique($files)); +} + +/** + * @return array> data file => manifests that import it (empty: none) + */ +function cdm_evaluate(string $root, array $files): array +{ + $byFile = array_fill_keys($files, []); + foreach (cdm_manifests($root) as $manifest) { + $sources = cdm_sources($root, $manifest); + foreach ($files as $file) { + if (in_array($file, $sources, true)) { + $byFile[$file][] = $manifest; + } + } + } + + return $byFile; +} + +function cdm_main(array $argv): int +{ + $root = fi_project_root(); + $files = array_slice($argv, 1); + if (array_filter($files, static fn (string $f): bool => str_starts_with($f, '-')) !== []) { + fwrite(STDERR, "usage: php check-data-manifests.php [...]\n"); + + return 2; + } + $manifests = cdm_manifests($root); + if ($manifests === []) { + fwrite(STDERR, "No import manifest found: no recipe in config/install runs data:import --config=.\n"); + + return 2; + } + $files = $files !== [] ? $files : cdm_changed_files($root); + $byFile = cdm_evaluate($root, $files); + $orphans = array_keys(array_filter($byFile, static fn (array $m): bool => $m === [])); + + fwrite(STDOUT, sprintf("%d data file(s) checked against %d manifest(s) the recipes run.\n", count($files), count($manifests))); + foreach ($byFile as $file => $importedBy) { + fwrite(STDOUT, sprintf(" %-4s %s%s\n", $importedBy === [] ? 'NONE' : 'ok', $file, $importedBy === [] ? ' imported by no manifest a recipe runs' : ' ' . implode(', ', $importedBy))); + } + + return $orphans === [] ? 0 : 1; +} + +if (realpath($argv[0] ?? '') === __FILE__) { + exit(cdm_main($argv)); +} diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/check-dod.php b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/check-dod.php index cb19e1f..20b016f 100644 --- a/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/check-dod.php +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/check-dod.php @@ -4,35 +4,31 @@ * Definition of Done: is the feature integration finished — DONE or NOT DONE, item by item. * * A run can install a feature, see most checks pass and still not be finished: a blocked - * verification, a baseline that never ran, a module that moved without a reason, no test, release - * steps nobody proved. This script decides the status from evidence, so the report cannot claim - * more than the evidence shows. Its first output line is the report's first line, word for word. + * verification, a baseline that never ran, a module that moved without being needed, no test, a data + * file no environment imports, release steps nobody proved. This script decides the status from + * evidence — tool output, lock files, the checklist, the project files — so a status cannot claim + * more than the evidence shows. Its first output line is the run's status. * * Usage (from the project root, or set SPRYKER_PROJECT_ROOT): * php check-dod.php e.g. .ai-dev/feature-install/recurring-orders * - * Evidence it reads from the state dir: - * checklist.json rows, verdicts, `test` rows, `tests_waived` (items 4, 5, 7, 8, 9) - * dod.json scope, baselines, accepted module moves, after-install checks, authored - * content, accepted unproven release steps (items 1, 2, 3, 6, 9, 10) - * composer.lock.before with the project's composer.lock and composer.json (item 3) + * Evidence it reads: + * baseline/, after/ the tool outputs compare-baselines.php reads (items 2, 6) + * composer.lock.before with composer.lock and composer.json: check-needed-moves.php (item 3) + * checklist.json rows, wiring, verdicts, `test` rows and their files, `tests_waived` + * (items 4, 5, 7, 8) * release-steps.md the release-steps log (item 10): a row is met when its status starts * with `verified`, `not needed` or `covered` - * - * dod.json: + * dod.json what no file shows (items 1, 3, 9, 10, and waivers for 2 and 6): * { * "scope": {"feature": "...", "install_release": "...", "update_mode": "-w", "branch": "...", * "confirmed": ""}, - * "baselines": {"phpstan": "valid", "sniffer": "valid", "tests": "valid", - * "backoffice-crawl": "valid", "storage-counts": "valid"}, - * "accepted_moves": {"spryker/": ""}, - * "checks": {"phpstan": "pass", "sniffer": "pass", "tests": "pass", "backoffice-crawl": "pass", - * "storage-counts": "pass", "frontend-build": "pass"}, + * "accepted_moves": {"spryker/": ""}, + * "data_files": ["data/import/..."], * "authored_content": [{"file": "...", "what": "...", "approved": ""}], - * "release_steps_accepted": "" + * "release_steps_accepted": "", + * "waived": {"baseline:backoffice-crawl": "", "check:frontend-build": "..."} * } - * A baseline is `valid`; a check is `pass`. Anything else is unmet, except `waived: `. `blocked: ` records a blocker, and a blocker is unmet. * * Exit codes: 0 DONE; 1 NOT DONE (each unmet item listed); 2 usage or unreadable state. */ @@ -43,9 +39,9 @@ require_once __DIR__ . '/check-checklist.php'; require_once __DIR__ . '/check-lock-diff.php'; require_once __DIR__ . '/check-feature-installed.php'; - -const DOD_BASELINES = ['phpstan', 'sniffer', 'tests', 'backoffice-crawl', 'storage-counts']; -const DOD_CHECKS = ['phpstan', 'sniffer', 'tests', 'backoffice-crawl', 'storage-counts', 'frontend-build']; +require_once __DIR__ . '/check-needed-moves.php'; +require_once __DIR__ . '/compare-baselines.php'; +require_once __DIR__ . '/check-data-manifests.php'; const DOD_ITEMS = [ 1 => 'the developer confirmed the scope', @@ -56,27 +52,19 @@ 6 => 'no regression against the baselines, and the frontend builds pass', 7 => 'every verification passed', 8 => 'passing tests cover the feature', - 9 => 'every text the agent wrote is approved', + 9 => 'every data file reaches an environment, and every text the agent wrote is approved', 10 => 'the release steps are proven', ]; -function dod_waived(string $value): bool -{ - return (bool)preg_match('/^waived:\s*\S/', $value); -} - /** - * @return list unmet entries of a baselines or checks map + * @return list unmet reasons of a measured group, minus the ones the developer waived */ -function dod_unmet_map(array $map, array $required, string $passValue): array +function dod_unwaived(array $measured, array $waived, string $prefix): array { $unmet = []; - foreach ($required as $name) { - $value = trim((string)($map[$name] ?? '')); - if ($value === '') { - $unmet[] = "$name: not recorded"; - } elseif ($value !== $passValue && !dod_waived($value)) { - $unmet[] = "$name: $value"; + foreach ($measured as $name => $problem) { + if ($problem !== null && trim((string)($waived["$prefix:$name"] ?? '')) === '') { + $unmet[] = "$name: $problem"; } } @@ -84,7 +72,7 @@ function dod_unmet_map(array $map, array $required, string $passValue): array } /** - * @return list release-steps log rows whose status is not verified or not needed + * @return list release-steps log rows whose status is not verified, not needed or covered */ function dod_unproven_release_steps(string $file): array { @@ -121,6 +109,7 @@ function dod_evaluate(string $root, string $stateDir): array $checklist = fi_load_checklist($stateDir . '/checklist.json'); $dod = json_decode((string)@file_get_contents($stateDir . '/dod.json'), true); $dod = is_array($dod) ? $dod : []; + $waived = (array)($dod['waived'] ?? []); $result = array_fill_keys(array_keys(DOD_ITEMS), []); $scope = $dod['scope'] ?? []; @@ -130,37 +119,41 @@ function dod_evaluate(string $root, string $stateDir): array } } - $result[2] = dod_unmet_map($dod['baselines'] ?? [], DOD_BASELINES, 'valid'); + $measured = cb_evaluate($stateDir); + $result[2] = dod_unwaived($measured['baselines'], $waived, 'baseline'); + $result[6] = dod_unwaived($measured['checks'], $waived, 'check'); $before = $stateDir . '/composer.lock.before'; - if ($checklist === null || !is_file($before) || !is_file($root . '/composer.lock')) { - $result[3][] = 'cannot compare: checklist.json, composer.lock.before or composer.lock is missing'; + if (!is_file($before) || !is_file($root . '/composer.lock')) { + $result[3][] = 'cannot compare: composer.lock.before or composer.lock is missing'; } else { - $after = fi_lock_packages($root . '/composer.lock'); - $features = cld_features_from_checklist($checklist); - $outside = array_diff_key(cld_moved(fi_lock_packages($before), $after), cld_tree($after, $features)); - foreach ($outside as $package => $versions) { - if (trim((string)($dod['accepted_moves'][$package] ?? '')) === '') { - $result[3][] = sprintf('%s %s -> %s moved outside the feature tree with no reason', $package, $versions['before'] ?? '(new)', $versions['after'] ?? '(removed)'); - } - } $composerJson = (array)json_decode((string)@file_get_contents($root . '/composer.json'), true); + $classified = cnm_classify(fi_lock_packages($before), fi_lock_packages($root . '/composer.lock'), $composerJson); + foreach (cnm_open($classified, (array)($dod['accepted_moves'] ?? [])) as $package => $move) { + $result[3][] = sprintf('%s %s -> %s: %s, and no reason recorded', $package, $move['before'], $move['after'], $move['verdict']); + } + $features = $checklist !== null ? array_map('strtolower', cld_features_from_checklist($checklist)) : []; foreach (cld_dev_constraints($composerJson) as $package => $constraint) { - if (in_array(strtolower($package), array_map('strtolower', $features), true)) { + if (in_array(strtolower($package), $features, true)) { $result[3][] = "$package has the dev constraint $constraint"; } } } if ($checklist === null) { - $result[4][] = 'checklist.json is missing or unreadable'; - $result[7][] = 'checklist.json is missing or unreadable'; - $result[8][] = 'checklist.json is missing or unreadable'; + foreach ([4, 5, 7, 8] as $item) { + $result[$item][] = 'checklist.json is missing or unreadable'; + } } else { $byItem = cc_problems_by_item($checklist, 'report'); $result[4] = $byItem['rows']; $result[7] = $byItem['verification']; $result[8] = $byItem['tests']; + foreach ($checklist['rows'] as $row) { + if (($row['kind'] ?? '') === 'test' && ($row['status'] ?? '') === 'done' && !is_file($root . '/' . ltrim((string)($row['target'] ?? ''), '/'))) { + $result[8][] = sprintf('%s: the test file %s does not exist', $row['id'] ?? '?', $row['target'] ?? ''); + } + } $namespaces = cfi_project_namespaces($root); $providers = cfi_dependency_providers($root, $namespaces); @@ -174,9 +167,20 @@ function dod_evaluate(string $root, string $stateDir): array $result[5][] = sprintf('%s %s: %s', $row['id'] ?? '?', $row['target'] ?? '', $state['state']); } } - } - $result[6] = dod_unmet_map($dod['checks'] ?? [], DOD_CHECKS, 'pass'); + $dataRowsDone = array_filter($checklist['rows'], static fn (array $row): bool => in_array($row['kind'] ?? '', FI_DATA_KINDS, true) && ($row['status'] ?? '') === 'done'); + $dataFiles = array_values(array_filter((array)($dod['data_files'] ?? []), 'is_string')); + if ($dataRowsDone !== [] && $dataFiles === []) { + $result[9][] = 'data rows are done, but dod.json data_files does not list the files the hand-off wrote'; + } + if ($dataFiles !== []) { + foreach (cdm_evaluate($root, $dataFiles) as $file => $importedBy) { + if ($importedBy === []) { + $result[9][] = "$file is imported by no manifest a recipe runs"; + } + } + } + } foreach ($dod['authored_content'] ?? [] as $content) { if (trim((string)($content['approved'] ?? '')) === '') { diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/check-needed-moves.php b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/check-needed-moves.php new file mode 100644 index 0000000..6ba4e1b --- /dev/null +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/check-needed-moves.php @@ -0,0 +1,149 @@ + [--after composer.lock] + * [--composer composer.json] [--accepted ] + * + * --accepted moves listed with a reason in dod.json `accepted_moves` are not reported as open + * + * Per moved package: `needed` (a requirer or a conflict rules out the old version, named), + * `not needed` (the old version satisfies every requirer), or `unknown` (a constraint it cannot + * read, for example a branch). New and removed packages are listed, not judged. + * + * Exit codes: 0 every move is needed or accepted; 1 a move is not needed or unknown, and not + * accepted; 2 usage or unreadable input. + */ + +declare(strict_types=1); + +require_once __DIR__ . '/lib.php'; + +/** + * @return array}> + */ +function cnm_classify(array $before, array $after, array $composerJson): array +{ + $result = []; + $names = array_unique(array_merge(array_keys($before), array_keys($after))); + sort($names); + foreach ($names as $name) { + $old = $before[$name]['version'] ?? null; + $new = $after[$name]['version'] ?? null; + if ($old === $new) { + continue; + } + if ($old === null || $new === null) { + $result[$name] = ['before' => $old, 'after' => $new, 'verdict' => $old === null ? 'new' : 'removed', 'why' => []]; + continue; + } + $blockers = []; + $unknown = []; + $requirers = []; + foreach ($after as $requirer => $package) { + foreach (['require' => 'requires', 'conflict' => 'conflicts with'] as $section => $relation) { + foreach ($package[$section] ?? [] as $dependency => $constraint) { + if (strtolower($dependency) === $name) { + $requirers[] = [$requirer, $relation, (string)$constraint]; + } + } + } + } + foreach (['require', 'require-dev'] as $section) { + foreach ($composerJson[$section] ?? [] as $dependency => $constraint) { + if (strtolower((string)$dependency) === $name) { + $requirers[] = ['composer.json', 'requires', (string)$constraint]; + } + } + } + foreach ($requirers as [$requirer, $relation, $constraint]) { + $satisfied = fi_version_satisfies($old, $constraint); + if ($satisfied === null) { + $unknown[] = "$requirer $relation $constraint"; + } elseif ($relation === 'requires' && $satisfied === false) { + $blockers[] = "$requirer requires $constraint"; + } elseif ($relation === 'conflicts with' && $satisfied === true) { + $blockers[] = "$requirer conflicts with $constraint"; + } + } + $result[$name] = match (true) { + $blockers !== [] => ['before' => $old, 'after' => $new, 'verdict' => 'needed', 'why' => $blockers], + $unknown !== [] => ['before' => $old, 'after' => $new, 'verdict' => 'unknown', 'why' => $unknown], + default => ['before' => $old, 'after' => $new, 'verdict' => 'not needed', 'why' => ["$old satisfies every requirer"]], + }; + } + + return $result; +} + +/** + * @return array}> the + * not-needed and unknown moves that have no reason in `accepted_moves` + */ +function cnm_open(array $classified, array $acceptedMoves): array +{ + return array_filter( + $classified, + static fn (array $move, string $name): bool => in_array($move['verdict'], ['not needed', 'unknown'], true) + && trim((string)($acceptedMoves[$name] ?? '')) === '', + ARRAY_FILTER_USE_BOTH + ); +} + +function cnm_main(array $argv): int +{ + $root = fi_project_root(); + $options = ['before' => null, 'after' => $root . '/composer.lock', 'composer' => $root . '/composer.json', 'accepted' => null]; + for ($i = 1; $i < count($argv); $i++) { + $key = substr((string)$argv[$i], 2); + if (!array_key_exists($key, $options) || !str_starts_with((string)$argv[$i], '--')) { + fwrite(STDERR, "unknown argument {$argv[$i]}\n"); + + return 2; + } + $options[$key] = $argv[++$i] ?? null; + } + if ($options['before'] === null || !is_file($options['before']) || !is_file((string)$options['after'])) { + fwrite(STDERR, "usage: php check-needed-moves.php --before [--after composer.lock] [--composer composer.json] [--accepted ]\n"); + + return 2; + } + $composerJson = (array)json_decode((string)@file_get_contents((string)$options['composer']), true); + $classified = cnm_classify(fi_lock_packages($options['before']), fi_lock_packages((string)$options['after']), $composerJson); + $dod = $options['accepted'] !== null ? (array)json_decode((string)@file_get_contents($options['accepted']), true) : []; + $open = cnm_open($classified, (array)($dod['accepted_moves'] ?? [])); + + $counts = array_count_values(array_column($classified, 'verdict')); + fwrite(STDOUT, sprintf("%d package(s) moved: %s.\n", count($classified), implode(', ', array_map(static fn ($v, $n) => "$n $v", array_keys($counts), $counts)))); + foreach (['not needed', 'unknown', 'needed', 'new', 'removed'] as $verdict) { + foreach ($classified as $name => $move) { + if ($move['verdict'] !== $verdict) { + continue; + } + $accepted = trim((string)($dod['accepted_moves'][$name] ?? '')); + fwrite(STDOUT, sprintf(" %-11s %-50s %s -> %s%s\n", strtoupper($verdict), $name, $move['before'] ?? '(none)', $move['after'] ?? '(none)', $accepted !== '' ? ' accepted: ' . $accepted : '')); + if ($move['why'] !== [] && $verdict !== 'not needed') { + fwrite(STDOUT, ' ' . implode('; ', array_slice($move['why'], 0, 3)) . "\n"); + } + } + } + if ($open !== []) { + fwrite(STDOUT, sprintf("\n%d move(s) the feature does not need: move each back (composer require :), or record the developer's reason in dod.json accepted_moves.\n", count($open))); + } + + return $open === [] ? 0 : 1; +} + +if (realpath($argv[0] ?? '') === __FILE__) { + exit(cnm_main($argv)); +} diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/compare-baselines.php b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/compare-baselines.php new file mode 100644 index 0000000..f610a14 --- /dev/null +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/compare-baselines.php @@ -0,0 +1,207 @@ +`; code 0 passes. + * A build the project does not have: no file. + * + * Usage (from the project root): + * php compare-baselines.php + * + * Exit codes: 0 every baseline is valid and nothing regressed; 1 a baseline is not valid or a check + * regressed (each named); 2 usage. + */ + +declare(strict_types=1); + +require_once __DIR__ . '/lib.php'; +require_once __DIR__ . '/../../spryker-upgrade/scripts/check-baselines.php'; + +const CB_BASELINES = [ + 'phpstan' => 'phpstan-baseline-run.txt', + 'sniffer' => 'sniff-baseline.txt', + 'tests' => 'codecept-baseline.txt', + 'backoffice-crawl' => 'backoffice-smoke-baseline.json', + 'storage-counts' => 'storage-search-counts-before.json', +]; + +const CB_BUILDS = ['yves-build.txt', 'zed-build.txt', 'mp-build.txt']; + +function cb_text(string $file): ?string +{ + return is_file($file) ? bl_plain_text((string)file_get_contents($file)) : null; +} + +function cb_phpstan_errors(string $text): ?int +{ + if (preg_match('/Found (\d+) (?:\S+ )?errors?/', $text, $m)) { + return (int)$m[1]; + } + + return preg_match('/\[OK\] No errors/', $text) ? 0 : null; +} + +function cb_sniff_findings(string $text): ?int +{ + if (preg_match('/A TOTAL OF (\d+) ERRORS? AND (\d+) WARNINGS?/', $text, $m)) { + return (int)$m[1] + (int)$m[2]; + } + if (preg_match_all('/FOUND (\d+) ERRORS?(?: AND (\d+) WARNINGS?)?/', $text, $m, PREG_SET_ORDER)) { + return array_sum(array_map(static fn (array $hit): int => (int)$hit[1] + (int)($hit[2] ?? 0), $m)); + } + + return bl_content_problem('sniff-baseline.txt', $text) === null ? 0 : null; +} + +/** + * @return array{total: ?int, failing: list} + */ +function cb_codecept(string $text): array +{ + $failing = []; + if (preg_match_all('/^\s*\d+\) (\S.*?)\s*$/m', $text, $m)) { + $failing = array_values(array_unique(array_map('trim', $m[1]))); + } + $total = null; + if (preg_match_all('/Tests: \d+, Assertions: \d+(?:, Errors: (\d+))?(?:, Failures: (\d+))?/', $text, $m, PREG_SET_ORDER)) { + $total = array_sum(array_map(static fn (array $hit): int => (int)($hit[1] ?? 0) + (int)($hit[2] ?? 0), $m)); + } elseif (preg_match('/\bOK \(\d+ tests?/', $text)) { + $total = 0; + } + + return ['total' => $total, 'failing' => $failing]; +} + +/** + * @return array{baselines: array, checks: array} each name → null + * when met, else the reason + */ +function cb_evaluate(string $stateDir): array +{ + $baselineDir = $stateDir . '/baseline'; + $afterDir = $stateDir . '/after'; + $baselines = []; + foreach (CB_BASELINES as $name => $file) { + $contents = @file_get_contents($baselineDir . '/' . $file); + $baselines[$name] = $contents === false ? "missing baseline/$file" : bl_content_problem($file, $contents); + } + + $checks = []; + $before = cb_text($baselineDir . '/phpstan-baseline-run.txt'); + $after = cb_text($afterDir . '/phpstan-after.txt'); + $checks['phpstan'] = match (true) { + $after === null => 'missing after/phpstan-after.txt', + cb_phpstan_errors($after) === null => 'after/phpstan-after.txt has no PHPStan result line', + $before === null || cb_phpstan_errors($before) === null => 'no valid baseline to compare with', + cb_phpstan_errors($after) > cb_phpstan_errors($before) => sprintf('errors grew from %d to %d', cb_phpstan_errors($before), cb_phpstan_errors($after)), + default => null, + }; + + $before = cb_text($baselineDir . '/sniff-baseline.txt'); + $after = cb_text($afterDir . '/sniff-after.txt'); + $checks['sniffer'] = match (true) { + $after === null => 'missing after/sniff-after.txt', + cb_sniff_findings($after) === null => 'after/sniff-after.txt has no sniffer result', + $before === null || cb_sniff_findings($before) === null => 'no valid baseline to compare with', + cb_sniff_findings($after) > cb_sniff_findings($before) => sprintf('findings grew from %d to %d', cb_sniff_findings($before), cb_sniff_findings($after)), + default => null, + }; + + $before = cb_text($baselineDir . '/codecept-baseline.txt'); + $after = cb_text($afterDir . '/codecept-after.txt'); + if ($after === null) { + $checks['tests'] = 'missing after/codecept-after.txt'; + } elseif ($before === null) { + $checks['tests'] = 'no valid baseline to compare with'; + } else { + $old = cb_codecept($before); + $new = cb_codecept($after); + $newFailures = array_values(array_diff($new['failing'], $old['failing'])); + $checks['tests'] = match (true) { + $new['total'] === null => 'after/codecept-after.txt has no summary line', + $newFailures !== [] => sprintf('%d test(s) fail that passed before: %s', count($newFailures), implode('; ', array_slice($newFailures, 0, 3))), + $new['failing'] === [] && $old['total'] !== null && $new['total'] > $old['total'] => sprintf('failures grew from %d to %d', $old['total'], $new['total']), + default => null, + }; + } + + $report = json_decode((string)@file_get_contents($baselineDir . '/backoffice-smoke-report.json'), true); + if (!is_array($report) || !is_array($report['results'] ?? null)) { + $checks['backoffice-crawl'] = 'missing baseline/backoffice-smoke-report.json (run backoffice-smoke.php again after the install)'; + } else { + $new = array_filter($report['results'], static fn (array $r): bool => ($r['problem'] ?? null) !== null && empty($r['inBaseline'])); + $checks['backoffice-crawl'] = $new === [] ? null : sprintf('%d page(s) or endpoint(s) fail that did not before: %s', count($new), implode('; ', array_slice(array_column($new, 'url'), 0, 3))); + } + + $report = json_decode((string)@file_get_contents($baselineDir . '/storage-search-counts-report.json'), true); + if (!is_array($report) || !isset($report['rows'])) { + $checks['storage-counts'] = 'missing baseline/storage-search-counts-report.json (snapshot after, then --compare before after)'; + } else { + $failing = array_filter((array)$report['rows'], static fn (array $r): bool => !empty($r['failing'])); + $checks['storage-counts'] = $failing === [] ? null : sprintf('%d table(s) lost rows: %s', count($failing), implode(', ', array_slice(array_column($failing, 'table'), 0, 3))); + } + + $builds = []; + foreach (CB_BUILDS as $file) { + $text = cb_text($afterDir . '/' . $file); + if ($text === null) { + continue; + } + if (!preg_match_all('/^exit (\d+)\s*$/m', $text, $m)) { + $builds[] = "after/$file does not end with `exit `"; + } elseif ((int)end($m[1]) !== 0) { + $builds[] = sprintf('%s failed (exit %d)', basename($file, '.txt'), (int)end($m[1])); + } + } + $hasBuild = array_filter(CB_BUILDS, static fn (string $file): bool => is_file($afterDir . '/' . $file)) !== []; + $checks['frontend-build'] = match (true) { + !$hasBuild => 'no build output in after/ (yves-build.txt, zed-build.txt, mp-build.txt)', + $builds !== [] => implode('; ', $builds), + default => null, + }; + + return ['baselines' => $baselines, 'checks' => $checks]; +} + +function cb_main(array $argv): int +{ + $stateDir = $argv[1] ?? null; + if ($stateDir === null || !is_dir($stateDir)) { + fwrite(STDERR, "usage: php compare-baselines.php \n"); + + return 2; + } + $result = cb_evaluate(rtrim($stateDir, '/')); + $problems = 0; + foreach (['baselines' => 'Baselines', 'checks' => 'After the install'] as $group => $title) { + fwrite(STDOUT, "$title:\n"); + foreach ($result[$group] as $name => $problem) { + $problems += $problem === null ? 0 : 1; + fwrite(STDOUT, sprintf(" %-5s %-17s %s\n", $problem === null ? 'ok' : 'FAIL', $name, $problem ?? '')); + } + } + + return $problems === 0 ? 0 : 1; +} + +if (realpath($argv[0] ?? '') === __FILE__) { + exit(cb_main($argv)); +} diff --git a/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/dump-state.php b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/dump-state.php new file mode 100644 index 0000000..eba3474 --- /dev/null +++ b/plugins/spryker-ai-dev-sdk/skills/spryker-feature-install/scripts/dump-state.php @@ -0,0 +1,233 @@ +] [--user ] [--password-env ] + * + * Connection: SPRYKER_DB_ENGINE (mysql|pgsql), SPRYKER_DB_HOST, SPRYKER_DB_PORT, SPRYKER_DB_DATABASE, + * SPRYKER_DB_USERNAME, SPRYKER_DB_PASSWORD as the Docker SDK sets them; SPRYKER_SEARCH_HOST and + * SPRYKER_SEARCH_PORT for the search engine (left out when not set). --dsn, --user and + * --password-env override the database settings. + * + * Exit: --dump 0 written, 2 usage or connection error. --compare 0 equal, 1 differences (listed), + * 2 usage. + */ + +declare(strict_types=1); + +const DS_SKIP_TABLES = '/^(propel_migration|spy_queue_process|spy_.*_lock|spy_oauth_(access|refresh)_token|spy_session.*|spy_event_behavior_entity_change|spy_.*_log|spy_customer_session|spy_.*_history_log)$/'; +const DS_SKIP_COLUMN = '/^(id_.*|fk_.*|.*_at|uuid|key|created|updated|reference)$/'; +const DS_SKIP_JSON_KEY = '/^(id|uuid|fk.*|id[A-Z_].*|.*Id|.*_id|.*At|.*_at|_timestamp|key)$/'; + +function ds_strip_json(mixed $value): mixed +{ + if (!is_array($value)) { + return $value; + } + $clean = []; + foreach ($value as $key => $item) { + if (is_string($key) && preg_match(DS_SKIP_JSON_KEY, $key)) { + continue; + } + $clean[$key] = ds_strip_json($item); + } + if (array_is_list($clean)) { + $encoded = array_map(static fn ($item) => json_encode($item), $clean); + sort($encoded); + + return $encoded; + } + ksort($clean); + + return $clean; +} + +/** + * The row as compared: identifier and timestamp columns removed, JSON values normalised the same way. + */ +function ds_normalise_row(array $row): string +{ + $clean = []; + foreach ($row as $column => $value) { + if (preg_match(DS_SKIP_COLUMN, (string)$column)) { + continue; + } + if (is_string($value) && $value !== '' && ($value[0] === '{' || $value[0] === '[')) { + $decoded = json_decode($value, true); + if (is_array($decoded)) { + $value = json_encode(ds_strip_json($decoded)); + } + } + $clean[$column] = $value; + } + ksort($clean); + + return json_encode($clean); +} + +/** + * @return array + */ +function ds_dump_tables(PDO $pdo, string $engine): array +{ + $tables = match ($engine) { + 'sqlite' => $pdo->query("SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%'")->fetchAll(PDO::FETCH_COLUMN), + 'pgsql' => $pdo->query("SELECT table_name FROM information_schema.tables WHERE table_schema = 'public' AND table_type = 'BASE TABLE'")->fetchAll(PDO::FETCH_COLUMN), + default => $pdo->query('SHOW TABLES')->fetchAll(PDO::FETCH_COLUMN), + }; + sort($tables); + $result = []; + foreach ($tables as $table) { + if (preg_match(DS_SKIP_TABLES, (string)$table)) { + continue; + } + $quoted = $engine === 'mysql' ? '`' . $table . '`' : '"' . $table . '"'; + $hashes = []; + $statement = $pdo->query('SELECT * FROM ' . $quoted); + while (($row = $statement->fetch(PDO::FETCH_ASSOC)) !== false) { + $hashes[] = md5(ds_normalise_row($row)); + } + sort($hashes); + $result[(string)$table] = ['rows' => count($hashes), 'hash' => md5(implode('', $hashes))]; + } + + return $result; +} + +/** + * @return array index => document count; empty when no search engine is configured + */ +function ds_dump_search(array $env): array +{ + $host = $env['SPRYKER_SEARCH_HOST'] ?? ''; + if ($host === '' || !function_exists('curl_init')) { + return []; + } + $handle = curl_init(sprintf('http://%s:%s/_cat/indices?format=json', $host, $env['SPRYKER_SEARCH_PORT'] ?? '9200')); + curl_setopt_array($handle, [CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 20]); + $indices = json_decode((string)curl_exec($handle), true); + $counts = []; + foreach (is_array($indices) ? $indices : [] as $index) { + if (isset($index['index']) && !str_starts_with((string)$index['index'], '.')) { + $counts[(string)$index['index']] = (int)($index['docs.count'] ?? 0); + } + } + ksort($counts); + + return $counts; +} + +/** + * @return list one line per difference + */ +function ds_compare(array $a, array $b): array +{ + $differences = []; + $tables = array_unique(array_merge(array_keys($a['tables'] ?? []), array_keys($b['tables'] ?? []))); + sort($tables); + foreach ($tables as $table) { + $left = $a['tables'][$table] ?? null; + $right = $b['tables'][$table] ?? null; + if ($left === null || $right === null) { + $differences[] = sprintf('table %s exists only in %s', $table, $left === null ? 'the second dump' : 'the first dump'); + } elseif ($left['rows'] !== $right['rows']) { + $differences[] = sprintf('table %s: %d rows vs %d rows', $table, $left['rows'], $right['rows']); + } elseif ($left['hash'] !== $right['hash']) { + $differences[] = sprintf('table %s: same row count (%d), different content', $table, $left['rows']); + } + } + $indices = array_unique(array_merge(array_keys($a['search'] ?? []), array_keys($b['search'] ?? []))); + sort($indices); + foreach ($indices as $index) { + $left = $a['search'][$index] ?? null; + $right = $b['search'][$index] ?? null; + if ($left !== $right) { + $differences[] = sprintf('search index %s: %s vs %s documents', $index, $left ?? 'none', $right ?? 'none'); + } + } + + return $differences; +} + +function ds_file(string $labelOrPath): string +{ + return is_file($labelOrPath) ? $labelOrPath : __DIR__ . '/state-' . $labelOrPath . '.json'; +} + +function ds_main(array $argv): int +{ + $usage = "usage: php dump-state.php --dump