From c09cb497e95fd3a5105e906e6fc4c4145ce75d5b Mon Sep 17 00:00:00 2001 From: Konstantin Konovalov Date: Sun, 1 Nov 2026 17:07:27 +0400 Subject: [PATCH 1/9] Docs: keep the chat in English as well Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CLAUDE.md b/CLAUDE.md index f1f520a..4f0806d 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -21,7 +21,7 @@ The project includes frontend test tooling for the React admin interface: ## Documentation Language -All specs and planning artifacts are written in English — OpenSpec proposals, delta specs, design docs and task lists under `openspec/changes/`, PRDs, plans and analysis docs under `.claude/tasks/`, plus the changelog and README. This holds regardless of the language of the conversation that produced them: chat may be in Russian, the written artifact is English. +All specs and planning artifacts are written in English — OpenSpec proposals, delta specs, design docs and task lists under `openspec/changes/`, PRDs, plans and analysis docs under `.claude/tasks/`, plus the changelog and README. Chat is in English as well. ## Version Bump From 02356c8b10b95f695c8f731ff8cbfb5f1b7eb71e Mon Sep 17 00:00:00 2001 From: Konstantin Konovalov Date: Sun, 1 Nov 2026 17:07:27 +0400 Subject: [PATCH 2/9] OpenSpec: propose fix-woo-excluded-roles Co-Authored-By: Claude Opus 5.5 --- .../fix-woo-excluded-roles/.openspec.yaml | 2 + .../changes/fix-woo-excluded-roles/design.md | 146 ++++++++++++++++++ .../fix-woo-excluded-roles/proposal.md | 54 +++++++ .../specs/form-events/spec.md | 36 +++++ .../specs/woo-excluded-roles/spec.md | 107 +++++++++++++ .../changes/fix-woo-excluded-roles/tasks.md | 42 +++++ 6 files changed, 387 insertions(+) create mode 100644 openspec/changes/fix-woo-excluded-roles/.openspec.yaml create mode 100644 openspec/changes/fix-woo-excluded-roles/design.md create mode 100644 openspec/changes/fix-woo-excluded-roles/proposal.md create mode 100644 openspec/changes/fix-woo-excluded-roles/specs/form-events/spec.md create mode 100644 openspec/changes/fix-woo-excluded-roles/specs/woo-excluded-roles/spec.md create mode 100644 openspec/changes/fix-woo-excluded-roles/tasks.md diff --git a/openspec/changes/fix-woo-excluded-roles/.openspec.yaml b/openspec/changes/fix-woo-excluded-roles/.openspec.yaml new file mode 100644 index 0000000..25002a8 --- /dev/null +++ b/openspec/changes/fix-woo-excluded-roles/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-11-01 diff --git a/openspec/changes/fix-woo-excluded-roles/design.md b/openspec/changes/fix-woo-excluded-roles/design.md new file mode 100644 index 0000000..5bfd66f --- /dev/null +++ b/openspec/changes/fix-woo-excluded-roles/design.md @@ -0,0 +1,146 @@ +## Context + +See `proposal.md` for the motivation and `specs/` for the required behaviour. + +`pixelflow_current_user_has_excluded_role()` (`includes/helpers.php:303`) already gates the tracking +script (`pixelflow.php:288`), the held-events script (`pixelflow.php:333`) and form events +(`includes/forms/dispatcher.php:76`). The WooCommerce dispatcher never calls it. + +Every WooCommerce event goes through `PixelFlow_WooCommerce_Cart_Hooks::post_event()`: the two +AddToCart producers (`class-woocommerce-hooks.php:257`, `:440`), InitiateCheckout (`:683`), Purchase +(`:882`) and held replay (`trait-held-woo-events.php:134`). The only `/event` POST is reached from +it. `$this->options` already holds `pixelflow_general_options` +(`class-woocommerce-integration.php:64-66`). + +Purchase differs from the other two events. `pf_purchase_hook()` runs on `processing` and `completed` +in whatever request moved the order, including wp-admin, WP-CLI and gateway callbacks +(`class-woocommerce-hooks.php:104-110`). `pixelflow_request_owns_order()` (`includes/consent.php:440`) +decides whether that request is the buyer's and feeds the `allow_live` context flag. `_pf_purchase_sent` +is written only on a `sent` outcome. + +## Goals / Non-Goals + +**Goals:** + +- One gate that every live WooCommerce send passes through, matching the form events' behaviour: + no event, no blocked report, no hold. +- The settings page describes what the setting really does, including its limits. + +**Non-Goals:** + +- Detecting, warning about or removing tracking scripts added outside the plugin. The plugin cannot + control them; the settings text states the limit, and the site owner removes such a copy. +- Keeping excluded users' orders out of Purchase in every request (see Decision 2). +- A new blocked-report reason for excluded roles. `PIXELFLOW_BLOCKED_EVENT_REASONS` stays closed, as + in the form-events change. + +## Decisions + +### 1. Gate at the top of `post_event()` + +Insert the check after the context is read and before identity, consent and bot resolution: + +```php +if ( ! $this->flushing_held + && $allow_live + && pixelflow_current_user_has_excluded_role(is_array($this->options) ? $this->options : []) +) { + // Log 'USER ROLE IS EXCLUDED FROM TRACKING' through debug_log(), then: + return 'skipped'; +} +``` + +The log wording matches the form dispatcher. `debug_log()` already honours the debug switch. + +*Alternative rejected:* a check in each producer. That is four places to keep in step, and it would +need a separate exemption for the replay path. + +### 2. Purchase follows the current request, not the order's customer + +The maintainer chose this over checking the role of the order's customer. Skipping only when the +request is the buyer's (`allow_live`) needs no Purchase-specific code and keeps one rule for all +WooCommerce events. A real customer's order completed by excluded staff is still sent. + +*Accepted cost:* an excluded user's test order is skipped in their own request, but `_pf_purchase_sent` +stays unset, so a later gateway webhook, automation or other staff status change sends it. The spec +states this as required behaviour and the settings page states it to site owners. + +*Alternatives rejected by the maintainer:* checking the order's customer (closes the leak, but does +not count a staff member's genuine personal purchase); leaving Purchase untouched (admins' test orders +always count). + +### 3. Reuse the existing `skipped` outcome + +`skipped` already means "nothing was sent or reported". `send_settled_the_event()` returns false for +it, so AddToCart and InitiateCheckout release their dedupe keys +(`class-woocommerce-hooks.php:261`, `:444`, `:690`), and Purchase releases its delivery claim without +writing the sent marker (`:891`). A user who signs out and shops as a guest in the same session is therefore +not silenced by an earlier skip. + +Steps in `pf_purchase_hook()` before `post_event()`, namely the consent sync and the first-purchase +record, still run. They only write order data, which is correct for an order that may be delivered +later. + +### 4. Held replay stays exempt + +`flushing_held` bypasses the gate. Guests are never excluded (`includes/helpers.php:298`), so a held +recipe was captured for a guest, and the replay may run on a later request by someone else. The +existing `post_event()` code already treats replay as not belonging to the current request +(`class-woocommerce-hooks.php:2119-2120`). The gate returning early does not stop replay on page +views, because `resolve_held_events_on_page_view()` runs separately on `wp`. + +### 5. Settings text + +Title: `Exclude Tracking for User Roles`. + +Description, always shown: + +> Select user roles that should not be tracked while signed in. The tracking script is not loaded for +> them, and their form and WooCommerce events are not sent. Useful for excluding administrators, +> editors, or other internal users. + +Note, shown when at least one role is selected (replaces the current note): + +> **Note:** A tracking script added to the site by hand is not affected by this setting. + +Note, keeping its `excluded-roles-woo-note` test id and its display condition (WooCommerce active and +tracking on): + +> A Purchase can still be sent when a payment gateway, automation or another staff member changes the +> order's status, because that request does not belong to the excluded user. + +FAQ answer in `readme.txt:163` and `README.md:426`: + +> Yes. Under Advanced Settings, choose any user roles (Administrator, Editor, Shop manager and more) +> that should not be tracked. The tracking script is not loaded for them, and their form and +> WooCommerce events are not sent while they are signed in. A Purchase can still be sent when a +> payment gateway, automation or another staff member changes the order's status, and a tracking +> script added to the site by hand is not affected. + +### 6. Move the logged-in user stubs into the shared test bootstrap + +`is_user_logged_in()` and `wp_get_current_user()` exist only in `tests/bootstrap-forms.php:123-131`, +which loads `bootstrap-wp-stubs.php` first and declares them unguarded. After the gate, WooCommerce +tests that reach `post_event()` call them, so they would fatal. Adding a copy to the shared bootstrap +would redeclare them in the forms tests. Therefore the stubs move to `bootstrap-wp-stubs.php`, +defaulting to signed out through `$GLOBALS['__pf_user'] ?? null`, and leave `bootstrap-forms.php`. + +## Risks / Trade-offs + +- [Event counts drop on sites that already exclude roles] → Intended; the changelog line says so. +- [An excluded user's test order can still send Purchase] → Accepted (Decision 2), stated in the spec, + settings page and FAQ, and covered by a test. +- [The gate depends on WordPress knowing the user during the send] → Observed: on a live store, a + signed-in administrator's AddToCart and InitiateCheckout carried identity built from the current + user, so that storefront path resolves the user. Not observed: Store API requests from block cart + and checkout, where WordPress can drop cookie authentication. If the user is unknown there, the + helper returns false and the event is sent as today, so it fails open. The live scenario checks the + path the test site uses; any path found to fail open is reported before this change is called done. +- [Site owners still see page views from a hand-added script after updating] → The settings text states + the limit. The owner of the reporting site is told separately to remove their copy; that is not part + of this change. + +## Migration Plan + +No data migration. The behaviour changes when the plugin updates. Rollback is reverting to the +previous release. diff --git a/openspec/changes/fix-woo-excluded-roles/proposal.md b/openspec/changes/fix-woo-excluded-roles/proposal.md new file mode 100644 index 0000000..931f9c6 --- /dev/null +++ b/openspec/changes/fix-woo-excluded-roles/proposal.md @@ -0,0 +1,54 @@ +## Why + +A site owner excluded the Administrator role from tracking, browsed their store while signed in as +an administrator, and still saw AddToCart and InitiateCheckout arrive. The plugin's server-side +WooCommerce dispatcher never reads the excluded-roles setting: release 1.2.0 recorded this as a +known gap, stated it on the settings page and left the alignment to a separate change. No such +change exists yet, and this is it. + +The same report's browser page views have a different cause: the site carries a second copy of the +tracking script, added by hand, which no plugin setting can control. The plugin cannot fix that, but +the settings page can stop implying otherwise. + +## What Changes + +- Live AddToCart and InitiateCheckout are not sent while a signed-in user holds an excluded role: + no event, no blocked report, no hold. +- Purchase is not sent when the request that would send it belongs to the buyer and that buyer is + signed in with an excluded role. +- **Known limit, accepted:** the check looks at the current request, not at the order. If a later + request that is not the buyer's moves the same order to a purchasing status (a payment gateway + webhook, automation, another staff member), the Purchase is sent. An excluded staff member + completing a real customer's order also still sends it. +- Replaying events held before the user signed in stays independent of the current request's role. +- The settings control is renamed from `Exclude Script for User Roles` to + `Exclude Tracking for User Roles`. Its text states what is excluded and both limits: the Purchase + limit above, and that a tracking script added to the site by hand is not affected. +- The FAQ answer in `readme.txt` and `README.md` is updated to match. +- Release 1.2.3, as agreed with the maintainer. +- Sites that already exclude roles will see fewer WooCommerce events after updating. That is the + intended result, and the changelog line says so. + +## Capabilities + +### New Capabilities + +- `woo-excluded-roles`: how the excluded-roles setting applies to the plugin's browser script and to + server-side WooCommerce events. + +### Modified Capabilities + +- `form-events`: the requirement `The excluded-roles setting states where it does not apply` + demands a note saying WooCommerce events ignore the setting. That note becomes false, so the + requirement now names the new title and the two remaining limits. + +## Impact + +- `includes/woo/hooks/class-woocommerce-hooks.php`: the role gate in `post_event()`. +- `app/source/src/features/settings/components/AdvancedSettings.tsx` and its test: title and text. +- `tests/`: a new `test-woo-excluded-roles.php`; the logged-in user stubs move into the shared + bootstrap, because every WooCommerce test that reaches `post_event()` now needs them. +- `e2e/live/tests/`: a new scenario for a signed-in excluded administrator on the storefront. +- `readme.txt`, `README.md`, `pixelflow.php`: FAQ, changelog and version. +- `docs/test-scenarios.html`: new rows and the record of the full run. +- No API, consent or blocked-report contract changes. diff --git a/openspec/changes/fix-woo-excluded-roles/specs/form-events/spec.md b/openspec/changes/fix-woo-excluded-roles/specs/form-events/spec.md new file mode 100644 index 0000000..f43eef2 --- /dev/null +++ b/openspec/changes/fix-woo-excluded-roles/specs/form-events/spec.md @@ -0,0 +1,36 @@ +## MODIFIED Requirements + +### Requirement: The excluded-roles setting states where it does not apply + +The settings page SHALL title the control `Exclude Tracking for User Roles` and SHALL state that, for +a selected role, the plugin's tracking script is not loaded and form and WooCommerce events are not +sent while such a user is signed in. Once at least one role is selected, the page SHALL state that a +tracking script added to the site by hand is not affected by the setting. When WooCommerce tracking +is on, the page SHALL also state that a Purchase can still be sent when a request other than the +excluded user's own, such as a payment gateway webhook or another staff member, changes the order's +status; that statement SHALL NOT be shown when WooCommerce tracking is off, since such a site has no +such exception. These statements SHALL NOT change what any event sends. + +#### Scenario: The setting states what it excludes + +- **WHEN** the settings page is viewed +- **THEN** the control is titled `Exclude Tracking for User Roles` and says that the tracking script + is not loaded and that form and WooCommerce events are not sent for the selected roles + +#### Scenario: The hand-added script limit is stated + +- **WHEN** the settings page is viewed with at least one role selected +- **THEN** the page states that a tracking script added to the site by hand is not affected + +#### Scenario: The limitation is stated on a store + +- **WHEN** the settings page is viewed on a site where WooCommerce is active and + WooCommerce tracking is on +- **THEN** the control carries a note that a Purchase can still be sent when a request other than the + excluded user's own changes the order's status + +#### Scenario: The limitation is not stated without WooCommerce tracking + +- **WHEN** the settings page is viewed on a site with no WooCommerce, or with + WooCommerce tracking off +- **THEN** no such note is shown diff --git a/openspec/changes/fix-woo-excluded-roles/specs/woo-excluded-roles/spec.md b/openspec/changes/fix-woo-excluded-roles/specs/woo-excluded-roles/spec.md new file mode 100644 index 0000000..f7bb273 --- /dev/null +++ b/openspec/changes/fix-woo-excluded-roles/specs/woo-excluded-roles/spec.md @@ -0,0 +1,107 @@ +## Purpose + +Defines how the excluded-roles setting applies to the plugin's browser script and to its server-side +WooCommerce events, including where the setting deliberately stops applying. + +## ADDED Requirements + +### Requirement: The plugin's browser script is not loaded for an excluded role + +The plugin SHALL NOT output its tracking script or its held-events script on a storefront page +requested by a signed-in user whose role the site has excluded from tracking. A guest SHALL never be +treated as excluded. This requirement covers only scripts the plugin outputs itself. + +#### Scenario: Excluded administrator opens a storefront page + +- **WHEN** a signed-in user whose role is excluded opens a storefront page +- **THEN** the page contains neither the plugin's tracking script nor its held-events script + +#### Scenario: Guest opens a storefront page + +- **WHEN** a visitor who is not signed in opens a storefront page on a site that excludes a role +- **THEN** the page contains the plugin's tracking script + +#### Scenario: A script added by hand stays on the page + +- **WHEN** a tracking script has been added to the site outside the plugin and a signed-in user + whose role is excluded opens a storefront page +- **THEN** the plugin does not remove that script, and the settings page has stated this limit + +### Requirement: Live storefront events are not sent for an excluded role + +The plugin SHALL NOT send an AddToCart or InitiateCheckout event from a request made by a signed-in +user whose role the site has excluded from tracking. Such a request SHALL produce no event, no +blocked report and no held event, whatever the consent state. While WooCommerce debug logging is on, +the debug log SHALL record that the event was skipped because the user's role is excluded. + +#### Scenario: Excluded administrator adds a product to the cart + +- **WHEN** a signed-in user whose role is excluded adds a product to the cart +- **THEN** no AddToCart event and no blocked report are sent + +#### Scenario: Excluded administrator opens the checkout + +- **WHEN** a signed-in user whose role is excluded opens the checkout with items in the cart +- **THEN** no InitiateCheckout event and no blocked report are sent + +#### Scenario: Excluded role with an unanswered consent banner + +- **WHEN** a signed-in user whose role is excluded adds a product to the cart while the consent + banner is unanswered +- **THEN** nothing is held, and no event is sent later for that action + +#### Scenario: Skip is visible in the debug log + +- **WHEN** WooCommerce debug logging is on and an event is skipped because the user's role is + excluded +- **THEN** the debug log records the skip with that reason + +#### Scenario: A role that is not excluded still sends + +- **WHEN** a signed-in user whose role is not excluded adds a product to the cart on a site that + excludes another role +- **THEN** the AddToCart event is sent as usual + +#### Scenario: A guest still sends + +- **WHEN** a visitor who is not signed in adds a product to the cart on a site that excludes a role +- **THEN** the AddToCart event is sent as usual + +### Requirement: Purchase is not sent from an excluded buyer's own request + +The plugin SHALL NOT send a Purchase event from a request that belongs to the order's buyer while +that request is made by a signed-in user whose role is excluded, and SHALL send no blocked report +for it. The setting SHALL be evaluated against the current request only, not against the order's +customer, and skipping SHALL NOT mark the order as delivered. A request that does not belong to the +buyer SHALL NOT be affected by the setting, so a Purchase for such an order is sent when a later +request of that kind moves it to a purchasing status. + +#### Scenario: Excluded administrator completes their own checkout + +- **WHEN** a signed-in user whose role is excluded places an order and the status change happens in + that user's own request +- **THEN** no Purchase event and no blocked report are sent + +#### Scenario: Excluded staff member completes a real customer's order + +- **WHEN** a signed-in staff member whose role is excluded moves another customer's order to a + purchasing status in wp-admin +- **THEN** the Purchase event for that order is sent + +#### Scenario: A later webhook moves an excluded buyer's skipped order + +- **WHEN** a Purchase was skipped for an excluded buyer's order, and a payment gateway webhook or + other request that is not the buyer's later moves that order to a purchasing status +- **THEN** the Purchase event for that order is sent + +### Requirement: Held events are replayed whatever the current request's role + +The plugin SHALL NOT apply the excluded-roles setting when it replays events held earlier in the +visit, because the replaying request may belong to a different identity than the action that was +held. + +#### Scenario: Replay on a request by an excluded user + +- **WHEN** events held earlier are replayed during a request made by a signed-in user whose role is + excluded +- **THEN** the held events are sent diff --git a/openspec/changes/fix-woo-excluded-roles/tasks.md b/openspec/changes/fix-woo-excluded-roles/tasks.md new file mode 100644 index 0000000..d0e1575 --- /dev/null +++ b/openspec/changes/fix-woo-excluded-roles/tasks.md @@ -0,0 +1,42 @@ +## 1. Setup + +- [x] 1.1 Create the branch `fix/woo-excluded-roles` from `main`; the fix does not depend on the unreleased build work on `feat/separate-dev-and-prod-builds` + +## 2. Test bootstrap + +- [x] 2.1 Move `is_user_logged_in()` and `wp_get_current_user()` from `tests/bootstrap-forms.php` to `tests/bootstrap-wp-stubs.php`, defaulting to signed out +- [x] 2.2 Run the PHP suite; every test passes before the gate exists + +## 3. Dispatcher gate (test first) + +- [x] 3.1 Add `tests/test-woo-excluded-roles.php`, failing first, covering: excluded role skips AddToCart, InitiateCheckout and Purchase with `allow_live` true, with no `/event` or `/blocked-events` POST and nothing held under an unanswered banner +- [x] 3.2 Add cases: another role sends; a guest sends; `allow_live` false sends for an excluded user; replay under `flushing_held` sends for an excluded user +- [x] 3.3 Add cases through `pf_purchase_hook()`: a skip leaves `_pf_purchase_sent` unset and releases the claim; a later non-buyer request for the same order sends the Purchase +- [x] 3.4 Add a case: the debug log records `USER ROLE IS EXCLUDED FROM TRACKING` when debug logging is on +- [x] 3.5 Add the gate to `post_event()` as in design Decision 1; `php tests/test-woo-excluded-roles.php` passes +- [x] 3.6 Run the whole PHP suite; every test passes + +## 4. Settings page and docs + +- [x] 4.1 Update `AdvancedSettings.test.tsx` to the new title and both notes, keeping the checks that hide the Purchase note when WooCommerce tracking is off or WooCommerce is inactive; add a check for the hand-added script note +- [x] 4.2 Update the title, description and notes in `AdvancedSettings.tsx` as in design Decision 5; the frontend suite passes +- [x] 4.3 Update the FAQ answer in `readme.txt` and `README.md` as in design Decision 5 +- [x] 4.4 Check that no user-facing text outside `openspec/changes/archive/` still uses `Exclude Script for User Roles` or says WooCommerce events ignore the setting + +## 5. Live scenario + +- [x] 5.1 Add `e2e/live/tests/excluded-role.spec.ts` with the role excluded for a signed-in administrator and restored afterwards: no plugin scripts on storefront pages, and no AddToCart or InitiateCheckout sent, with the skip in the debug log +- [x] 5.2 Extend the scenario: that administrator's own checkout sends no Purchase, and a status change from a request that is not theirs then sends it +- [x] 5.3 Determine whether the test site's cart and checkout use the Store API; if any path sends because the user is unknown, report it before continuing (design Risks) + +## 6. Release + +- [x] 6.1 Bump to 1.2.3: `pixelflow.php` header and `PIXELFLOW_VERSION`, `readme.txt` `Stable tag` +- [x] 6.2 Add the one-line English changelog entry to `readme.txt` and `README.md`, stating that excluded roles now also stop WooCommerce events and that event counts on those sites may drop + +## 7. Full run and report + +- [ ] 7.1 Run the PHP suite, frontend suite, admin E2E (`e2e/tests`) and live matrix (`e2e/live`); every suite passes +- [ ] 7.2 Add `ROLE-*` rows to `docs/test-scenarios.html` for the scenarios above, including the accepted Purchase limit +- [ ] 7.3 Update the report's version, header, "Last full run" line and counts, then publish it with `e2e/live/scripts/publish-report.sh` +- [ ] 7.4 Check that no commit, spec or report text contains a client name, domain, IP address or absolute event count From 1ac60d6a5d13cfc2fa3ca4d2ac76cf4f3ddf385c Mon Sep 17 00:00:00 2001 From: Konstantin Konovalov Date: Sun, 1 Nov 2026 17:07:27 +0400 Subject: [PATCH 3/9] Skip WooCommerce events on an excluded role's own requests The excluded-roles setting removed the tracking script but left server-side AddToCart, InitiateCheckout and Purchase events running, so an excluded administrator's cart and checkout were still captured. post_event() now skips them with no blocked report and nothing held. It judges only the user's own request: a replay of events held earlier and a request that is not the buyer's (staff completing an order, a gateway webhook) are unaffected. A skipped Purchase is not recorded as delivered, so such a request can send it later. That limit is accepted and stated on the settings page. Co-Authored-By: Claude Opus 5.5 --- .../woo/hooks/class-woocommerce-hooks.php | 15 + tests/bootstrap-forms.php | 10 - tests/bootstrap-wp-stubs.php | 11 + tests/test-woo-excluded-roles.php | 782 ++++++++++++++++++ 4 files changed, 808 insertions(+), 10 deletions(-) create mode 100644 tests/test-woo-excluded-roles.php diff --git a/includes/woo/hooks/class-woocommerce-hooks.php b/includes/woo/hooks/class-woocommerce-hooks.php index 6c51392..35733fa 100644 --- a/includes/woo/hooks/class-woocommerce-hooks.php +++ b/includes/woo/hooks/class-woocommerce-hooks.php @@ -2110,6 +2110,21 @@ private function post_event(array $payload, array $context = []): string $order = isset($context['order']) && $context['order'] instanceof WC_Order ? $context['order'] : null; $bot_rule = isset($context['bot_rule']) && is_string($context['bot_rule']) ? $context['bot_rule'] : null; + // Same rule as form events: an excluded role sends no event and no blocked report, and is + // never held. It judges only the user's own request, so a replay of events held earlier + // and a request that is not the buyer's (staff completing an order, a gateway webhook) + // are unaffected. A skipped Purchase is not recorded as delivered, so such a request can + // still send it later. + if ( ! $this->flushing_held + && $allow_live + && pixelflow_current_user_has_excluded_role(is_array($this->options) ? $this->options : []) + ) { + $event_name = isset($payload['eventData']['eventName']) ? (string) $payload['eventData']['eventName'] : 'unknown'; + $this->debug_log($event_name, $payload, 'USER ROLE IS EXCLUDED FROM TRACKING'); + + return 'skipped'; + } + // Identity is resolved here rather than in the customer-data builders: this is the one // point every event type passes through, and the only place $context exists — which the // pixelflow_external_id filter is contracted to receive. Resolving before diff --git a/tests/bootstrap-forms.php b/tests/bootstrap-forms.php index a7ef452..3973045 100644 --- a/tests/bootstrap-forms.php +++ b/tests/bootstrap-forms.php @@ -120,16 +120,6 @@ function wp_parse_url($url, $component = -1) return parse_url((string) $url, $component); } -function is_user_logged_in(): bool -{ - return $GLOBALS['__pf_user'] !== null; -} - -function wp_get_current_user() -{ - return $GLOBALS['__pf_user']; -} - function wp_doing_ajax(): bool { return false; diff --git a/tests/bootstrap-wp-stubs.php b/tests/bootstrap-wp-stubs.php index 84681a6..e2baa45 100644 --- a/tests/bootstrap-wp-stubs.php +++ b/tests/bootstrap-wp-stubs.php @@ -99,6 +99,17 @@ function is_admin(): bool return ! empty($GLOBALS['__pf_admin']); } +function is_user_logged_in(): bool +{ + // Signed out unless a test sets $GLOBALS['__pf_user'] to an object with `roles`. + return ($GLOBALS['__pf_user'] ?? null) !== null; +} + +function wp_get_current_user() +{ + return $GLOBALS['__pf_user'] ?? null; +} + function sanitize_text_field($str) { return is_string($str) ? trim($str) : $str; diff --git a/tests/test-woo-excluded-roles.php b/tests/test-woo-excluded-roles.php new file mode 100644 index 0000000..3be5c31 --- /dev/null +++ b/tests/test-woo-excluded-roles.php @@ -0,0 +1,782 @@ + $url, + 'payload' => json_decode((string) ($args['body'] ?? '{}'), true), + ]; + + return ['response' => ['code' => 200]]; +} + +function wp_remote_retrieve_response_code($response) +{ + return is_array($response) ? ($response['response']['code'] ?? '') : ''; +} + +function wp_remote_retrieve_response_message($response) +{ + return is_array($response) ? ($response['response']['message'] ?? '') : ''; +} + +function wp_remote_retrieve_body($response) +{ + return is_array($response) ? ($response['body'] ?? '') : ''; +} + +class WP_Error +{ +} + +/** Minimal stand-in for WC_Order, enough to drive pf_purchase_hook(). */ +class WC_Order +{ + /** @var array */ + public $meta = []; + + /** @var array */ + public $items = []; + + /** @var int */ + private $id; + + public function __construct(int $id) + { + $this->id = $id; + } + + public function get_id(): int + { + return $this->id; + } + + public function get_meta($key, $single = true) + { + return $this->meta[$key] ?? ''; + } + + public function update_meta_data($key, $value): void + { + $this->meta[$key] = $value; + } + + public function delete_meta_data($key): void + { + unset($this->meta[$key]); + } + + public function save(): void + { + } + + public function get_items($type = 'line_item'): array + { + return $this->items; + } + + public function get_currency() + { + return 'USD'; + } + + public function get_total() + { + return 25.0; + } + + public function get_shipping_total() + { + return 0.0; + } + + public function get_total_tax() + { + return 0.0; + } + + public function get_customer_id() + { + return 0; + } + + public function get_billing_email() + { + return 'buyer@example.test'; + } + + public function get_billing_phone() + { + return '5415550123'; + } + + public function get_billing_first_name() + { + return 'Pixel'; + } + + public function get_billing_last_name() + { + return 'Flow'; + } + + public function get_billing_city() + { + return 'Springfield'; + } + + public function get_billing_state() + { + return 'OR'; + } + + public function get_billing_postcode() + { + return '97477'; + } + + public function get_billing_country() + { + return 'US'; + } + + public function get_checkout_order_received_url() + { + return 'https://example.test/order-received/' . $this->id; + } +} + +class WC_Product +{ + public function get_sku() + { + return 'PF-TEST'; + } + + public function get_id() + { + return 4242; + } + + public function get_price() + { + return 25.0; + } + + public function get_name() + { + return 'PF Test Product'; + } +} + +class WC_Order_Item_Product +{ + public function get_product() + { + return new WC_Product(); + } + + public function get_product_id() + { + return 4242; + } + + public function get_variation_id() + { + return 0; + } + + public function get_quantity() + { + return 1; + } + + public function get_name() + { + return 'PF Test Product'; + } + + public function get_total() + { + return 25.0; + } + + public function get_subtotal() + { + return 25.0; + } +} + +/** In-memory stand-in for the Woo session the hold queue lives in. */ +class PixelFlow_Test_Woo_Session +{ + /** @var array */ + private $data = []; + + public function get(string $key) + { + return $this->data[$key] ?? null; + } + + public function set(string $key, $value): void + { + $this->data[$key] = $value; + } + + public function get_customer_id(): string + { + return 'test-customer'; + } + + public function save_data(): void + { + } +} + +function WC() +{ + return $GLOBALS['__pf_test_wc']; +} + +require_once dirname(__DIR__) . '/includes/helpers.php'; +require_once dirname(__DIR__) . '/includes/consent.php'; +require_once dirname(__DIR__) . '/includes/blocked-events.php'; +require_once dirname(__DIR__) . '/includes/held-events.php'; +require_once dirname(__DIR__) . '/includes/woo/hooks/class-woocommerce-hooks.php'; + +const PF_SITE = 'wp_0123456789abcdef0123456789abcdef'; + +function pf_hooks(array $options = ['excluded_user_roles' => ['administrator']]): PixelFlow_WooCommerce_Cart_Hooks +{ + return new PixelFlow_WooCommerce_Cart_Hooks('https://example.test/api', 'k', PF_SITE, $options); +} + +function pf_post_event(PixelFlow_WooCommerce_Cart_Hooks $hooks, array $payload, array $context = []): string +{ + $reflection = new ReflectionMethod(PixelFlow_WooCommerce_Cart_Hooks::class, 'post_event'); + $reflection->setAccessible(true); + + return (string) $reflection->invoke($hooks, $payload, $context); +} + +function pf_payload(string $event_name): array +{ + return [ + 'siteId' => PF_SITE, + 'eventData' => [ + 'event_id' => 'event-1', + 'eventName' => $event_name, + 'eventTime' => 1757000000, + 'customerData' => [], + 'additionalData' => [ + 'currency' => 'USD', + 'value' => 25.0, + 'contentType' => 'product', + 'contents' => [['id' => '4242', 'quantity' => 1, 'item_price' => 25.0]], + ], + ], + ]; +} + +/** @param string[] $roles */ +function pf_sign_in(array $roles): void +{ + $GLOBALS['__pf_user'] = (object) ['roles' => $roles]; +} + +function pf_consent_cookie(string $state): string +{ + return base64_encode( + (string) wp_json_encode(['s' => $state, 't' => 1757000000000, 'src' => 'api', 'v' => 1]) + ); +} + +function pf_grant_consent(): void +{ + $_COOKIE[PIXELFLOW_CONSENT_COOKIE_NAME] = pf_consent_cookie('granted'); +} + +/** @return array Posts to the given endpoint suffix */ +function pf_posts_to(string $suffix): array +{ + return array_values(array_filter( + $GLOBALS['__pf_test_posts'], + static fn ($post) => substr((string) $post['url'], -strlen($suffix)) === $suffix + )); +} + +/** An order with one reportable line that the current visitor's cookie ties to them. */ +function pf_order_owned_by_visitor(int $id): WC_Order +{ + $order = new WC_Order($id); + $order->items = [new WC_Order_Item_Product()]; + $order->update_meta_data('_pf_cookie__pf_uid', 'visitor-1'); + $order->update_meta_data('_pf_cookie__pf_consent', pf_consent_cookie('granted')); + $GLOBALS['__pf_test_orders'][$id] = $order; + + $_COOKIE['_pf_uid'] = 'visitor-1'; + + return $order; +} + +/** What a later request that is not the buyer's looks like: no user, none of the buyer's cookies. */ +function pf_forget_request(): void +{ + $GLOBALS['__pf_user'] = null; + unset($_COOKIE['_pf_uid']); +} + +/** + * @return string|null Null when nothing was sent or reported, otherwise what was + */ +function pf_nothing_left_the_site(): ?string +{ + if (pf_posts_to('/event') !== []) { + return 'an event was sent'; + } + if (pf_posts_to('/blocked-events') !== []) { + return 'a blocked report was sent'; + } + + return null; +} + +$failures = []; +$passes = 0; + +/** + * @param string $label + * @param callable $fn + */ +function pf_run_role_case(string $label, callable $fn, array &$failures, int &$passes): void +{ + $_COOKIE = []; + $_GET = []; + $_SERVER['REQUEST_METHOD'] = 'POST'; + $_SERVER['HTTP_USER_AGENT'] = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) Chrome/140.0 Safari/537.36'; + + $GLOBALS['__pf_user'] = null; + $GLOBALS['__pf_test_posts'] = []; + $GLOBALS['__pf_test_orders'] = []; + $GLOBALS['__pf_test_options'] = ['pixelflow_debug_log_key' => 'excludedroles']; + $GLOBALS['__pf_test_wc'] = (object) ['session' => new PixelFlow_Test_Woo_Session()]; + + $path = pixelflow_get_debug_log_path(); + if ($path !== '' && file_exists($path)) { + unlink($path); + } + + try { + $result = $fn(); + } catch (\Throwable $e) { + $result = sprintf('%s: %s', get_class($e), $e->getMessage()); + } + + if ($result === true) { + $passes++; + echo "PASS {$label}\n"; + } else { + $failures[] = "{$label}: {$result}"; + echo "FAIL {$label}\n {$result}\n"; + } +} + +// --------------------------------------------------------------------- +// The excluded user's own request. +// --------------------------------------------------------------------- + +foreach (['AddToCart', 'InitiateCheckout', 'Purchase'] as $event_name) { + pf_run_role_case( + "Excluded administrator: {$event_name} from their own request is skipped", + /** @return bool|string */ + function () use ($event_name) { + pf_sign_in(['administrator']); + pf_grant_consent(); + + $outcome = pf_post_event(pf_hooks(), pf_payload($event_name), ['allow_live' => true]); + + if ($outcome !== 'skipped') { + return "expected the skipped outcome, got {$outcome}"; + } + + return pf_nothing_left_the_site() ?? true; + }, + $failures, + $passes + ); +} + +pf_run_role_case( + 'Excluded administrator with several roles is excluded by any of them', + /** @return bool|string */ + function () { + pf_sign_in(['customer', 'administrator']); + pf_grant_consent(); + + return pf_post_event(pf_hooks(), pf_payload('AddToCart')) === 'skipped' + ? (pf_nothing_left_the_site() ?? true) + : 'a second role did not count'; + }, + $failures, + $passes +); + +foreach (['AddToCart', 'InitiateCheckout'] as $event_name) { + pf_run_role_case( + "Excluded administrator: {$event_name} under an unanswered banner is not held", + /** @return bool|string */ + function () use ($event_name) { + pf_sign_in(['administrator']); + $_COOKIE[PIXELFLOW_NO_CONSENT_DECISION_COOKIE_NAME] = PIXELFLOW_NO_CONSENT_DECISION_COOKIE_VALUE; + + $outcome = pf_post_event(pf_hooks(), pf_payload($event_name)); + + if ($outcome !== 'skipped') { + return "expected the skipped outcome, got {$outcome}"; + } + if (pixelflow_get_held_woo_events() !== []) { + return 'the event was queued for later'; + } + + return pf_nothing_left_the_site() ?? true; + }, + $failures, + $passes + ); +} + +pf_run_role_case( + 'Excluded administrator under declined consent sends no blocked report', + /** @return bool|string */ + function () { + pf_sign_in(['administrator']); + $_COOKIE[PIXELFLOW_CONSENT_COOKIE_NAME] = pf_consent_cookie('denied'); + + pf_post_event(pf_hooks(), pf_payload('AddToCart')); + + return pf_nothing_left_the_site() ?? true; + }, + $failures, + $passes +); + +pf_run_role_case( + 'The skip is recorded in the debug log when debug logging is on', + /** @return bool|string */ + function () { + pf_sign_in(['administrator']); + pf_grant_consent(); + + pf_post_event( + pf_hooks(['excluded_user_roles' => ['administrator'], 'woo_debug_enabled' => 1]), + pf_payload('AddToCart') + ); + + $path = pixelflow_get_debug_log_path(); + $log = $path !== '' && file_exists($path) ? (string) file_get_contents($path) : ''; + + return strpos($log, 'USER ROLE IS EXCLUDED FROM TRACKING') !== false + ? true + : 'the debug log does not record the reason'; + }, + $failures, + $passes +); + +// --------------------------------------------------------------------- +// Who is not affected. +// --------------------------------------------------------------------- + +pf_run_role_case( + 'A role that is not excluded still sends', + /** @return bool|string */ + function () { + pf_sign_in(['customer']); + pf_grant_consent(); + + $outcome = pf_post_event(pf_hooks(), pf_payload('AddToCart')); + + return $outcome === 'sent' && count(pf_posts_to('/event')) === 1 + ? true + : "expected one event, got {$outcome}"; + }, + $failures, + $passes +); + +pf_run_role_case( + 'A guest still sends', + /** @return bool|string */ + function () { + pf_grant_consent(); + + $outcome = pf_post_event(pf_hooks(), pf_payload('AddToCart')); + + return $outcome === 'sent' && count(pf_posts_to('/event')) === 1 + ? true + : "expected one event, got {$outcome}"; + }, + $failures, + $passes +); + +pf_run_role_case( + 'With no roles excluded, an administrator still sends', + /** @return bool|string */ + function () { + pf_sign_in(['administrator']); + pf_grant_consent(); + + $outcome = pf_post_event(pf_hooks([]), pf_payload('AddToCart')); + + return $outcome === 'sent' ? true : "expected one event, got {$outcome}"; + }, + $failures, + $passes +); + +pf_run_role_case( + 'A request that is not the buyer\'s is not affected by the signed-in user\'s role', + /** @return bool|string */ + function () { + pf_sign_in(['administrator']); + pf_grant_consent(); + + $outcome = pf_post_event(pf_hooks(), pf_payload('Purchase'), ['allow_live' => false]); + + return $outcome === 'sent' && count(pf_posts_to('/event')) === 1 + ? true + : "expected one event, got {$outcome}"; + }, + $failures, + $passes +); + +pf_run_role_case( + 'Events held earlier are replayed on an excluded user\'s request', + /** @return bool|string */ + function () { + pixelflow_enqueue_held_woo_event( + pixelflow_held_event_recipe_from_payload(pf_payload('AddToCart'), 4242, 0) + ); + pf_sign_in(['administrator']); + pf_grant_consent(); + + pf_hooks()->resolve_held_events_on_page_view(); + + if (count(pf_posts_to('/event')) !== 1) { + return 'the held event was not replayed'; + } + + return pixelflow_get_held_woo_events() === [] ? true : 'the queue was not emptied'; + }, + $failures, + $passes +); + +// --------------------------------------------------------------------- +// Purchase, through the whole hook. +// --------------------------------------------------------------------- + +pf_run_role_case( + 'An excluded buyer\'s own status change sends nothing and leaves the order undelivered', + /** @return bool|string */ + function () { + $order = pf_order_owned_by_visitor(101); + pf_sign_in(['administrator']); + pf_grant_consent(); + + pf_hooks()->pf_purchase_hook(101); + + $leaked = pf_nothing_left_the_site(); + if ($leaked !== null) { + return $leaked; + } + if ((string) $order->get_meta('_pf_purchase_sent', true) !== '') { + return 'the order was recorded as delivered'; + } + if (array_key_exists('pixelflow_purchase_claim_101', $GLOBALS['__pf_test_options'])) { + return 'the delivery claim was not released'; + } + + return true; + }, + $failures, + $passes +); + +pf_run_role_case( + 'A later webhook sends the Purchase for an order skipped earlier', + /** @return bool|string */ + function () { + $order = pf_order_owned_by_visitor(102); + pf_sign_in(['administrator']); + pf_grant_consent(); + pf_hooks()->pf_purchase_hook(102); + if (pf_posts_to('/event') !== []) { + return 'the first request should have sent nothing'; + } + + pf_forget_request(); + pf_hooks()->pf_purchase_hook(102); + + $events = pf_posts_to('/event'); + if (count($events) !== 1 || ($events[0]['payload']['eventData']['eventName'] ?? '') !== 'Purchase') { + return 'expected one Purchase from the later request, got ' . count($events); + } + + return (string) $order->get_meta('_pf_purchase_sent', true) === '1' + ? true + : 'the order was not recorded as delivered'; + }, + $failures, + $passes +); + +pf_run_role_case( + 'Excluded staff completing another customer\'s order still send its Purchase', + /** @return bool|string */ + function () { + $order = pf_order_owned_by_visitor(103); + pf_forget_request(); + pf_sign_in(['administrator']); + + pf_hooks()->pf_purchase_hook(103); + + $events = pf_posts_to('/event'); + if (count($events) !== 1 || ($events[0]['payload']['eventData']['eventName'] ?? '') !== 'Purchase') { + return 'expected one Purchase, got ' . count($events); + } + + return (string) $order->get_meta('_pf_purchase_sent', true) === '1' + ? true + : 'the order was not recorded as delivered'; + }, + $failures, + $passes +); + +echo sprintf("\nExcluded roles on WooCommerce events: %d passed, %d failed\n", $passes, count($failures)); + +exit($failures === [] ? 0 : 1); From 776a22c9339d76b1dc43909ea7edfbcb01f5194c Mon Sep 17 00:00:00 2001 From: Konstantin Konovalov Date: Sun, 1 Nov 2026 17:07:27 +0400 Subject: [PATCH 4/9] Settings: rename the excluded-roles setting and state its limits Co-Authored-By: Claude Opus 5.5 --- .../components/AdvancedSettings.test.tsx | 37 ++++++++++++++++++- .../settings/components/AdvancedSettings.tsx | 16 ++++---- 2 files changed, 44 insertions(+), 9 deletions(-) diff --git a/app/source/src/features/settings/components/AdvancedSettings.test.tsx b/app/source/src/features/settings/components/AdvancedSettings.test.tsx index bef04ee..9fe70ae 100644 --- a/app/source/src/features/settings/components/AdvancedSettings.test.tsx +++ b/app/source/src/features/settings/components/AdvancedSettings.test.tsx @@ -177,12 +177,45 @@ describe('AdvancedSettings — excluded roles and WooCommerce event sending', () Object.keys(contextOverrides).forEach((key) => delete contextOverrides[key]); }); - it('states the limitation when WooCommerce tracking is on', () => { + it('states what the setting excludes under its new title', () => { + Object.assign(contextOverrides, { availableRoles: roles }); + render(); + + expect(screen.getByText('Exclude Tracking for User Roles')).toBeInTheDocument(); + expect( + screen.getByText( + /tracking script is not loaded for them, and their form and WooCommerce events are not sent/ + ) + ).toBeInTheDocument(); + }); + + it('states the hand-added script limit once a role is selected', () => { + Object.assign(contextOverrides, { + availableRoles: roles, + generalOptions: { ...generalOptions, excluded_user_roles: ['administrator'] }, + }); + render(); + + expect( + screen.getByText(/tracking script added to the site by hand is not affected/) + ).toBeInTheDocument(); + }); + + it('does not state the hand-added script limit with no role selected', () => { + Object.assign(contextOverrides, { availableRoles: roles }); + render(); + + expect( + screen.queryByText(/tracking script added to the site by hand is not affected/) + ).not.toBeInTheDocument(); + }); + + it('states the Purchase limit when WooCommerce tracking is on', () => { Object.assign(contextOverrides, { availableRoles: roles }); render(); expect(screen.getByTestId('excluded-roles-woo-note')).toHaveTextContent( - 'not applied to WooCommerce event sending' + "A Purchase can still be sent when a payment gateway, automation or another staff member changes the order's status" ); }); diff --git a/app/source/src/features/settings/components/AdvancedSettings.tsx b/app/source/src/features/settings/components/AdvancedSettings.tsx index 128f76e..bed9c01 100644 --- a/app/source/src/features/settings/components/AdvancedSettings.tsx +++ b/app/source/src/features/settings/components/AdvancedSettings.tsx @@ -133,11 +133,12 @@ export function AdvancedSettings() { {availableRoles.length > 0 && (

