toga-ai 1.0.846 → 1.0.847
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/knowledge/2.0/apps/toga2-commerce/INDEX.md +2 -1
- package/knowledge/2.0/apps/toga2-commerce/architecture.md +6 -3
- package/knowledge/2.0/apps/toga2-commerce/features/header-order-for-dropdown.md +36 -32
- package/knowledge/2.0/apps/toga2-commerce/features/view-as-session-tokens.md +90 -0
- package/knowledge/2.0/apps/toga2-commerce/workflows/cypress-testing.md +22 -3
- package/knowledge/INDEX.md +1 -1
- package/package.json +1 -1
|
@@ -13,12 +13,13 @@
|
|
|
13
13
|
| [Client Fields — per-tenant / language / role content & config](features/client-fields.md) | Per-tenant/language/role JSON config that drives almost all commerce UI text, fields, and login fetches (Layer A global + Layer B FIELDS registry); open before |
|
|
14
14
|
| [Config-Driven Expedited Shipping Gating (Cart)](features/expedited-shipping-gating.md) | Expedited shipping options are config-gated to show only when the cart holds a computer kit; open when touching cart shipping-method options or the gate config. |
|
|
15
15
|
| [Filter / Search-Results Page & the Two Search Entry Points](features/filter-search-results-page.md) | Two search entry points (Home in-place vs Header→/filter) render the same card via different code paths and FIELDS files; open for any search-results or kit-car |
|
|
16
|
-
| [Header "Order for <Name>" dropdown + the
|
|
16
|
+
| [Header "Order for <Name>" dropdown + the persisted pick handed to the cart](features/header-order-for-dropdown.md) | Header pill that lets a buyer pick who they are ordering for from any page, and the persisted store that hands that pick to the cart's order-for cascade; open b |
|
|
17
17
|
| [Inactive-item purchase gating (standalone lines only — kits are exempt by design)](features/inactive-item-purchase-gating.md) | `Items.isActive = 0` blocks standalone purchase but means something different on kit components, so the gate keys on purchase CONTEXT not the flag; open when to |
|
|
18
18
|
| [Multi-Tenant Resolution & Theming](features/multi-tenant-theming.md) | How the hostname resolves the tenant and fans out to API base URL, theme (CSS variables), and fields; open when adding a tenant or debugging wrong-theme/wrong-A |
|
|
19
19
|
| [Order-submit sync sequencing (useSubmitOrder) — why these calls must not run in parallel](features/order-submit-sync-sequencing.md) | The item sync must finish before the header sync on order submit, or concurrent line deletes race a depth-3 response into an uncaught api2 500; open when touchi |
|
|
20
20
|
| [Config-Driven Shipping Cost Waiver (Standard Ground free for computer kits)](features/shipping-cost-waiver-gating.md) | Config-driven cost waiver making Standard Ground free for a bare computer kit (Compass USA); open when touching shipping cost gates or the Compass free-freight |
|
|
21
21
|
| [Storefront persona gating — the Home page's kit / category / item counts, and the persona switcher](features/storefront-persona-gating-and-home-counts.md) | What a storefront user sees on the Home page is decided **in the front end**, from `user._personaIds`, not by the API's ACL. |
|
|
22
|
+
| [View-as another user — parked admin tokens & return-to-self](features/view-as-session-tokens.md) | How an admin impersonates another user and gets back: the delegated token pair, the parked admin pair in localStorage, and the return path. |
|
|
22
23
|
| [AWS Amplify Build & Deploy (non-prod environments)](workflows/amplify-build-and-deploy.md) | How toga2-commerce builds/deploys on AWS Amplify (one dynamic amplify.yml, branch-per-env, per-env blox channel); open to deploy, stand up an env, resolve a blo |
|
|
23
24
|
| [Cart e2e — Cypress conventions & harness (toga2-commerce)](workflows/cypress-testing.md) | Cypress e2e conventions + the Cart harness (cartV2.cy.ts) for toga2-commerce; read before adding any spec here, and note it doubles as the config-cart refactor |
|
|
24
25
|
| [Diagnosing ERR_HTTP2_PROTOCOL_ERROR (one client fails, everyone else is fine)](workflows/http2-protocol-error-diagnosis.md) | Diagnose ERR_HTTP2_PROTOCOL_ERROR when one client/network fails a togacommerce tenant but everyone else works (usually the client's TLS-inspection proxy, not ou |
|
|
@@ -6,7 +6,7 @@ project: TOGa Commerce
|
|
|
6
6
|
client: shared
|
|
7
7
|
type: architecture
|
|
8
8
|
status: active
|
|
9
|
-
updated: 2026-09-
|
|
9
|
+
updated: 2026-09-21
|
|
10
10
|
owners: ["apeterson", "tcox"]
|
|
11
11
|
files:
|
|
12
12
|
- src/main.tsx
|
|
@@ -15,6 +15,7 @@ files:
|
|
|
15
15
|
- src/contexts/AuthContext.tsx
|
|
16
16
|
- src/contexts/helpers/getLoginSettings.ts
|
|
17
17
|
- src/api/axiosInstance.ts
|
|
18
|
+
- src/api/sessionTokens.ts
|
|
18
19
|
- src/stores/
|
|
19
20
|
- src/themeConfig/ThemeContext.tsx
|
|
20
21
|
- src/fieldsConfig/index.ts
|
|
@@ -27,6 +28,7 @@ related:
|
|
|
27
28
|
- 2.0/apps/toga2-commerce/workflows/amplify-build-and-deploy.md
|
|
28
29
|
- 2.0/apps/api2/architecture.md
|
|
29
30
|
- 2.0/apps/toga2-commerce/features/filter-search-results-page.md
|
|
31
|
+
- 2.0/apps/toga2-commerce/features/view-as-session-tokens.md
|
|
30
32
|
---
|
|
31
33
|
|
|
32
34
|
Whole-repo map of the toga2-commerce React storefront (bootstrap, routing, MVVM pages, state, API, multi-tenant resolution); open when working anywhere in this repo.
|
|
@@ -124,7 +126,7 @@ Most use the `persist` middleware (localStorage). Verified files:
|
|
|
124
126
|
| `useEditOrderZu` | "Edit existing order" mode flag + original snapshot |
|
|
125
127
|
| `useEditOrderUuidStore` | UUID of the order being edited |
|
|
126
128
|
| `useSelectedUserZu` | "Order for" user selected in cart |
|
|
127
|
-
| `useOrderForZu` | Header "order for"
|
|
129
|
+
| `useOrderForZu` | Header "order for" pick — **persisted** (`order-for-zu`), owner-scoped: always read via `getOrderForUserFor(pick, ownerUuid)` (see header-order-for-dropdown) |
|
|
128
130
|
| `useReturnOriginalUserFromViewAsStore` | "View as another user" return-to-self tracking |
|
|
129
131
|
| `useEmailOptionsStore` | Notification CC email options (see cart-notification-emails) |
|
|
130
132
|
| `useBundleBuilderZu` | Bundle-builder wizard selections |
|
|
@@ -146,7 +148,8 @@ Most use the `persist` middleware (localStorage). Verified files:
|
|
|
146
148
|
- **Transaction id:** a request interceptor stamps every call with `params.transactionId = uuidv4()`.
|
|
147
149
|
- **Auth token:** a second request interceptor attaches `Authorization: Bearer <token>` — using the stored `accessToken` if a `user` exists in localStorage, otherwise fetching a **public token** via `POST {baseURL}/auth/public`.
|
|
148
150
|
- **1 ms delay interceptor:** a third request interceptor `await delay(1)` before sending.
|
|
149
|
-
- **401 handling:** response interceptor attempts `POST {baseURL}/auth/refresh` (Bearer refresh token) once (`_retry`), retries the original request on success, else calls `performLogout()` (clears all auth + cart + `commerce` cache keys and redirects to `/`).
|
|
151
|
+
- **401 handling:** response interceptor attempts `POST {baseURL}/auth/refresh` (Bearer refresh token) once (`_retry`), retries the original request on success, else calls `performLogout()` (clears all auth + cart + `commerce` cache keys and redirects to `/`). The refresh is **single-flight** (one module-level promise) and **identity-bound** — it returns `null` if `localStorage.refreshToken` changed while in flight, so it cannot overwrite a just-minted delegated pair.
|
|
152
|
+
- **Token storage lives in `src/api/sessionTokens.ts`** (host from `src/api/apiBaseUrl.ts`). Besides `accessToken` / `refreshToken` it owns **`originalAuthTokens`** — the admin's own pair parked during view-as and restored on return; `/auth/encrypted` is never called to re-mint. See [view-as-session-tokens](features/view-as-session-tokens.md).
|
|
150
153
|
- Failures are reported to **Sentry** with `errorType: "API"` tags.
|
|
151
154
|
|
|
152
155
|
The backend (`api2`) returns the standard 2.0 envelope (`success`/`data`/`errors`; see api2 arch); generic CRUD helpers live in `src/api/genericApi.ts` (paginated `getData`, `saveData`, `updateData`, `deleteData`, optional `?depth=-1` for nested responses).
|
|
@@ -1,17 +1,16 @@
|
|
|
1
1
|
---
|
|
2
|
-
title: Header "Order for <Name>" dropdown + the
|
|
2
|
+
title: Header "Order for <Name>" dropdown + the persisted pick handed to the cart
|
|
3
3
|
framework: "2.0"
|
|
4
4
|
repo: toga2-commerce
|
|
5
5
|
project: TOGa Commerce
|
|
6
6
|
client: shared
|
|
7
7
|
type: feature
|
|
8
|
-
status:
|
|
8
|
+
status: active
|
|
9
9
|
updated: 2026-09-17
|
|
10
10
|
owners: [tcox]
|
|
11
11
|
files:
|
|
12
12
|
- src/components/OrderForDropdown/OrderForDropdown.tsx
|
|
13
13
|
- src/components/OrderForDropdown/useOrderForDropdownViewModel.ts
|
|
14
|
-
- src/components/OrderForDropdown/types.ts
|
|
15
14
|
- src/stores/useOrderForZu.ts
|
|
16
15
|
- src/components/Header/Header.tsx
|
|
17
16
|
- src/pages/Cart/view/cartForm/EditCart.tsx
|
|
@@ -25,77 +24,81 @@ related:
|
|
|
25
24
|
- 2.0/apps/toga2-commerce/features/client-fields.md
|
|
26
25
|
- 2.0/apps/toga2-commerce/features/cart-notification-emails.md
|
|
27
26
|
- 2.0/apps/toga2-commerce/features/cart-page-config-architecture.md
|
|
27
|
+
- 2.0/apps/toga2-commerce/features/view-as-session-tokens.md
|
|
28
28
|
- 2.0/apps/toga2-commerce/workflows/cypress-testing.md
|
|
29
29
|
---
|
|
30
30
|
|
|
31
|
-
Header pill that lets a buyer pick who they are ordering for from any page, and the
|
|
31
|
+
Header pill that lets a buyer pick who they are ordering for from any page, and the persisted store that hands that pick to the cart's order-for cascade; open before touching the header pill, `useOrderForZu`, or the cart `orderFor` field.
|
|
32
32
|
|
|
33
33
|
## Summary
|
|
34
34
|
|
|
35
|
-
TRUE-81851. Before this, "order for someone else" existed **only** on the cart form. The header now renders an **"Order for <Name>"** pill (next to the logo on desktop, inside the mobile `SlideMenu`) that sets the same pick from any page. The header does **not** run the order-for cascade — it
|
|
35
|
+
TRUE-81851 (pill) + TRUE-81852 (persistence). Before this, "order for someone else" existed **only** on the cart form. The header now renders an **"Order for <Name>"** pill (next to the logo on desktop, inside the mobile `SlideMenu`) that sets the same pick from any page. The header does **not** run the order-for cascade — it stores the pick and the **cart stays the single owner** of the cascade.
|
|
36
36
|
|
|
37
|
-
**
|
|
37
|
+
**The pick is sticky.** Developer requirement: *"Order for needs to be persistent once chosen until the user changes it back to themself or logs out."* The store is persisted to localStorage and survives order submit, edit-order exit, view-as return, and page reload.
|
|
38
38
|
|
|
39
|
-
**Per-role, per-tenant gated.** Copy and the on/off switch live in `HEADERFIELDS.json` under
|
|
39
|
+
**Per-role, per-tenant gated.** Copy and the on/off switch live in `HEADERFIELDS.json` under an `orderFor` key, Compass USA only: `isEnabled` true for ADMIN / MANAGER / SUPERUSER, false for USER. Compass Canada and Quad have no key, so the component renders nothing (see gotchas).
|
|
40
40
|
|
|
41
41
|
## How it works
|
|
42
42
|
|
|
43
43
|
### 1. The pill (`src/components/OrderForDropdown/`)
|
|
44
44
|
|
|
45
|
-
MVVM split: `OrderForDropdown.tsx` (view), `useOrderForDropdownViewModel.ts` (state + queries), `types.ts`, `index.ts`. Rendered from `
|
|
45
|
+
MVVM split: `OrderForDropdown.tsx` (view), `useOrderForDropdownViewModel.ts` (state + queries), `types.ts`, `index.ts`. Rendered from `Header.tsx`; hidden in edit-order mode.
|
|
46
46
|
|
|
47
47
|
- Trigger label: **"Order for Myself"** when ordering for yourself, else **"Order for <Name>"**.
|
|
48
|
-
-
|
|
49
|
-
- Icons are the **exact Figma SVG paths inlined** (24x24 user, 12.64x6.82 chevron) — not FontAwesome.
|
|
48
|
+
- Teal `#00B9A8` outline + inset glow on hover, when open, and when someone other than the signed-in user is picked (`data-active="yes"`). Icons are the inlined Figma SVG paths, not FontAwesome.
|
|
50
49
|
- Menu: search box → yourself first as **"<Name> (Myself)"** → the user list → **Load more** past 100. Check mark on the current pick. `aria` listbox/option roles, Escape closes and returns focus to the trigger, outside click closes.
|
|
51
50
|
- Copy keys under `orderFor`: `isEnabled`, `label`, `searchPlaceholder`, `myselfLabel`, `loadingMessage`, `noOptionsFoundMessage`, `loadMoreLabel` — in all four COMPASS/ENGLISH role files.
|
|
52
51
|
|
|
53
52
|
### 2. There is no "delegation" API — it is the cart's own user list
|
|
54
53
|
|
|
55
|
-
Verified 2026-09-17 across `toga2-commerce`, `api2`, `_underscore`, `dbchanges2` and the client-sandbox + prod databases
|
|
54
|
+
Verified 2026-09-17 across `toga2-commerce`, `api2`, `_underscore`, `dbchanges2` and the client-sandbox + prod databases: **no delegation endpoint or table exists.** api2's `/auth/delegator` is the view-as token, unrelated (see [view-as-session-tokens](view-as-session-tokens.md)).
|
|
56
55
|
|
|
57
|
-
The list is the same `GET /users` the cart
|
|
56
|
+
The list is the same `GET /users` the cart uses, via `getUserOptions()` / `getSearchValuesFromAdvancedInput()` in `src/pages/Cart/api/CartApi.ts`:
|
|
58
57
|
|
|
59
58
|
- **Admins** get all active users; server-side search when `CARTPAGE settings.isSearchAnyoneEnabled`.
|
|
60
59
|
- **Supervisors** get their direct reports through the `Users@supervisor` join, filtered locally.
|
|
61
|
-
- Field lists come from the per-tenant `CARTPAGE.ts
|
|
60
|
+
- Field lists come from the per-tenant `CARTPAGE.ts`, read through `useAssignClientFields(fieldKey, language, user).fields.CARTPAGEFIELDS`.
|
|
62
61
|
|
|
63
62
|
Hook queries: `useInfiniteQuery(["orderForDelegationList", user.uuid, fieldKey])` in pages of 100, and `useQuery(["orderForDelegationSearch", user.uuid, fieldKey, text])` debounced 400 ms with a 3-character minimum.
|
|
64
63
|
|
|
65
|
-
### 3.
|
|
64
|
+
### 3. `useOrderForZu` — persisted, owner-scoped
|
|
66
65
|
|
|
67
|
-
|
|
66
|
+
`src/stores/useOrderForZu.ts` uses Zustand `persist` with localStorage key **`order-for-zu`**. Stored shape `{ uuid, name, email, ownerUuid }`, where `ownerUuid` is the **signed-in user's** uuid at pick time. Picking yourself is stored too, so the cart knows to reset.
|
|
68
67
|
|
|
69
|
-
`
|
|
68
|
+
- `getOrderForUserFor(pick, ownerUuid)` returns the pick **only** when `pick.ownerUuid === ownerUuid`. A different login, or a view-as target, never inherits it. A stale pick (ownerUuid mismatch) is cleared on cart mount.
|
|
69
|
+
- **Cleared only by:** picking yourself in the header · the cart's clear-user action (`CartPage.handleClearUser` → `clearOrderForUser()`) · logout (`AuthContext.logout`).
|
|
70
|
+
- **Kept across:** order submit (`useSubmitOrder.ts`, `createNewSalesOrderSubmit.ts`), edit-order exit (`exitEditOrderModeGlobalSyncReset.ts`), view-as return (`AuthLayout.returnToYourViewOnClick`), and full page reload. The clears that used to live in those four places were removed.
|
|
70
71
|
|
|
71
|
-
|
|
72
|
-
- `ownerUuid` is the signed-in user who made the pick. `getPendingOrderForUserFor(pending, ownerUuid)` returns `null` for anyone else, so a view-as switch or a new login can never inherit someone else's pick.
|
|
73
|
-
- `EditCart.tsx` applies the pick to `orderFor` as **"Name (email)"** — the exact label shape the cart's own input produces — then clears the store.
|
|
74
|
-
- An `appliedHeaderPickRef` is set **before** `setValue` and checked **both before and after** the mount seed's `await fetchUserByContactUuid(...)`, so a pick made while that fetch is in flight is not overwritten by the saved contact.
|
|
75
|
-
- Header display order: pending pick (newest) → `useSelectedUserZu.selectedUser` → self.
|
|
72
|
+
### 4. Header ↔ cart sync
|
|
76
73
|
|
|
77
|
-
|
|
74
|
+
The cart owns the cascade: `EditCart.tsx` watches the react-hook-form field `orderFor`, fetches the full user, then sets the sales-quote contact, manager name, cost center and notification emails, and stores the full user in `useSelectedUserZu`. The header must **not** duplicate that (~100 lines) and must **not** write `useSelectedUserZu` directly — the cascade needs the *previous* value and a *full* user object.
|
|
78
75
|
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
76
|
+
- `EditCart.tsx` applies the saved pick as **"Name (email)"** (the exact label shape the cart's own input produces) whenever the form's `orderFor` uuid differs from the stored pick. `appliedHeaderPickRef` is set **before** `setValue` and checked **both before and after** the mount seed's `await fetchUserByContactUuid(...)`, so the saved contact cannot overwrite a pick applied while that fetch is in flight.
|
|
77
|
+
- The cart's user-load cascade writes back: `onSuccess` calls `setOrderForUser({ uuid, name: _name, email, ownerUuid: user.uuid })` so header and cart never drift.
|
|
78
|
+
- `onError` calls `handleClearUser()` (required `EditCartTypes` prop passed from `CartPage.tsx`) and raises an error toast from the `CARTPAGE.ts` key `orderFor.settings.loadUserErrorMessage`, with the same string hardcoded as a fallback for tenants without the key.
|
|
79
|
+
- Header display order: stored pick → `useSelectedUserZu.selectedUser` → self.
|
|
82
80
|
|
|
83
|
-
|
|
81
|
+
Rejected: header writes `useSelectedUserZu` directly; header runs its own copy of the cascade.
|
|
84
82
|
|
|
85
|
-
### 5. e2e spec
|
|
83
|
+
### 5. e2e spec
|
|
86
84
|
|
|
87
|
-
`cypress/e2e/homePage/orderForDropdown.cy.ts
|
|
85
|
+
`cypress/e2e/homePage/orderForDropdown.cy.ts` — 4 tests, Compass tenant, **4/4 green**. Asserts the pick survives a route change (via the `account-icon` router Link) and `cy.reload()`, and reads `localStorage['order-for-zu'].state.orderForUser.uuid` / `.ownerUuid` directly.
|
|
88
86
|
|
|
89
87
|
Test ids: `order-for-dropdown`, `order-for-trigger`, `order-for-current-name`, `order-for-menu`, `order-for-search`, `order-for-option`, `order-for-load-more` (mobile variants add `-mobile`).
|
|
90
88
|
|
|
91
89
|
## Gotchas
|
|
92
90
|
|
|
93
|
-
- **
|
|
91
|
+
- **The `ownerUuid` guard is what makes persistence safe — never drop it.** A persisted pick with no owner check is inherited by the next login or by a view-as target and silently orders for the wrong person. Read the store through `getOrderForUserFor(pick, ownerUuid)`, never raw.
|
|
94
92
|
- **Do not set `useSelectedUserZu` from the header.** The cascade reads the *previous* selected user out of the store (see [cart-notification-emails](cart-notification-emails.md)); writing it early makes the previous-user email cleanup a no-op and strands the old person's notification emails on the order.
|
|
95
|
-
- **A missing `orderFor` key renders nothing, by design.** `useAssignClientFields` has no fallback for a missing key, so Compass Canada and Quad get `undefined` and the component returns `null` —
|
|
93
|
+
- **A missing `orderFor` key renders nothing, by design.** `useAssignClientFields` has no fallback for a missing key, so Compass Canada and Quad get `undefined` and the component returns `null` — safe default-off. Adding a tenant means adding the key to every role file for that tenant.
|
|
96
94
|
- **`appliedHeaderPickRef` must be checked after the awaited mount fetch too.** Checking only before the `await fetchUserByContactUuid(...)` lets the saved contact overwrite a pick made while the fetch was in flight.
|
|
97
|
-
- **`_production` and `_sandbox-client` have diverged in `EditCart.tsx`** — `_production` lacks the sandbox delegate-manager code, so a stashed patch will not apply cleanly to that file. To move uncommitted work between branches
|
|
98
|
-
- **Tailwind: `max-h-300px` is not a token**
|
|
95
|
+
- **`_production` and `_sandbox-client` have diverged in `EditCart.tsx`** — `_production` lacks the sandbox delegate-manager code, so a stashed patch will not apply cleanly to that file. To move uncommitted work between branches: `git diff stash@{0}^1 stash@{0} > patch`, dry-run with `git apply --check --3way patch`, then `git apply --3way --exclude=<conflicting file> patch` and hand-port the conflicting file. Keep the stash until the work is committed.
|
|
96
|
+
- **Tailwind: `max-h-300px` is not a token** — use `max-h-[300px]`. `w-345px`, `h-300px`, `border-1` and `shadow-subMenu` do exist.
|
|
97
|
+
|
|
98
|
+
## Change history
|
|
99
|
+
|
|
100
|
+
- 2026-09-17 — Pick is now persisted to `localStorage["order-for-zu"]` with an `ownerUuid` guard (TRUE-81852); the submit / edit-order-exit / view-as-return / reload clears were removed, and the cart writes the loaded user back to the store. Spec now 4/4 green. (tcox)
|
|
101
|
+
- 2026-09-17 — Header order-for pill added (TRUE-81851), in-memory hand-off store, cart clears on failed user load. (tcox)
|
|
99
102
|
|
|
100
103
|
## Related
|
|
101
104
|
|
|
@@ -103,4 +106,5 @@ Test ids: `order-for-dropdown`, `order-for-trigger`, `order-for-current-name`, `
|
|
|
103
106
|
- [client-fields](client-fields.md)
|
|
104
107
|
- [cart-notification-emails](cart-notification-emails.md)
|
|
105
108
|
- [cart-page-config-architecture](cart-page-config-architecture.md)
|
|
109
|
+
- [view-as-session-tokens](view-as-session-tokens.md)
|
|
106
110
|
- [cypress-testing](../workflows/cypress-testing.md)
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: View-as another user — parked admin tokens & return-to-self
|
|
3
|
+
framework: "2.0"
|
|
4
|
+
repo: toga2-commerce
|
|
5
|
+
project: TOGa Commerce
|
|
6
|
+
client: shared
|
|
7
|
+
type: feature
|
|
8
|
+
status: active
|
|
9
|
+
updated: 2026-09-17
|
|
10
|
+
owners: [tcox]
|
|
11
|
+
files:
|
|
12
|
+
- src/api/sessionTokens.ts
|
|
13
|
+
- src/api/apiBaseUrl.ts
|
|
14
|
+
- src/api/axiosInstance.ts
|
|
15
|
+
- src/contexts/AuthContext.tsx
|
|
16
|
+
- src/components/AuthLayout/AuthLayout.tsx
|
|
17
|
+
- src/components/NavIcons/NavIconList.tsx
|
|
18
|
+
- cypress/e2e/viewAs/viewAsUser.cy.ts
|
|
19
|
+
related:
|
|
20
|
+
- 2.0/apps/toga2-commerce/architecture.md
|
|
21
|
+
- 2.0/apps/toga2-commerce/features/header-order-for-dropdown.md
|
|
22
|
+
- 2.0/apps/toga2-commerce/workflows/cypress-testing.md
|
|
23
|
+
- 2.0/apps/api2/architecture.md
|
|
24
|
+
---
|
|
25
|
+
|
|
26
|
+
How an admin impersonates another user and gets back: the delegated token pair, the parked admin pair in localStorage, and the return path. Open before touching auth tokens, the axios refresh, or the view-as button.
|
|
27
|
+
|
|
28
|
+
## Summary
|
|
29
|
+
|
|
30
|
+
TRUE-81852 (commit `a8c3a537`). An admin can browse the storefront **as** another user. Previously, returning to yourself re-minted the admin's tokens through the privileged `/auth/encrypted` call. Now the admin's **own** token pair is parked in localStorage when delegation starts and put back on return — `/auth/encrypted` is no longer called on return at all.
|
|
31
|
+
|
|
32
|
+
All token plumbing lives in **`src/api/sessionTokens.ts`** (new). `src/api/apiBaseUrl.ts` (new) exports `apiBaseUrl` so both the axios instance and the token helpers resolve the same host. `src/utils/auth.ts` and `handleClientAuthentication` / `UserData` in `Login/api/LoginApi.tsx` were dead and were deleted.
|
|
33
|
+
|
|
34
|
+
## How it works
|
|
35
|
+
|
|
36
|
+
### Entering view-as (`NavIconList.tsx` onSuccess)
|
|
37
|
+
|
|
38
|
+
1. `fetchUserTokens(uuid, "/auth/delegator")` mints the delegated pair for the target user.
|
|
39
|
+
2. `beginDelegation(delegatedPair, adminUuid)` parks the admin's current pair under localStorage key **`originalAuthTokens`** as `{ v: 1, access, refresh, userUuid, apiHost, savedAt }`, then writes the delegated pair into `accessToken` / `refreshToken`.
|
|
40
|
+
3. It **never overwrites an existing parked pair** — view-as is one level deep. `isViewAsEnabled` also hides the button when `hasSavedOriginalTokens()` is true.
|
|
41
|
+
4. On any error entering view-as, it rolls back: `restoreOriginalTokens` if a pair is parked, plus `clearOriginalUser()`.
|
|
42
|
+
|
|
43
|
+
### Returning (`AuthLayout.returnToYourViewOnClick`)
|
|
44
|
+
|
|
45
|
+
`restoreOriginalTokens(adminUuid)`:
|
|
46
|
+
|
|
47
|
+
1. Checks `userUuid` **and** `apiHost` match, and age ≤ `PARKED_PAIR_MAX_AGE_MS` (**12h**). It **always removes** the parked key, pass or fail.
|
|
48
|
+
2. On success: puts the admin pair back; if the access JWT is expired (`isAccessTokenExpired` decodes `exp`), calls `refreshAuthTokens()` once **before** the cache clear.
|
|
49
|
+
3. On failure: logs a Sentry warning, clears the view-as store, logs out, navigates to `/`. There is **no** `/auth/encrypted` fallback.
|
|
50
|
+
4. Removes `localStorage["commerce"]` (the persisted react-query cache) so the impersonated user's rows cannot rehydrate under the admin.
|
|
51
|
+
|
|
52
|
+
### Where else the parked pair is cleared
|
|
53
|
+
|
|
54
|
+
`login()` clears it (and the view-as store) first; `fetchPublicToken` and `performLogout` clear it; module load sweeps it when there is no `accessToken`.
|
|
55
|
+
|
|
56
|
+
### Refresh safety (`axiosInstance.ts`)
|
|
57
|
+
|
|
58
|
+
The 401 refresh is **single-flight** (one module-level promise shared by concurrent 401s) and **identity-bound**: `requestRefreshedTokens` returns `null` if `localStorage.refreshToken` changed while the refresh was in flight. That stops an in-flight admin refresh from overwriting a just-minted delegated pair (or the reverse).
|
|
59
|
+
|
|
60
|
+
### Decisions (CSO review — SHIP WITH FIXES)
|
|
61
|
+
|
|
62
|
+
Identity-bound refresh · one-level view-as · 12h max parked age · no `/auth/encrypted` fallback (log out instead) · never put error objects in `JSON.parse` failure logs · match on `apiHost` only (clientId dropped).
|
|
63
|
+
|
|
64
|
+
### e2e (`cypress/e2e/viewAs/viewAsUser.cy.ts`)
|
|
65
|
+
|
|
66
|
+
Seeds a long-lived `ADMIN_ACCESS_JWT`; stubs `/auth/delegator` → `mock-delegated-access-token` / `-refresh`, and `**/v2/pages/meta?page=home-page&app=commerce*`; the fetchUser stub matches on a RegExp over the `?fields=uuid,_name,...` list. Asserts: delegated pair active + parked pair present; after return, `accessToken === ADMIN_ACCESS_JWT`, parked key null, and **zero** calls to `/auth/encrypted`. 1/1 green.
|
|
67
|
+
|
|
68
|
+
## Gotchas
|
|
69
|
+
|
|
70
|
+
- **Never re-mint the admin's tokens on return.** The old `/auth/encrypted` path was a privileged call made from the browser. Restore the parked pair, or log out — those are the only two outcomes.
|
|
71
|
+
- **Always remove `originalAuthTokens`, even on a failed restore.** Leaving a stale parked pair blocks the next view-as (`beginDelegation` refuses to overwrite) and keeps an old admin refresh token on disk.
|
|
72
|
+
- **Clear `localStorage["commerce"]` on return.** The persisted query cache is shared; without the clear, the impersonated user's data rehydrates under the admin identity (see the 24h persisted-cache gotcha in [architecture](../architecture.md)).
|
|
73
|
+
- **Keep the refresh identity-bound.** A refresh that resolves after the identity changed must return `null`, not write tokens.
|
|
74
|
+
- **A view-as test must stub `/v2/pages/meta?page=home-page&app=commerce`.** Unstubbed, the real call fails and triggers the enter-view-as rollback, so the spec sees a return-to-admin it did not ask for.
|
|
75
|
+
|
|
76
|
+
## Open items (out of ticket, not fixed)
|
|
77
|
+
|
|
78
|
+
- `SENTRY_AUTH_TOKEN` is committed in 25 tracked `.env*` files — treat it as compromised and rotate it. (Never store the value in this KB.)
|
|
79
|
+
- Confirm api2 authorizes `/auth/delegator` **server-side** as admin-only; the client-side gate is not a control.
|
|
80
|
+
|
|
81
|
+
## Change history
|
|
82
|
+
|
|
83
|
+
- 2026-09-17 — Created. Admin pair parked in `originalAuthTokens` on delegation and restored on return; `/auth/encrypted` re-mint removed; single-flight identity-bound refresh (TRUE-81852, commit a8c3a537). (tcox)
|
|
84
|
+
|
|
85
|
+
## Related
|
|
86
|
+
|
|
87
|
+
- [architecture](../architecture.md)
|
|
88
|
+
- [header-order-for-dropdown](header-order-for-dropdown.md)
|
|
89
|
+
- [cypress-testing](../workflows/cypress-testing.md)
|
|
90
|
+
- [api2 architecture](../../api2/architecture.md)
|
|
@@ -11,12 +11,12 @@ owners: [tcox]
|
|
|
11
11
|
files:
|
|
12
12
|
- toga2-commerce/cypress/e2e/cartPage/cartV2.cy.ts
|
|
13
13
|
- toga2-commerce/cypress/e2e/homePage/orderForDropdown.cy.ts
|
|
14
|
+
- toga2-commerce/cypress/e2e/viewAs/viewAsUser.cy.ts
|
|
14
15
|
- toga2-commerce/cypress/fixtures/cart/fetchUserShippingMethods.json
|
|
15
16
|
- toga2-commerce/cypress/support/commands.ts
|
|
16
17
|
- toga2-commerce/cypress/support/e2e.ts
|
|
17
18
|
- toga2-commerce/src/pages/Cart/CartPage.tsx
|
|
18
19
|
- toga2-commerce/src/pages/Cart/view/cartForm/CartForm.tsx
|
|
19
|
-
- toga2-commerce/src/pages/Cart/view/cartForm/CartFormSection.tsx
|
|
20
20
|
- toga2-commerce/src/pages/Cart/view/cartTable/CartContentsTable.tsx
|
|
21
21
|
- toga2-commerce/src/pages/Cart/view/cartTable/CartTableItem.tsx
|
|
22
22
|
- toga2-commerce/src/components/Inputs/AdvancedInput.tsx
|
|
@@ -27,6 +27,7 @@ related:
|
|
|
27
27
|
- 2.0/apps/toga2-commerce/features/expedited-shipping-gating.md
|
|
28
28
|
- 2.0/apps/toga2-commerce/features/cart-bundle-submission-and-identity.md
|
|
29
29
|
- 2.0/apps/toga2-commerce/features/header-order-for-dropdown.md
|
|
30
|
+
- 2.0/apps/toga2-commerce/features/view-as-session-tokens.md
|
|
30
31
|
- 2.0/apps/toga25-supply/workflows/cypress-testing.md
|
|
31
32
|
---
|
|
32
33
|
|
|
@@ -100,7 +101,12 @@ The cart UI was instrumented with `data-testid` attributes so specs anchor on **
|
|
|
100
101
|
|
|
101
102
|
### Other active specs
|
|
102
103
|
|
|
103
|
-
- `cypress/e2e/homePage/orderForDropdown.cy.ts`
|
|
104
|
+
- `cypress/e2e/homePage/orderForDropdown.cy.ts` — the header order-for pill, COMPASS only, 4 tests, **4/4 green**. Asserts the pick survives a route change and `cy.reload()` by reading `localStorage['order-for-zu']`. Ids `order-for-*` (see [header-order-for-dropdown](../features/header-order-for-dropdown.md)).
|
|
105
|
+
- `cypress/e2e/viewAs/viewAsUser.cy.ts` — admin view-as enter/return, **1/1 green**. Seeds a long-lived admin JWT, stubs `/auth/delegator` and `**/v2/pages/meta?page=home-page&app=commerce*` (see [view-as-session-tokens](../features/view-as-session-tokens.md)).
|
|
106
|
+
|
|
107
|
+
### Known-red specs (pre-existing, not yours)
|
|
108
|
+
|
|
109
|
+
On prod base `aedd1f7a`, Compass tenant: **13 failures** — `getSupportV2` (4), `homePageContentV2` (7), `firstTimeLoggingIn` (2). Reproduced identically on an untouched `git archive aedd1f7a` copy, so they are **not** caused by feature work. Likely cause: the login command's `/users/{uuid}` stub field list no longer matches the app's request, so the call falls through to the real API and 401s. Full Compass suite on the TRUE-81852 feature branch: **54 pass / 13 fail** — the same 13.
|
|
104
110
|
|
|
105
111
|
**Not yet covered — slice 2 work-list:**
|
|
106
112
|
- **Bundle scenarios** — blocked on the stale bundle seeds (rebuild `seedCartBundle` / `seedSalesQuoteBundle` first, above).
|
|
@@ -114,13 +120,24 @@ The cart UI was instrumented with `data-testid` attributes so specs anchor on **
|
|
|
114
120
|
2. Start the **dev server separately** first: `npm run compass` | `npm run compasscanada` | `npm run quad`.
|
|
115
121
|
3. **Windows invocation:** `$env:TENANT="compass"; npm run cypress` — `cross-env` is **not** installed, so set the env var in the shell.
|
|
116
122
|
4. Requires **hosts-file entries** `127.0.0.1 compass|compasscanada|quad.togacommerce` (present on this machine but **undocumented in the README** — a new dev must add them).
|
|
123
|
+
5. Headless run (works despite there being no npm script): `Remove-Item Env:ELECTRON_RUN_AS_NODE` first (see gotcha), then `$env:TENANT="compass"; npx cypress run --env TENANT=compass` with vite dev serving `http://compass.togacommerce:5173`.
|
|
117
124
|
|
|
118
125
|
## Gotchas
|
|
119
126
|
|
|
127
|
+
- **`ELECTRON_RUN_AS_NODE=1` breaks every spec in a VS Code terminal.** VS Code's integrated terminals set it, and `npx cypress run` then fails verification on every spec with `Cypress.exe ... bad option: --smoke-test`. Fix: `Remove-Item Env:ELECTRON_RUN_AS_NODE` in that shell before running. Reinstalling the Cypress binary does **not** help.
|
|
128
|
+
- **The users API URL-encodes hyphens as `%2D`.** A glob like `**/v2/users?*no-such*` never matches — use a hyphen-free search term in the test, or match with a RegExp.
|
|
129
|
+
- **"Get Support" in the header is a plain `<a>`** (full page reload). To test that state survives a *route change*, click `account-icon` — that one is a router `Link`.
|
|
130
|
+
- **The `EnvironmentBadge` covers the header corner.** For outside-click tests, click `header-search-input` instead of the corner.
|
|
131
|
+
- **A later `cy.intercept` wins over an earlier one for the same URL** — define the narrow override after the general stub, not before.
|
|
120
132
|
- **`BaseButton` never sets the native `disabled` attribute (test-critical).** `src/components/BaseButton/BaseButton.tsx` sets `aria-disabled="true"|"false"` and suppresses `onClick` inside `handleClick` — it deliberately leaves the element enabled so a disabled button (e.g. **Proceed to Checkout**) still receives mouse events and its `BaseTooltip` (*"Please complete all required fields to proceed."*) works. Cypress assertions **MUST** use `.should('have.attr', 'aria-disabled', 'true'|'false')`, **never** `.should('be.disabled')` — `be.disabled` times out even though the button is visually/functionally disabled. (This cost the only 2 first-run failures.)
|
|
121
133
|
- **Seed → then `cy.visit('/cart')`.** The persist stores rehydrate on load only; seeding `localStorage` and navigating in-app leaves the stores stale (see seeding section).
|
|
122
134
|
- **Bundle seeds are on the legacy shape** — do not write a bundle spec against them until they are rebuilt to the `bundleZuCartUuid` + `bundleProgressContents` contract.
|
|
123
|
-
- **ESLint fails repo-wide in a fresh checkout** because `.eslintrc.cjs` references `eslint-plugin-react-compiler`, which is not installed; `npm install --save-dev eslint-plugin-react-compiler` fixes it. To lint without touching the checkout, run `eslint --no-eslintrc
|
|
135
|
+
- **ESLint fails repo-wide in a fresh checkout** because `.eslintrc.cjs` references `eslint-plugin-react-compiler`, which is not installed; `npm install --save-dev eslint-plugin-react-compiler` fixes it. To lint without touching the checkout, run `npx eslint --no-eslintrc --plugin react-hooks --plugin @typescript-eslint <files>`. This is a local-environment issue, not a spec problem.
|
|
136
|
+
|
|
137
|
+
## Change history
|
|
138
|
+
|
|
139
|
+
- 2026-09-17 — Added `viewAsUser.cy.ts`; orderForDropdown now green; recorded the `ELECTRON_RUN_AS_NODE` failure, the intercept pitfalls, and the 13 pre-existing red specs on base `aedd1f7a`. (tcox)
|
|
140
|
+
- 2026-09-17 — Created with the V2 convention set and the `cartV2.cy.ts` cart harness (slice 1). (tcox)
|
|
124
141
|
|
|
125
142
|
## Related
|
|
126
143
|
|
|
@@ -128,4 +145,6 @@ The cart UI was instrumented with `data-testid` attributes so specs anchor on **
|
|
|
128
145
|
- [cart-notification-emails](../features/cart-notification-emails.md)
|
|
129
146
|
- [expedited-shipping-gating](../features/expedited-shipping-gating.md)
|
|
130
147
|
- [cart-bundle-submission-and-identity](../features/cart-bundle-submission-and-identity.md)
|
|
148
|
+
- [header-order-for-dropdown](../features/header-order-for-dropdown.md)
|
|
149
|
+
- [view-as-session-tokens](../features/view-as-session-tokens.md)
|
|
131
150
|
- [toga25-supply Cypress harness](../../toga25-supply/workflows/cypress-testing.md)
|
package/knowledge/INDEX.md
CHANGED
|
@@ -31,7 +31,7 @@ _Auto-generated by `knowledge.js index`. Do not hand-edit._
|
|
|
31
31
|
- **talos-backend** (TOGa IQ Backend) — 1 doc(s) → [2.0/apps/talos-backend/INDEX.md](2.0/apps/talos-backend/INDEX.md)
|
|
32
32
|
- **voice-to-voice** (TOGa Voice) — 4 doc(s) → [2.0/apps/voice-to-voice/INDEX.md](2.0/apps/voice-to-voice/INDEX.md)
|
|
33
33
|
- **ai-bdr** (AI-BDR) — 13 doc(s) → [2.0/apps/ai-bdr/INDEX.md](2.0/apps/ai-bdr/INDEX.md)
|
|
34
|
-
- **toga2-commerce** (TOGa Commerce) —
|
|
34
|
+
- **toga2-commerce** (TOGa Commerce) — 24 doc(s) → [2.0/apps/toga2-commerce/INDEX.md](2.0/apps/toga2-commerce/INDEX.md)
|
|
35
35
|
- **toga25-supply** (TOGa 2.5 Supply) — 21 doc(s) → [2.0/apps/toga25-supply/INDEX.md](2.0/apps/toga25-supply/INDEX.md)
|
|
36
36
|
- **toga-blox** (TOGa Blox) — 14 doc(s) → [2.0/apps/toga-blox/INDEX.md](2.0/apps/toga-blox/INDEX.md)
|
|
37
37
|
- **bdr** (BDR) — 0 doc(s) → [2.0/apps/bdr/INDEX.md](2.0/apps/bdr/INDEX.md)
|
package/package.json
CHANGED