- Exclude Script for User Roles + Exclude Tracking for User Roles

- Select user roles that should NOT have the tracking script injected when they visit - the site. Useful for excluding administrators, editors, or other internal users. + Select user roles that should not be tracked while signed in. The tracking script is + not loaded for them, and their form and WooCommerce events are not sent. Useful for + excluding administrators, editors, or other internal users.

{availableRoles.map((role) => { @@ -162,14 +163,15 @@ export function AdvancedSettings() {
{excludedRoles.length > 0 && (

- Note: Users with excluded roles will not have tracking script - injected. + Note: A tracking script added to the site by hand is not affected + by this setting.

)} {isWooCommerceActive && generalOptions.woo_enabled === 1 && (

- This setting is not applied to WooCommerce event sending: add to cart, checkout - and purchase events are still sent for these roles. Form events are not. + A Purchase can still be sent when a payment gateway, automation or another staff + member changes the order's status, because that request does not belong to the + excluded user.

)}
From dcc27e015e06425a99975fbe9e2f3f7a40c4a4f6 Mon Sep 17 00:00:00 2001 From: Konstantin Konovalov Date: Sun, 1 Nov 2026 17:07:27 +0400 Subject: [PATCH 5/9] Live E2E: cover the excluded-roles setting on the storefront Co-Authored-By: Claude Opus 5.5 --- e2e/live/helpers/debug-log.ts | 7 ++ e2e/live/pages/settings-page.ts | 7 ++ e2e/live/presets.ts | 10 ++ e2e/live/tests/excluded-role.spec.ts | 144 +++++++++++++++++++++++++++ 4 files changed, 168 insertions(+) create mode 100644 e2e/live/tests/excluded-role.spec.ts diff --git a/e2e/live/helpers/debug-log.ts b/e2e/live/helpers/debug-log.ts index 004242a..90566e3 100644 --- a/e2e/live/helpers/debug-log.ts +++ b/e2e/live/helpers/debug-log.ts @@ -159,6 +159,13 @@ export function skippedRecords(records: EventRecord[], name: string): EventRecor ); } +/** Records for one event name that the plugin skipped because the user's role is excluded. */ +export function excludedRoleRecords(records: EventRecord[], name: string): EventRecord[] { + return recordsNamed(records, name).filter( + (record) => record.response === 'USER ROLE IS EXCLUDED FROM TRACKING' + ); +} + /** * Blocked-events beacons for one event name. * diff --git a/e2e/live/pages/settings-page.ts b/e2e/live/pages/settings-page.ts index 6a1f0a6..9f10cb7 100644 --- a/e2e/live/pages/settings-page.ts +++ b/e2e/live/pages/settings-page.ts @@ -149,6 +149,13 @@ export class SettingsPage { await this.openWooTab(); } + /** One role's switch under "Exclude Tracking for User Roles". */ + async setRoleExcluded(role: string, excluded: boolean): Promise { + await this.openAdvancedTab(); + await this.setSwitch(`exclude-role-${role}`, excluded); + await this.openWooTab(); + } + private excludedSkuChip(sku: string): Locator { return this.page.getByRole('button', { name: `Remove SKU ${sku}` }); } diff --git a/e2e/live/presets.ts b/e2e/live/presets.ts index 46c32f3..0567561 100644 --- a/e2e/live/presets.ts +++ b/e2e/live/presets.ts @@ -19,6 +19,8 @@ export interface SettingsState { /** "Enable event for free products". Defaults to all enabled. */ freebies?: Partial>; excludedSkus?: string[]; + /** Role keys under "Exclude Tracking for User Roles". None unless given, so every preset restores it. */ + excludedRoles?: string[]; /** "Only the customer's first purchase". Off unless given, so every preset restores it. */ firstPurchase?: { lookback?: 'all' | 'days'; @@ -40,6 +42,10 @@ export async function applySettings(page: Page, state: SettingsState): Promise { + await withAdminPage(browser, (page) => applySettings(page, rolesExcluded('administrator'))); +}); + +test.afterAll(async ({ browser }) => { + await withAdminPage(browser, (page) => applySettings(page, TRACK_EVERYTHING)); +}); + +test.describe('A signed-in administrator with the role excluded', () => { + test.use({ storageState: ADMIN_STATE }); + + test('gets none of the plugin scripts', async ({ page }) => { + await page.goto(URLS.fixtureListing, { waitUntil: 'domcontentloaded' }); + + await expect(page.locator('#wpadminbar'), 'the page was not served signed in').toHaveCount(1); + await expect(page.locator(TRACKING_SCRIPT)).toHaveCount(0); + await expect(page.locator(HELD_EVENTS_SCRIPT)).toHaveCount(0); + }); + + test('sends no AddToCart or InitiateCheckout', async ({ shop, cart }) => { + await shop.open(); + await shop.addToCart(PRODUCTS.tshirt); + await cart.open(); + await cart.proceedToCheckout(); + + const records = await waitForRecords( + (seen) => + excludedRoleRecords(seen, 'AddToCart').length >= 1 && + excludedRoleRecords(seen, 'InitiateCheckout').length >= 1, + { description: 'AddToCart and InitiateCheckout skipped for the excluded role' } + ); + + await expectNoTrackedEvents(); + expect(blockedRecords(records), 'a skip must not send a blocked report').toHaveLength(0); + }); + + test('sends no Purchase from their own checkout, and a later request that is not theirs does', async ({ + shop, + cart, + checkout, + }) => { + await shop.open(); + await shop.addToCart(PRODUCTS.tshirt); + await cart.open(); + await cart.proceedToCheckout(); + await checkout.completeOrder(); + + const orderId = checkout.orderId(); + await waitForRecords((seen) => excludedRoleRecords(seen, 'Purchase').length >= 1, { + description: 'Purchase skipped for the excluded role', + }); + await expectNoTrackedEvents(); + expect(blockedRecords(readEventRecords()), 'a skip must not send a blocked report').toHaveLength(0); + expect(readOrderMeta(orderId).sent, 'a skipped order was recorded as delivered').toBe(false); + + // Automation over WP-CLI stands in for a gateway webhook: no signed-in user and none of the + // buyer's cookies. This is the accepted limit of the setting, pinned so it stays deliberate. + truncateDebugLog(); + setOrderStatus(orderId, 'completed'); + + const records = await waitForEvent('Purchase', 1, { timeoutMs: 40_000 }); + expect(sentRecords(records, 'Purchase')).toHaveLength(1); + expect(readOrderMeta(orderId).sent).toBe(true); + }); +}); + +forEachPersona('With the administrator role excluded, a visitor outside it', () => { + test('still gets the tracking script and sends AddToCart', async ({ page, shop }) => { + await page.goto(URLS.fixtureListing, { waitUntil: 'domcontentloaded' }); + await expect(page.locator(TRACKING_SCRIPT)).toHaveCount(1); + + await shop.open(); + await shop.addToCart(PRODUCTS.tshirt); + + const records = await waitForEvent('AddToCart'); + expect(sentRecords(records, 'AddToCart')).toHaveLength(1); + expect(excludedRoleRecords(records, 'AddToCart')).toHaveLength(0); + }); +}); + +test.describe('A real customer whose order an excluded administrator completes', () => { + test.use({ storageState: CUSTOMER_STATE }); + + test('still has the Purchase sent', async ({ page, browser }) => { + // An order the customer has yet to pay for: a completed checkout would already have sent its + // Purchase at the thank-you page. Opening the pay page records their granted consent on it. + const orderId = createPendingOrder(CUSTOMER.username, PRODUCTS.tshirt.id); + await page.goto(orderPayUrl(orderId), { waitUntil: 'domcontentloaded' }); + truncateDebugLog(); + + await withAdminPage(browser, async (adminPage) => { + await adminPage.goto(URLS.adminOrder(orderId), { waitUntil: 'domcontentloaded' }); + await adminPage.selectOption('#order_status', 'wc-processing'); + await adminPage.locator('button.save_order').first().click(); + await adminPage.waitForLoadState('domcontentloaded'); + }); + + const records = await waitForEvent('Purchase', 1, { timeoutMs: 40_000 }); + expect(sentRecords(records, 'Purchase')).toHaveLength(1); + expect(excludedRoleRecords(records, 'Purchase')).toHaveLength(0); + expect(readOrderMeta(orderId).sent).toBe(true); + }); +}); From 4ecfab821ad1899dbd06d962579aca3442dbbb71 Mon Sep 17 00:00:00 2001 From: Konstantin Konovalov Date: Sun, 1 Nov 2026 17:07:27 +0400 Subject: [PATCH 6/9] Release 1.2.3 Co-Authored-By: Claude Opus 5.5 --- README.md | 5 ++++- pixelflow.php | 4 ++-- readme.txt | 7 +++++-- 3 files changed, 11 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 7286e51..936cddb 100644 --- a/README.md +++ b/README.md @@ -423,7 +423,7 @@ Yes. Turn on product IDs in WooCommerce Settings and choose the format that matc ### Can I stop admins and staff being tracked? -Yes. Under Advanced Settings, choose any user roles (Administrator, Editor, Shop manager and more) that should not have the tracking script loaded. +Yes. Under Advanced Settings, choose any user roles (Administrator, Editor, Shop manager and more) that should not be tracked. The tracking script is not loaded for them, and their form and WooCommerce events are not sent while they are signed in. A Purchase can still be sent when a payment gateway, automation or another staff member changes the order's status, and a tracking script added to the site by hand is not affected. ### Is PixelFlow GDPR compliant? @@ -469,6 +469,9 @@ Documentation, video tutorials and email support on all plans. Ask a question in ## Changelog +### 1.2.3 +Excluded user roles now also stop WooCommerce AddToCart, InitiateCheckout and Purchase events from their own signed-in requests, so sites that exclude roles may see lower event counts + ### 1.2.2 WooCommerce: optional setting to send Purchase only for a customer's first paid order, so subscription renewals and repeat orders stop counting as new purchases. Forms: events now include city, state, postcode and country from the visitor's location when the form has no such fields. diff --git a/pixelflow.php b/pixelflow.php index 0a996c1..6017234 100644 --- a/pixelflow.php +++ b/pixelflow.php @@ -2,7 +2,7 @@ /** * Plugin Name: PixelFlow – Meta & TikTok Pixel + Conversions API for WooCommerce * Description: Facebook Pixel & TikTok Pixel with server-side Conversions API (CAPI) for WooCommerce & WordPress. Auto-tracks sales & forms. No code, no GTM. - * Version: 1.2.2 + * Version: 1.2.3 * Requires at least: 6.5 * Requires PHP: 7.4 * Author: PixelFlow Team @@ -19,7 +19,7 @@ } // Define plugin constants -define('PIXELFLOW_VERSION', '1.2.2'); +define('PIXELFLOW_VERSION', '1.2.3'); define('PIXELFLOW_PLUGIN_URL', plugin_dir_url(__FILE__)); define('PIXELFLOW_PLUGIN_PATH', plugin_dir_path(__FILE__)); define('PIXELFLOW_PLUGIN_BASENAME', plugin_basename(__FILE__)); diff --git a/readme.txt b/readme.txt index 71650e6..8602ad4 100644 --- a/readme.txt +++ b/readme.txt @@ -4,7 +4,7 @@ Tags: facebook pixel, conversions api, tiktok pixel, meta pixel, server-side tra Requires at least: 6.5 Tested up to: 7.1 Requires PHP: 7.4 -Stable tag: 1.2.2 +Stable tag: 1.2.3 License: GPLv2 or later License URI: https://www.gnu.org/licenses/gpl-2.0.html @@ -160,7 +160,7 @@ Yes. Turn on product IDs in WooCommerce Settings and choose the format that matc = Can I stop admins and staff being tracked? = -Yes. Under Advanced Settings, choose any user roles (Administrator, Editor, Shop manager and more) that should not have the tracking script loaded. +Yes. Under Advanced Settings, choose any user roles (Administrator, Editor, Shop manager and more) that should not be tracked. The tracking script is not loaded for them, and their form and WooCommerce events are not sent while they are signed in. A Purchase can still be sent when a payment gateway, automation or another staff member changes the order's status, and a tracking script added to the site by hand is not affected. = Is PixelFlow GDPR compliant? = @@ -197,6 +197,9 @@ Documentation, video tutorials and email support on all plans. Ask a question in == Changelog == += 1.2.3 = +Excluded user roles now also stop WooCommerce AddToCart, InitiateCheckout and Purchase events from their own signed-in requests, so sites that exclude roles may see lower event counts + = 1.2.2 = WooCommerce: optional setting to send Purchase only for a customer's first paid order, so subscription renewals and repeat orders stop counting as new purchases. Forms: events now include city, state, postcode and country from the visitor's location when the form has no such fields. From 6d4fc6480b6c476fb660bf2707e0f1275e72bcf4 Mon Sep 17 00:00:00 2001 From: Konstantin Konovalov Date: Sun, 1 Nov 2026 17:08:10 +0400 Subject: [PATCH 7/9] Docs: record the 2026-11-01 run and excluded roles in the scenario matrix Co-Authored-By: Claude Opus 5.5 --- docs/test-scenarios.html | 31 ++++++++++++++----- .../changes/fix-woo-excluded-roles/tasks.md | 8 ++--- 2 files changed, 28 insertions(+), 11 deletions(-) diff --git a/docs/test-scenarios.html b/docs/test-scenarios.html index 94742f3..6c5c27e 100644 --- a/docs/test-scenarios.html +++ b/docs/test-scenarios.html @@ -86,15 +86,15 @@
-

PixelFlow 1.2.2 — Test Scenario Matrix

-

What the plugin's behaviour is actually verified against, organised by capability rather than by test file. Generated 2026-10-11 from feat/wordpress-first-purchase, for the OpenSpec changes add-woo-first-purchase-only and add-form-location-from-cookie.

-

Last full run: 2026-10-11 on c52533c — PHP 482/482 (35 files, on PHP 8.3; not rerun on PHP 7.4) · component tests 72/72 · admin E2E 7/7 (these three on 8ce5a6f; later commits change no PHP or admin code) · live storefront matrix 133/134 in one run, with the browser leaving through an EU address. The one failure, the Elementor Pro case of the form hold spec, came from the suite itself (a click before Elementor bound its submit, and a repeat window the reset no longer cleared); after the fix in 9059e44 that case passed five times in a row.

+

PixelFlow 1.2.3 — Test Scenario Matrix

+

What the plugin's behaviour is actually verified against, organised by capability rather than by test file. Generated 2026-11-01 from fix/woo-excluded-roles, for the OpenSpec change fix-woo-excluded-roles.

+

Last full run: 2026-11-01 on 4ecfab8 — PHP 512/512 (38 files, on PHP 8.5.4; not rerun on PHP 7.4) · component tests 80/80 · admin E2E 7/7 · live storefront matrix 140/140 in one run, with the browser leaving through an EU address.

-
207scenarios in this matrix
-
192covered
+
217scenarios in this matrix
+
202covered
15partial or uncovered
-
695automated cases (482 PHP · 72 vitest · 7 admin E2E · 134 live E2E)
+
739automated cases (512 PHP · 80 vitest · 7 admin E2E · 140 live E2E)
@@ -402,7 +402,7 @@

17. Form events < FRM-26A form the listing missedSends with its computed configuration; adds no rowtests/test-form-adapters.phpCovered FRM-27Configured form deleted, trashed, unpublished or deactivatedDeleted or trashed: missing, locked, config kept, nothing sent; unpublished or deactivated: not missing; reappearing form resumes its configtests/test-form-missing.phpCovered FRM-28Forms tab in the settings pagePlugin status line, single double-count warning, switches, events, mapping panel, stale-choice highlight, save-only-what-changedapp/source/src/test/forms-settings.test.tsx · e2e/tests/forms-settings.spec.tsCovered -FRM-29Excluded-roles noteShown only with WooCommerce tracking onapp/source/src/features/settings/components/AdvancedSettings.test.tsxCovered +FRM-29Excluded-roles Purchase noteShown only with WooCommerce active and its tracking onapp/source/src/features/settings/components/AdvancedSettings.test.tsxCovered FRM-30Site without WooCommerceForm flush script loads; send, hold and replay work; nothing reaches the WooCommerce queuetests/test-form-*.php (no WC()) · e2e/live/tests/forms-without-woo.spec.tsCovered FRM-31Two concurrent requests of one double clickThe request whose repeat-window insert loses sends nothing; closed windows are deleted by the next claimtests/test-form-skips.php (the lost insert is simulated)Covered FRM-32An older held recipe when a later hold saves the queue again; a hint cookie whose queue is goneEach recipe expires 48 h after it was stored; the state route removes the stale cookietests/test-form-hold.phpCovered @@ -450,6 +450,23 @@

The former exclude argument (a NOT IN clause) cost 2–6 ms of the 40–65 ms legacy query at 50,000 orders. The cost is paid once per order, in the request that moves it to processing or completed, and only on stores that turn the setting on. Accepted and documented; an indexed email lookup for legacy storage would be a separate change.

+

20. Excluded user roles — what a signed-in user with an excluded role still sends

+
+ + + + + + + + + + + + + +
IDScenarioExpected behaviourVerified inStatus
ROLE-01A signed-in administrator with the role excluded opens a storefront pageNone of the plugin's scripts are on the pagee2e/live/tests/excluded-role.spec.tsCovered
ROLE-02That user adds to cart and goes to checkoutNo AddToCart or InitiateCheckout and no /blocked-events report; the debug log records USER ROLE IS EXCLUDED FROM TRACKINGtests/test-woo-excluded-roles.php · e2e/live/tests/excluded-role.spec.tsCovered
ROLE-03The same events under an unanswered banner or declined consentNothing is held and no blocked report is senttests/test-woo-excluded-roles.phpCovered
ROLE-04A user with several roles, one of them excludedExcludedtests/test-woo-excluded-roles.phpCovered
ROLE-05The excluded user's own checkoutNo Purchase; the order is not recorded as delivered (_pf_purchase_sent stays unset)tests/test-woo-excluded-roles.php · e2e/live/tests/excluded-role.spec.tsCovered
ROLE-06A later request that is not theirs moves that order: a gateway webhook, automation or another staff member (accepted limit)The skipped Purchase is sent once, because that request does not belong to the excluded user; the settings page states thistests/test-woo-excluded-roles.php · e2e/live/tests/excluded-role.spec.ts (status change over WP-CLI)Covered
ROLE-07An excluded administrator completes a real customer's order in wp-adminThe customer's Purchase is senttests/test-woo-excluded-roles.php · e2e/live/tests/excluded-role.spec.tsCovered
ROLE-08A role that is not excluded, a guest, or no roles excluded at allEvents are sent as before; on the storefront the tracking script is presenttests/test-woo-excluded-roles.php · e2e/live/tests/excluded-role.spec.ts (guest and customer)Covered
ROLE-09Events held earlier are replayed on an excluded user's requestThey are sent; the replay is not judged by the current user's roletests/test-woo-excluded-roles.phpCovered
ROLE-10The setting on the settings pageTitled Exclude Tracking for User Roles; says a tracking script added by hand is not affected once a role is selectedapp/source/src/features/settings/components/AdvancedSettings.test.tsxCovered
+