fsanyoto commited on
Commit
da5297e
Β·
verified Β·
1 Parent(s): f6c60ab

Deploy AIOS web (React glide grid + FastAPI slice)

Browse files
This view is limited to 50 files because it contains too many changes. Β  See raw diff
Files changed (50) hide show
  1. api/main.py +356 -354
  2. api/pages.py +10 -4
  3. api/routes_admin.py +414 -1
  4. api/routes_customers.py +328 -264
  5. api/routes_grid.py +89 -7
  6. api/routes_pages.py +7 -8
  7. api/routes_products.py +197 -0
  8. royalimports_os/aios_grid.py +65 -21
  9. royalimports_os/aios_grid_fields.json +340 -230
  10. royalimports_os/core/grid_events.py +41 -13
  11. royalimports_os/core/perm_migrate.py +156 -0
  12. royalimports_os/core/perm_scope.py +286 -0
  13. royalimports_os/core/perms.py +13 -1
  14. royalimports_os/core/registry.py +39 -8
  15. royalimports_os/core/users.py +36 -5
  16. royalimports_os/harness/analyst.py +55 -2
  17. royalimports_os/harness/filter_eval.py +485 -0
  18. royalimports_os/modules/customer_data.py +4 -0
  19. royalimports_os/modules/digest.py +4 -1
  20. royalimports_os/modules/product_data.py +146 -0
  21. web/dist-embed/index.html +0 -0
  22. web/src/customer-grid/ColumnMenu.tsx +0 -0
  23. web/src/customer-grid/CustomerGrid.tsx +0 -0
  24. web/src/customer-grid/Toolbar.tsx +0 -0
  25. web/src/customer-grid/ViewSidebar.tsx +0 -0
  26. web/src/customer-grid/apiBridge.ts +43 -22
  27. web/src/customer-grid/clipboard.ts +66 -5
  28. web/src/customer-grid/cohortRail.ts +92 -0
  29. web/src/customer-grid/iconShapes.ts +9 -1
  30. web/src/customer-grid/icons.tsx +2 -1
  31. web/src/customer-grid/theme.ts +92 -48
  32. web/src/customer-grid/timeSeriesData.ts +112 -0
  33. web/src/customer-grid/types.ts +86 -0
  34. web/src/customer-grid/useCustomerData.ts +16 -6
  35. web/src/customer-grid/useGridColumns.ts +349 -327
  36. web/src/customer-grid/viewModes.tsx +831 -831
  37. web/src/filter-kit/FieldsHidePanel.tsx +318 -0
  38. web/src/filter-kit/FilterBuilderPanel.tsx +982 -0
  39. web/src/filter-kit/Popover.tsx +130 -0
  40. web/src/filter-kit/WindowPicker.tsx +93 -0
  41. web/src/filter-kit/index.ts +22 -0
  42. web/src/filter-kit/ops.ts +380 -0
  43. web/src/index.css +297 -25
  44. web/src/settings/PermsEditor.tsx +388 -0
  45. web/src/settings/SettingsModal.tsx +158 -81
  46. web/src/settings/permsModel.ts +434 -0
  47. web/src/settings/settingsApi.ts +60 -3
  48. web/src/shell/Shell.tsx +28 -9
  49. web/src/shell/nav.ts +23 -17
  50. web/src/viz/DashboardView.css +67 -0
api/main.py CHANGED
@@ -1,354 +1,356 @@
1
- """AIOS web API β€” the ONE shared, stateless process the Streamlit exit is aimed at.
2
-
3
- It REUSES the `royalimports_os/` data layer verbatim (nothing re-implemented): the canonical,
4
- reconciled Odoo model stays server-side and the browser only ever sees derived JSON. Serves the
5
- JSON API under `/api/*` and the built React bundle (`aios-web/web/dist`) at `/`.
6
-
7
- WHAT CHANGED IN EXIT WAVE 1 (2026-07-30) β€” three things, all of them load-bearing:
8
-
9
- * **Real sessions replace HTTP Basic.** The whole app used to sit behind one shared
10
- `APP_PASSWORD` with the browser's native Basic prompt, which means every caller was the same
11
- anonymous principal and no route could scope anything. Now a signed stateless cookie carries
12
- a real `core/users` identity (X3), and every v1 route resolves BU + own-book scope from the
13
- user RECORD. `/api/health` stays unauthenticated (liveness only).
14
- * **The overlay fork is deleted.** `aios-web/api/data/overlay.json` was a second writable home
15
- for user-owned fields the Streamlit app keeps in the tenant store. ONE store now (C1c).
16
- * **The SSL shim is env-gated.** It used to run at import, unconditionally.
17
-
18
- ⚠ TENANT RESOLUTION IS PER REQUEST (X7). Nothing tenant-shaped is held at module level; the
19
- session's tenant claim resolves through `harness.runtime.get_runtime`, which is LRU-bounded. This
20
- is the rule the ~30–80 MB/tenant target depends on β€” EXIT-0 measured the alternative at a ~0.6 GB
21
- commit FLOOR per tenant, duplicated within 2% per tenant, nothing shared.
22
- """
23
- import os
24
- import sys
25
- from pathlib import Path
26
-
27
- # --- the local Odoo SSL quirk, now BEHIND A GATE -------------------------------------------------
28
- # The Windows trust store reports the (valid) Odoo cert as expired, so local runs need an
29
- # unverified default context; the HF Space and the container are unaffected. This used to run
30
- # unconditionally at import β€” i.e. the shipped container disabled TLS verification for every
31
- # outbound HTTPS call it ever made, to Odoo and to everything else, forever. That is a
32
- # man-in-the-middle away from being someone else's data. It is now opt-in, must be set
33
- # deliberately, and is never on by default.
34
- # β›” NEVER set AIOS_INSECURE_SSL in a deployed environment. It exists for one developer laptop.
35
- if os.environ.get("AIOS_INSECURE_SSL") == "1":
36
- import ssl
37
- ssl._create_default_https_context = ssl._create_unverified_context # noqa: S323
38
-
39
- # --- reuse the tenant #0 data layer verbatim. RI_DIR overrides the location in the container
40
- # (where the layout differs from the local sibling-dir default). ---
41
- _HERE = Path(__file__).resolve()
42
- _RI = Path(os.environ.get("RI_DIR") or (_HERE.parents[2] / "royalimports_os"))
43
- for _p in (str(_RI), str(_HERE.parent)):
44
- if _p not in sys.path:
45
- sys.path.insert(0, _p)
46
-
47
- from dotenv import load_dotenv # noqa: E402
48
- load_dotenv(_RI / ".env") # Odoo creds + APP_PASSWORD, git-ignored, never committed/printed
49
-
50
- from fastapi import Body, Depends, FastAPI, Request # noqa: E402
51
- from fastapi.middleware.gzip import GZipMiddleware # noqa: E402
52
- from fastapi.responses import JSONResponse # noqa: E402
53
- from fastapi.staticfiles import StaticFiles # noqa: E402
54
- from starlette.exceptions import HTTPException as StarletteHTTPException # noqa: E402
55
-
56
- import aios_session # noqa: E402
57
- import routes_admin # noqa: E402
58
- import routes_auth # noqa: E402
59
- import routes_customers # noqa: E402
60
- import routes_grid # noqa: E402
61
- import routes_nav # noqa: E402
62
- import routes_pages # noqa: E402
63
- import routes_records # noqa: E402
64
- from core import grid_events # noqa: E402
65
- from deps import Session, module_gate # noqa: E402
66
-
67
- _WEB_DIST = _HERE.parents[1] / "web" / "dist"
68
-
69
- # --- THE CANONICAL FIELD CONTRACT: a startup assertion, and the referee gate's subject ----------
70
- # Every field tags its semantic TYPE and its SOURCE. `source='odoo'` is READ-ONLY (Odoo is never
71
- # written); `source='overlay'` is the editable stratum that lives OUTSIDE Odoo. Loaded from the
72
- # ONE canonical file shared with the embedded host (`royalimports_os/aios_grid_fields.json`), so
73
- # embed == standalone by construction.
74
- #
75
- # TWO REASONS THIS IS HERE and not folded into the routes:
76
- # 1. It FAILS LOUDLY at import when the file is missing β€” which means the deploy or the RI_DIR
77
- # layout is broken, and discovering that from a 500 on the first customer request instead of
78
- # at startup costs a debugging session. (The pre-wave main.py had this guard; the EXIT-2a
79
- # rewrite dropped it and this restores it.)
80
- # 2. `aios-web/verify_fields_contract.py` β€” the cross-side REFEREE β€” reads `FIELDS` and
81
- # `_PASSTHROUGH_KEYS` from this module to prove the canonical file, `aios_grid.py` and this
82
- # API have not drifted. The rewrite removed them and the referee went red; retargeting the
83
- # gate would have been the wrong repair ([[gate-can-report-green-on-nothing]]: retarget, do
84
- # not delete β€” but only when the subject genuinely moved. Here it should not have moved).
85
- #
86
- # ⚠ THE ROUTES SERVE A SUPERSET OF THIS. `routes_customers._payload` derives its field list from
87
- # `aios_grid.fields_from_workspace(ws)`, which is `FIELDS` PLUS the session user's own custom_ and
88
- # measure_ columns β€” the same list the Streamlit host renders. That is the point: the standalone
89
- # shell now sees the user's own columns instead of the bare base contract. `FIELDS` is the
90
- # canonical FLOOR, asserted below to be exactly what `aios_grid` starts from.
91
- import json as _json_contract # noqa: E402
92
- _FIELDS_PATH = _RI / "aios_grid_fields.json"
93
- if not _FIELDS_PATH.is_file():
94
- raise FileNotFoundError(
95
- f"AIOS web API: canonical field contract missing at {_FIELDS_PATH}. Set RI_DIR to the "
96
- "royalimports_os root (it also carries the data layer this API imports)."
97
- )
98
- _contract = _json_contract.loads(_FIELDS_PATH.read_text(encoding="utf-8"))
99
- FIELDS = _contract["fields"] if isinstance(_contract, dict) else _contract
100
- # text/status/select/date pass through untouched; every OTHER odoo field is numeric -> rounded.
101
- # Derived from field TYPE (not a hand-kept key list) so a new text/date field can never be
102
- # wrongly rounded. `select` joined 2026-08-02 (dba) β€” a choice label rounded would be garbage.
103
- _PASSTHROUGH_KEYS = {f["key"] for f in FIELDS
104
- if f["source"] == "odoo" and f["type"] in ("text", "status", "select",
105
- "date")}
106
-
107
- app = FastAPI(title="AIOS web API")
108
-
109
- # The customers payload measured 1.15 MB of JSON on the live Space, shipped UNCOMPRESSED β€” with
110
- # the 754 KB bundle behind it, most of "the app is slow" was bytes on the wire. gzip takes the
111
- # payload to ~10–15% of that. minimum_size spares the tiny acks the overhead.
112
- app.add_middleware(GZipMiddleware, minimum_size=1024)
113
-
114
-
115
- @app.exception_handler(StarletteHTTPException)
116
- def _error_shape(request: Request, exc: StarletteHTTPException):
117
- """ONE error shape for every non-2xx (X2): `{"error": {"code", "message"}}`.
118
-
119
- `deps.err` already raises detail in that shape; anything FastAPI raises on its own (a 404, a
120
- 422 from a malformed path param) is wrapped here so a client never has to branch on two
121
- different error bodies.
122
- """
123
- detail = exc.detail
124
- if isinstance(detail, dict) and "error" in detail:
125
- body = detail
126
- else:
127
- body = {"error": {"code": f"http_{exc.status_code}", "message": str(detail)}}
128
- return JSONResponse(body, status_code=exc.status_code,
129
- headers=getattr(exc, "headers", None))
130
-
131
-
132
- @app.exception_handler(grid_events.StoreUnavailable)
133
- def _store_unavailable(request: Request, exc: grid_events.StoreUnavailable):
134
- """THE SAFETY NET for "the store is down" β†’ 503, from anywhere.
135
-
136
- ⚠ WHY THIS IS APP-LEVEL AND NOT A `try` PER ROUTE. It was a try per route first, and a
137
- `StoreUnavailable` raised while BUILDING THE PAYLOAD β€” before the route reached its own
138
- try/except β€” surfaced as a 500. A store outage is a normal operational state and every route
139
- here touches the store at least twice (the workspace read, then the write), so "remember to
140
- wrap it" is a rule that gets forgotten once and then reports the wrong thing. One handler
141
- means a store outage can only ever be a 503, whichever call raised it.
142
-
143
- The seam raises this only when the caller passed no `fallback_ws` β€” i.e. exactly on this
144
- adapter, which has no durable session dict to degrade into. A 200 over a write that
145
- evaporated is the failure the whole rule exists to prevent.
146
- """
147
- return JSONResponse(
148
- {"error": {"code": "store_unavailable",
149
- "message": "the tenant store is unavailable β€” no change was saved"}},
150
- status_code=503)
151
-
152
-
153
- @app.get("/api/health")
154
- def health():
155
- """Unauthenticated LIVENESS only β€” it must answer before anyone can sign in, so it may not
156
- reveal anything about the deployment beyond "the process is up". No version, no tenant list,
157
- no config: a health endpoint is the one URL every scanner finds first."""
158
- return {"ok": True}
159
-
160
-
161
- app.include_router(routes_auth.router)
162
- app.include_router(routes_nav.router)
163
- app.include_router(routes_customers.router)
164
- app.include_router(routes_grid.router)
165
- app.include_router(routes_records.router)
166
- # EXIT wave 2: the Y1 page-data envelope (one route for every ported dashboard) and Y4's user
167
- # administration. `routes_pages` imports `pages`, which lazily imports each `pages_*` builder β€” so
168
- # a new page is a builder module plus one registry line, and nothing here changes.
169
- app.include_router(routes_pages.router)
170
- app.include_router(routes_admin.router)
171
-
172
-
173
- # --- DEPRECATED ALIASES (removed when S2's shell flips; kept so the current bundle keeps working)
174
- # They are the v1 handlers with the v1 session requirement β€” NOT the old unauthenticated Basic
175
- # behavior. An alias that kept the old auth would be a bypass of everything above it.
176
- _GATE = module_gate(routes_customers.MODULE)
177
-
178
-
179
- @app.get("/api/customers", deprecated=True)
180
- def _customers_alias(session: Session = Depends(_GATE)):
181
- return routes_customers._payload(session)
182
-
183
-
184
- @app.patch("/api/customers/{pid}", deprecated=True)
185
- def _patch_alias(pid: int, body: dict = Body(default=None),
186
- session: Session = Depends(_GATE)):
187
- return routes_customers.patch_customer(pid, body, session)
188
-
189
-
190
- def _assert_contract_floor():
191
- """The canonical FIELDS must be exactly what `aios_grid` starts an empty workspace from.
192
-
193
- This is what stops `FIELDS` becoming a constant that exists only to satisfy a gate. If the
194
- canonical JSON and `aios_grid.fields_from_workspace({})` ever disagree, the standalone API and
195
- the embedded host are serving two different schemas and the grid's own contract has forked β€”
196
- the exact drift `verify_fields_contract.py` was written to catch, now also caught at startup
197
- on whatever machine is actually running.
198
- """
199
- import aios_grid
200
- base = [f for f in aios_grid.fields_from_workspace({}) if not f.get("custom")]
201
- if [f["key"] for f in base] != [f["key"] for f in FIELDS]:
202
- raise RuntimeError(
203
- "AIOS web API: the canonical field contract and aios_grid.fields_from_workspace({}) "
204
- "disagree on the base field set β€” embed and standalone would serve different schemas. "
205
- "Run aios-web/verify_fields_contract.py.")
206
-
207
-
208
- def _startup_notes():
209
- """Say the two things an operator must know, once, at import β€” never in a response body."""
210
- if aios_session.EPHEMERAL_SECRET:
211
- print("[aios-api] AIOS_SESSION_SECRET is not set β€” signing with a random per-process "
212
- "key. Sessions will not survive a restart and will not work across workers. "
213
- "Set it in production.")
214
- if os.environ.get("AIOS_INSECURE_SSL") == "1":
215
- print("[aios-api] AIOS_INSECURE_SSL=1 β€” TLS verification is DISABLED for outbound "
216
- "requests. Local development only; never in a deployed environment.")
217
-
218
-
219
- _assert_contract_floor()
220
- _startup_notes()
221
-
222
-
223
- # β›” THE STATIC MOUNT IS NOW UNAUTHENTICATED, and that is a change this wave made on purpose.
224
- # Before EXIT-3a, `BasicAuth` middleware gated the WHOLE app including this mount. A branded login
225
- # page cannot live behind a password prompt, so the shell's own assets must be public β€” which they
226
- # are: `index.html`, the JS/CSS bundle and the favicon reveal nothing.
227
- #
228
- # ⚠ WHAT THAT SILENTLY DE-GATED, caught in review rather than in production. `web/dist/` also
229
- # carries `sample_customers.json`, a DEV FIXTURE copied from `web/public/`. Its 8 customers are
230
- # synthetic, but the `agent` column holds REAL EMPLOYEE NAMES, and it went from Basic-gated to
231
- # publicly fetchable in this commit. Nothing needs it: both the API bridge and `useCustomerData`
232
- # deleted their sample fallback on purpose ("NOTHING HERE FALLS BACK TO sample_customers.json"),
233
- # and it survives only because it sits in `web/public/`. So it is refused here β€” 404, the same
234
- # answer as any other path that is not part of the app.
235
- #
236
- # The right long-term fix is deleting it from `web/public/` (S2's lane β€” flagged in the mailbox);
237
- # this guard is what makes the API safe regardless of what the bundle happens to contain.
238
- _DEV_FIXTURES = {"sample_customers.json"}
239
-
240
-
241
- class _AppStatic(StaticFiles):
242
- async def get_response(self, path, scope):
243
- if Path(path).name in _DEV_FIXTURES:
244
- raise StarletteHTTPException(status_code=404, detail="Not Found")
245
- resp = await super().get_response(path, scope)
246
- # Vite content-hashes everything under assets/ (a change is a NEW url), so those are
247
- # immutable β€” a repeat visit re-downloads zero bytes instead of the whole 750 KB bundle.
248
- # index.html must stay revalidated or a deploy would strand returning browsers on the old
249
- # bundle; ETag/304 makes that revalidation a header exchange, not a transfer.
250
- # ⚠ Normalised first: on a Windows host StaticFiles hands this path with backslashes,
251
- # and `startswith("assets/")` silently skipped every asset (measured on the local probe).
252
- if path.replace("\\", "/").lstrip("/").startswith("assets/"):
253
- resp.headers["Cache-Control"] = "public, max-age=31536000, immutable"
254
- else:
255
- resp.headers["Cache-Control"] = "no-cache"
256
- return resp
257
-
258
-
259
- # static bundle LAST so /api/* wins; html=True serves index.html at / plus the built assets
260
- if _WEB_DIST.is_dir():
261
- app.mount("/", _AppStatic(directory=str(_WEB_DIST), html=True), name="web")
262
-
263
-
264
- # --- boot prewarm (AIOS_PREWARM=1 β€” set by the Dockerfile, never by tests) -----------------------
265
- # Without this, the first visitor after every deploy/restart pays the full Odoo pool build in
266
- # their request. The thread warms the CONSOLIDATED scope (None, None) + every registered page's
267
- # default envelope; scoped users still pay their own scope's first build, once.
268
- # Env-gated rather than a startup event so importing `api.main` in a gate (verify_api and friends
269
- # run against fakes) can never fire a live Odoo pull.
270
- def _seed_and_sync_store():
271
- """Bring the analytical store (harness.datastore) LIVE for this container β€” the app.py
272
- bootstrap, mirrored (2026-07-31, owner item 1).
273
-
274
- `harness.datastore` powers every measure column/condition, and ONLY app.py used to call
275
- `ensure_seed()` β€” so on a fresh Space disk this container resolved measures against a store
276
- that never existed and every measure cell served blank. Seeding alone was NOT enough either,
277
- and that was measured live the same day: "datastore seeded in 1.7s" followed by an endless
278
- `api:measure-column: ModelError the data cache is still warming up` β€” `ready()` demands
279
- EVERY entity at phase 'live', and a seed that predates a newer entity leaves it un-synced
280
- forever in a process with no sync loop. The SYNC SPRINT after the seed is what closes the
281
- write_date gap and backfills anything the seed lacks (app.py:7779's exact pattern, bounded
282
- passes). Fail-quiet throughout: no seed/token/Odoo β†’ the columns stay blank, the rows still
283
- serve.
284
- """
285
- import time as _t
286
- t0 = _t.time()
287
- try:
288
- from harness import datastore as _ds
289
- if _ds.ensure_seed():
290
- print(f"[aios-api] datastore seeded in {_t.time() - t0:.1f}s")
291
- # DEDICATED Odoo connection for this thread (the W6 postmortem rule): the sync's
292
- # search_reads must never interleave on the shared client's xmlrpc transport.
293
- import core.odoo as _odoo
294
- try:
295
- _odoo._tlocal.client = _odoo.OdooClient()
296
- except Exception:
297
- pass
298
- res = {}
299
- for i in range(12):
300
- res = _ds.sync_all(log=lambda *a, **k: None)
301
- print(f"[aios-api] datastore sync pass {i + 1}: "
302
- + ", ".join(f"{k}={v.get('phase')}" for k, v in sorted(res.items())))
303
- if all(v.get("phase") == "live" for v in res.values()):
304
- break
305
- print(f"[aios-api] datastore sync done in {_t.time() - t0:.1f}s "
306
- f"(ready={_ds.ready()})")
307
- except Exception as e: # noqa: BLE001
308
- print(f"[aios-api] datastore seed/sync skipped: {e}")
309
-
310
-
311
- def _store_resync_loop():
312
- """Keep the analytical mirror current β€” the API-process stand-in for the re-sync the
313
- Streamlit app piggybacks on page renders. Measure memos key on the pool stamp, so a
314
- refreshed pool re-reads the freshly synced store."""
315
- import time as _t
316
- while True:
317
- _t.sleep(1800)
318
- try:
319
- from harness import datastore as _ds
320
- import core.odoo as _odoo
321
- try:
322
- _odoo._tlocal.client = _odoo.OdooClient()
323
- except Exception:
324
- pass
325
- _ds.sync_all(log=lambda *a, **k: None)
326
- except Exception as e: # noqa: BLE001
327
- print(f"[aios-api] store resync failed: {e}")
328
-
329
-
330
- def _prewarm():
331
- import time as _t
332
- t0 = _t.time()
333
- # ⚠ The store sync runs in its OWN thread, never ahead of the pool warm: a stale seed can
334
- # take many minutes of XML-RPC to close, and the first live probe of this arrangement
335
- # showed the pool warm (42s) silently queued behind it β€” the whole app cold for every
336
- # visitor while a background column channel caught up. Measure cells retry via the
337
- # transient rule until the sync lands; nothing else waits on it.
338
- import threading as _th
339
- _th.Thread(target=_seed_and_sync_store, daemon=True, name="store-seed-sync").start()
340
- try:
341
- from harness import runtime as _runtime
342
- rt = _runtime.get_runtime("royal-imports")
343
- routes_customers.warm_default(rt)
344
- import pages as _pages
345
- _pages.warm_default(rt)
346
- print(f"[aios-api] prewarm done in {_t.time() - t0:.1f}s")
347
- except Exception as e: # noqa: BLE001 β€” boot must not die on a warm-up
348
- print(f"[aios-api] prewarm skipped: {e}")
349
-
350
-
351
- if os.environ.get("AIOS_PREWARM") == "1":
352
- import threading as _threading
353
- _threading.Thread(target=_prewarm, daemon=True, name="prewarm").start()
354
- _threading.Thread(target=_store_resync_loop, daemon=True, name="store-resync").start()
 
 
 
1
+ """AIOS web API β€” the ONE shared, stateless process the Streamlit exit is aimed at.
2
+
3
+ It REUSES the `royalimports_os/` data layer verbatim (nothing re-implemented): the canonical,
4
+ reconciled Odoo model stays server-side and the browser only ever sees derived JSON. Serves the
5
+ JSON API under `/api/*` and the built React bundle (`aios-web/web/dist`) at `/`.
6
+
7
+ WHAT CHANGED IN EXIT WAVE 1 (2026-07-30) β€” three things, all of them load-bearing:
8
+
9
+ * **Real sessions replace HTTP Basic.** The whole app used to sit behind one shared
10
+ `APP_PASSWORD` with the browser's native Basic prompt, which means every caller was the same
11
+ anonymous principal and no route could scope anything. Now a signed stateless cookie carries
12
+ a real `core/users` identity (X3), and every v1 route resolves BU + own-book scope from the
13
+ user RECORD. `/api/health` stays unauthenticated (liveness only).
14
+ * **The overlay fork is deleted.** `aios-web/api/data/overlay.json` was a second writable home
15
+ for user-owned fields the Streamlit app keeps in the tenant store. ONE store now (C1c).
16
+ * **The SSL shim is env-gated.** It used to run at import, unconditionally.
17
+
18
+ ⚠ TENANT RESOLUTION IS PER REQUEST (X7). Nothing tenant-shaped is held at module level; the
19
+ session's tenant claim resolves through `harness.runtime.get_runtime`, which is LRU-bounded. This
20
+ is the rule the ~30–80 MB/tenant target depends on β€” EXIT-0 measured the alternative at a ~0.6 GB
21
+ commit FLOOR per tenant, duplicated within 2% per tenant, nothing shared.
22
+ """
23
+ import os
24
+ import sys
25
+ from pathlib import Path
26
+
27
+ # --- the local Odoo SSL quirk, now BEHIND A GATE -------------------------------------------------
28
+ # The Windows trust store reports the (valid) Odoo cert as expired, so local runs need an
29
+ # unverified default context; the HF Space and the container are unaffected. This used to run
30
+ # unconditionally at import β€” i.e. the shipped container disabled TLS verification for every
31
+ # outbound HTTPS call it ever made, to Odoo and to everything else, forever. That is a
32
+ # man-in-the-middle away from being someone else's data. It is now opt-in, must be set
33
+ # deliberately, and is never on by default.
34
+ # β›” NEVER set AIOS_INSECURE_SSL in a deployed environment. It exists for one developer laptop.
35
+ if os.environ.get("AIOS_INSECURE_SSL") == "1":
36
+ import ssl
37
+ ssl._create_default_https_context = ssl._create_unverified_context # noqa: S323
38
+
39
+ # --- reuse the tenant #0 data layer verbatim. RI_DIR overrides the location in the container
40
+ # (where the layout differs from the local sibling-dir default). ---
41
+ _HERE = Path(__file__).resolve()
42
+ _RI = Path(os.environ.get("RI_DIR") or (_HERE.parents[2] / "royalimports_os"))
43
+ for _p in (str(_RI), str(_HERE.parent)):
44
+ if _p not in sys.path:
45
+ sys.path.insert(0, _p)
46
+
47
+ from dotenv import load_dotenv # noqa: E402
48
+ load_dotenv(_RI / ".env") # Odoo creds + APP_PASSWORD, git-ignored, never committed/printed
49
+
50
+ from fastapi import Body, Depends, FastAPI, Request # noqa: E402
51
+ from fastapi.middleware.gzip import GZipMiddleware # noqa: E402
52
+ from fastapi.responses import JSONResponse # noqa: E402
53
+ from fastapi.staticfiles import StaticFiles # noqa: E402
54
+ from starlette.exceptions import HTTPException as StarletteHTTPException # noqa: E402
55
+
56
+ import aios_session # noqa: E402
57
+ import routes_admin # noqa: E402
58
+ import routes_auth # noqa: E402
59
+ import routes_customers # noqa: E402
60
+ import routes_grid # noqa: E402
61
+ import routes_nav # noqa: E402
62
+ import routes_pages # noqa: E402
63
+ import routes_products # noqa: E402 (wave 15 C-TOPIC β€” gated, not yet in the nav)
64
+ import routes_records # noqa: E402
65
+ from core import grid_events # noqa: E402
66
+ from deps import Session, module_gate # noqa: E402
67
+
68
+ _WEB_DIST = _HERE.parents[1] / "web" / "dist"
69
+
70
+ # --- THE CANONICAL FIELD CONTRACT: a startup assertion, and the referee gate's subject ----------
71
+ # Every field tags its semantic TYPE and its SOURCE. `source='odoo'` is READ-ONLY (Odoo is never
72
+ # written); `source='overlay'` is the editable stratum that lives OUTSIDE Odoo. Loaded from the
73
+ # ONE canonical file shared with the embedded host (`royalimports_os/aios_grid_fields.json`), so
74
+ # embed == standalone by construction.
75
+ #
76
+ # TWO REASONS THIS IS HERE and not folded into the routes:
77
+ # 1. It FAILS LOUDLY at import when the file is missing β€” which means the deploy or the RI_DIR
78
+ # layout is broken, and discovering that from a 500 on the first customer request instead of
79
+ # at startup costs a debugging session. (The pre-wave main.py had this guard; the EXIT-2a
80
+ # rewrite dropped it and this restores it.)
81
+ # 2. `aios-web/verify_fields_contract.py` β€” the cross-side REFEREE β€” reads `FIELDS` and
82
+ # `_PASSTHROUGH_KEYS` from this module to prove the canonical file, `aios_grid.py` and this
83
+ # API have not drifted. The rewrite removed them and the referee went red; retargeting the
84
+ # gate would have been the wrong repair ([[gate-can-report-green-on-nothing]]: retarget, do
85
+ # not delete β€” but only when the subject genuinely moved. Here it should not have moved).
86
+ #
87
+ # ⚠ THE ROUTES SERVE A SUPERSET OF THIS. `routes_customers._payload` derives its field list from
88
+ # `aios_grid.fields_from_workspace(ws)`, which is `FIELDS` PLUS the session user's own custom_ and
89
+ # measure_ columns β€” the same list the Streamlit host renders. That is the point: the standalone
90
+ # shell now sees the user's own columns instead of the bare base contract. `FIELDS` is the
91
+ # canonical FLOOR, asserted below to be exactly what `aios_grid` starts from.
92
+ import json as _json_contract # noqa: E402
93
+ _FIELDS_PATH = _RI / "aios_grid_fields.json"
94
+ if not _FIELDS_PATH.is_file():
95
+ raise FileNotFoundError(
96
+ f"AIOS web API: canonical field contract missing at {_FIELDS_PATH}. Set RI_DIR to the "
97
+ "royalimports_os root (it also carries the data layer this API imports)."
98
+ )
99
+ _contract = _json_contract.loads(_FIELDS_PATH.read_text(encoding="utf-8"))
100
+ FIELDS = _contract["fields"] if isinstance(_contract, dict) else _contract
101
+ # text/status/select/date pass through untouched; every OTHER odoo field is numeric -> rounded.
102
+ # Derived from field TYPE (not a hand-kept key list) so a new text/date field can never be
103
+ # wrongly rounded. `select` joined 2026-08-02 (dba) β€” a choice label rounded would be garbage.
104
+ _PASSTHROUGH_KEYS = {f["key"] for f in FIELDS
105
+ if f["source"] == "odoo" and f["type"] in ("text", "status", "select",
106
+ "date")}
107
+
108
+ app = FastAPI(title="AIOS web API")
109
+
110
+ # The customers payload measured 1.15 MB of JSON on the live Space, shipped UNCOMPRESSED β€” with
111
+ # the 754 KB bundle behind it, most of "the app is slow" was bytes on the wire. gzip takes the
112
+ # payload to ~10–15% of that. minimum_size spares the tiny acks the overhead.
113
+ app.add_middleware(GZipMiddleware, minimum_size=1024)
114
+
115
+
116
+ @app.exception_handler(StarletteHTTPException)
117
+ def _error_shape(request: Request, exc: StarletteHTTPException):
118
+ """ONE error shape for every non-2xx (X2): `{"error": {"code", "message"}}`.
119
+
120
+ `deps.err` already raises detail in that shape; anything FastAPI raises on its own (a 404, a
121
+ 422 from a malformed path param) is wrapped here so a client never has to branch on two
122
+ different error bodies.
123
+ """
124
+ detail = exc.detail
125
+ if isinstance(detail, dict) and "error" in detail:
126
+ body = detail
127
+ else:
128
+ body = {"error": {"code": f"http_{exc.status_code}", "message": str(detail)}}
129
+ return JSONResponse(body, status_code=exc.status_code,
130
+ headers=getattr(exc, "headers", None))
131
+
132
+
133
+ @app.exception_handler(grid_events.StoreUnavailable)
134
+ def _store_unavailable(request: Request, exc: grid_events.StoreUnavailable):
135
+ """THE SAFETY NET for "the store is down" β†’ 503, from anywhere.
136
+
137
+ ⚠ WHY THIS IS APP-LEVEL AND NOT A `try` PER ROUTE. It was a try per route first, and a
138
+ `StoreUnavailable` raised while BUILDING THE PAYLOAD β€” before the route reached its own
139
+ try/except β€” surfaced as a 500. A store outage is a normal operational state and every route
140
+ here touches the store at least twice (the workspace read, then the write), so "remember to
141
+ wrap it" is a rule that gets forgotten once and then reports the wrong thing. One handler
142
+ means a store outage can only ever be a 503, whichever call raised it.
143
+
144
+ The seam raises this only when the caller passed no `fallback_ws` β€” i.e. exactly on this
145
+ adapter, which has no durable session dict to degrade into. A 200 over a write that
146
+ evaporated is the failure the whole rule exists to prevent.
147
+ """
148
+ return JSONResponse(
149
+ {"error": {"code": "store_unavailable",
150
+ "message": "the tenant store is unavailable β€” no change was saved"}},
151
+ status_code=503)
152
+
153
+
154
+ @app.get("/api/health")
155
+ def health():
156
+ """Unauthenticated LIVENESS only β€” it must answer before anyone can sign in, so it may not
157
+ reveal anything about the deployment beyond "the process is up". No version, no tenant list,
158
+ no config: a health endpoint is the one URL every scanner finds first."""
159
+ return {"ok": True}
160
+
161
+
162
+ app.include_router(routes_auth.router)
163
+ app.include_router(routes_nav.router)
164
+ app.include_router(routes_customers.router)
165
+ app.include_router(routes_products.router)
166
+ app.include_router(routes_grid.router)
167
+ app.include_router(routes_records.router)
168
+ # EXIT wave 2: the Y1 page-data envelope (one route for every ported dashboard) and Y4's user
169
+ # administration. `routes_pages` imports `pages`, which lazily imports each `pages_*` builder β€” so
170
+ # a new page is a builder module plus one registry line, and nothing here changes.
171
+ app.include_router(routes_pages.router)
172
+ app.include_router(routes_admin.router)
173
+
174
+
175
+ # --- DEPRECATED ALIASES (removed when S2's shell flips; kept so the current bundle keeps working)
176
+ # They are the v1 handlers with the v1 session requirement β€” NOT the old unauthenticated Basic
177
+ # behavior. An alias that kept the old auth would be a bypass of everything above it.
178
+ _GATE = module_gate(routes_customers.MODULE)
179
+
180
+
181
+ @app.get("/api/customers", deprecated=True)
182
+ def _customers_alias(session: Session = Depends(_GATE)):
183
+ return routes_customers._payload(session)
184
+
185
+
186
+ @app.patch("/api/customers/{pid}", deprecated=True)
187
+ def _patch_alias(pid: int, body: dict = Body(default=None),
188
+ session: Session = Depends(_GATE)):
189
+ return routes_customers.patch_customer(pid, body, session)
190
+
191
+
192
+ def _assert_contract_floor():
193
+ """The canonical FIELDS must be exactly what `aios_grid` starts an empty workspace from.
194
+
195
+ This is what stops `FIELDS` becoming a constant that exists only to satisfy a gate. If the
196
+ canonical JSON and `aios_grid.fields_from_workspace({})` ever disagree, the standalone API and
197
+ the embedded host are serving two different schemas and the grid's own contract has forked β€”
198
+ the exact drift `verify_fields_contract.py` was written to catch, now also caught at startup
199
+ on whatever machine is actually running.
200
+ """
201
+ import aios_grid
202
+ base = [f for f in aios_grid.fields_from_workspace({}) if not f.get("custom")]
203
+ if [f["key"] for f in base] != [f["key"] for f in FIELDS]:
204
+ raise RuntimeError(
205
+ "AIOS web API: the canonical field contract and aios_grid.fields_from_workspace({}) "
206
+ "disagree on the base field set β€” embed and standalone would serve different schemas. "
207
+ "Run aios-web/verify_fields_contract.py.")
208
+
209
+
210
+ def _startup_notes():
211
+ """Say the two things an operator must know, once, at import β€” never in a response body."""
212
+ if aios_session.EPHEMERAL_SECRET:
213
+ print("[aios-api] AIOS_SESSION_SECRET is not set β€” signing with a random per-process "
214
+ "key. Sessions will not survive a restart and will not work across workers. "
215
+ "Set it in production.")
216
+ if os.environ.get("AIOS_INSECURE_SSL") == "1":
217
+ print("[aios-api] AIOS_INSECURE_SSL=1 β€” TLS verification is DISABLED for outbound "
218
+ "requests. Local development only; never in a deployed environment.")
219
+
220
+
221
+ _assert_contract_floor()
222
+ _startup_notes()
223
+
224
+
225
+ # β›” THE STATIC MOUNT IS NOW UNAUTHENTICATED, and that is a change this wave made on purpose.
226
+ # Before EXIT-3a, `BasicAuth` middleware gated the WHOLE app including this mount. A branded login
227
+ # page cannot live behind a password prompt, so the shell's own assets must be public β€” which they
228
+ # are: `index.html`, the JS/CSS bundle and the favicon reveal nothing.
229
+ #
230
+ # ⚠ WHAT THAT SILENTLY DE-GATED, caught in review rather than in production. `web/dist/` also
231
+ # carries `sample_customers.json`, a DEV FIXTURE copied from `web/public/`. Its 8 customers are
232
+ # synthetic, but the `agent` column holds REAL EMPLOYEE NAMES, and it went from Basic-gated to
233
+ # publicly fetchable in this commit. Nothing needs it: both the API bridge and `useCustomerData`
234
+ # deleted their sample fallback on purpose ("NOTHING HERE FALLS BACK TO sample_customers.json"),
235
+ # and it survives only because it sits in `web/public/`. So it is refused here β€” 404, the same
236
+ # answer as any other path that is not part of the app.
237
+ #
238
+ # The right long-term fix is deleting it from `web/public/` (S2's lane β€” flagged in the mailbox);
239
+ # this guard is what makes the API safe regardless of what the bundle happens to contain.
240
+ _DEV_FIXTURES = {"sample_customers.json"}
241
+
242
+
243
+ class _AppStatic(StaticFiles):
244
+ async def get_response(self, path, scope):
245
+ if Path(path).name in _DEV_FIXTURES:
246
+ raise StarletteHTTPException(status_code=404, detail="Not Found")
247
+ resp = await super().get_response(path, scope)
248
+ # Vite content-hashes everything under assets/ (a change is a NEW url), so those are
249
+ # immutable β€” a repeat visit re-downloads zero bytes instead of the whole 750 KB bundle.
250
+ # index.html must stay revalidated or a deploy would strand returning browsers on the old
251
+ # bundle; ETag/304 makes that revalidation a header exchange, not a transfer.
252
+ # ⚠ Normalised first: on a Windows host StaticFiles hands this path with backslashes,
253
+ # and `startswith("assets/")` silently skipped every asset (measured on the local probe).
254
+ if path.replace("\\", "/").lstrip("/").startswith("assets/"):
255
+ resp.headers["Cache-Control"] = "public, max-age=31536000, immutable"
256
+ else:
257
+ resp.headers["Cache-Control"] = "no-cache"
258
+ return resp
259
+
260
+
261
+ # static bundle LAST so /api/* wins; html=True serves index.html at / plus the built assets
262
+ if _WEB_DIST.is_dir():
263
+ app.mount("/", _AppStatic(directory=str(_WEB_DIST), html=True), name="web")
264
+
265
+
266
+ # --- boot prewarm (AIOS_PREWARM=1 β€” set by the Dockerfile, never by tests) -----------------------
267
+ # Without this, the first visitor after every deploy/restart pays the full Odoo pool build in
268
+ # their request. The thread warms the CONSOLIDATED scope (None, None) + every registered page's
269
+ # default envelope; scoped users still pay their own scope's first build, once.
270
+ # Env-gated rather than a startup event so importing `api.main` in a gate (verify_api and friends
271
+ # run against fakes) can never fire a live Odoo pull.
272
+ def _seed_and_sync_store():
273
+ """Bring the analytical store (harness.datastore) LIVE for this container β€” the app.py
274
+ bootstrap, mirrored (2026-07-31, owner item 1).
275
+
276
+ `harness.datastore` powers every measure column/condition, and ONLY app.py used to call
277
+ `ensure_seed()` β€” so on a fresh Space disk this container resolved measures against a store
278
+ that never existed and every measure cell served blank. Seeding alone was NOT enough either,
279
+ and that was measured live the same day: "datastore seeded in 1.7s" followed by an endless
280
+ `api:measure-column: ModelError the data cache is still warming up` β€” `ready()` demands
281
+ EVERY entity at phase 'live', and a seed that predates a newer entity leaves it un-synced
282
+ forever in a process with no sync loop. The SYNC SPRINT after the seed is what closes the
283
+ write_date gap and backfills anything the seed lacks (app.py:7779's exact pattern, bounded
284
+ passes). Fail-quiet throughout: no seed/token/Odoo β†’ the columns stay blank, the rows still
285
+ serve.
286
+ """
287
+ import time as _t
288
+ t0 = _t.time()
289
+ try:
290
+ from harness import datastore as _ds
291
+ if _ds.ensure_seed():
292
+ print(f"[aios-api] datastore seeded in {_t.time() - t0:.1f}s")
293
+ # DEDICATED Odoo connection for this thread (the W6 postmortem rule): the sync's
294
+ # search_reads must never interleave on the shared client's xmlrpc transport.
295
+ import core.odoo as _odoo
296
+ try:
297
+ _odoo._tlocal.client = _odoo.OdooClient()
298
+ except Exception:
299
+ pass
300
+ res = {}
301
+ for i in range(12):
302
+ res = _ds.sync_all(log=lambda *a, **k: None)
303
+ print(f"[aios-api] datastore sync pass {i + 1}: "
304
+ + ", ".join(f"{k}={v.get('phase')}" for k, v in sorted(res.items())))
305
+ if all(v.get("phase") == "live" for v in res.values()):
306
+ break
307
+ print(f"[aios-api] datastore sync done in {_t.time() - t0:.1f}s "
308
+ f"(ready={_ds.ready()})")
309
+ except Exception as e: # noqa: BLE001
310
+ print(f"[aios-api] datastore seed/sync skipped: {e}")
311
+
312
+
313
+ def _store_resync_loop():
314
+ """Keep the analytical mirror current β€” the API-process stand-in for the re-sync the
315
+ Streamlit app piggybacks on page renders. Measure memos key on the pool stamp, so a
316
+ refreshed pool re-reads the freshly synced store."""
317
+ import time as _t
318
+ while True:
319
+ _t.sleep(1800)
320
+ try:
321
+ from harness import datastore as _ds
322
+ import core.odoo as _odoo
323
+ try:
324
+ _odoo._tlocal.client = _odoo.OdooClient()
325
+ except Exception:
326
+ pass
327
+ _ds.sync_all(log=lambda *a, **k: None)
328
+ except Exception as e: # noqa: BLE001
329
+ print(f"[aios-api] store resync failed: {e}")
330
+
331
+
332
+ def _prewarm():
333
+ import time as _t
334
+ t0 = _t.time()
335
+ # ⚠ The store sync runs in its OWN thread, never ahead of the pool warm: a stale seed can
336
+ # take many minutes of XML-RPC to close, and the first live probe of this arrangement
337
+ # showed the pool warm (42s) silently queued behind it β€” the whole app cold for every
338
+ # visitor while a background column channel caught up. Measure cells retry via the
339
+ # transient rule until the sync lands; nothing else waits on it.
340
+ import threading as _th
341
+ _th.Thread(target=_seed_and_sync_store, daemon=True, name="store-seed-sync").start()
342
+ try:
343
+ from harness import runtime as _runtime
344
+ rt = _runtime.get_runtime("royal-imports")
345
+ routes_customers.warm_default(rt)
346
+ import pages as _pages
347
+ _pages.warm_default(rt)
348
+ print(f"[aios-api] prewarm done in {_t.time() - t0:.1f}s")
349
+ except Exception as e: # noqa: BLE001 β€” boot must not die on a warm-up
350
+ print(f"[aios-api] prewarm skipped: {e}")
351
+
352
+
353
+ if os.environ.get("AIOS_PREWARM") == "1":
354
+ import threading as _threading
355
+ _threading.Thread(target=_prewarm, daemon=True, name="prewarm").start()
356
+ _threading.Thread(target=_store_resync_loop, daemon=True, name="store-resync").start()
api/pages.py CHANGED
@@ -301,14 +301,20 @@ def register(key, builder):
301
 
302
  def builder_for(key):
303
  """The builder for `key`, or None. A missing key is a 404 at the route β€” NOT a 403: an
304
- unported page is a fact about our roadmap, not about this user's grants."""
305
- if not _BUILDERS:
306
- import pages_sales # noqa: F401 (self-registers on import)
 
 
 
 
 
 
 
307
  return _BUILDERS.get(str(key or "").strip().lower())
308
 
309
 
310
  def known_pages():
311
- builder_for("") # force the lazy import
312
  return sorted(_BUILDERS)
313
 
314
 
 
301
 
302
  def builder_for(key):
303
  """The builder for `key`, or None. A missing key is a 404 at the route β€” NOT a 403: an
304
+ unported page is a fact about our roadmap, not about this user's grants.
305
+
306
+ ⚠ Wave 16 (owner item 7, R3/R11): `pages_sales` is UNREGISTERED β€” the lazy self-import
307
+ that used to live here is gone, so a production process holds ZERO builders and every
308
+ /pages/{key} is a 404 until the next surface (Collections / Procurement) registers.
309
+ The registry mechanism itself is untouched: a future builder self-registers on import,
310
+ and routes_pages.py should import it at module level so deploy_web.py's import walk can
311
+ see it (the wave-9 missing-module scar). pages_sales.py stays on disk as the template
312
+ and as verify_api section G's fixture β€” the gate imports it explicitly.
313
+ """
314
  return _BUILDERS.get(str(key or "").strip().lower())
315
 
316
 
317
  def known_pages():
 
318
  return sorted(_BUILDERS)
319
 
320
 
api/routes_admin.py CHANGED
@@ -93,7 +93,36 @@ def _view(uname, rec):
93
  "active": bool(rec.get("active", True)),
94
  # The session-revocation handle. An admin needs it: it is the only visible evidence
95
  # that "sign them out everywhere" actually happened.
96
- "epoch": int(rec.get("epoch") or 0)}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
97
 
98
 
99
  # ── request validation: every rule below is fail-closed ──────────────────────────────────────────
@@ -299,6 +328,386 @@ def set_password(username: str, body: dict = Body(default=None),
299
  return Response(status_code=204)
300
 
301
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
302
  @router.get("/settings")
303
  def settings(session: Session = Depends(require_session)):
304
  """The session's OWN settings β€” any authenticated user, not admin-only.
@@ -316,6 +725,10 @@ def settings(session: Session = Depends(require_session)):
316
  "team_id": perms.scope_team_id(session.user),
317
  "agent": perms.scope_agent(session.user),
318
  "modules": sorted(modules) if modules is not None else "all",
 
 
 
 
319
  },
320
  "tenant": {"key": session.tenant, "name": getattr(session.runtime, "name",
321
  session.tenant)},
 
93
  "active": bool(rec.get("active", True)),
94
  # The session-revocation handle. An admin needs it: it is the only visible evidence
95
  # that "sign them out everywhere" actually happened.
96
+ "epoch": int(rec.get("epoch") or 0),
97
+ # S3 ask 4 β€” one sentence for the roster's Access column, so the list does not need
98
+ # a /perms round trip per row to fill one cell. Computed from the same record the
99
+ # editor will open, so the two cannot disagree.
100
+ "accessSummary": _access_summary(rec),
101
+ "perms_v": int(rec.get("perms_v") or 0)}
102
+
103
+
104
+ def _access_summary(rec):
105
+ """One sentence describing what this account may reach. Deliberately says LESS than the
106
+ editor: it is a signpost, not a rule listing, and a summary that tried to spell out filters
107
+ would be wrong the moment a filter got interesting."""
108
+ import core.perm_scope as perm_scope
109
+
110
+ if perms.is_admin(rec):
111
+ # amendment 4: an admin bypasses `perms` entirely, so rendering their stored rules as if
112
+ # they applied is the one misreading of that clause that could actually hurt.
113
+ return "Everything (admin)"
114
+ if not perm_scope.is_migrated(rec):
115
+ mods = perms.allowed_modules(rec)
116
+ return "All modules (legacy rules)" if mods is None else \
117
+ f"{len(mods)} module{'' if len(mods) == 1 else 's'} (legacy rules)"
118
+ entries = (rec.get("perms") or {})
119
+ opened = [k for k, e in entries.items() if isinstance(e, dict) and e.get("access", True)]
120
+ restricted = sum(1 for k in opened
121
+ if (entries[k].get("filter") or entries[k].get("hiddenFields")))
122
+ if not opened:
123
+ return "No modules"
124
+ base = f"{len(opened)} module{'' if len(opened) == 1 else 's'}"
125
+ return f"{base}, {restricted} restricted" if restricted else base
126
 
127
 
128
  # ── request validation: every rule below is fail-closed ──────────────────────────────────────────
 
328
  return Response(status_code=204)
329
 
330
 
331
+ # ── C-PERM (wave 15): per-module access + permanent filters + hidden fields ──────────────────
332
+ #: The modules the permission editor governs β€” the GRID surfaces, the ones with a field schema
333
+ #: to filter and hide. Amendment 6 ships the wall on `customer_data` alone and adds
334
+ #: `product_data` when C-TOPIC lands; the list is the one place that changes.
335
+ _PERM_MODULES = ("customer_data",)
336
+
337
+
338
+ def _module_fields(key):
339
+ """The field schema the editor builds its pickers from β€” the SAME vocabulary the grid uses,
340
+ so an admin filters on exactly what the user sees.
341
+
342
+ β›” Returned WITHOUT any per-user hiding applied, deliberately: this is the admin choosing
343
+ what to hide, so hiding the choices would make a field unhideable the moment it was hidden
344
+ once for somebody. The route is admin-gated; the projection a MEMBER receives is the one
345
+ `perm_scope.visible_fields` narrows.
346
+ """
347
+ import aios_grid
348
+ out = []
349
+ for f in aios_grid.FIELDS:
350
+ if not isinstance(f, dict) or not f.get("key"):
351
+ continue
352
+ out.append({"key": f["key"], "label": f.get("label") or f["key"],
353
+ "type": f.get("type") or "text",
354
+ **({"options": f["options"]} if isinstance(f.get("options"), list) else {})})
355
+ return out
356
+
357
+
358
+ def _clean_perms(v):
359
+ """Validate a whole `perms` block. FAIL-CLOSED, and LOUD rather than lenient.
360
+
361
+ β›” WHY THIS REFUSES WHERE `clean_filter_tree` DROPS. The view sanitiser is deliberately
362
+ drop-per-node: one bad rule must never cost a user their whole saved view. A PERMISSION
363
+ filter is the opposite situation β€” an admin types "agent is Tara", a leaf is silently
364
+ dropped, and the stored wall is EMPTY. The admin sees "Saved", the account sees the whole
365
+ book, and nothing anywhere says so. So anything that would be dropped is a 400 instead:
366
+ the filter is re-validated with `clean_filter_tree` and the result must come back with the
367
+ SAME leaf count it went in with.
368
+
369
+ Shape (C-PERM amendment 2 β€” a `FilterTree` is a PAIR, `{conj?, nodes}`; `clean_filter_tree`
370
+ validates the NODE LIST alone and never sees the root conjunction, so the two are checked
371
+ separately and a bare node list is refused rather than silently read as `and`).
372
+ """
373
+ import aios_grid
374
+
375
+ if v is None:
376
+ return None
377
+ if not isinstance(v, dict):
378
+ raise err(400, "bad_perms", "perms must be an object keyed by module")
379
+ unknown = sorted(set(v) - set(_PERM_MODULES))
380
+ if unknown:
381
+ raise err(400, "bad_perms",
382
+ f"unknown module keys: {unknown} β€” the permission editor governs "
383
+ f"{list(_PERM_MODULES)}")
384
+ out = {}
385
+ for key, raw in v.items():
386
+ if not isinstance(raw, dict):
387
+ raise err(400, "bad_perms", f"{key}: each entry must be an object")
388
+ valid_keys = {f["key"] for f in _module_fields(key)}
389
+ hidden = raw.get("hiddenFields") or []
390
+ if not isinstance(hidden, list):
391
+ raise err(400, "bad_perms", f"{key}: hiddenFields must be a list")
392
+ bad = sorted({str(h) for h in hidden} - valid_keys)
393
+ if bad:
394
+ # A hiddenFields entry naming nothing hides nothing β€” and reads as a restriction
395
+ # that is not there.
396
+ raise err(400, "bad_perms",
397
+ f"{key}: hiddenFields names unknown fields {bad}")
398
+ tree = raw.get("filter")
399
+ clean_tree = None
400
+ if tree not in (None, {}, []):
401
+ if not isinstance(tree, dict) or not isinstance(tree.get("nodes"), list):
402
+ raise err(400, "bad_filter",
403
+ f"{key}: filter must be {{conj?, nodes:[…]}} β€” a bare list would lose "
404
+ f"the root conjunction, and an 'or' wall read as 'and' restricts "
405
+ f"nothing it was meant to")
406
+ conj = tree.get("conj", "and")
407
+ if conj not in ("and", "or"):
408
+ raise err(400, "bad_filter", f"{key}: conj must be 'and' or 'or'")
409
+ nodes = tree["nodes"]
410
+ cleaned = aios_grid.clean_filter_tree(nodes, valid_keys, cohort_ids=None)
411
+ if _leaf_count(cleaned) != _leaf_count(nodes):
412
+ raise err(400, "bad_filter",
413
+ f"{key}: the filter contains conditions this module cannot evaluate "
414
+ f"(an unknown field, an unknown operator, or a cohort leaf β€” cohorts "
415
+ f"are per-user and cannot be a permanent rule). Refused rather than "
416
+ f"saved with the bad conditions silently removed, which would store a "
417
+ f"weaker wall than the one on screen.")
418
+ clean_tree = {"conj": conj, "nodes": cleaned}
419
+ out[key] = {"access": bool(raw.get("access", True)),
420
+ "filter": clean_tree,
421
+ "hiddenFields": sorted({str(h) for h in hidden})}
422
+ _refuse_unshapeable_bu(out)
423
+ return out
424
+
425
+
426
+ def _refuse_unshapeable_bu(perms_out):
427
+ """β›” A BU CONDITION THE PUSHDOWN CANNOT READ IS A VALUE LEAK WEARING A CORRECT ROW LIST.
428
+
429
+ Amendment 3 in one more place. `perm_scope.derive_pool_scope` recognises exactly the shapes
430
+ that PIN a business unit: a top-level `dba eq` leaf, or a top-level OR-group of them β€” which
431
+ is what `perm_migrate` emits and what the condition builder produces for "is any of". An
432
+ admin composing the same intent a slightly different way (a NESTED group, `dba neq Royal`, a
433
+ `dba` leaf one level down) produces a filter that still narrows the ROWS correctly through
434
+ `permits()` β€” and leaves the pool built CONSOLIDATED, so every surviving row carries
435
+ Fisch+Royal numbers. The row list looks right. The revenue is another BU's.
436
+
437
+ That is precisely the defect amendment 3 exists for, re-entering through the editor R9 just
438
+ shipped, and it cannot be caught downstream: by then the numbers are simply wrong, with
439
+ nothing anomalous about them.
440
+
441
+ So it is refused at the WRITE, where a person is present to fix it. The discriminator is
442
+ narrow on purpose β€” the filter must MENTION `dba` and must fail to pin a team. A wall like
443
+ `dba is Fisch OR revenue > 1000` genuinely does not confine anyone to one BU, and
444
+ consolidated values are the correct answer for it, so it is not caught here (`derive` also
445
+ refuses it) and must not be.
446
+ """
447
+ import core.perm_scope as perm_scope
448
+
449
+ for key, e in perms_out.items():
450
+ tree = e.get("filter")
451
+ if not tree or not _mentions_dba(tree.get("nodes")):
452
+ continue
453
+ probe = {"role": "user", "perms_v": perm_scope.PERMS_VERSION,
454
+ "perms": {key: {"access": True, "filter": tree, "hiddenFields": []}}}
455
+ team_id, _ = perm_scope.derive_pool_scope(probe, key)
456
+ if team_id is None and _confines_to_one_bu(tree):
457
+ raise err(400, "bu_condition_shape",
458
+ f"{key}: this filter restricts the business unit in a way the data layer "
459
+ f"cannot push into the query, so the rows would be correct while the "
460
+ f"revenue figures on them stayed consolidated across both units. Express "
461
+ f"the business-unit condition as a TOP-LEVEL condition β€” 'DBA is Fisch', "
462
+ f"or an 'any of' over the brands β€” and keep any other rules alongside it.")
463
+
464
+
465
+ def _guard_bu_widening(rec, cleaned, confirmed):
466
+ """β›” THE TWO-CLICK LEAK: a SECOND save that silently drops the business-unit condition.
467
+
468
+ `_fold_legacy_scope` runs only while a record is un-migrated, which is correct β€” after the
469
+ first save the filter IS the whole wall and the admin owns it. But the first save also
470
+ CHANGES the tree (it folds the BU condition in), so a client holding the tree it submitted
471
+ rather than the one the server returned will, on its next save, PUT a payload with no BU
472
+ condition β€” and a whole-record replace deletes it. Measured, not theorised: the same client
473
+ payload saved twice takes the pool scope from `(6, 'Ann')` to `(None, 'Ann')`, which is both
474
+ business units.
475
+
476
+ So a save that REMOVES the brand confinement is refused unless it says it means to. Widening
477
+ BU access is a legitimate thing for an administrator to do β€” it is just never a thing to do
478
+ by accident, and the difference between the two is one explicit flag.
479
+
480
+ ⚠ Deliberately NOT solved by always folding the legacy scope: that would make a BU
481
+ restriction permanent and unremovable, which contradicts R1 (the filter is the wall, and the
482
+ admin edits it). The right shape is "you may widen, say so".
483
+ """
484
+ import core.perm_scope as perm_scope
485
+
486
+ if confirmed:
487
+ return
488
+ stored = (rec.get("perms") or {}) if isinstance(rec.get("perms"), dict) else {}
489
+ for key, new_entry in cleaned.items():
490
+ if not new_entry.get("access", True):
491
+ # Revoking the module entirely is the OPPOSITE of widening, and the filter on a
492
+ # denied entry governs nothing. Guarding it would make "lock this account out"
493
+ # require a confirm_widen flag, which reads as nonsense to whoever hits it.
494
+ continue
495
+ old = stored.get(key)
496
+ if not isinstance(old, dict):
497
+ continue # nothing stored yet: the fold already handled it
498
+ old_tree, new_tree = old.get("filter"), new_entry.get("filter")
499
+ if not old_tree or not _confines_to_one_bu(old_tree):
500
+ continue # was not confined -> this save cannot widen it
501
+ if new_tree and _confines_to_one_bu(new_tree):
502
+ continue # still confined -> not a widening
503
+ raise err(400, "bu_widening",
504
+ f"{key}: this would REMOVE the business-unit restriction and give the account "
505
+ f"both units. If that is intended, resend with confirm_widen: true. If it is "
506
+ f"not, reload the account's permissions first β€” saving a filter loaded before "
507
+ f"the last change drops the conditions it did not know about.")
508
+ # A guard is only as good as its trigger: `perm_scope` is imported so a future reader sees
509
+ # the connection to derive_pool_scope, which is what the removed condition was feeding.
510
+ _ = perm_scope
511
+
512
+
513
+ def _mentions_dba(nodes):
514
+ for n in nodes or ():
515
+ if not isinstance(n, dict):
516
+ continue
517
+ if isinstance(n.get("children"), list):
518
+ if _mentions_dba(n["children"]):
519
+ return True
520
+ elif n.get("colId") == "dba":
521
+ return True
522
+ return False
523
+
524
+
525
+ def _confines_to_one_bu(tree):
526
+ """Does the BRAND STRUCTURE ALONE confine the reader to one business unit?
527
+
528
+ ⚠ "Alone" is the whole precision of this function, and getting it wrong makes the guard
529
+ refuse legitimate walls. `dba is Fisch OR ar_open > 1000` does NOT confine anybody β€” a
530
+ high-balance Royal customer satisfies it β€” so consolidated values are the correct answer and
531
+ refusing it would be a false positive. My first attempt evaluated synthetic rows carrying
532
+ only `dba`, which made `ar_open > 1000` read false on every probe row and turned that exact
533
+ wall into a "confinement" it is not.
534
+
535
+ So every NON-`dba` leaf is treated as TRUE β€” the most generous reading, i.e. "suppose the
536
+ reader satisfies everything else; can they still see both brands?" If yes, the wall does not
537
+ confine and the pool is correctly consolidated. If no, the brand structure is doing the
538
+ confining and `derive_pool_scope` must be able to see it, or the numbers are wrong.
539
+ """
540
+ def admits(node, brand):
541
+ if isinstance(node.get("children"), list):
542
+ kids = [admits(k, brand) for k in node["children"] if isinstance(k, dict)]
543
+ if not kids:
544
+ return True
545
+ return any(kids) if node.get("conj") == "or" else all(kids)
546
+ if node.get("colId") != "dba":
547
+ return True # every other condition: assume satisfied
548
+ want = str(node.get("value") or "").strip().lower()
549
+ op = node.get("op")
550
+ if op == "eq":
551
+ return brand.lower() == want
552
+ if op == "neq":
553
+ return brand.lower() != want
554
+ if op == "contains":
555
+ return want in brand.lower()
556
+ if op == "doesNotContain":
557
+ return want not in brand.lower()
558
+ if op == "isEmpty":
559
+ return False # a probe brand is never blank
560
+ if op == "isNotEmpty":
561
+ return True
562
+ return True # an op that cannot judge a brand does not confine
563
+
564
+ nodes, conj = (tree.get("nodes") or []), tree.get("conj", "and")
565
+ root = {"conj": conj, "children": nodes}
566
+ admitted = {b for b in ("Fisch", "Royal", "Both") if admits(root, b)}
567
+ if not admitted:
568
+ return False # admits nothing at all β€” a different problem
569
+ # 'Both' belongs to either unit, so it cannot by itself widen the answer.
570
+ return not ({"Fisch", "Royal"} <= admitted)
571
+
572
+
573
+ def _leaf_count(nodes):
574
+ n = 0
575
+ for node in nodes or ():
576
+ if isinstance(node, dict) and isinstance(node.get("children"), list):
577
+ n += _leaf_count(node["children"])
578
+ else:
579
+ n += 1
580
+ return n
581
+
582
+
583
+ def _fold_legacy_scope(rec, cleaned):
584
+ """β›” MIGRATING A RECORD MUST NEVER WIDEN IT. The invariant this function exists to hold.
585
+
586
+ Writing perms stamps `perms_v: 1`, and that marker SWITCHES OFF the legacy `bus`/`agent`
587
+ fallback in `perm_scope` (amendment 4 β€” absence must start meaning DENY). So a first write
588
+ whose filter carries no BU condition silently promotes a Royal-only account to BOTH business
589
+ units: the wall that used to come from `bus` is gone and nothing replaced it.
590
+
591
+ Caught by the end-to-end leg in `verify_api` and by nothing else β€” every model-level check
592
+ passed, because the model was doing exactly what it was told. The account simply received
593
+ the other BU's customers on the wire.
594
+
595
+ So on the FIRST perms write we fold the legacy scope in, as ordinary conditions, exactly as
596
+ `perm_migrate` would: this IS R1's migration, performed at the moment the record acquires a
597
+ perms block. From then on the admin sees those leaves in the editor (GET returns the folded
598
+ filter) and can change them like any other condition β€” which is R1's whole point, and why
599
+ this is a one-time fold rather than a permanent floor AND-ed on every write.
600
+
601
+ Idempotent by construction: it runs only while the record is un-migrated, and the write that
602
+ calls it is the write that migrates it.
603
+ """
604
+ import core.perm_migrate as perm_migrate
605
+ import core.perm_scope as perm_scope
606
+
607
+ if perm_scope.is_migrated(rec):
608
+ return cleaned
609
+ legacy = perm_migrate.filter_for(rec)
610
+ if not legacy:
611
+ return cleaned # nothing to preserve: the account was unrestricted
612
+ out = {}
613
+ for key, e in cleaned.items():
614
+ tree = e.get("filter")
615
+ if not tree or not tree.get("nodes"):
616
+ folded = legacy
617
+ else:
618
+ # AND the two roots together. The submitted tree keeps its own conjunction by being
619
+ # nested as a GROUP β€” flattening an `or` tree into an `and` root would turn the
620
+ # admin's "A or B" into "A and B", which is a different and much narrower wall.
621
+ folded = {"conj": "and",
622
+ "nodes": list(legacy["nodes"]) + [{"conj": tree.get("conj", "and"),
623
+ "children": list(tree["nodes"])}]}
624
+ out[key] = dict(e, filter=folded)
625
+ return out
626
+
627
+
628
+ @router.get("/admin/users/{username}/perms")
629
+ def get_perms(username: str, session: Session = Depends(admin_gate)):
630
+ """This account's permission block plus the field schema the editor needs to render it."""
631
+ reg = _registry()
632
+ uname = str(username or "").strip().lower()
633
+ if uname not in reg:
634
+ raise err(404, "no_such_user", f"no account named {uname!r}")
635
+ import core.perm_scope as perm_scope
636
+
637
+ rec = reg[uname]
638
+ stored = rec.get("perms") or {}
639
+ # S3 ask 3 β€” AN ENTRY FOR EVERY DECLARED MODULE, never a gap the client has to default.
640
+ # The PUT is a whole-record replace over this same module list, so a key declared here and
641
+ # omitted from `perms` would become an explicit DENY the moment anyone pressed Save. The
642
+ # default sent is the EFFECTIVE one (`may_access`), so an un-migrated record shows the
643
+ # access its legacy grant currently gives rather than a guess in either direction.
644
+ perms_out = {}
645
+ for k in _PERM_MODULES:
646
+ e = stored.get(k)
647
+ perms_out[k] = e if isinstance(e, dict) else {
648
+ "access": bool(perm_scope.may_access(rec, k)), "filter": None, "hiddenFields": []}
649
+ return {"username": uname,
650
+ "perms": perms_out,
651
+ # S3 ask 2 β€” the marker rides the GET. An absent module entry means DENY on a
652
+ # migrated record and LEGACY on an un-migrated one: opposite meanings for identical
653
+ # JSON, so the client cannot render honestly without knowing which world it is in.
654
+ "perms_v": int(rec.get("perms_v") or 0),
655
+ # `role == 'admin'` bypasses perms entirely (amendment 4) β€” sent so the editor can
656
+ # say "Everything (admin)" instead of rendering stored rules that do not apply.
657
+ "is_admin": perms.is_admin(rec),
658
+ "modules": [{"key": k, "label": _MODULE_LABELS.get(k, k)} for k in _PERM_MODULES],
659
+ # S3 ask 1 β€” CANONICAL SHAPE: a BARE ARRAY of fields per module key. Not the nav
660
+ # schema envelope; the editor needs the field list and nothing else, and one shape
661
+ # beats two readings of a sentence.
662
+ "fields_by_module": {k: _module_fields(k) for k in _PERM_MODULES}}
663
+
664
+
665
+ @router.put("/admin/users/{username}/perms")
666
+ def put_perms(username: str, body: dict = Body(default=None),
667
+ session: Session = Depends(admin_gate)):
668
+ """Replace this account's permission block wholesale.
669
+
670
+ WHOLESALE, not a merge: "remove this restriction" has to be expressible, and a merge cannot
671
+ express a deletion without a second vocabulary for it.
672
+
673
+ ⚠ NO EPOCH BUMP, for the same reason `PATCH /admin/users/{u}` does not bump one:
674
+ `deps._user_for` re-reads the record on every request, so a narrowed wall applies to the
675
+ target's LIVE session on its very next call. Bumping would only add a forced re-login on top
676
+ of a change that has already taken effect.
677
+ """
678
+ body = body if isinstance(body, dict) else {}
679
+ reg = _registry()
680
+ uname = str(username or "").strip().lower()
681
+ if uname not in reg:
682
+ raise err(404, "no_such_user", f"no account named {uname!r}")
683
+ if "perms" not in body:
684
+ raise err(400, "empty_patch", "no perms to save")
685
+
686
+ # THE SELF-LOCKOUT GUARD, the twin of `self_demote` on the PATCH route. An admin bypasses
687
+ # perm_scope entirely, so this cannot brick them today β€” but it stops an administrator
688
+ # writing a wall for themselves that would bite the moment their role changed.
689
+ if uname == session.uname:
690
+ raise err(400, "self_perms",
691
+ "you cannot set permissions on your own account β€” ask another admin")
692
+
693
+ cleaned = _clean_perms(body.get("perms")) or {}
694
+ cleaned = _fold_legacy_scope(reg[uname], cleaned)
695
+ _guard_bu_widening(reg[uname], cleaned, bool(body.get("confirm_widen")))
696
+ users.set_access(uname, perms=cleaned)
697
+ fresh = _registry()
698
+ rec = fresh.get(uname) or {}
699
+ if int(rec.get("perms_v") or 0) < users.PERMS_VERSION:
700
+ # The store took the write and did not record it. A 200 here would tell an administrator
701
+ # the wall is up when it is not β€” the one direction this must never fail in.
702
+ raise err(503, "store_unavailable",
703
+ "the permissions were not saved β€” the account is UNCHANGED")
704
+ return {"username": uname, "perms": rec.get("perms") or {},
705
+ "perms_v": int(rec.get("perms_v") or 0)}
706
+
707
+
708
+ _MODULE_LABELS = {"customer_data": "Customer", "product_data": "Product"}
709
+
710
+
711
  @router.get("/settings")
712
  def settings(session: Session = Depends(require_session)):
713
  """The session's OWN settings β€” any authenticated user, not admin-only.
 
725
  "team_id": perms.scope_team_id(session.user),
726
  "agent": perms.scope_agent(session.user),
727
  "modules": sorted(modules) if modules is not None else "all",
728
+ # C-PERM: the caller's OWN effective wall, read-only. The grid uses it to grey
729
+ # pickers rather than to enforce β€” hidden fields are stripped from every data wire
730
+ # regardless, so a client that ignores this is narrowed anyway, never widened.
731
+ "perms": session.user.get("perms") or {},
732
  },
733
  "tenant": {"key": session.tenant, "name": getattr(session.runtime, "name",
734
  session.tenant)},
api/routes_customers.py CHANGED
@@ -1,264 +1,328 @@
1
- """routes_customers.py β€” X2's read + write of the customer table, BU-SCOPED (EXIT-3b / EXIT-2a).
2
-
3
- Two things happen here that did not happen in the pre-wave `main.py`:
4
-
5
- 1. **ROWS ARE SCOPED TO THE SESSION.** The old `/api/customers` served `cl.pool()` β€” the whole
6
- book, to anyone holding the shared APP_PASSWORD. Now the pool is built with
7
- `(team_id, agent_name)` derived from the USER RECORD, so a Royal-only user never receives a
8
- Fisch row and an agent-linked login never receives another rep's book. The scope is applied
9
- at the QUERY, not as a post-filter, so there is no moment at which the other BU's rows exist
10
- in this response.
11
-
12
- 2. **THE OVERLAY FORK IS GONE.** `aios-web/api/data/overlay.json` was a SECOND writable home
13
- for the same user-owned fields the Streamlit app keeps in the tenant store β€” two truths, and
14
- whichever process you asked last was right. Reads and writes now both go through
15
- `modules.customer_data`'s table-workspace functions: ONE store (C1c, ARCHITECTURE Β§1a rule 3).
16
-
17
- ⚠ ONE STORE IS NOT YET ONE CACHE (strangler-period, booked honestly). `core.store.get()` is
18
- cache-first per PROCESS, so a write from the Streamlit container is invisible to a running API
19
- container until its cache is refreshed, and vice versa. Deleting the fork removes the second
20
- SOURCE OF TRUTH; it does not make the two runtimes coherent. The fix is X4/Postgres (task C-4,
21
- owner-blocked on B-3), and no test here may claim read-your-writes ACROSS runtimes β€” a TestClient
22
- proof is single-process and would report green on exactly the thing that is still broken.
23
- """
24
- import time
25
-
26
- from fastapi import APIRouter, Body, Depends
27
-
28
- import scope_cache
29
- from deps import Session, err, module_gate, perms
30
-
31
- router = APIRouter(prefix="/api/v1")
32
-
33
- #: The surface these routes serve. Both legs are gated on it, so a user without the grant gets a
34
- #: 403 rather than an empty table that looks like "you have no customers".
35
- MODULE = "customer_data"
36
-
37
- _CACHE_TTL = 900 # the pool build is slow (Odoo + reconciliation); 15 min, as before
38
-
39
-
40
- def _pool_rows(session: Session):
41
- """The reconciled Odoo pool for this session's SCOPE β€” the slow part, and the only part that
42
- may be shared between users.
43
-
44
- β›” WHAT MAY BE CACHED HERE, AND WHY THE LINE IS EXACTLY HERE. The cache key is
45
- `(team_id, agent)` and the cached value is the raw pool: Odoo-source columns only. That is
46
- genuinely scope-shaped β€” two users with the same BU and the same book are asking the same
47
- question, and `cl.pool()` is expensive (an Odoo pull plus reconciliation).
48
-
49
- The FULL PAYLOAD is NOT cacheable on this key, and caching it here was a real defect I shipped
50
- and then removed. `fields` comes from `fields_from_workspace(ws)` β€” that user's own `custom_`
51
- and `measure_` columns β€” and every overlay cell comes from `ws['overlays']`; the table
52
- workspace is read as `data[username]` and written as `patch_table_overlay(uname, …)`, i.e.
53
- PER USER. So two Royal-only users with no agent link share `(6, None)` and the second one
54
- would have been served the FIRST one's private notes and private columns. The scope key was
55
- right for the pool and wrong for everything wrapped around it.
56
-
57
- It survived a green 129-check battery because every fixture user had a DISTINCT
58
- `(team_id, agent)` pair, so no two of them ever collided on the key β€” the test set could not
59
- express the bug. `verify_api.py` now carries a same-scope second user for exactly this.
60
- """
61
- rt = session.runtime
62
- team_id = perms.scope_team_id(session.user)
63
- agent = perms.scope_agent(session.user)
64
- return _pool_for(rt, team_id, agent)
65
-
66
-
67
- def _pool_for(rt, team_id, agent):
68
- """The cached pool for an explicit scope β€” session-free so the prewarm thread and the
69
- stale-refresh path can call it. STALE-WHILE-REFRESH (scope_cache): once a copy exists no
70
- request blocks on the 10–30s Odoo rebuild again; only a scope's FIRST-ever build does."""
71
- import modules.customer_data as cl
72
-
73
- key = ("pool", team_id, agent)
74
-
75
- def _build():
76
- # ⚠ THE SCOPE GOES INTO THE BUILDER. `pool(agent_name, team_id)` is the same reconciled
77
- # builder the Streamlit page uses β€” passing the scope here is what makes the isolation a
78
- # property of the QUERY instead of a filter someone can forget to apply downstream.
79
- return cl.pool(agent, team_id)
80
-
81
- def _evict():
82
- # Bounded: a scope cache that only ever grows is a memory leak in a shared process.
83
- if len(rt.pool_cache) > 16:
84
- for stale in sorted(rt.pool_cache, key=lambda k: rt.pool_cache[k][0])[:8]:
85
- rt.pool_cache.pop(stale, None)
86
-
87
- return scope_cache.get(rt.pool_cache, key, _CACHE_TTL, _build, _evict)
88
-
89
-
90
- def warm_default(rt):
91
- """Boot prewarm: the consolidated pool `(None, None)` β€” the scope every admin and every
92
- all-BU account lands on. Called from main.py's prewarm thread only."""
93
- _pool_for(rt, None, None)
94
-
95
-
96
- def _team_agent(session: Session):
97
- return perms.scope_team_id(session.user), perms.scope_agent(session.user)
98
-
99
-
100
- def _pool_stamp(rt, team_id, agent):
101
- """The cached pool's build timestamp β€” the DATA STAMP in every measure-memo key, so a pool
102
- refresh invalidates the memoised answers exactly when the underlying rows changed."""
103
- entry = rt.pool_cache.get(("pool", team_id, agent))
104
- return entry[0] if isinstance(entry, tuple) and entry else 0
105
-
106
-
107
- def _measure_err(tag, e):
108
- try:
109
- import harness.telemetry as _tel
110
- _tel.error(f"api:{tag}", e)
111
- except Exception:
112
- pass
113
-
114
-
115
- def grid_assembly(session: Session, scope: str = "customer", storage_key: str = "",
116
- consume_corrections: bool = True):
117
- """ONE assembly of this session's grid state, shared by `/customers`, `/workspace` and the
118
- events route (2026-07-31 β€” the standalone measure gap, owner item 1).
119
-
120
- What it adds over the pre-wave hand-rolled `_payload` loop, and why it replaced it:
121
-
122
- * rows go through `aios_grid.rows_from_pool` β€” the SAME builder the embedded host uses,
123
- so `lat`/`lon` (the Map view's data), `_created` and every derived column ride each row
124
- by construction instead of by a second loop that drifts. The hand loop was written to
125
- mirror the pre-Map contract and silently dropped the coordinates: the shell's Map view
126
- had nothing to plot ("the Map no longer works").
127
- * `derived` carries the cohort column's cells AND the measure columns' values, resolved
128
- through `core.measure_resolve` (EXIT-5's extraction of the `_cl_measure_*` family).
129
- Without them every measure column the owner built rendered BLANK in the shell.
130
- * `measures` (the offer) and `measure_sets` (condition answers) are computed here so the
131
- events route can finally validate measure fields/conditions instead of refusing them
132
- (an empty `measure_offer` made `clean_measure_field` reject every create over HTTP).
133
-
134
- Memos live on the TENANT RUNTIME (`rt.measure_memo` / `rt.mset_memo`) β€” bounded by the
135
- module's own clear-past-cap rule, keyed on (stamp, scope, pool identity, question), nothing
136
- user-shaped in them.
137
- """
138
- import aios_grid
139
- from core import grid_events, measure_resolve
140
-
141
- rt = session.runtime
142
- team_id, agent = _team_agent(session)
143
- rows_src = _pool_for(rt, team_id, agent)
144
- pids = frozenset(r["pid"] for r in rows_src if r.get("pid") is not None)
145
- ws = grid_events.table_workspace(
146
- _ctx_for(session, pids), allowed_pids=pids,
147
- consume_corrections=consume_corrections)
148
- workspace, fields, views, lists = aios_grid.workspace_wire(
149
- ws, session.uname, set(pids), defs={}, scope_key=scope, storage_key=storage_key)
150
-
151
- today = time.strftime("%Y-%m-%d")
152
- stamp = _pool_stamp(rt, team_id, agent)
153
- measures = measure_resolve.offer(team_id, on_error=_measure_err)
154
- measure_sets = measure_resolve.condition_sets(
155
- [v.get("config") or {} for v in (views or [])], None, team_id, pids, today, stamp,
156
- rt.mset_memo, on_error=_measure_err)
157
- # The derived channel: cohort membership cells + measure column values, ONE dict β€” the
158
- # same read-only channel the embed host hands to rows_from_pool.
159
- derived = aios_grid.cohort_cells(lists)
160
- for pid, cells in measure_resolve.column_values(
161
- fields, team_id, pids, today, stamp, rt.measure_memo,
162
- on_error=_measure_err).items():
163
- derived.setdefault(pid, {}).update(cells)
164
-
165
- return {"rows_src": rows_src, "pids": pids, "ws": ws, "workspace": workspace,
166
- "fields": fields, "views": views, "lists": lists, "derived": derived,
167
- "measures": measures, "measure_sets": measure_sets, "today": today,
168
- "team_id": team_id}
169
-
170
-
171
- def _payload(session: Session):
172
- """`{fields, rows, today, pulled_at}` β€” X2's shape, which `verify_fields_contract.py`
173
- referees. Rows are now built by `aios_grid.rows_from_pool` (embed == standalone by
174
- construction); see `grid_assembly` for what that fixed.
175
-
176
- ⚠ `rows_src` is the SHARED cached list β€” `rows_from_pool` reads it and builds NEW dicts,
177
- never mutating a cached row (the same-scope-second-user leak rule).
178
- """
179
- import aios_grid
180
-
181
- g = grid_assembly(session)
182
- rows = aios_grid.rows_from_pool(
183
- g["rows_src"], g["fields"], g["ws"].get("overlays"), derived=g["derived"])
184
- return {"fields": g["fields"], "rows": rows,
185
- # `today` rides the payload because every relative date condition must resolve against
186
- # the TENANT's day, never the browser's β€” a client that falls back to its own clock
187
- # disagrees with the server for everyone west of it.
188
- "today": g["today"],
189
- "pulled_at": time.strftime("%Y-%m-%d %H:%M")}
190
-
191
-
192
- def _ctx_for(session: Session, pids):
193
- """An EventCtx for the READ path β€” no fallback workspace, so a store outage is a 503 rather
194
- than a phantom in-memory workspace an API request cannot persist."""
195
- from core import grid_events
196
- return grid_events.EventCtx(
197
- uname=session.uname, allowed_pids=frozenset(pids or ()), fields=[],
198
- admin=session.admin, fallback_ws=None, seen_ids={})
199
-
200
-
201
- def allowed_pids(session: Session):
202
- """The pids this session may touch β€” the POOL's own ids, so the write wall and the read scope
203
- can never disagree.
204
-
205
- Reads `_pool_rows` rather than `_payload`: the wall only needs identities, and going through
206
- the full payload would pay for a workspace read and a row assembly on every write.
207
- """
208
- return frozenset(r["pid"] for r in _pool_rows(session) if r.get("pid") is not None)
209
-
210
-
211
- @router.get("/customers")
212
- def customers(session: Session = Depends(module_gate(MODULE))):
213
- return _payload(session)
214
-
215
-
216
- @router.patch("/customers/{pid}")
217
- def patch_customer(pid: int, body: dict = Body(default=None),
218
- session: Session = Depends(module_gate(MODULE))):
219
- """Write the EDITABLE overlay stratum only β€” Odoo stays read-only, forever.
220
-
221
- Routed through `core.grid_events.handle_one` as an `overlay_patch` event rather than writing
222
- the store directly: that handler is where the per-key `permissions.edit` wall, the pid wall
223
- and the truncation rules live, and a second implementation of those would be a second set of
224
- them to keep in step. The response reports what was ACCEPTED, which is not always what was
225
- asked for.
226
- """
227
- from core import grid_events
228
-
229
- updates = dict(body or {})
230
- if not updates:
231
- raise err(400, "empty_patch", "no fields to update")
232
- pool = allowed_pids(session)
233
- if pid not in pool:
234
- # 403, not 404: the pid may well exist β€” it is simply not in this session's book, and
235
- # saying "no such customer" would confirm the opposite to anyone who guessed right.
236
- raise err(403, "out_of_scope", "that customer is not in your book")
237
- payload = _payload(session)
238
- ctx = grid_events.EventCtx(
239
- uname=session.uname, allowed_pids=pool, fields=payload["fields"],
240
- admin=session.admin, fallback_ws=None, seen_ids={})
241
- try:
242
- grid_events.handle_one(
243
- {"id": f"patch:{pid}:{time.time_ns()}", "type": "overlay_patch",
244
- "pid": pid, "updates": updates}, ctx)
245
- except grid_events.StoreUnavailable:
246
- raise err(503, "store_unavailable",
247
- "the tenant store is unavailable β€” your change was not saved")
248
-
249
- # What actually landed, read back from the store rather than echoed from the request: a
250
- # refused key or a truncated value must not be reported as accepted.
251
- stored = (grid_events.table_workspace(_ctx_for(session, pool), allowed_pids=None)
252
- .get("overlays") or {}).get(str(pid)) or {}
253
- accepted = {k: stored.get(k) for k in updates if k in stored}
254
- refused = sorted(k for k in updates if k not in accepted or stored.get(k) != str(updates[k]))
255
- # No cache to patch: the overlay stratum is re-read from the store on every `_payload`, so
256
- # read-your-writes within this runtime is a property of the design rather than of a
257
- # write-through step somebody has to remember. (It was a write-through step while the whole
258
- # payload was cached on a scope key β€” the arrangement that leaked one user's notes to
259
- # another. See `_pool_rows`.) Cross-RUNTIME coherence is still not claimed: the module
260
- # docstring says why, and Postgres is the fix.
261
- out = {"ok": True, "pid": pid, "updates": accepted}
262
- if refused:
263
- out["refused"] = refused
264
- return out
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """routes_customers.py β€” X2's read + write of the customer table, BU-SCOPED (EXIT-3b / EXIT-2a).
2
+
3
+ Two things happen here that did not happen in the pre-wave `main.py`:
4
+
5
+ 1. **ROWS ARE SCOPED TO THE SESSION.** The old `/api/customers` served `cl.pool()` β€” the whole
6
+ book, to anyone holding the shared APP_PASSWORD. Now the pool is built with
7
+ `(team_id, agent_name)` derived from the USER RECORD, so a Royal-only user never receives a
8
+ Fisch row and an agent-linked login never receives another rep's book. The scope is applied
9
+ at the QUERY, not as a post-filter, so there is no moment at which the other BU's rows exist
10
+ in this response.
11
+
12
+ 2. **THE OVERLAY FORK IS GONE.** `aios-web/api/data/overlay.json` was a SECOND writable home
13
+ for the same user-owned fields the Streamlit app keeps in the tenant store β€” two truths, and
14
+ whichever process you asked last was right. Reads and writes now both go through
15
+ `modules.customer_data`'s table-workspace functions: ONE store (C1c, ARCHITECTURE Β§1a rule 3).
16
+
17
+ ⚠ ONE STORE IS NOT YET ONE CACHE (strangler-period, booked honestly). `core.store.get()` is
18
+ cache-first per PROCESS, so a write from the Streamlit container is invisible to a running API
19
+ container until its cache is refreshed, and vice versa. Deleting the fork removes the second
20
+ SOURCE OF TRUTH; it does not make the two runtimes coherent. The fix is X4/Postgres (task C-4,
21
+ owner-blocked on B-3), and no test here may claim read-your-writes ACROSS runtimes β€” a TestClient
22
+ proof is single-process and would report green on exactly the thing that is still broken.
23
+ """
24
+ import time
25
+
26
+ from fastapi import APIRouter, Body, Depends
27
+
28
+ import scope_cache
29
+ from deps import Session, err, module_gate, perms
30
+
31
+ router = APIRouter(prefix="/api/v1")
32
+
33
+ #: The surface these routes serve. Both legs are gated on it, so a user without the grant gets a
34
+ #: 403 rather than an empty table that looks like "you have no customers".
35
+ MODULE = "customer_data"
36
+
37
+ _CACHE_TTL = 900 # the pool build is slow (Odoo + reconciliation); 15 min, as before
38
+
39
+
40
+ def _pool_rows(session: Session):
41
+ """The reconciled Odoo pool for this session's SCOPE β€” the slow part, and the only part that
42
+ may be shared between users.
43
+
44
+ β›” WHAT MAY BE CACHED HERE, AND WHY THE LINE IS EXACTLY HERE. The cache key is
45
+ `(team_id, agent)` and the cached value is the raw pool: Odoo-source columns only. That is
46
+ genuinely scope-shaped β€” two users with the same BU and the same book are asking the same
47
+ question, and `cl.pool()` is expensive (an Odoo pull plus reconciliation).
48
+
49
+ The FULL PAYLOAD is NOT cacheable on this key, and caching it here was a real defect I shipped
50
+ and then removed. `fields` comes from `fields_from_workspace(ws)` β€” that user's own `custom_`
51
+ and `measure_` columns β€” and every overlay cell comes from `ws['overlays']`; the table
52
+ workspace is read as `data[username]` and written as `patch_table_overlay(uname, …)`, i.e.
53
+ PER USER. So two Royal-only users with no agent link share `(6, None)` and the second one
54
+ would have been served the FIRST one's private notes and private columns. The scope key was
55
+ right for the pool and wrong for everything wrapped around it.
56
+
57
+ It survived a green 129-check battery because every fixture user had a DISTINCT
58
+ `(team_id, agent)` pair, so no two of them ever collided on the key β€” the test set could not
59
+ express the bug. `verify_api.py` now carries a same-scope second user for exactly this.
60
+ """
61
+ rt = session.runtime
62
+ team_id, agent = _team_agent(session)
63
+ return _pool_for(rt, team_id, agent)
64
+
65
+
66
+ def _pool_for(rt, team_id, agent):
67
+ """The cached pool for an explicit scope β€” session-free so the prewarm thread and the
68
+ stale-refresh path can call it. STALE-WHILE-REFRESH (scope_cache): once a copy exists no
69
+ request blocks on the 10–30s Odoo rebuild again; only a scope's FIRST-ever build does."""
70
+ import modules.customer_data as cl
71
+
72
+ key = ("pool", team_id, agent)
73
+
74
+ def _build():
75
+ # ⚠ THE SCOPE GOES INTO THE BUILDER. `pool(agent_name, team_id)` is the same reconciled
76
+ # builder the Streamlit page uses β€” passing the scope here is what makes the isolation a
77
+ # property of the QUERY instead of a filter someone can forget to apply downstream.
78
+ return cl.pool(agent, team_id)
79
+
80
+ def _evict():
81
+ # Bounded: a scope cache that only ever grows is a memory leak in a shared process.
82
+ if len(rt.pool_cache) > 16:
83
+ for stale in sorted(rt.pool_cache, key=lambda k: rt.pool_cache[k][0])[:8]:
84
+ rt.pool_cache.pop(stale, None)
85
+
86
+ return scope_cache.get(rt.pool_cache, key, _CACHE_TTL, _build, _evict)
87
+
88
+
89
+ def warm_default(rt):
90
+ """Boot prewarm: the consolidated pool `(None, None)` β€” the scope every admin and every
91
+ all-BU account lands on. Called from main.py's prewarm thread only."""
92
+ _pool_for(rt, None, None)
93
+
94
+
95
+ def _team_agent(session: Session):
96
+ """The `(team_id, agent)` this session's POOL is built with β€” ONE derivation point, used by
97
+ `_pool_rows` and `grid_assembly` alike, so the cache key and the query can never disagree.
98
+
99
+ β›” WAVE 15 R1: THIS NOW COMES FROM THE PERMANENT FILTER (C-PERM amendment 3). `team_id` is
100
+ not a row filter β€” `customer_data._pool_build` passes it into `cust._cust_rev` three times
101
+ and into `_cadence_bulk`, so it decides what `rev`/`ly`/`ltm`/`aov`/`status` MEAN. Enforcing
102
+ a BU purely as a post-filter would keep the row list right and silently consolidate every
103
+ number. So the pushdown survives as a DERIVATION OF the declared filter rather than a second
104
+ wall beside it, and `perm_scope.derive_pool_scope` falls back to the legacy `bus`/`agent`
105
+ derivation for any record the migration has not reached yet.
106
+ """
107
+ import core.perm_scope as perm_scope
108
+ return perm_scope.derive_pool_scope(session.user, MODULE)
109
+
110
+
111
+ def _pool_stamp(rt, team_id, agent):
112
+ """The cached pool's build timestamp β€” the DATA STAMP in every measure-memo key, so a pool
113
+ refresh invalidates the memoised answers exactly when the underlying rows changed."""
114
+ entry = rt.pool_cache.get(("pool", team_id, agent))
115
+ return entry[0] if isinstance(entry, tuple) and entry else 0
116
+
117
+
118
+ def _measure_err(tag, e):
119
+ try:
120
+ import harness.telemetry as _tel
121
+ _tel.error(f"api:{tag}", e)
122
+ except Exception:
123
+ pass
124
+
125
+
126
+ def grid_assembly(session: Session, scope: str = "customer", storage_key: str = "",
127
+ consume_corrections: bool = True):
128
+ """ONE assembly of this session's grid state, shared by `/customers`, `/workspace` and the
129
+ events route (2026-07-31 β€” the standalone measure gap, owner item 1).
130
+
131
+ What it adds over the pre-wave hand-rolled `_payload` loop, and why it replaced it:
132
+
133
+ * rows go through `aios_grid.rows_from_pool` β€” the SAME builder the embedded host uses,
134
+ so `lat`/`lon` (the Map view's data), `_created` and every derived column ride each row
135
+ by construction instead of by a second loop that drifts. The hand loop was written to
136
+ mirror the pre-Map contract and silently dropped the coordinates: the shell's Map view
137
+ had nothing to plot ("the Map no longer works").
138
+ * `derived` carries the cohort column's cells AND the measure columns' values, resolved
139
+ through `core.measure_resolve` (EXIT-5's extraction of the `_cl_measure_*` family).
140
+ Without them every measure column the owner built rendered BLANK in the shell.
141
+ * `measures` (the offer) and `measure_sets` (condition answers) are computed here so the
142
+ events route can finally validate measure fields/conditions instead of refusing them
143
+ (an empty `measure_offer` made `clean_measure_field` reject every create over HTTP).
144
+
145
+ Memos live on the TENANT RUNTIME (`rt.measure_memo` / `rt.mset_memo`) β€” bounded by the
146
+ module's own clear-past-cap rule, keyed on (stamp, scope, pool identity, question), nothing
147
+ user-shaped in them.
148
+ """
149
+ import aios_grid
150
+ from core import grid_events, measure_resolve
151
+
152
+ import core.perm_scope as perm_scope
153
+
154
+ rt = session.runtime
155
+ team_id, agent = _team_agent(session)
156
+ rows_src = _pool_for(rt, team_id, agent)
157
+ # β›” THE ROW WALL, APPLIED BEFORE `pids` IS TAKEN. Everything downstream is bounded by that
158
+ # frozenset β€” `allowed_pids` for the workspace, cohort membership, measure resolution β€” so
159
+ # scoping here means a row this account may not see never enters ANY of them, rather than
160
+ # being filtered out of one payload and surviving in another.
161
+ #
162
+ # Evaluated against the CANONICAL field list, not the per-user assembled one, for two
163
+ # reasons: the assembled list is not built yet (it needs `pids`), and a permanent filter may
164
+ # only ever name a canonical field anyway β€” `routes_admin._clean_perms` validates it against
165
+ # exactly this schema and 400s otherwise. `permits()` denies on anything it cannot answer.
166
+ rows_src = perm_scope.apply_row_scope(rows_src, session.user, MODULE, aios_grid.FIELDS)
167
+ pids = frozenset(r["pid"] for r in rows_src if r.get("pid") is not None)
168
+ ws = grid_events.table_workspace(
169
+ _ctx_for(session, pids), allowed_pids=pids,
170
+ consume_corrections=consume_corrections)
171
+ workspace, fields, views, lists = aios_grid.workspace_wire(
172
+ ws, session.uname, set(pids), defs={}, scope_key=scope, storage_key=storage_key)
173
+ # THE FIELD WALL β€” a TRANSITIVE closure (C-PERM amendment 5), so hiding a field also hides
174
+ # every formula computed FROM it. Formulas evaluate in the browser from `{ref}`s, so
175
+ # shipping a dependent formula while withholding its input either leaks the input through
176
+ # the formula's value or silently computes a wrong one; only removing both is coherent.
177
+ # Applied AFTER workspace_wire because custom + measure columns are what it must cover.
178
+ hidden = perm_scope.hidden_keys(session.user, MODULE, fields)
179
+ if hidden:
180
+ fields = [f for f in fields if f.get("key") not in hidden]
181
+ # The field LIST and the ROW payload are two different wires. Narrowing only the first
182
+ # would leave the value sitting in the second, where anything can read it.
183
+ rows_src = [perm_scope.strip_row(r, hidden) for r in rows_src]
184
+
185
+ today = time.strftime("%Y-%m-%d")
186
+ stamp = _pool_stamp(rt, team_id, agent)
187
+ measures = measure_resolve.offer(team_id, on_error=_measure_err)
188
+ measure_sets = measure_resolve.condition_sets(
189
+ [v.get("config") or {} for v in (views or [])], None, team_id, pids, today, stamp,
190
+ rt.mset_memo, on_error=_measure_err)
191
+ # The derived channel: cohort membership cells + measure column values, ONE dict β€” the
192
+ # same read-only channel the embed host hands to rows_from_pool.
193
+ derived = aios_grid.cohort_cells(lists)
194
+ for pid, cells in measure_resolve.column_values(
195
+ fields, team_id, pids, today, stamp, rt.measure_memo,
196
+ on_error=_measure_err).items():
197
+ derived.setdefault(pid, {}).update(cells)
198
+
199
+ return {"rows_src": rows_src, "pids": pids, "ws": ws, "workspace": workspace,
200
+ "fields": fields, "views": views, "lists": lists, "derived": derived,
201
+ "measures": measures, "measure_sets": measure_sets, "today": today,
202
+ "team_id": team_id}
203
+
204
+
205
+ def _payload(session: Session):
206
+ """`{fields, rows, today, pulled_at}` β€” X2's shape, which `verify_fields_contract.py`
207
+ referees. Rows are now built by `aios_grid.rows_from_pool` (embed == standalone by
208
+ construction); see `grid_assembly` for what that fixed.
209
+
210
+ ⚠ `rows_src` is the SHARED cached list β€” `rows_from_pool` reads it and builds NEW dicts,
211
+ never mutating a cached row (the same-scope-second-user leak rule).
212
+ """
213
+ import aios_grid
214
+
215
+ g = grid_assembly(session)
216
+ rows = aios_grid.rows_from_pool(
217
+ g["rows_src"], g["fields"], g["ws"].get("overlays"), derived=g["derived"])
218
+ return {"fields": g["fields"], "rows": rows,
219
+ # `today` rides the payload because every relative date condition must resolve against
220
+ # the TENANT's day, never the browser's β€” a client that falls back to its own clock
221
+ # disagrees with the server for everyone west of it.
222
+ "today": g["today"],
223
+ "pulled_at": time.strftime("%Y-%m-%d %H:%M")}
224
+
225
+
226
+ def _ctx_for(session: Session, pids):
227
+ """An EventCtx for the READ path β€” no fallback workspace, so a store outage is a 503 rather
228
+ than a phantom in-memory workspace an API request cannot persist."""
229
+ from core import grid_events
230
+ return grid_events.EventCtx(
231
+ uname=session.uname, allowed_pids=frozenset(pids or ()), fields=[],
232
+ # C-PERM: the write wall's field half. Computed from the CANONICAL contract because
233
+ # `fields=[]` here β€” the closure only needs the schema, not this user's column list.
234
+ hidden_keys=_hidden_for(session),
235
+ admin=session.admin, fallback_ws=None, seen_ids={})
236
+
237
+
238
+
239
+ def _hidden_for(session: Session):
240
+ """The fields this session's permissions hide β€” the write wall's half of C-PERM.
241
+
242
+ Read paths strip these from both wires so they cannot be SEEN; this is what stops them
243
+ being WRITTEN by a caller who knows the key. Evaluated against the canonical contract, the
244
+ same schema `routes_admin._clean_perms` validates a hiddenFields entry against.
245
+ """
246
+ import aios_grid
247
+ import core.perm_scope as perm_scope
248
+
249
+ return perm_scope.hidden_keys(session.user, MODULE, aios_grid.FIELDS)
250
+
251
+ def allowed_pids(session: Session):
252
+ """The pids this session may touch β€” the POOL's own ids, so the write wall and the read scope
253
+ can never disagree.
254
+
255
+ Reads `_pool_rows` rather than `_payload`: the wall only needs identities, and going through
256
+ the full payload would pay for a workspace read and a row assembly on every write.
257
+
258
+ β›” THE PERMANENT FILTER APPLIES HERE TOO, AND FORGETTING IT IS A WRITE-WITHOUT-READ HOLE.
259
+ `_pool_rows` is built with the DERIVED pushdown, which expresses only what a `(team_id,
260
+ agent)` pair can express. Any part of the wall the pushdown cannot carry β€” `revenue > 1000`,
261
+ a nested group, a condition on any other column β€” leaves the pool WIDER than the filter. Read
262
+ paths close that gap with `apply_row_scope`; without the same call here the write wall would
263
+ be the wider set, and a restricted user could PATCH a row this API will not show them.
264
+ Same function, same order as `grid_assembly`, so the two walls cannot drift.
265
+ """
266
+ import core.perm_scope as perm_scope
267
+ import aios_grid
268
+
269
+ rows = perm_scope.apply_row_scope(_pool_rows(session), session.user, MODULE,
270
+ aios_grid.FIELDS)
271
+ return frozenset(r["pid"] for r in rows if r.get("pid") is not None)
272
+
273
+
274
+ @router.get("/customers")
275
+ def customers(session: Session = Depends(module_gate(MODULE))):
276
+ return _payload(session)
277
+
278
+
279
+ @router.patch("/customers/{pid}")
280
+ def patch_customer(pid: int, body: dict = Body(default=None),
281
+ session: Session = Depends(module_gate(MODULE))):
282
+ """Write the EDITABLE overlay stratum only β€” Odoo stays read-only, forever.
283
+
284
+ Routed through `core.grid_events.handle_one` as an `overlay_patch` event rather than writing
285
+ the store directly: that handler is where the per-key `permissions.edit` wall, the pid wall
286
+ and the truncation rules live, and a second implementation of those would be a second set of
287
+ them to keep in step. The response reports what was ACCEPTED, which is not always what was
288
+ asked for.
289
+ """
290
+ from core import grid_events
291
+
292
+ updates = dict(body or {})
293
+ if not updates:
294
+ raise err(400, "empty_patch", "no fields to update")
295
+ pool = allowed_pids(session)
296
+ if pid not in pool:
297
+ # 403, not 404: the pid may well exist β€” it is simply not in this session's book, and
298
+ # saying "no such customer" would confirm the opposite to anyone who guessed right.
299
+ raise err(403, "out_of_scope", "that customer is not in your book")
300
+ payload = _payload(session)
301
+ ctx = grid_events.EventCtx(
302
+ uname=session.uname, allowed_pids=pool, fields=payload["fields"],
303
+ admin=session.admin, fallback_ws=None, seen_ids={},
304
+ hidden_keys=_hidden_for(session))
305
+ try:
306
+ grid_events.handle_one(
307
+ {"id": f"patch:{pid}:{time.time_ns()}", "type": "overlay_patch",
308
+ "pid": pid, "updates": updates}, ctx)
309
+ except grid_events.StoreUnavailable:
310
+ raise err(503, "store_unavailable",
311
+ "the tenant store is unavailable β€” your change was not saved")
312
+
313
+ # What actually landed, read back from the store rather than echoed from the request: a
314
+ # refused key or a truncated value must not be reported as accepted.
315
+ stored = (grid_events.table_workspace(_ctx_for(session, pool), allowed_pids=None)
316
+ .get("overlays") or {}).get(str(pid)) or {}
317
+ accepted = {k: stored.get(k) for k in updates if k in stored}
318
+ refused = sorted(k for k in updates if k not in accepted or stored.get(k) != str(updates[k]))
319
+ # No cache to patch: the overlay stratum is re-read from the store on every `_payload`, so
320
+ # read-your-writes within this runtime is a property of the design rather than of a
321
+ # write-through step somebody has to remember. (It was a write-through step while the whole
322
+ # payload was cached on a scope key β€” the arrangement that leaked one user's notes to
323
+ # another. See `_pool_rows`.) Cross-RUNTIME coherence is still not claimed: the module
324
+ # docstring says why, and Postgres is the fix.
325
+ out = {"ok": True, "pid": pid, "updates": accepted}
326
+ if refused:
327
+ out["refused"] = refused
328
+ return out
api/routes_grid.py CHANGED
@@ -39,15 +39,36 @@ _MAX_EVENTS = 24
39
 
40
  def _ctx(session: Session, fields, pids, **kw):
41
  from core import grid_events
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
  return grid_events.EventCtx(
43
  uname=session.uname, allowed_pids=pids, fields=fields, admin=session.admin,
 
 
 
 
44
  fallback_ws=None, seen_ids={}, **kw)
45
 
46
 
47
- #: The two surfaces the ONE grid serves. `cohort` is the same table over hand-curated SETS rather
48
  #: than over the whole scoped pool β€” `app.py:page_cohort` calls the same `_table_grid` with
49
- #: `cohort_mode=True, scope_key='cohort'`.
50
- _SCOPES = ("customer", "cohort")
 
51
 
52
 
53
  def _scope_or_400(raw):
@@ -81,11 +102,51 @@ def workspace(scope: str = "customer",
81
  from routes_customers import grid_assembly
82
 
83
  scope = _scope_or_400(scope)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84
  # The storage key mirrors the host's own convention byte-for-byte (app.py's `_table_grid`
85
  # call sites) with the session's TENANT in the host's hardcoded slot, so localStorage state
86
  # carries across embed ⇄ standalone on the same browser.
87
- team_id = perms.scope_team_id(session.user)
88
- agent = perms.scope_agent(session.user)
 
 
 
 
89
  bu = team_id if team_id is not None else "all"
90
  if scope == "cohort":
91
  storage_key = f"{session.tenant}:cohort:{session.uname}:{bu}"
@@ -202,7 +263,7 @@ def _ts_label(bucket, start):
202
 
203
 
204
  @router.post("/grid/timeseries")
205
- def grid_timeseries(body: dict = Body(default=None),
206
  session: Session = Depends(module_gate(MODULE))):
207
  """Pooled measure values per calendar bucket β€” the time-series view's data channel.
208
 
@@ -225,6 +286,16 @@ def grid_timeseries(body: dict = Body(default=None),
225
  from harness import windows as _wn
226
  from routes_customers import _pool_stamp, _team_agent, allowed_pids
227
 
 
 
 
 
 
 
 
 
 
 
228
  body = body or {}
229
  bucket = body.get("bucket")
230
  if bucket not in _TS_BUCKETS:
@@ -397,7 +468,18 @@ def grid_events_route(body: dict = Body(default=None),
397
  scope = _scope_or_400((body or {}).get("scopeKey"))
398
  # This assembly validates the write; it is not a payload the browser will render. Leave
399
  # one-shot field-name correction acks queued for the subsequent /workspace refresh.
400
- g = grid_assembly(session, scope=scope, consume_corrections=False)
 
 
 
 
 
 
 
 
 
 
 
401
  # ⚠ THE MEASURE CONTEXT IS NOT OPTIONAL (2026-07-31). Without `measure_offer`,
402
  # `clean_measure_field` had an empty admission list and every measure-column create over
403
  # HTTP was silently refused; without `measure_keys`, `clean_filter_tree` stripped every
 
39
 
40
  def _ctx(session: Session, fields, pids, **kw):
41
  from core import grid_events
42
+ import aios_grid
43
+ import core.perm_scope as perm_scope
44
+
45
+ # Wave 16 C-TOPIC: the ctx is TOPIC-SHAPED. The product scope swaps all three of the
46
+ # things a write is validated against β€” the module the permission wall reads, the canonical
47
+ # contract the hidden-field closure runs over, and the TABLE OPS the write lands in.
48
+ # Getting any one of them from the other topic is the "validated against the wrong field
49
+ # contract" near-miss the wave-15 routes_products header warned about.
50
+ if kw.get("scope_key") == "product":
51
+ import modules.product_data as pd
52
+ from routes_products import MODULE as _PMOD, pd_fields
53
+
54
+ module, canonical = _PMOD, pd_fields(consolidated=True)
55
+ kw.setdefault("table", pd.TABLE_OPS)
56
+ else:
57
+ module, canonical = MODULE, aios_grid.FIELDS
58
  return grid_events.EventCtx(
59
  uname=session.uname, allowed_pids=pids, fields=fields, admin=session.admin,
60
+ # C-PERM: the write wall's field half, on the EVENTS transport too. This route takes the
61
+ # component's event objects verbatim, so a hidden key would otherwise arrive here with
62
+ # nothing between it and the store.
63
+ hidden_keys=perm_scope.hidden_keys(session.user, module, canonical),
64
  fallback_ws=None, seen_ids={}, **kw)
65
 
66
 
67
+ #: The surfaces the ONE grid serves. `cohort` is the same table over hand-curated SETS rather
68
  #: than over the whole scoped pool β€” `app.py:page_cohort` calls the same `_table_grid` with
69
+ #: `cohort_mode=True, scope_key='cohort'`. `product` (wave 16 C-TOPIC) is the SKU table:
70
+ #: same engine, its own pool, field contract and workspace BUCKET (routes_products).
71
+ _SCOPES = ("customer", "cohort", "product")
72
 
73
 
74
  def _scope_or_400(raw):
 
102
  from routes_customers import grid_assembly
103
 
104
  scope = _scope_or_400(scope)
105
+ # ── Wave 16 C-TOPIC: the PRODUCT surface has its own assembly (own pool, own field
106
+ # contract, own workspace BUCKET) and the contract's own storage key. It branches before
107
+ # the customer derivation because the customer storage key embeds (bu, agent) while the
108
+ # product one is deliberately `all:all` β€” one product workspace per user (the wave doc's
109
+ # C-TOPIC line), since BU narrows the product VALUES, not which workspace you own.
110
+ if scope == "product":
111
+ from routes_products import MODULE as PRODUCT_MODULE, product_assembly
112
+
113
+ # β›” THE GATE CHANGES WITH THE SCOPE. This route's dependency asserts the CUSTOMER
114
+ # grant; a caller asking for the product surface must hold the PRODUCT grant too, or a
115
+ # customer-only account could read product workspaces through this one door.
116
+ session.require(PRODUCT_MODULE)
117
+ storage_key = f"{session.tenant}:product-list:{session.uname}:all:all"
118
+ try:
119
+ g = product_assembly(session, scope=scope, storage_key=storage_key)
120
+ except grid_events.StoreUnavailable:
121
+ raise err(503, "store_unavailable", "the tenant store is unavailable")
122
+ workspace = g["workspace"]
123
+ workspace["overlays"] = g["ws"].get("overlays") or {}
124
+ # The measure channel is EMPTY on this topic (customer-grain descope) β€” stated
125
+ # explicitly so the client's pickers grey rather than guess.
126
+ workspace["measures"] = g["measures"]
127
+ workspace["measureSets"] = g["measure_sets"]
128
+ workspace["derived"] = {}
129
+ workspace["viewer"] = {"name": session.uname, "isAdmin": bool(session.admin)}
130
+ try:
131
+ from core import users as _users
132
+ workspace["userOptions"] = _users.assignable_people()
133
+ workspace["userAvatars"] = {k: v for k, v in _users.avatar_map().items()
134
+ if str(v).startswith("data:image/")}
135
+ except Exception:
136
+ workspace["userOptions"] = []
137
+ workspace["userAvatars"] = {}
138
+ workspace["scopeKey"] = scope
139
+ return {"workspace": workspace}
140
+
141
  # The storage key mirrors the host's own convention byte-for-byte (app.py's `_table_grid`
142
  # call sites) with the session's TENANT in the host's hardcoded slot, so localStorage state
143
  # carries across embed ⇄ standalone on the same browser.
144
+ # Wave 15 R1 β€” the SAME derivation the pool uses (`routes_customers._team_agent`), so the
145
+ # storage key cannot drift from the scope it names. Value-identical for every migrated
146
+ # record (verify_perm_scope section D proves the derivation reproduces the legacy scope
147
+ # exactly), so nobody's saved localStorage state moves when the migration runs.
148
+ import core.perm_scope as perm_scope
149
+ team_id, agent = perm_scope.derive_pool_scope(session.user, MODULE)
150
  bu = team_id if team_id is not None else "all"
151
  if scope == "cohort":
152
  storage_key = f"{session.tenant}:cohort:{session.uname}:{bu}"
 
263
 
264
 
265
  @router.post("/grid/timeseries")
266
+ def grid_timeseries(body: dict = Body(default=None), scope: str = "customer",
267
  session: Session = Depends(module_gate(MODULE))):
268
  """Pooled measure values per calendar bucket β€” the time-series view's data channel.
269
 
 
286
  from harness import windows as _wn
287
  from routes_customers import _pool_stamp, _team_agent, allowed_pids
288
 
289
+ # Wave 16 C-TOPIC: the channel is CUSTOMER-GRAIN (measure_resolve's own grain), so the
290
+ # product surface is refused in words rather than answered with an id-space accident β€”
291
+ # product pids are CRC32 hashes and would mostly fall outside the customer book anyway,
292
+ # but "mostly" is not a wall. The client hides the mode for this topic; this is the
293
+ # server's half of the same refusal.
294
+ if _scope_or_400(scope) == "product":
295
+ raise err(400, "bad_timeseries",
296
+ "the product surface has no time-series channel yet β€” measures are "
297
+ "customer-grain")
298
+
299
  body = body or {}
300
  bucket = body.get("bucket")
301
  if bucket not in _TS_BUCKETS:
 
468
  scope = _scope_or_400((body or {}).get("scopeKey"))
469
  # This assembly validates the write; it is not a payload the browser will render. Leave
470
  # one-shot field-name correction acks queued for the subsequent /workspace refresh.
471
+ # Wave 16 C-TOPIC: the PRODUCT topic gets the product assembly β€” product field contract,
472
+ # product pids, and (below) the product TABLE OPS, so a product event is validated against
473
+ # and lands in the product bucket. The measure/cohort context is honestly EMPTY there:
474
+ # `clean_measure_field` refuses measure creates on this surface by construction (the
475
+ # customer-grain descope), which is the fail-closed shape, not an accident.
476
+ if scope == "product":
477
+ from routes_products import MODULE as PRODUCT_MODULE, product_assembly
478
+
479
+ session.require(PRODUCT_MODULE) # the route's own dependency asserts only customer_data
480
+ g = product_assembly(session, consume_corrections=False)
481
+ else:
482
+ g = grid_assembly(session, scope=scope, consume_corrections=False)
483
  # ⚠ THE MEASURE CONTEXT IS NOT OPTIONAL (2026-07-31). Without `measure_offer`,
484
  # `clean_measure_field` had an empty admission list and every measure-column create over
485
  # HTTP was silently refused; without `measure_keys`, `clean_filter_tree` stripped every
api/routes_pages.py CHANGED
@@ -19,14 +19,13 @@ FAIL-CLOSED, and the order matters:
19
  from fastapi import APIRouter, Depends, Query
20
 
21
  import pages
22
- # β›” IMPORTED HERE AT MODULE LEVEL ON PURPOSE, even though `pages.builder_for` also imports it
23
- # lazily. `deploy_web.py` ships a hand-maintained file set, and W2-11 adds a `check_include()`-style
24
- # IMPORT WALK to catch what that set misses β€” a walk that only follows module-level imports would
25
- # never reach a builder registered from inside a function body, and a missing module CRASHED the
26
- # live Space on 2026-07-04. One visible import makes the builder reachable by static analysis; the
27
- # lazy import in `pages.py` stays as the fallback that keeps the registry self-assembling.
28
- # (No circularity: `pages` is fully loaded by the line above before `pages_sales` imports it back.)
29
- import pages_sales # noqa: F401
30
  from deps import Session, require_session
31
 
32
  router = APIRouter(prefix="/api/v1")
 
19
  from fastapi import APIRouter, Depends, Query
20
 
21
  import pages
22
+ # ⚠ Wave 16 (owner item 7): the module-level pages_sales import was REMOVED β€” the Sales page
23
+ # is retired, so no builder registers in production and every /pages/{key} 404s (a roadmap
24
+ # fact, not a grant fact). When the next builder lands (Collections / Procurement), import it
25
+ # HERE at module level, not only lazily: deploy_web.py's import walk follows module-level
26
+ # imports, and a builder registered from inside a function body is invisible to it β€” a
27
+ # missing module CRASHED the live Space on 2026-07-04. (verify_api section G scans this file
28
+ # for the retired import β€” phrase any mention of it so the scan cannot read prose as code.)
 
29
  from deps import Session, require_session
30
 
31
  router = APIRouter(prefix="/api/v1")
api/routes_products.py ADDED
@@ -0,0 +1,197 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """routes_products.py β€” the PRODUCT table's read seam (wave 15 item 9/10, contract C-TOPIC).
2
+
3
+ The proof that C-TOPIC's bet is real: **a second table object is a pool module plus a route, not
4
+ a second component tree**. Everything structural here is borrowed rather than re-implemented β€”
5
+ the permission wall (`core.perm_scope`), the row builder (`aios_grid.rows_from_pool`), the
6
+ scope-keyed stale-while-refresh cache (`scope_cache`), the error shape, the module gate.
7
+
8
+ β›” NOT REACHABLE FROM THE NAV YET, AND THAT IS THE POINT OF LANDING IT THIS WAY. There is no
9
+ `product_data` registry row, so `core.perms.nav_pages` never emits one and no user can navigate
10
+ here; the route answers only to a caller who already knows the URL AND holds the grant. That
11
+ keeps a half-built surface off the owner's screen while the server half is real, gated and
12
+ reviewable β€” rather than shipping a nav entry that opens onto columns nobody has reconciled.
13
+ Wave 16 adds the registry row, the client `topic` prop and the write path; both are named in the
14
+ wave doc rather than left implicit.
15
+
16
+ Wave 16 (C-TOPIC's second half): the WRITE PATH exists now, and it is exactly what the wave-15
17
+ header demanded before one could β€” its OWN table workspace bucket
18
+ (`modules.product_data.TABLE_OPS`, store key 'product_table_workspace') and its own event
19
+ validation (the events route builds the ctx over the PRODUCT field contract + product pids +
20
+ the product ops). β›” The separate bucket is load-bearing, not tidy: product pids are CRC32
21
+ hashes and customer pids are Odoo partner ids β€” one shared overlay bucket and a hash collision
22
+ silently writes a product note onto somebody's customer.
23
+ """
24
+ import time
25
+
26
+ from fastapi import Body, Depends
27
+
28
+ from fastapi import APIRouter
29
+
30
+ import scope_cache
31
+ from deps import Session, err, module_gate
32
+
33
+ router = APIRouter(prefix="/api/v1")
34
+
35
+ #: The registry key this surface WILL carry. The gate is live now even though the nav is not, so
36
+ #: the day the registry row appears the wall is already the one that was tested.
37
+ MODULE = "product_data"
38
+
39
+ _CACHE_TTL = 900
40
+
41
+
42
+ def _pool_for(rt, team_id):
43
+ """The cached SKU pool for one scope. Same stale-while-refresh discipline as the customer
44
+ pool: only a scope's FIRST-ever build blocks, and the cache key is the SCOPE, never the user
45
+ β€” the customer route learned that the hard way (a per-user payload cached on a scope key
46
+ served one user's private columns to another)."""
47
+ import modules.product_data as pd
48
+
49
+ # ⚠ Signature is (cache, key, ttl, build) β€” the wave-15 version passed `ttl=` as a keyword
50
+ # after the build lambda and DIED on every call ("multiple values for 'ttl'"). Latent until
51
+ # wave 16 because nothing drove this route end-to-end: verify_perm_scope's section H stubs
52
+ # the pool a layer below. verify_api's W16 section now exercises the real call.
53
+ return scope_cache.get(rt.pool_cache, ("product_pool", team_id), _CACHE_TTL,
54
+ lambda: pd.pool(team_id=team_id))
55
+
56
+
57
+ def product_assembly(session: Session, scope: str = "product", storage_key: str = "",
58
+ consume_corrections: bool = True):
59
+ """The product topic's mirror of `routes_customers.grid_assembly` β€” SAME g-dict keys, so
60
+ the /workspace and events routes consume either interchangeably.
61
+
62
+ Three deliberate absences, each a topic fact rather than a gap:
63
+ * `measures`/`measure_sets` are EMPTY β€” `core.measure_resolve` is CUSTOMER-grain (the
64
+ C-TOPIC v1 descope, booked in the wave doc); the events ctx therefore refuses measure
65
+ creates on this surface, which is the correct fail-closed shape.
66
+ * `lists` is EMPTY and `workspace_wire(with_cohorts=False)` β€” cohorts store PARTNER pids;
67
+ resolving them against CRC32 product pids would intersect two unrelated id spaces.
68
+ * `derived` is EMPTY β€” it exists to carry cohort + measure cells, and there are neither.
69
+ """
70
+ import aios_grid
71
+ import core.perm_scope as perm_scope
72
+ import modules.product_data as pd
73
+ from core import grid_events
74
+
75
+ team_id, _agent = perm_scope.derive_pool_scope(session.user, MODULE)
76
+ try:
77
+ rows_src = _pool_for(session.runtime, team_id)
78
+ except Exception as e:
79
+ raise err(503, "pool_unavailable",
80
+ f"the product catalogue could not be built β€” {str(e)[:160]}")
81
+
82
+ fields_base = pd_fields(consolidated=team_id is None)
83
+ # The SAME wall the customer assembly applies, in the same order: rows first (before pids
84
+ # are taken, so an out-of-filter row never enters allowed_pids), then the field closure,
85
+ # then the values stripped from the rows as well as the field list.
86
+ rows_src = perm_scope.apply_row_scope(rows_src, session.user, MODULE, fields_base)
87
+ pids = frozenset(r["pid"] for r in rows_src if r.get("pid") is not None)
88
+
89
+ ctx = grid_events.EventCtx(
90
+ uname=session.uname, allowed_pids=pids, fields=[],
91
+ hidden_keys=perm_scope.hidden_keys(session.user, MODULE, fields_base),
92
+ admin=session.admin, fallback_ws=None, seen_ids={},
93
+ scope_key="product", table=pd.TABLE_OPS)
94
+ ws = grid_events.table_workspace(ctx, allowed_pids=pids,
95
+ consume_corrections=consume_corrections)
96
+ workspace, fields, views, lists = aios_grid.workspace_wire(
97
+ ws, session.uname, set(pids), defs={}, scope_key=scope, storage_key=storage_key,
98
+ fields_base=fields_base, with_cohorts=False)
99
+
100
+ hidden = perm_scope.hidden_keys(session.user, MODULE, fields)
101
+ if hidden:
102
+ fields = [f for f in fields if f.get("key") not in hidden]
103
+ rows_src = [perm_scope.strip_row(r, hidden) for r in rows_src]
104
+
105
+ return {"rows_src": rows_src, "pids": pids, "ws": ws, "workspace": workspace,
106
+ "fields": fields, "views": views, "lists": lists, "derived": {},
107
+ "measures": [], "measure_sets": {}, "today": time.strftime("%Y-%m-%d"),
108
+ "team_id": team_id}
109
+
110
+
111
+ @router.get("/products")
112
+ def products(session: Session = Depends(module_gate(MODULE))):
113
+ """The product table for this session's scope β€” the /customers envelope byte-for-byte
114
+ (`{fields, rows, today, pulled_at}`) plus two additive keys (`identity`, `scope`).
115
+
116
+ The BU scope is DERIVED FROM THE PERMANENT FILTER (`perm_scope.derive_pool_scope`), exactly
117
+ as the customer route derives it β€” and for the same reason, which is worth restating because
118
+ it is the wave's central lesson: `team_id` shapes the revenue VALUES on each row, so a BU
119
+ enforced as a post-filter yields a correct row list carrying both units' numbers.
120
+ """
121
+ import aios_grid
122
+
123
+ g = product_assembly(session)
124
+ rows = aios_grid.rows_from_pool(
125
+ g["rows_src"], g["fields"], g["ws"].get("overlays"), derived=g["derived"])
126
+ return {"fields": g["fields"], "rows": rows,
127
+ "today": g["today"], "pulled_at": time.strftime("%Y-%m-%d %H:%M"),
128
+ "identity": {"pid": "pid", "businessKey": "code"},
129
+ "scope": {"team_id": g["team_id"], "consolidated": g["team_id"] is None}}
130
+
131
+
132
+ @router.patch("/products/{pid}")
133
+ def patch_product(pid: int, body: dict = Body(default=None),
134
+ session: Session = Depends(module_gate(MODULE))):
135
+ """Write the product table's EDITABLE overlay stratum β€” the customers PATCH, on the product
136
+ topic's ctx. Routed through `core.grid_events.handle_one` so the per-key `permissions.edit`
137
+ wall, the pid wall and the truncation rules stay ONE implementation; the ctx's `table` ops
138
+ aim the write at the PRODUCT bucket."""
139
+ import modules.product_data as pd
140
+ from core import grid_events
141
+
142
+ updates = dict(body or {})
143
+ if not updates:
144
+ raise err(400, "empty_patch", "no fields to update")
145
+ g = product_assembly(session, consume_corrections=False)
146
+ if pid not in g["pids"]:
147
+ # 403, not 404 β€” the code may exist; it is simply not in this session's catalogue.
148
+ raise err(403, "out_of_scope", "that product is not in your catalogue")
149
+ import core.perm_scope as perm_scope
150
+
151
+ ctx = grid_events.EventCtx(
152
+ uname=session.uname, allowed_pids=g["pids"], fields=g["fields"],
153
+ admin=session.admin, fallback_ws=None, seen_ids={},
154
+ hidden_keys=perm_scope.hidden_keys(
155
+ session.user, MODULE, pd_fields(consolidated=g["team_id"] is None)),
156
+ scope_key="product", table=pd.TABLE_OPS)
157
+ try:
158
+ grid_events.handle_one(
159
+ {"id": f"patch:product:{pid}:{time.time_ns()}", "type": "overlay_patch",
160
+ "pid": pid, "updates": updates}, ctx)
161
+ except grid_events.StoreUnavailable:
162
+ raise err(503, "store_unavailable",
163
+ "the tenant store is unavailable β€” your change was not saved")
164
+
165
+ # What actually landed, read back from the PRODUCT bucket rather than echoed from the
166
+ # request: a refused key or a truncated value must not be reported as accepted.
167
+ stored = (grid_events.table_workspace(ctx, allowed_pids=None)
168
+ .get("overlays") or {}).get(str(pid)) or {}
169
+ accepted = {k: stored.get(k) for k in updates if k in stored}
170
+ refused = sorted(k for k in updates
171
+ if k not in accepted or stored.get(k) != str(updates[k]))
172
+ out = {"pid": pid, "updates": accepted}
173
+ if refused:
174
+ out["refused"] = refused
175
+ return out
176
+
177
+
178
+ def pd_fields(consolidated=True):
179
+ """The product field contract, minus the CONSOLIDATED-only columns when the caller is scoped.
180
+
181
+ β›” The omission is the SCOPE RULE, not a display preference (see `modules/product_data`
182
+ decision 2): `inventory.sku_inventory` is brand-independent, so serving those columns to a
183
+ BU-scoped caller would put company-wide stock beside BU-shaped revenue in one row. A column
184
+ that is absent asks a question; one that is silently company-wide answers a different one.
185
+ """
186
+ import json
187
+ from pathlib import Path
188
+
189
+ import aios_grid
190
+
191
+ doc = json.loads((Path(aios_grid.__file__).resolve().parent /
192
+ "aios_grid_fields.json").read_text(encoding="utf-8"))
193
+ fields = list((doc.get("product_data") or {}).get("fields") or [])
194
+ if consolidated:
195
+ return fields
196
+ import modules.product_data as pd
197
+ return [f for f in fields if f.get("key") not in pd.CONSOLIDATED_ONLY]
royalimports_os/aios_grid.py CHANGED
@@ -70,6 +70,17 @@ def _load_fields():
70
 
71
  FIELDS = _load_fields()
72
 
 
 
 
 
 
 
 
 
 
 
 
73
  # text/date fields pass through untouched; every OTHER odoo (numeric) field is rounded β€”
74
  # mirrors aios-web/api/main.py _payload() exactly so embed == standalone byte-for-byte.
75
 
@@ -386,7 +397,7 @@ def measure_fields_of(fields):
386
  return [f for f in fields or [] if isinstance(f.get("measure"), dict)]
387
 
388
 
389
- def fields_from_workspace(workspace=None, cohorts=False, scope_key=None):
390
  """Overlay persisted notes/custom fields onto the immutable source-field contract.
391
 
392
  `cohorts=True` appends the derived cohort column β€” see `cohort_field`. Appended LAST and
@@ -405,11 +416,18 @@ def fields_from_workspace(workspace=None, cohorts=False, scope_key=None):
405
  saved def carrying `scope` is emitted only when it matches β€” so a cohort-specific field
406
  never appears on the Customer table. FAIL-CLOSED: a caller that passes no scope_key sees
407
  only unscoped (global) fields; base contract fields are never scoped.
 
 
 
 
 
 
408
  """
409
  saved = dict((workspace or {}).get("fields") or {})
410
  out = []
411
- base_keys = {field["key"] for field in FIELDS}
412
- for base in FIELDS:
 
413
  meta = saved.get(base["key"]) or {}
414
  field = dict(base)
415
  if isinstance(meta.get("note"), str):
@@ -725,7 +743,10 @@ _LEGACY_MODES = {'dashboard': 'chart'}
725
  #: Chart kinds a chart-mode view may hold (wave-8 I19, contract C2). Mirrors the client's
726
  #: union. Deliberately small: the owner asked to "start with simple charts" and expand, and a
727
  #: kind the client cannot draw is worse than one that does not exist yet.
728
- CHART_KINDS = {'bar', 'line', 'area', 'donut', 'kpi'}
 
 
 
729
  CHART_AGGS = {'sum', 'avg', 'count', 'min', 'max'}
730
  MAX_CHARTS = 12 #: per view β€” a dashboard, not an unbounded render loop
731
  MAX_CHART_TITLE = 60
@@ -835,6 +856,13 @@ def _clean_chart(raw, valid_keys):
835
  if (isinstance(n, int) and not isinstance(n, bool)
836
  and 1 <= n <= TS_MAX_LAST_N):
837
  out['span'] = {'lastN': n}
 
 
 
 
 
 
 
838
  return out
839
 
840
 
@@ -1256,11 +1284,16 @@ def _default_view_config(fields):
1256
  }
1257
 
1258
 
1259
- def views_from_defs(defs, saved_views, fields):
1260
- """Convert legacy list formulas into the shared serializable SavedView contract."""
 
 
 
 
 
1261
  base = _default_view_config(fields)
1262
  views = [{
1263
- "id": "all-customers", "name": "All customers", "kind": "system",
1264
  "locked": True, "config": dict(base),
1265
  }]
1266
  op_map = {">=": "gte", ">": "gt", "<=": "lte", "<": "lt", "=": "eq",
@@ -1303,7 +1336,8 @@ def views_from_defs(defs, saved_views, fields):
1303
  return views
1304
 
1305
 
1306
- def workspace_wire(ws, uname, pool_pids, defs=None, scope_key='customer', storage_key=None):
 
1307
  """The client's `GridWorkspace` WIRE SHAPE from the stored table workspace β€” the ONE
1308
  projection, shared by both servers (app.py's `_table_grid` and the API's `/workspace`).
1309
 
@@ -1319,23 +1353,33 @@ def workspace_wire(ws, uname, pool_pids, defs=None, scope_key='customer', storag
1319
 
1320
  HOST-ONLY extras stay with the host: `docs`/`docPayload`, `pool`, `hideViews`,
1321
  `cohortMode`/`scopeChoice` (the API stamps its own from `?scope=`).
 
 
 
 
 
1322
  """
1323
  import modules.cohort as cohort_mod
1324
 
1325
  cohort_lists = []
1326
- for cid, c in sorted(cohort_mod.visible(uname, pool_pids).items(),
1327
- key=lambda kv: (kv[1].get('name') or '').lower()):
1328
- members = [p for p in (c.get('members') or []) if p in pool_pids]
1329
- entry = {'id': cid, 'name': c.get('name') or cid, 'pids': members}
1330
- # Rule 8b: a member can drop out of the 24-month pool without the cohort being wrong,
1331
- # and a silently smaller cohort is exactly what the unverifiable-count rule forbids.
1332
- missing = len(c.get('members') or []) - len(members)
1333
- if missing:
1334
- entry['missing'] = missing
1335
- cohort_lists.append(entry)
1336
-
1337
- fields = fields_from_workspace(ws, cohorts=bool(cohort_lists), scope_key=scope_key)
1338
- views = views_from_defs(defs or {}, ws.get('views'), fields)
 
 
 
 
 
1339
  workspace = {'storageKey': storage_key, 'views': views, 'lists': cohort_lists}
1340
  # Owner item 3 (2026-07-31): where this user left off. The client's own localStorage copy
1341
  # wins when present; this is the server's answer for a FRESH browser, which used to fall
 
70
 
71
  FIELDS = _load_fields()
72
 
73
+
74
+ def product_fields():
75
+ """The PRODUCT table's canonical contract (wave 15 C-TOPIC, `product_data` key in the same
76
+ JSON). A separate accessor rather than a second module constant so the one file-read and the
77
+ one failure mode stay shared with `FIELDS`."""
78
+ doc = json.loads(_FIELDS_PATH.read_text(encoding="utf-8"))
79
+ fields = (doc.get("product_data") or {}).get("fields")
80
+ if not isinstance(fields, list) or not fields:
81
+ raise ValueError(f"aios_grid: {_FIELDS_PATH} has no product_data.fields list.")
82
+ return fields
83
+
84
  # text/date fields pass through untouched; every OTHER odoo (numeric) field is rounded β€”
85
  # mirrors aios-web/api/main.py _payload() exactly so embed == standalone byte-for-byte.
86
 
 
397
  return [f for f in fields or [] if isinstance(f.get("measure"), dict)]
398
 
399
 
400
+ def fields_from_workspace(workspace=None, cohorts=False, scope_key=None, fields_base=None):
401
  """Overlay persisted notes/custom fields onto the immutable source-field contract.
402
 
403
  `cohorts=True` appends the derived cohort column β€” see `cohort_field`. Appended LAST and
 
416
  saved def carrying `scope` is emitted only when it matches β€” so a cohort-specific field
417
  never appears on the Customer table. FAIL-CLOSED: a caller that passes no scope_key sees
418
  only unscoped (global) fields; base contract fields are never scoped.
419
+
420
+ `fields_base` (wave 16 C-TOPIC) β€” the canonical contract to overlay onto. Absent = the
421
+ CUSTOMER contract (`FIELDS`), byte-identical to before the parameter existed; the product
422
+ surface passes `product_fields()`. The workspace dict a caller hands in must already be the
423
+ matching table object's bucket β€” this function cannot tell a customer overlay from a
424
+ product one, which is exactly why the buckets are separate stores.
425
  """
426
  saved = dict((workspace or {}).get("fields") or {})
427
  out = []
428
+ base_fields = fields_base if fields_base is not None else FIELDS
429
+ base_keys = {field["key"] for field in base_fields}
430
+ for base in base_fields:
431
  meta = saved.get(base["key"]) or {}
432
  field = dict(base)
433
  if isinstance(meta.get("note"), str):
 
743
  #: Chart kinds a chart-mode view may hold (wave-8 I19, contract C2). Mirrors the client's
744
  #: union. Deliberately small: the owner asked to "start with simple charts" and expand, and a
745
  #: kind the client cannot draw is worse than one that does not exist yet.
746
+ #: Wave-16 C-CHARTCAP: + 'table' β€” the group-by aggregate table (by-rep / by-BU /
747
+ #: top-customers, the third Sales block shape). Client renderer: DashboardView's
748
+ #: GroupTableView over salesParity.tableFromSpec.
749
+ CHART_KINDS = {'bar', 'line', 'area', 'donut', 'kpi', 'table'}
750
  CHART_AGGS = {'sum', 'avg', 'count', 'min', 'max'}
751
  MAX_CHARTS = 12 #: per view β€” a dashboard, not an unbounded render loop
752
  MAX_CHART_TITLE = 60
 
856
  if (isinstance(n, int) and not isinstance(n, bool)
857
  and 1 <= n <= TS_MAX_LAST_N):
858
  out['span'] = {'lastN': n}
859
+ # ── Wave-16 C-CHARTCAP: the YoY companion. Kept ONLY where it can mean something β€”
860
+ # beside a kept bucket (the compare series) or on a sum-of-metric KPI (the delta
861
+ # line). Anything else is a stored claim the renderer would have to re-refuse.
862
+ # Mirrors the client's cleanCharts rule key for key.
863
+ if raw.get('compare') == 'prior_year' and (
864
+ out.get('bucket') or (kind == 'kpi' and out.get('agg') == 'sum')):
865
+ out['compare'] = 'prior_year'
866
  return out
867
 
868
 
 
1284
  }
1285
 
1286
 
1287
+ def views_from_defs(defs, saved_views, fields, system_name="All customers"):
1288
+ """Convert legacy list formulas into the shared serializable SavedView contract.
1289
+
1290
+ `system_name` (wave 16 C-TOPIC) labels the system view per TOPIC ("All products" on the
1291
+ product surface). The ID stays "all-customers" on every topic β€” the client pins it
1292
+ (UNDELETABLE_VIEW_IDS, the landing default), and an id that varies by surface would fork
1293
+ that contract for a label's sake."""
1294
  base = _default_view_config(fields)
1295
  views = [{
1296
+ "id": "all-customers", "name": system_name, "kind": "system",
1297
  "locked": True, "config": dict(base),
1298
  }]
1299
  op_map = {">=": "gte", ">": "gt", "<=": "lte", "<": "lt", "=": "eq",
 
1336
  return views
1337
 
1338
 
1339
+ def workspace_wire(ws, uname, pool_pids, defs=None, scope_key='customer', storage_key=None,
1340
+ fields_base=None, with_cohorts=True):
1341
  """The client's `GridWorkspace` WIRE SHAPE from the stored table workspace β€” the ONE
1342
  projection, shared by both servers (app.py's `_table_grid` and the API's `/workspace`).
1343
 
 
1353
 
1354
  HOST-ONLY extras stay with the host: `docs`/`docPayload`, `pool`, `hideViews`,
1355
  `cohortMode`/`scopeChoice` (the API stamps its own from `?scope=`).
1356
+
1357
+ Wave 16 C-TOPIC: `fields_base` selects the canonical contract (absent = customer,
1358
+ byte-identical); `with_cohorts=False` is the PRODUCT surface β€” cohorts are customer
1359
+ machinery (`modules/cohort` stores partner pids), and resolving them against product pids
1360
+ would intersect two unrelated id spaces and render a plausible, meaningless member count.
1361
  """
1362
  import modules.cohort as cohort_mod
1363
 
1364
  cohort_lists = []
1365
+ if with_cohorts:
1366
+ for cid, c in sorted(cohort_mod.visible(uname, pool_pids).items(),
1367
+ key=lambda kv: (kv[1].get('name') or '').lower()):
1368
+ members = [p for p in (c.get('members') or []) if p in pool_pids]
1369
+ entry = {'id': cid, 'name': c.get('name') or cid, 'pids': members}
1370
+ # Rule 8b: a member can drop out of the 24-month pool without the cohort being
1371
+ # wrong, and a silently smaller cohort is exactly what the unverifiable-count rule
1372
+ # forbids.
1373
+ missing = len(c.get('members') or []) - len(members)
1374
+ if missing:
1375
+ entry['missing'] = missing
1376
+ cohort_lists.append(entry)
1377
+
1378
+ fields = fields_from_workspace(ws, cohorts=bool(cohort_lists), scope_key=scope_key,
1379
+ fields_base=fields_base)
1380
+ views = views_from_defs(defs or {}, ws.get('views'), fields,
1381
+ system_name=("All products" if scope_key == 'product'
1382
+ else "All customers"))
1383
  workspace = {'storageKey': storage_key, 'views': views, 'lists': cohort_lists}
1384
  # Owner item 3 (2026-07-31): where this user left off. The client's own localStorage copy
1385
  # wins when present; this is the server's answer for a FRESH browser, which used to fall
royalimports_os/aios_grid_fields.json CHANGED
@@ -1,230 +1,340 @@
1
- {
2
- "_comment": "CANONICAL field contract for the AIOS Airtable-style grid β€” the SINGLE source of truth. Consumed by royalimports_os/aios_grid.py (embed/Space host) and aios-web/api/main.py (standalone API), and regenerated into aios-web/web/public/sample_customers.json. Edit HERE only, then run aios-web/verify_fields_contract.py. source=odoo is READ-ONLY; source=overlay is the editable stratum (notes/tags) outside Odoo. type in {text,status,select,currency,int,date,pct} (select = a fixed-choice READ-ONLY brand attribute; dba is the first, wave 2026-08-02). `description` (wave 5) is the CANONICAL per-field description β€” every field must carry one, and since wave 7 (owner W8, 2026-07-28) every description is ONE SHORT PLAIN sentence (two only when a fact would otherwise mislead): what the field IS, nothing else β€” no filter tips, no '(none)' coaching, no rationale; the user's workspace NOTE overrides it in the (i) hover, never in this file. BUILDER FACT (documented here, deliberately NOT in user-facing text): blank text attributes display as '(none)', so `is '(none)'` β€” not `is empty` β€” finds the blanks on agent/city/state/country/zip/payment_terms/pricelist/tags. filterable:false = the CONDITION BUILDER does not offer it (still displayed, still sortable); every such field must have a replacement declared in aios-web/verify_fields_contract.py. 2026-07-27 partner attributes: country/zip/payment_terms/pricelist/tags/customer_since all ship default:false. zip is TEXT because a postal code has leading zeros. Odoo's credit_limit (1% populated) and user_id salesperson (2%) are deliberately ABSENT; agent_ids is the salesperson field and AR is where credit exposure comes from. Wave-5 item 8 (2026-07-27): ltm_rev and at_risk are DELETED β€” LTM's replacement is a creatable Sales measure column (the demo column IS Sales Β· the last 12 months), at_risk's replacement is a formula field, e.g. MAX(0, {revenue_ly} - {revenue_ytd}). Wave-6 item 8 (2026-07-27, the no-buildable-presets rule): revenue_ytd, revenue_ly, orders_24m, aov and yoy_pct are DELETED β€” every one is self-buildable, so a frozen pre-set beside the builder was two ways to ask one question. Replacements (recorded in verify_fields_contract.py): creatable measure columns for Sales / Orders / Avg order $ over any period (harness/measure_filter.py ADMITTED carries revenue, orders and the composite aov), and a formula over two measure columns for YoY, e.g. ({sales_ytd} - {sales_ly}) / {sales_ly}. Stale view colIds naming the five self-heal on the next autosave (the established rule).",
3
- "fields": [
4
- {
5
- "key": "customer",
6
- "label": "Customer",
7
- "type": "text",
8
- "source": "odoo",
9
- "pinned": true,
10
- "default": true,
11
- "description": "The customer's name in Odoo. One row per customer who ordered in the last 24 months."
12
- },
13
- {
14
- "key": "odoo_status",
15
- "label": "Odoo record",
16
- "type": "status",
17
- "source": "odoo",
18
- "default": false,
19
- "description": "Whether this customer still exists in Odoo. Archived means deleted there."
20
- },
21
- {
22
- "key": "agent",
23
- "label": "Agent",
24
- "type": "text",
25
- "source": "odoo",
26
- "default": true,
27
- "description": "The sales agent who owns this account."
28
- },
29
- {
30
- "key": "dba",
31
- "label": "DBA",
32
- "type": "select",
33
- "source": "odoo",
34
- "default": false,
35
- "options": [
36
- "Fisch",
37
- "Royal",
38
- "Both"
39
- ],
40
- "description": "The brand this customer buys from - Fisch, Royal, or both. Amazon-channel orders are not a DBA."
41
- },
42
- {
43
- "key": "salesperson",
44
- "label": "Salesperson",
45
- "type": "text",
46
- "source": "odoo",
47
- "default": false,
48
- "description": "Who keyed in most of this customer's orders β€” not the Agent, who owns the account."
49
- },
50
- {
51
- "key": "city",
52
- "label": "City",
53
- "type": "text",
54
- "source": "odoo",
55
- "default": true,
56
- "description": "City on the customer's Odoo address."
57
- },
58
- {
59
- "key": "state",
60
- "label": "State",
61
- "type": "text",
62
- "source": "odoo",
63
- "default": true,
64
- "description": "State or province on the customer's Odoo address."
65
- },
66
- {
67
- "key": "country",
68
- "label": "Country",
69
- "type": "text",
70
- "source": "odoo",
71
- "default": false,
72
- "description": "Country on the customer's Odoo address."
73
- },
74
- {
75
- "key": "zip",
76
- "label": "ZIP",
77
- "type": "text",
78
- "source": "odoo",
79
- "default": false,
80
- "description": "Postal code on the customer's Odoo address."
81
- },
82
- {
83
- "key": "customer_since",
84
- "label": "Customer since",
85
- "type": "date",
86
- "source": "odoo",
87
- "default": false,
88
- "description": "When this customer was first set up in Odoo."
89
- },
90
- {
91
- "key": "tags",
92
- "label": "Tags",
93
- "type": "text",
94
- "source": "odoo",
95
- "default": false,
96
- "description": "Odoo labels on this customer, comma-separated."
97
- },
98
- {
99
- "key": "pricelist",
100
- "label": "Price list",
101
- "type": "text",
102
- "source": "odoo",
103
- "default": false,
104
- "description": "The price list this customer buys on."
105
- },
106
- {
107
- "key": "payment_terms",
108
- "label": "Payment terms",
109
- "type": "text",
110
- "source": "odoo",
111
- "default": false,
112
- "description": "Payment terms on this customer's account β€” Net 30, for example."
113
- },
114
- {
115
- "key": "last_order",
116
- "label": "Last order",
117
- "type": "date",
118
- "source": "odoo",
119
- "default": true,
120
- "description": "Date of the most recent confirmed order."
121
- },
122
- {
123
- "key": "overdue_days",
124
- "label": "Overdue days",
125
- "type": "int",
126
- "source": "odoo",
127
- "default": true,
128
- "description": "How many days late this customer is running against their own usual ordering rhythm."
129
- },
130
- {
131
- "_note": "filterable:false β€” DERIVED ANALYTIC: est_missed is min(cycles missed, 3) x AOV, a score we compute rather than an object the business has, so a condition on it would read as a fact about the customer when it is a fact about our arithmetic. It still displays and still sorts. Until wave 6 this flag also covered the frozen-window presets (revenue_ytd / revenue_ly / orders_24m / aov / yoy_pct); those are now DELETED outright under the owner's no-buildable-presets rule β€” see _comment. est_missed itself STAYS: no creatable measure or formula reproduces the cadence model behind it.",
132
- "key": "est_missed",
133
- "label": "Est. missed $",
134
- "type": "currency",
135
- "source": "odoo",
136
- "default": true,
137
- "agg": "sum",
138
- "filterable": false,
139
- "description": "Estimated sales missed while quiet: missed orders (capped at 3) times average order value. An estimate, not money owed."
140
- },
141
- {
142
- "key": "ar_open",
143
- "label": "AR open $",
144
- "type": "currency",
145
- "source": "odoo",
146
- "default": false,
147
- "description": "Invoiced money owed, not yet overdue."
148
- },
149
- {
150
- "key": "ar_overdue",
151
- "label": "AR overdue $",
152
- "type": "currency",
153
- "source": "odoo",
154
- "default": false,
155
- "description": "Invoiced money past due β€” same basis as the Collections page."
156
- },
157
- {
158
- "key": "ar_exposure",
159
- "label": "Credit exposure $",
160
- "type": "currency",
161
- "source": "odoo",
162
- "default": false,
163
- "description": "The most you could be out if they stopped paying today: open, overdue, draft and not-yet-invoiced."
164
- },
165
- {
166
- "key": "days_to_pay",
167
- "label": "Days to pay",
168
- "type": "int",
169
- "source": "odoo",
170
- "default": false,
171
- "description": "Average days to pay an invoice in full. Blank means no fully paid invoice yet."
172
- },
173
- {
174
- "key": "top_category",
175
- "label": "Top category",
176
- "type": "text",
177
- "source": "odoo",
178
- "default": false,
179
- "description": "The category this customer spent the most on in the last 12 months."
180
- },
181
- {
182
- "key": "top_category_pct",
183
- "label": "Top category %",
184
- "type": "pct",
185
- "source": "odoo",
186
- "default": false,
187
- "description": "Share of last-12-months spend that went to the top category."
188
- },
189
- {
190
- "key": "sku_count",
191
- "label": "SKUs bought",
192
- "type": "int",
193
- "source": "odoo",
194
- "default": false,
195
- "description": "Distinct products bought in the last 12 months."
196
- },
197
- {
198
- "key": "top_sku",
199
- "label": "Top SKU",
200
- "type": "text",
201
- "source": "odoo",
202
- "default": false,
203
- "description": "The product this customer spent the most on in the last 12 months."
204
- },
205
- {
206
- "key": "days_since",
207
- "label": "Days since order",
208
- "type": "int",
209
- "source": "odoo",
210
- "default": false,
211
- "description": "Days since the last confirmed order."
212
- },
213
- {
214
- "key": "typical_gap_days",
215
- "label": "Typical gap days",
216
- "type": "int",
217
- "source": "odoo",
218
- "default": false,
219
- "description": "Days this customer usually goes between orders, from their own history."
220
- },
221
- {
222
- "key": "notes",
223
- "label": "Notes",
224
- "type": "text",
225
- "source": "overlay",
226
- "default": false,
227
- "description": "Your notes on this customer. Saved in this app only, visible only to you."
228
- }
229
- ]
230
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_comment": "CANONICAL field contract for the AIOS Airtable-style grid \u2014 the SINGLE source of truth. Consumed by royalimports_os/aios_grid.py (embed/Space host) and aios-web/api/main.py (standalone API), and regenerated into aios-web/web/public/sample_customers.json. Edit HERE only, then run aios-web/verify_fields_contract.py. source=odoo is READ-ONLY; source=overlay is the editable stratum (notes/tags) outside Odoo. type in {text,status,select,currency,int,date,pct} (select = a fixed-choice READ-ONLY brand attribute; dba is the first, wave 2026-08-02). `description` (wave 5) is the CANONICAL per-field description \u2014 every field must carry one, and since wave 7 (owner W8, 2026-07-28) every description is ONE SHORT PLAIN sentence (two only when a fact would otherwise mislead): what the field IS, nothing else \u2014 no filter tips, no '(none)' coaching, no rationale; the user's workspace NOTE overrides it in the (i) hover, never in this file. BUILDER FACT (documented here, deliberately NOT in user-facing text): blank text attributes display as '(none)', so `is '(none)'` \u2014 not `is empty` \u2014 finds the blanks on agent/city/state/country/zip/payment_terms/pricelist/tags. filterable:false = the CONDITION BUILDER does not offer it (still displayed, still sortable); every such field must have a replacement declared in aios-web/verify_fields_contract.py. 2026-07-27 partner attributes: country/zip/payment_terms/pricelist/tags/customer_since all ship default:false. zip is TEXT because a postal code has leading zeros. Odoo's credit_limit (1% populated) and user_id salesperson (2%) are deliberately ABSENT; agent_ids is the salesperson field and AR is where credit exposure comes from. Wave-5 item 8 (2026-07-27): ltm_rev and at_risk are DELETED \u2014 LTM's replacement is a creatable Sales measure column (the demo column IS Sales \u00b7 the last 12 months), at_risk's replacement is a formula field, e.g. MAX(0, {revenue_ly} - {revenue_ytd}). Wave-6 item 8 (2026-07-27, the no-buildable-presets rule): revenue_ytd, revenue_ly, orders_24m, aov and yoy_pct are DELETED \u2014 every one is self-buildable, so a frozen pre-set beside the builder was two ways to ask one question. Replacements (recorded in verify_fields_contract.py): creatable measure columns for Sales / Orders / Avg order $ over any period (harness/measure_filter.py ADMITTED carries revenue, orders and the composite aov), and a formula over two measure columns for YoY, e.g. ({sales_ytd} - {sales_ly}) / {sales_ly}. Stale view colIds naming the five self-heal on the next autosave (the established rule).",
3
+ "fields": [
4
+ {
5
+ "key": "customer",
6
+ "label": "Customer",
7
+ "type": "text",
8
+ "source": "odoo",
9
+ "pinned": true,
10
+ "default": true,
11
+ "description": "The customer's name in Odoo. One row per customer who ordered in the last 24 months."
12
+ },
13
+ {
14
+ "key": "odoo_status",
15
+ "label": "Odoo record",
16
+ "type": "status",
17
+ "source": "odoo",
18
+ "default": false,
19
+ "description": "Whether this customer still exists in Odoo. Archived means deleted there."
20
+ },
21
+ {
22
+ "key": "agent",
23
+ "label": "Agent",
24
+ "type": "text",
25
+ "source": "odoo",
26
+ "default": true,
27
+ "description": "The sales agent who owns this account."
28
+ },
29
+ {
30
+ "key": "dba",
31
+ "label": "DBA",
32
+ "type": "select",
33
+ "source": "odoo",
34
+ "default": false,
35
+ "options": [
36
+ "Fisch",
37
+ "Royal",
38
+ "Both"
39
+ ],
40
+ "description": "The brand this customer buys from - Fisch, Royal, or both. Amazon-channel orders are not a DBA."
41
+ },
42
+ {
43
+ "key": "salesperson",
44
+ "label": "Salesperson",
45
+ "type": "text",
46
+ "source": "odoo",
47
+ "default": false,
48
+ "description": "Who keyed in most of this customer's orders \u2014 not the Agent, who owns the account."
49
+ },
50
+ {
51
+ "key": "city",
52
+ "label": "City",
53
+ "type": "text",
54
+ "source": "odoo",
55
+ "default": true,
56
+ "description": "City on the customer's Odoo address."
57
+ },
58
+ {
59
+ "key": "state",
60
+ "label": "State",
61
+ "type": "text",
62
+ "source": "odoo",
63
+ "default": true,
64
+ "description": "State or province on the customer's Odoo address."
65
+ },
66
+ {
67
+ "key": "country",
68
+ "label": "Country",
69
+ "type": "text",
70
+ "source": "odoo",
71
+ "default": false,
72
+ "description": "Country on the customer's Odoo address."
73
+ },
74
+ {
75
+ "key": "zip",
76
+ "label": "ZIP",
77
+ "type": "text",
78
+ "source": "odoo",
79
+ "default": false,
80
+ "description": "Postal code on the customer's Odoo address."
81
+ },
82
+ {
83
+ "key": "customer_since",
84
+ "label": "Customer since",
85
+ "type": "date",
86
+ "source": "odoo",
87
+ "default": false,
88
+ "description": "When this customer was first set up in Odoo."
89
+ },
90
+ {
91
+ "key": "tags",
92
+ "label": "Tags",
93
+ "type": "text",
94
+ "source": "odoo",
95
+ "default": false,
96
+ "description": "Odoo labels on this customer, comma-separated."
97
+ },
98
+ {
99
+ "key": "pricelist",
100
+ "label": "Price list",
101
+ "type": "text",
102
+ "source": "odoo",
103
+ "default": false,
104
+ "description": "The price list this customer buys on."
105
+ },
106
+ {
107
+ "key": "payment_terms",
108
+ "label": "Payment terms",
109
+ "type": "text",
110
+ "source": "odoo",
111
+ "default": false,
112
+ "description": "Payment terms on this customer's account \u2014 Net 30, for example."
113
+ },
114
+ {
115
+ "key": "last_order",
116
+ "label": "Last order",
117
+ "type": "date",
118
+ "source": "odoo",
119
+ "default": true,
120
+ "description": "Date of the most recent confirmed order."
121
+ },
122
+ {
123
+ "key": "overdue_days",
124
+ "label": "Overdue days",
125
+ "type": "int",
126
+ "source": "odoo",
127
+ "default": true,
128
+ "description": "How many days late this customer is running against their own usual ordering rhythm."
129
+ },
130
+ {
131
+ "_note": "filterable:false \u2014 DERIVED ANALYTIC: est_missed is min(cycles missed, 3) x AOV, a score we compute rather than an object the business has, so a condition on it would read as a fact about the customer when it is a fact about our arithmetic. It still displays and still sorts. Until wave 6 this flag also covered the frozen-window presets (revenue_ytd / revenue_ly / orders_24m / aov / yoy_pct); those are now DELETED outright under the owner's no-buildable-presets rule \u2014 see _comment. est_missed itself STAYS: no creatable measure or formula reproduces the cadence model behind it.",
132
+ "key": "est_missed",
133
+ "label": "Est. missed $",
134
+ "type": "currency",
135
+ "source": "odoo",
136
+ "default": true,
137
+ "agg": "sum",
138
+ "filterable": false,
139
+ "description": "Estimated sales missed while quiet: missed orders (capped at 3) times average order value. An estimate, not money owed."
140
+ },
141
+ {
142
+ "key": "ar_open",
143
+ "label": "AR open $",
144
+ "type": "currency",
145
+ "source": "odoo",
146
+ "default": false,
147
+ "description": "Invoiced money owed, not yet overdue."
148
+ },
149
+ {
150
+ "key": "ar_overdue",
151
+ "label": "AR overdue $",
152
+ "type": "currency",
153
+ "source": "odoo",
154
+ "default": false,
155
+ "description": "Invoiced money past due \u2014 same basis as the Collections page."
156
+ },
157
+ {
158
+ "key": "ar_exposure",
159
+ "label": "Credit exposure $",
160
+ "type": "currency",
161
+ "source": "odoo",
162
+ "default": false,
163
+ "description": "The most you could be out if they stopped paying today: open, overdue, draft and not-yet-invoiced."
164
+ },
165
+ {
166
+ "key": "days_to_pay",
167
+ "label": "Days to pay",
168
+ "type": "int",
169
+ "source": "odoo",
170
+ "default": false,
171
+ "description": "Average days to pay an invoice in full. Blank means no fully paid invoice yet."
172
+ },
173
+ {
174
+ "key": "top_category",
175
+ "label": "Top category",
176
+ "type": "text",
177
+ "source": "odoo",
178
+ "default": false,
179
+ "description": "The category this customer spent the most on in the last 12 months."
180
+ },
181
+ {
182
+ "key": "top_category_pct",
183
+ "label": "Top category %",
184
+ "type": "pct",
185
+ "source": "odoo",
186
+ "default": false,
187
+ "description": "Share of last-12-months spend that went to the top category."
188
+ },
189
+ {
190
+ "key": "sku_count",
191
+ "label": "SKUs bought",
192
+ "type": "int",
193
+ "source": "odoo",
194
+ "default": false,
195
+ "description": "Distinct products bought in the last 12 months."
196
+ },
197
+ {
198
+ "key": "top_sku",
199
+ "label": "Top SKU",
200
+ "type": "text",
201
+ "source": "odoo",
202
+ "default": false,
203
+ "description": "The product this customer spent the most on in the last 12 months."
204
+ },
205
+ {
206
+ "key": "days_since",
207
+ "label": "Days since order",
208
+ "type": "int",
209
+ "source": "odoo",
210
+ "default": false,
211
+ "description": "Days since the last confirmed order."
212
+ },
213
+ {
214
+ "key": "typical_gap_days",
215
+ "label": "Typical gap days",
216
+ "type": "int",
217
+ "source": "odoo",
218
+ "default": false,
219
+ "description": "Days this customer usually goes between orders, from their own history."
220
+ },
221
+ {
222
+ "key": "notes",
223
+ "label": "Notes",
224
+ "type": "text",
225
+ "source": "overlay",
226
+ "default": false,
227
+ "description": "Your notes on this customer. Saved in this app only, visible only to you."
228
+ }
229
+ ],
230
+ "_product_comment": "ADDITIVE, wave 15 C-TOPIC. The PRODUCT table's field contract. Kept as a SEPARATE top-level key rather than restructuring `fields` into {customer_data, product_data}: both existing readers (aios_grid._load_fields, aios-web/api/main.py) index doc['fields'] directly, and reshaping that mid-wave would break the embed for a cosmetic gain. The keyed shape can arrive when both readers move in ONE commit; until then this is the product half and `fields` is the customer half.",
231
+ "product_data": {
232
+ "identity": "pid",
233
+ "business_key": "code",
234
+ "fields": [
235
+ {
236
+ "key": "code",
237
+ "label": "SKU",
238
+ "type": "text",
239
+ "source": "odoo",
240
+ "pinned": true,
241
+ "default": true,
242
+ "description": "The SKU code \u2014 the product's real business key. `pid` is a stable CRC32 of it because the grid keys on an integer."
243
+ },
244
+ {
245
+ "key": "product",
246
+ "label": "Product",
247
+ "type": "text",
248
+ "source": "odoo",
249
+ "default": true,
250
+ "description": "Product name as it appears in Odoo."
251
+ },
252
+ {
253
+ "key": "category",
254
+ "label": "Category",
255
+ "type": "select",
256
+ "source": "odoo",
257
+ "default": true,
258
+ "description": "Product category; '(uncategorized)' when Odoo carries none."
259
+ },
260
+ {
261
+ "key": "rev_ytd",
262
+ "label": "Revenue YTD",
263
+ "type": "currency",
264
+ "source": "odoo",
265
+ "default": true,
266
+ "description": "Year-to-date revenue for this SKU, BU-scoped when the caller is."
267
+ },
268
+ {
269
+ "key": "rev_ly",
270
+ "label": "Revenue LY",
271
+ "type": "currency",
272
+ "source": "odoo",
273
+ "description": "Same period last year \u2014 seasonal wholesale compares like for like."
274
+ },
275
+ {
276
+ "key": "yoy_pct",
277
+ "label": "YoY %",
278
+ "type": "pct",
279
+ "source": "odoo",
280
+ "description": "Year-over-year change; null when last year was zero (a ratio to zero is not a number)."
281
+ },
282
+ {
283
+ "key": "qty_ytd",
284
+ "label": "Units YTD",
285
+ "type": "int",
286
+ "source": "odoo",
287
+ "description": "Units sold year to date."
288
+ },
289
+ {
290
+ "key": "orders_ytd",
291
+ "label": "Orders YTD",
292
+ "type": "int",
293
+ "source": "odoo",
294
+ "description": "Distinct orders containing this SKU, year to date."
295
+ },
296
+ {
297
+ "key": "on_hand",
298
+ "label": "On hand",
299
+ "type": "int",
300
+ "source": "odoo",
301
+ "description": "Units in stock. CONSOLIDATED \u2014 one physical warehouse, not brand-tagged, so this column is ABSENT for a BU-scoped caller rather than silently company-wide."
302
+ },
303
+ {
304
+ "key": "unit_cost",
305
+ "label": "Unit cost",
306
+ "type": "currency",
307
+ "source": "odoo",
308
+ "description": "Inventory unit cost. Consolidated; absent for a BU-scoped caller."
309
+ },
310
+ {
311
+ "key": "inv_value",
312
+ "label": "Stock value",
313
+ "type": "currency",
314
+ "source": "odoo",
315
+ "description": "On-hand value at cost. Consolidated; absent for a BU-scoped caller."
316
+ },
317
+ {
318
+ "key": "qty_ltm",
319
+ "label": "Units LTM",
320
+ "type": "int",
321
+ "source": "odoo",
322
+ "description": "Units sold in the last twelve months. Consolidated; absent for a BU-scoped caller."
323
+ },
324
+ {
325
+ "key": "dos",
326
+ "label": "Days of supply",
327
+ "type": "int",
328
+ "source": "odoo",
329
+ "description": "Days of supply at the LTM rate; null means it never sells through. Consolidated; absent for a BU-scoped caller."
330
+ },
331
+ {
332
+ "key": "stock_bucket",
333
+ "label": "Stock status",
334
+ "type": "select",
335
+ "source": "odoo",
336
+ "description": "Dead / excess / healthy bucket from the inventory module. Consolidated; absent for a BU-scoped caller."
337
+ }
338
+ ]
339
+ }
340
+ }
royalimports_os/core/grid_events.py CHANGED
@@ -112,7 +112,20 @@ class EventCtx:
112
  measure_offer: tuple = ()
113
  visible_views: tuple = ()
114
  admin: bool = False
 
 
 
 
 
 
 
115
  scope_key: str = 'customer'
 
 
 
 
 
 
116
  seen_ids: Optional[MutableMapping] = None
117
  fallback_ws: Optional[MutableMapping] = None
118
  out: EventResult = field(default_factory=EventResult)
@@ -125,6 +138,13 @@ class EventCtx:
125
  self.seen_ids = {}
126
 
127
 
 
 
 
 
 
 
 
128
  # ------------------------------------------------------------------ the workspace family (X1 amd.)
129
  def table_workspace(ctx, allowed_pids=None, consume_corrections=True):
130
  """Durable Airtable-style view/schema/overlay state, with an honest session fallback.
@@ -148,10 +168,10 @@ def table_workspace(ctx, allowed_pids=None, consume_corrections=True):
148
  """
149
  uname = ctx.uname
150
  if store.available():
151
- ws = cl_mod.table_workspace(
152
  uname, consume_corrections=bool(consume_corrections))
153
  try:
154
- shared = cl_mod.shared_table_views(uname, bool(ctx.admin))
155
  except Exception as _se:
156
  _tel.error('sharedviews:read', _se)
157
  shared = {}
@@ -410,7 +430,7 @@ def handle_one(event, ctx):
410
  vid = str(event.get('viewId') or '').strip()[:120]
411
  if vid and store.available():
412
  try:
413
- cl_mod.save_table_active_view(uname, vid)
414
  except Exception as _ae:
415
  _tel.error('grid:view-select', _ae)
416
  return False
@@ -430,7 +450,7 @@ def handle_one(event, ctx):
430
  seen.add(k)
431
  order.append(k)
432
  if store.available():
433
- cl_mod.save_table_record_layout(uname, order)
434
  else:
435
  _session_ready()
436
  if order:
@@ -530,7 +550,7 @@ def handle_one(event, ctx):
530
  # caller may not SEE reads as absent β€” which would look like a CREATE and let anybody
531
  # overwrite somebody else's shared view by guessing its id. Ask the store for the raw
532
  # record and refuse before deciding anything else. Fail-closed on both branches.
533
- _raw_shared = cl_mod.shared_table_view(view_id) if store.available() else None
534
  if _raw_shared is not None and not prior:
535
  return False # exists, not visible to this caller: refuse
536
  if _raw_shared is not None and not _tstore._may_edit(_raw_shared, uname, admin):
@@ -621,7 +641,7 @@ def handle_one(event, ctx):
621
  if view_id != 'all-customers':
622
  _reserved_view_names.append('All customers')
623
  if store.available():
624
- view = (cl_mod.save_table_view(
625
  uname, view, reserved_names=_reserved_view_names, is_admin=admin) or view)
626
  else:
627
  _session_ready()
@@ -666,11 +686,11 @@ def handle_one(event, ctx):
666
  # only. A collaborator can change what a shared view shows; they cannot destroy
667
  # everybody else's copy of it, because there is only one copy.
668
  if store.available():
669
- _raw_shared = cl_mod.shared_table_view(view_id)
670
  if _raw_shared is not None and not _tstore._may_administer(
671
  _raw_shared, uname, admin):
672
  return False
673
- cl_mod.delete_table_view(uname, view_id)
674
  else:
675
  _session_ready()
676
  ws['views'].pop(view_id, None)
@@ -807,7 +827,7 @@ def handle_one(event, ctx):
807
  and isinstance(value, dict))
808
  ]
809
  if store.available():
810
- field = (cl_mod.save_table_field(
811
  uname, field, reserved_names=_reserved_field_names,
812
  correction_id=event_id) or field)
813
  else:
@@ -1052,7 +1072,7 @@ def handle_one(event, ctx):
1052
  _res = _mutate(table_workspace(ctx, consume_corrections=False))
1053
  if _res is None:
1054
  return False # refused: nothing is written
1055
- cl_mod.save_table_folders(uname, _res[0], _res[1])
1056
  # True: the sidebars render from server state (which folder holds what), not from local
1057
  # optimism β€” the same contract the cohort panel's membership edits ride.
1058
  return True
@@ -1069,7 +1089,7 @@ def handle_one(event, ctx):
1069
  if not (key.startswith('custom_') or key.startswith(_ag3.MEASURE_FIELD_PREFIX)):
1070
  return False
1071
  if store.available():
1072
- cl_mod.delete_table_field(uname, key)
1073
  else:
1074
  _session_ready()
1075
  ws['fields'].pop(key, None)
@@ -1121,7 +1141,7 @@ def handle_one(event, ctx):
1121
  else:
1122
  clone.pop('scope', None)
1123
  if store.available():
1124
- clone = (cl_mod.duplicate_table_field(
1125
  uname, src_key, new_key, clone,
1126
  reserved_names=_reserved_field_names,
1127
  correction_id=event_id) or clone)
@@ -1198,6 +1218,14 @@ def handle_one(event, ctx):
1198
  if key not in overlay_keys or not isinstance(value, (str, int, float)):
1199
  refused = True
1200
  continue
 
 
 
 
 
 
 
 
1201
  # Wave-5 item 1: `permissions.edit` is enforced HERE, per key β€” the client hiding
1202
  # its editor is courtesy, this is the wall. Fail-closed: a restricted field with
1203
  # no readable createdBy admits only admins.
@@ -1246,7 +1274,7 @@ def handle_one(event, ctx):
1246
  updates[key] = clean
1247
  if updates:
1248
  if store.available():
1249
- cl_mod.patch_table_overlay(uname, pid, updates)
1250
  else:
1251
  _session_ready()
1252
  ws['overlays'].setdefault(str(pid), {}).update(updates)
 
112
  measure_offer: tuple = ()
113
  visible_views: tuple = ()
114
  admin: bool = False
115
+ #: β›” WAVE 15 C-PERM β€” the fields this caller's PERMANENT PERMISSIONS hide, transitive
116
+ #: closure included (`core.perm_scope.hidden_keys`). A SECURITY parameter in the same class
117
+ #: as `allowed_pids`, and here for the same reason: the read paths strip a hidden field from
118
+ #: both wires, so a caller cannot SEE it β€” but without this they could still WRITE it by
119
+ #: naming the key, because `overlay_keys` only asks whether the column exists. Empty means
120
+ #: "nothing hidden", which is every legacy record and therefore every caller today.
121
+ hidden_keys: frozenset = frozenset()
122
  scope_key: str = 'customer'
123
+ #: Wave 16 C-TOPIC β€” the TABLE OPS this ctx reads and writes (a `core.table_store.make`
124
+ #: object). None = the CUSTOMER table (`modules.customer_data.TABLE_OPS`), which keeps
125
+ #: every existing caller byte-identical. The PRODUCT surface passes
126
+ #: `modules.product_data.TABLE_OPS` so its views/fields/overlays land in the product
127
+ #: bucket β€” never the customer one, whose pids are a different id space entirely.
128
+ table: Optional[object] = None
129
  seen_ids: Optional[MutableMapping] = None
130
  fallback_ws: Optional[MutableMapping] = None
131
  out: EventResult = field(default_factory=EventResult)
 
138
  self.seen_ids = {}
139
 
140
 
141
+ def _tops(ctx):
142
+ """The table-ops object this ctx operates on β€” the customer table unless the caller chose
143
+ another topic. ONE resolution point so 'which bucket does this write land in' has exactly
144
+ one answer per event."""
145
+ return ctx.table if ctx.table is not None else cl_mod.TABLE_OPS
146
+
147
+
148
  # ------------------------------------------------------------------ the workspace family (X1 amd.)
149
  def table_workspace(ctx, allowed_pids=None, consume_corrections=True):
150
  """Durable Airtable-style view/schema/overlay state, with an honest session fallback.
 
168
  """
169
  uname = ctx.uname
170
  if store.available():
171
+ ws = _tops(ctx).workspace(
172
  uname, consume_corrections=bool(consume_corrections))
173
  try:
174
+ shared = _tops(ctx).shared_views(uname, bool(ctx.admin))
175
  except Exception as _se:
176
  _tel.error('sharedviews:read', _se)
177
  shared = {}
 
430
  vid = str(event.get('viewId') or '').strip()[:120]
431
  if vid and store.available():
432
  try:
433
+ _tops(ctx).save_active_view(uname, vid)
434
  except Exception as _ae:
435
  _tel.error('grid:view-select', _ae)
436
  return False
 
450
  seen.add(k)
451
  order.append(k)
452
  if store.available():
453
+ _tops(ctx).save_record_layout(uname, order)
454
  else:
455
  _session_ready()
456
  if order:
 
550
  # caller may not SEE reads as absent β€” which would look like a CREATE and let anybody
551
  # overwrite somebody else's shared view by guessing its id. Ask the store for the raw
552
  # record and refuse before deciding anything else. Fail-closed on both branches.
553
+ _raw_shared = _tops(ctx).shared_view(view_id) if store.available() else None
554
  if _raw_shared is not None and not prior:
555
  return False # exists, not visible to this caller: refuse
556
  if _raw_shared is not None and not _tstore._may_edit(_raw_shared, uname, admin):
 
641
  if view_id != 'all-customers':
642
  _reserved_view_names.append('All customers')
643
  if store.available():
644
+ view = (_tops(ctx).save_view(
645
  uname, view, reserved_names=_reserved_view_names, is_admin=admin) or view)
646
  else:
647
  _session_ready()
 
686
  # only. A collaborator can change what a shared view shows; they cannot destroy
687
  # everybody else's copy of it, because there is only one copy.
688
  if store.available():
689
+ _raw_shared = _tops(ctx).shared_view(view_id)
690
  if _raw_shared is not None and not _tstore._may_administer(
691
  _raw_shared, uname, admin):
692
  return False
693
+ _tops(ctx).delete_view(uname, view_id)
694
  else:
695
  _session_ready()
696
  ws['views'].pop(view_id, None)
 
827
  and isinstance(value, dict))
828
  ]
829
  if store.available():
830
+ field = (_tops(ctx).save_field(
831
  uname, field, reserved_names=_reserved_field_names,
832
  correction_id=event_id) or field)
833
  else:
 
1072
  _res = _mutate(table_workspace(ctx, consume_corrections=False))
1073
  if _res is None:
1074
  return False # refused: nothing is written
1075
+ _tops(ctx).save_folders(uname, _res[0], _res[1])
1076
  # True: the sidebars render from server state (which folder holds what), not from local
1077
  # optimism β€” the same contract the cohort panel's membership edits ride.
1078
  return True
 
1089
  if not (key.startswith('custom_') or key.startswith(_ag3.MEASURE_FIELD_PREFIX)):
1090
  return False
1091
  if store.available():
1092
+ _tops(ctx).delete_field(uname, key)
1093
  else:
1094
  _session_ready()
1095
  ws['fields'].pop(key, None)
 
1141
  else:
1142
  clone.pop('scope', None)
1143
  if store.available():
1144
+ clone = (_tops(ctx).duplicate_field(
1145
  uname, src_key, new_key, clone,
1146
  reserved_names=_reserved_field_names,
1147
  correction_id=event_id) or clone)
 
1218
  if key not in overlay_keys or not isinstance(value, (str, int, float)):
1219
  refused = True
1220
  continue
1221
+ # C-PERM: a field this caller's permissions HIDE cannot be written, only refused.
1222
+ # `overlay_keys` asks whether the column exists, not whether this person may touch
1223
+ # it β€” so without this line a restricted user who knows a hidden key could PATCH a
1224
+ # value they are not allowed to read back. Refused LOUDLY (repaint) so the client
1225
+ # reverts rather than showing a value the store never took.
1226
+ if key in (ctx.hidden_keys or frozenset()):
1227
+ refused = True
1228
+ continue
1229
  # Wave-5 item 1: `permissions.edit` is enforced HERE, per key β€” the client hiding
1230
  # its editor is courtesy, this is the wall. Fail-closed: a restricted field with
1231
  # no readable createdBy admits only admins.
 
1274
  updates[key] = clean
1275
  if updates:
1276
  if store.available():
1277
+ _tops(ctx).patch_overlay(uname, pid, updates)
1278
  else:
1279
  _session_ready()
1280
  ws['overlays'].setdefault(str(pid), {}).update(updates)
royalimports_os/core/perm_migrate.py ADDED
@@ -0,0 +1,156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """core/perm_migrate.py β€” R1's one-time migration: `bus`/`agent` become a PERMANENT FILTER.
2
+
3
+ Owner ruling R1: BU access stops being its own field and becomes an ordinary permanent filter
4
+ under the permissioning engine, declared and edited exactly like "Agent is Tara". This module
5
+ builds that filter from the legacy record and β€” the part that matters β€” PROVES the swap is a
6
+ no-op before anything relies on it.
7
+
8
+ β›” WHY THE PROOF IS ABOUT VALUES AND NOT ABOUT ROWS (C-PERM amendment 3).
9
+ `modules/customer_data._pool_build` passes `team_id` into `cust._cust_rev` three times (YTD, LY,
10
+ LTM) and into `cust._cadence_bulk`. It therefore decides what `rev`, `ly`, `ltm`, `aov`,
11
+ `est_missed` and the derived `status` MEAN β€” it is not a row filter. Swap it for a post-filter
12
+ and a Fisch-only user keeps a plausible row LIST while every number on it quietly becomes
13
+ Fisch+Royal, worst for `dba = Both` customers, who are precisely the ones a BU filter admits.
14
+ A pid-set reconciliation reports GREEN on that. So `reconcile()` compares VALUES.
15
+
16
+ The pushdown survives as `perm_scope.derive_pool_scope` β€” a DERIVATION OF the filter rather than
17
+ a wall beside it β€” so a correctly migrated record produces the IDENTICAL pool call, and the
18
+ reconciliation below should be exact rather than merely close. If it is not exact, that is a
19
+ finding for the owner, not a tolerance to widen.
20
+ """
21
+ import core.perm_scope as perm_scope
22
+ import core.perms as perms
23
+
24
+ MODULE = 'customer_data'
25
+
26
+ #: `_dba_attrs` emits exactly {'Fisch','Royal','Both'} (blank = no brand attributable in 24
27
+ #: months). A BU grant admits its own brand AND the dual-brand customers: a Both customer IS a
28
+ #: Fisch customer. Mirrors `perm_scope._DBA_TEAM`, inverted.
29
+ #:
30
+ #: ⚠ TWO VALUES, AND THE COLUMN VOCABULARY HAS NO "IS ANY OF". `FILTER_OPS` is single-valued by
31
+ #: design (`eq`, `neq`, `contains`, …) β€” `anyOf` belongs to the COHORT vocabulary and is
32
+ #: deliberately DISJOINT from it, so a column leaf carrying `anyOf` is refused by every engine
33
+ #: (`filter_eval` returns False, `clean_filter_tree` drops it). This migration's first draft
34
+ #: emitted exactly that and `reconcile()` caught it as two lost customers. So the BU condition
35
+ #: is an OR GROUP of `eq` leaves, which is what the condition builder itself produces.
36
+ _TEAM_DBA = {5: ('Fisch', 'Both'), 6: ('Royal', 'Both')}
37
+
38
+
39
+ def filter_for(rec):
40
+ """The permanent filter equivalent to this record's legacy `bus` + `agent`, or None when the
41
+ record was unrestricted (an admin, or `bus:'all'` with no agent link).
42
+
43
+ AND-conjoined at the root, and top-level by construction β€” which is also what makes it
44
+ pushdown-derivable (`derive_pool_scope` reads top-level AND leaves only).
45
+ """
46
+ nodes = []
47
+ team_id = perms.scope_team_id(rec)
48
+ if team_id in _TEAM_DBA:
49
+ nodes.append({'conj': 'or',
50
+ 'children': [{'colId': 'dba', 'op': 'eq', 'value': v, 'value2': ''}
51
+ for v in _TEAM_DBA[team_id]]})
52
+ agent = perms.scope_agent(rec)
53
+ if agent:
54
+ nodes.append({'colId': 'agent', 'op': 'eq', 'value': str(agent), 'value2': ''})
55
+ if not nodes:
56
+ return None
57
+ return {'conj': 'and', 'nodes': nodes}
58
+
59
+
60
+ def perms_for(rec, modules=(MODULE,)):
61
+ """The `perms` block this legacy record becomes.
62
+
63
+ ⚠ ACCESS IS COPIED FROM THE OLD GRANT, NOT ASSUMED. `may_open` is what decided reachability
64
+ before this wave, so migrating a record must not widen it β€” and on a migrated record an
65
+ undeclared module DENIES (amendment 4), so every module the user could reach has to be
66
+ declared here or the migration is a lockout.
67
+ """
68
+ out = {}
69
+ for key in modules:
70
+ out[key] = {'access': bool(perms.may_open(rec, key)),
71
+ 'filter': filter_for(rec),
72
+ 'hiddenFields': []}
73
+ return out
74
+
75
+
76
+ def plan(registry_dict, modules=(MODULE,)):
77
+ """`{username: perms_block}` for every record that is not already migrated.
78
+
79
+ Admins are included and get an all-access block with no filter: they bypass `perm_scope`
80
+ anyway, but leaving them un-migrated would keep the legacy reader alive for the one account
81
+ most likely to be inspected when something looks wrong.
82
+ """
83
+ out = {}
84
+ for uname, rec in (registry_dict or {}).items():
85
+ if not isinstance(rec, dict) or perm_scope.is_migrated(rec):
86
+ continue
87
+ out[uname] = perms_for(rec, modules)
88
+ return out
89
+
90
+
91
+ #: The row members whose meaning depends on `team_id` β€” the ones amendment 3 is about. A
92
+ #: reconciliation that skipped these would be the pid-only gate that cannot see the leak.
93
+ VALUE_KEYS = ('rev', 'ly', 'ltm', 'aov', 'est_missed', 'status', 'orders', 'last_order')
94
+
95
+
96
+ def reconcile(rec, pool_fn, modules=(MODULE,)):
97
+ """Prove the migrated record sees EXACTLY what the legacy record saw.
98
+
99
+ `pool_fn(agent, team_id) -> rows` is injected so this is testable without Odoo and so the
100
+ caller decides whether to hit the live builder or a fixture.
101
+
102
+ Returns `{ok, legacy_scope, derived_scope, lost, gained, value_diffs}`:
103
+ * `lost` β€” pids the legacy wall admitted and the migrated one drops. Expected to be
104
+ EMPTY. One narrow class is known and must be REPORTED rather than tolerated:
105
+ `_dba_attrs` uses a 731-day window while `_cust_rev`'s LY window can reach a
106
+ little further back, so a customer whose only in-scope revenue predates that
107
+ window carries a BLANK `dba` and fails a `dba` leaf. Blank is the honest "no
108
+ brand attributable" state, so such a customer is NAMED here, never rounded
109
+ away.
110
+ * `gained` β€” pids the migrated wall admits and the legacy one did not. Must be empty: it
111
+ is the widening direction, and there is no acceptable non-empty value.
112
+ * `value_diffs` β€” per-pid disagreements on VALUE_KEYS. The assertion amendment 3 exists
113
+ for; a non-empty list means the pushdown was not applied and the numbers are
114
+ consolidated.
115
+ """
116
+ legacy_scope = (perms.scope_agent(rec), perms.scope_team_id(rec))
117
+ migrated = dict(rec)
118
+ migrated['perms'] = perms_for(rec, modules)
119
+ migrated['perms_v'] = perm_scope.PERMS_VERSION
120
+ team_id, agent = perm_scope.derive_pool_scope(migrated, MODULE)
121
+ derived_scope = (agent, team_id)
122
+
123
+ legacy_rows = pool_fn(legacy_scope[0], legacy_scope[1])
124
+ derived_rows = pool_fn(agent, team_id)
125
+ fields = _fields_of(legacy_rows)
126
+ kept = perm_scope.apply_row_scope(derived_rows, migrated, MODULE, fields)
127
+
128
+ legacy_by = {r.get('pid'): r for r in legacy_rows}
129
+ kept_by = {r.get('pid'): r for r in kept}
130
+ lost = sorted(set(legacy_by) - set(kept_by))
131
+ gained = sorted(set(kept_by) - set(legacy_by))
132
+
133
+ value_diffs = []
134
+ for pid in sorted(set(legacy_by) & set(kept_by)):
135
+ a, b = legacy_by[pid], kept_by[pid]
136
+ for k in VALUE_KEYS:
137
+ if k in a and a.get(k) != b.get(k):
138
+ value_diffs.append({'pid': pid, 'key': k,
139
+ 'legacy': a.get(k), 'migrated': b.get(k)})
140
+ return {'ok': not lost and not gained and not value_diffs,
141
+ 'legacy_scope': legacy_scope, 'derived_scope': derived_scope,
142
+ 'lost': lost, 'gained': gained, 'value_diffs': value_diffs,
143
+ 'names': {r.get('pid'): r.get('customer') for r in legacy_rows
144
+ if r.get('pid') in set(lost)}}
145
+
146
+
147
+ def _fields_of(rows):
148
+ """A field list good enough to EVALUATE with, inferred from the assembled rows.
149
+
150
+ The permanent filters this module builds name `dba` (text) and `agent` (text) only, so the
151
+ inference is exact for them. It is deliberately not a schema: `permits()` needs types to
152
+ dispatch comparisons, and inferring `text` for an unknown key would be a guess with
153
+ consequences β€” so anything not recognised is left out, which makes its leaf unanswerable and
154
+ therefore DENYING rather than silently mistyped.
155
+ """
156
+ return [{'key': 'dba', 'type': 'text'}, {'key': 'agent', 'type': 'text'}]
royalimports_os/core/perm_scope.py ADDED
@@ -0,0 +1,286 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """core/perm_scope.py β€” the permission WALL for table modules (wave 15, C-PERM).
2
+
3
+ ONE place answers the three questions a restricted account raises on a grid surface:
4
+
5
+ may_access(user, module) may they open it at all?
6
+ visible_fields(fields, u, mod) which COLUMNS may they receive?
7
+ apply_row_scope(rows, u, mod, …) which ROWS may they receive?
8
+
9
+ plus one that exists only because of how the pool is built:
10
+
11
+ derive_pool_scope(user, module) which (team_id, agent) must the pool be BUILT with?
12
+
13
+ Both hosts call these β€” `aios-web/api` (`grid_assembly`) and `app.py` (`_table_grid`) β€” because
14
+ a wall that exists on one runtime and not the other is not a wall. `core/perms.py` stays what it
15
+ is (module GRANTS + the legacy BU derivation); this module is the row/field/pushdown layer that
16
+ sits on top, and it is deliberately a separate file so the legacy readers can keep their
17
+ semantics untouched while this one fails closed.
18
+
19
+ ────────────────────────────────────────────────────────────────────────────────────────────
20
+ THE RECORD
21
+
22
+ user['perms'] = {'<module_key>': {'access': bool,
23
+ 'filter': {'conj'?: 'and'|'or', 'nodes': [...]} | None,
24
+ 'hiddenFields': ['<field key>', ...]}}
25
+ user['perms_v'] = 1 stamped by the migration and by every write
26
+
27
+ `perms_v` is the EXPLICIT-RESOLUTION marker, and it is here because of `permissioning.md`
28
+ Part II gap #5: "`allowed_modules() is None` is fail-open by default … make 'resolved:
29
+ unrestricted' an explicit value so absence/uncertainty DENIES." The same class already shipped
30
+ twice in this codebase (`modules: []` and `bus: [<unknown id>]` both read as UNRESTRICTED β€”
31
+ `routes_admin.py`'s own docstring documents both). So:
32
+
33
+ * `perms_v` ABSENT β†’ the record is UN-MIGRATED, and the LEGACY wall applies unchanged
34
+ (`core.perms` module grants + the `bus`/`agent` query scope). That is not fail-open: it is
35
+ today's real wall, and it bounds the rollout window to "until the migration runs".
36
+ * `perms_v == 1` and the module has NO entry β†’ **DENY**. Absence now means what it says.
37
+ * `role == 'admin'` bypasses all of it β€” which is also what keeps BREAK-GLASS alive.
38
+ `deps._user_for` hands back a hardcoded master dict on a store outage
39
+ (`{'username':'admin','role':'admin','bus':'all','modules':'all'}`) that will never carry a
40
+ perms block; without this clause an explicit-marker scheme locks the owner out of their own
41
+ product at exactly the moment the store is broken.
42
+ """
43
+ import re
44
+
45
+ import core.perms as perms
46
+
47
+ #: `aios_grid._FORMULA_REF`'s pattern, restated rather than imported: this module is imported by
48
+ #: the API's request path and `aios_grid` pulls in the whole grid stack. Same regex, one line,
49
+ #: and `verify_api` asserts the two agree so it cannot drift into a different grammar.
50
+ _FORMULA_REF = re.compile(r"\{([^{}]*)\}")
51
+
52
+ PERMS_VERSION = 1
53
+
54
+
55
+ def _rec(user):
56
+ return user if isinstance(user, dict) else {}
57
+
58
+
59
+ def is_migrated(user):
60
+ """True once this record carries an explicit resolution. See the module docstring."""
61
+ return int(_rec(user).get('perms_v') or 0) >= PERMS_VERSION
62
+
63
+
64
+ def entry(user, module):
65
+ """This user's declared permissions for `module`, or None if nothing is declared.
66
+
67
+ None is AMBIGUOUS on purpose and every caller must resolve it against `is_migrated`:
68
+ on a migrated record it means DENY, on a legacy one it means "ask the old wall".
69
+ """
70
+ p = _rec(user).get('perms')
71
+ if not isinstance(p, dict):
72
+ return None
73
+ e = p.get(module)
74
+ return e if isinstance(e, dict) else None
75
+
76
+
77
+ def may_access(user, module):
78
+ """May this account open `module` at all? Fail-closed on a migrated record."""
79
+ if perms.is_admin(user):
80
+ return True
81
+ e = entry(user, module)
82
+ if e is not None:
83
+ return bool(e.get('access', True))
84
+ if is_migrated(user):
85
+ # Migrated and undeclared = denied. This is the whole point of the marker.
86
+ return False
87
+ return perms.may_open(user, module) # legacy record: the old grant wall
88
+
89
+
90
+ # ── FIELDS ───────────────────────────────────────────────────────────────────────────────────
91
+ def hidden_keys(user, module, fields):
92
+ """The TRANSITIVE closure of hidden field keys (C-PERM amendment 5).
93
+
94
+ β›” WHY A CLOSURE AND NOT A SET DIFFERENCE. A formula field is computed in the BROWSER
95
+ (`formulaEngine.ts`, injected by `computedRows`) from `{ref}`s into other columns, and a
96
+ measure column's value arrives precomputed in `derived`. So hiding field X has exactly three
97
+ possible outcomes and only one of them is coherent:
98
+
99
+ strip X, keep formulas β†’ every formula over X computes blank or wrong, silently
100
+ keep X's value for them β†’ X has leaked, wearing a formula's name
101
+ strip X AND its dependents→ the only honest answer
102
+
103
+ So a hidden field drags every formula that references it β€” and every formula that references
104
+ THAT formula, hence the fixpoint loop β€” out of the payload with it.
105
+
106
+ ⚠ This runs on every assembly, so it is a fixpoint over a handful of custom fields, not a
107
+ graph library. `MAX_PASSES` bounds a reference cycle the client would refuse to evaluate
108
+ anyway; without it a self-referential pair would spin here.
109
+ """
110
+ e = entry(user, module)
111
+ if perms.is_admin(user) or not e:
112
+ return frozenset()
113
+ hidden = {str(k) for k in (e.get('hiddenFields') or ()) if k}
114
+ if not hidden:
115
+ return frozenset()
116
+
117
+ refs = {}
118
+ for f in fields or ():
119
+ if not isinstance(f, dict) or not f.get('key'):
120
+ continue
121
+ expr = f.get('formula')
122
+ if isinstance(expr, str) and expr:
123
+ refs[f['key']] = {m.strip() for m in _FORMULA_REF.findall(expr) if m.strip()}
124
+
125
+ MAX_PASSES = 12
126
+ for _ in range(MAX_PASSES):
127
+ grew = False
128
+ for key, deps in refs.items():
129
+ if key not in hidden and deps & hidden:
130
+ hidden.add(key)
131
+ grew = True
132
+ if not grew:
133
+ break
134
+ return frozenset(hidden)
135
+
136
+
137
+ def visible_fields(fields, user, module):
138
+ """`fields` minus the hidden closure. Order preserved β€” the column order is the user's."""
139
+ hide = hidden_keys(user, module, fields)
140
+ if not hide:
141
+ return list(fields or ())
142
+ return [f for f in (fields or ())
143
+ if not (isinstance(f, dict) and f.get('key') in hide)]
144
+
145
+
146
+ def strip_row(row, hide):
147
+ """Drop hidden keys from ONE assembled row. Cheap enough to run per row, and it must run
148
+ per row: the field list and the row payload are two different wires, and stripping only the
149
+ first would leave the value sitting in the second where anyone can read it."""
150
+ if not hide or not isinstance(row, dict):
151
+ return row
152
+ return {k: v for k, v in row.items() if k not in hide}
153
+
154
+
155
+ # ── ROWS ─────────────────────────────────────────────────────────────────────────────────────
156
+ def apply_row_scope(rows, user, module, fields, ctx=None):
157
+ """The rows this account may receive: `filter_eval.permits` over the permanent filter.
158
+
159
+ `permits`, never `matches` β€” an unanswerable permanent filter DENIES rather than being
160
+ ignored. See `harness/filter_eval`'s docstring for the field-rename walkthrough that makes
161
+ the difference a leak rather than a preference.
162
+ """
163
+ if perms.is_admin(user):
164
+ return list(rows or ())
165
+ e = entry(user, module)
166
+ tree = (e or {}).get('filter')
167
+ if not tree:
168
+ return list(rows or ())
169
+ from harness import filter_eval as fe
170
+ return [r for r in (rows or ()) if fe.permits(tree, r, fields, ctx)]
171
+
172
+
173
+ # ── THE PUSHDOWN ─────────────────────────────────────────────────────────────────────────────
174
+ #: `dba` value sets that pin a BU, and the Odoo team they pin. `_dba_attrs` emits exactly
175
+ #: {'Fisch','Royal','Both'} (blank for "no brand attributable in 24 months"), so a permission
176
+ #: filter admitting Fisch admits {Fisch, Both} β€” a Both customer IS a Fisch customer.
177
+ _DBA_TEAM = ((frozenset({'fisch', 'both'}), 5), (frozenset({'royal', 'both'}), 6))
178
+
179
+ #: Only equality pushes down. `FILTER_OPS` is single-valued (there is no column-level "is any
180
+ #: of" β€” that vocabulary belongs to cohort leaves and is disjoint), so a multi-value BU
181
+ #: condition arrives as an OR GROUP of `eq` leaves, handled by `_group_dba_team` below.
182
+ _PUSHDOWN_OPS = frozenset({'eq'})
183
+
184
+
185
+ def derive_pool_scope(user, module):
186
+ """`(team_id, agent)` the POOL must be BUILT with, derived from the permanent filter.
187
+
188
+ β›” THIS EXISTS BECAUSE `team_id` SHAPES VALUES, NOT ROW MEMBERSHIP (C-PERM amendment 3).
189
+ `modules/customer_data._pool_build` passes `team_id` into `cust._cust_rev` three times (YTD,
190
+ LY, LTM) and into `cust._cadence_bulk`, so it decides what `rev`, `ly`, `ltm`, `aov`,
191
+ `est_missed` and the derived `status` MEAN. Enforce a BU purely as a post-filter and a
192
+ Fisch-only user keeps a correct-looking row LIST while every number on it silently becomes
193
+ Fisch+Royal β€” worst for `dba = Both` customers, who are exactly the ones a BU filter admits.
194
+ A pid-level reconciliation cannot see that; the values one can, and does.
195
+
196
+ So the query-level pushdown SURVIVES β€” but as a DERIVATION OF the permanent filter rather
197
+ than a second wall beside it, which is what keeps R1's "BU access is just a filter" true at
198
+ the level the owner asked for it (one declaration, one UI, one engine).
199
+
200
+ Pure, and recomputed per request rather than stored: a stored derivation drifts from the
201
+ filter it came from, and then two things disagree about what an account may see.
202
+
203
+ Reads TOP-LEVEL AND-conjunction leaves ONLY. A leaf under `or` guarantees no narrowing β€”
204
+ `dba is Fisch OR revenue > 10` must not pin the pool to Fisch β€” so it never pushes down.
205
+ Anything not recognised here simply is not pushed down; `apply_row_scope` still applies the
206
+ whole tree, so the wall is unchanged either way. Belt AND braces, deliberately: the pushdown
207
+ is what makes the VALUES right, `permits()` is what makes the ROWS right.
208
+ """
209
+ if perms.is_admin(user):
210
+ return None, None
211
+ e = entry(user, module)
212
+ tree = (e or {}).get('filter')
213
+ if not tree:
214
+ # Un-migrated records still answer through the legacy derivation, so the old wall keeps
215
+ # working until the migration has run.
216
+ if not is_migrated(user):
217
+ return perms.scope_team_id(user), perms.scope_agent(user)
218
+ return None, None
219
+
220
+ from harness import filter_eval as fe
221
+ nodes, conj = fe.tree_parts(tree)
222
+ if conj == 'or':
223
+ return None, None
224
+
225
+ team_id, agent = None, None
226
+ for n in nodes:
227
+ if not isinstance(n, dict):
228
+ continue
229
+ if isinstance(n.get('children'), list):
230
+ # A top-level OR GROUP under an AND root IS a guaranteed narrowing β€” every row must
231
+ # satisfy it β€” so it may push down, unlike a leaf under an OR ROOT (refused above).
232
+ # This is the shape a multi-value BU condition actually takes; see `_group_dba_team`.
233
+ tid = _group_dba_team(n)
234
+ if tid is not None:
235
+ team_id = tid if team_id in (None, tid) else None
236
+ continue
237
+ if n.get('op') not in _PUSHDOWN_OPS:
238
+ continue
239
+ col = n.get('colId')
240
+ raw = n.get('value')
241
+ if col == 'dba':
242
+ vals = {v.strip().lower() for v in str(raw or '').split(',') if v.strip()}
243
+ if not vals:
244
+ continue
245
+ for allowed, tid in _DBA_TEAM:
246
+ if vals <= allowed:
247
+ # Both BUs named = no narrowing to push; leave it to the post-filter.
248
+ team_id = tid if team_id in (None, tid) else None
249
+ break
250
+ elif col == 'agent':
251
+ v = str(raw or '').strip()
252
+ # A SET of agents cannot become the pool's single `agent_name`; the post-filter
253
+ # handles it. Only an unambiguous single value pushes down.
254
+ if v and ',' not in v:
255
+ agent = v
256
+ return team_id, agent
257
+
258
+
259
+ def _group_dba_team(group):
260
+ """The team a top-level `or` group pins, or None.
261
+
262
+ Recognises ONLY the exact shape "every child is a `dba eq <brand>` leaf" β€” the group the
263
+ condition builder emits for a multi-value BU condition, and the one `perm_migrate` writes.
264
+ Every OTHER group returns None and is left entirely to the post-filter: a group mixing `dba`
265
+ with another column, or containing a nested group, does not pin a BU on its own, and
266
+ guessing that it does would build the pool from the wrong book. Narrow by construction β€”
267
+ the pushdown may only ever be an OPTIMISATION of a constraint the filter already expresses.
268
+ """
269
+ if group.get('conj') != 'or':
270
+ return None
271
+ children = group.get('children') or []
272
+ if not children:
273
+ return None
274
+ vals = set()
275
+ for c in children:
276
+ if (not isinstance(c, dict) or isinstance(c.get('children'), list)
277
+ or c.get('colId') != 'dba' or c.get('op') != 'eq'):
278
+ return None
279
+ v = str(c.get('value') or '').strip().lower()
280
+ if not v:
281
+ return None
282
+ vals.add(v)
283
+ for allowed, tid in _DBA_TEAM:
284
+ if vals <= allowed:
285
+ return tid
286
+ return None
royalimports_os/core/perms.py CHANGED
@@ -29,7 +29,19 @@ import core.users as users
29
  # customer_data + cohort β€” and may_open() gives a parent grant to its children. Mapping it away
30
  # would silently narrow every "customers" grant to one child.
31
  _LEGACY_KEYS = {'myday': 'customer_data', 'customer_list': 'customer_data',
32
- 'map': 'customer_data', 'library': 'settings'}
 
 
 
 
 
 
 
 
 
 
 
 
33
 
34
 
35
  def is_admin(user):
 
29
  # customer_data + cohort β€” and may_open() gives a parent grant to its children. Mapping it away
30
  # would silently narrow every "customers" grant to one child.
31
  _LEGACY_KEYS = {'myday': 'customer_data', 'customer_list': 'customer_data',
32
+ 'map': 'customer_data', 'library': 'settings',
33
+ # wave 16 (item 5, R10): Cohort folded into the Customer rail as locked
34
+ # views β€” a cohort grant or ?page=cohort deep link lands on the grid that
35
+ # now hosts them.
36
+ 'cohort': 'customer_data',
37
+ # wave 16 (item 7, R11): the Agents PAGE is deleted; an 'agent'-granted
38
+ # login's surviving surface is the Customer grid over their OWN m2m book β€”
39
+ # the legacy query-scope (scope_agent reads the record's agent LINK, not
40
+ # this list) keeps that book exact, shared customers included. The R1
41
+ # migration deliberately SKIPS agent-linked records: `agent is X` cannot
42
+ # express m2m membership (a shared customer displays its primary agent),
43
+ # so their wall stays legacy until a membership predicate exists.
44
+ 'agent': 'customer_data'}
45
 
46
 
47
  def is_admin(user):
royalimports_os/core/registry.py CHANGED
@@ -34,8 +34,15 @@ Fields:
34
  # See [[connector-onboarding]]: the plug-in seam is datastore.py, and Odoo has no delegated
35
  # OAuth, so the "+ New" connect flow is the credential-form shape, not an OAuth redirect.
36
  REGISTRY = [
37
- {'key': 'sales', 'label': 'Sales', 'brand': True, 'hq': False, 'validate': True, 'source': 'Odoo',
38
- 'note': 'Revenue, YoY, seasonality, reps, customers, SKUs β€” by BU.'},
 
 
 
 
 
 
 
39
  # ARCHIVED AS A PAGE (owner item 14, wave 8): "archive the current form of the Customer
40
  # dashboard completely, i want to redesign it, exactly with the backend we have". So the
41
  # PAGE goes and the DATA LAYER stays β€” modules/customers.py still powers the Customer table's
@@ -67,12 +74,36 @@ REGISTRY = [
67
  # data moves, a cohort only changes when a person edits it. validate:False because
68
  # there is no Odoo aggregate to reconcile a hand-picked list against; its metrics are
69
  # the customers module's, already validated there.
70
- {'key': 'cohort', 'label': 'Cohort', 'brand': True, 'hq': False, 'validate': False, 'source': 'Odoo', 'parent': 'customers',
71
- 'note': 'Hand-curated, unchanging customer lists. Same grid as Data (filter, sort, '
72
- 'group, custom columns) but the SET is fixed: it changes only when someone '
73
- 'adds or removes a member. Populated from a view via ... > Add to list.'},
74
- {'key': 'agent', 'label': 'Agents', 'brand': True, 'hq': False, 'validate': True, 'source': 'Odoo',
75
- 'note': 'Per-agent book: sales (custom dates), returns, top SKUs, full customer list incl. inactive. Returns consolidated.'},
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
76
  {'key': 'products', 'label': 'SKU', 'brand': True, 'hq': False, 'validate': True, 'archived': True,
77
  'note': 'SKU movers, zombies, velocity, coverage, drawers β€” by BU (sales-derived).'},
78
  {'key': 'assortment', 'label': 'Assortment', 'brand': True, 'hq': False, 'validate': True, 'archived': True,
 
34
  # See [[connector-onboarding]]: the plug-in seam is datastore.py, and Odoo has no delegated
35
  # OAuth, so the "+ New" connect flow is the credential-form shape, not an OAuth redirect.
36
  REGISTRY = [
37
+ # ARCHIVED wave 16 (owner item 7, R3/R11, 2026-08-02): the PAGE went on the strength of
38
+ # C-CHARTCAP β€” every Sales block shape (YoY compare series, KPI delta tiles, group-by
39
+ # tables) is now assemblable BY HAND from the grid's chart/dashboard views, which is what
40
+ # R3 required before deletion. `modules/sales.py` (the data layer) STAYS β€” drawers and the
41
+ # briefing still read it, and pages_sales.py survives UNREGISTERED as the Y1 envelope's
42
+ # template + verify_api's fixture.
43
+ {'key': 'sales', 'label': 'Sales', 'brand': True, 'hq': False, 'validate': True, 'source': 'Odoo', 'archived': True,
44
+ 'note': 'Revenue, YoY, seasonality, reps, customers, SKUs β€” by BU. Retired wave 16: '
45
+ 'rebuild as grid chart/dashboard views (compare series, KPI deltas, tables).'},
46
  # ARCHIVED AS A PAGE (owner item 14, wave 8): "archive the current form of the Customer
47
  # dashboard completely, i want to redesign it, exactly with the backend we have". So the
48
  # PAGE goes and the DATA LAYER stays β€” modules/customers.py still powers the Customer table's
 
74
  # data moves, a cohort only changes when a person edits it. validate:False because
75
  # there is no Odoo aggregate to reconcile a hand-picked list against; its metrics are
76
  # the customers module's, already validated there.
77
+ # ARCHIVED wave 16 (owner item 5, R10 β€” the fold-in): every cohort now projects as a
78
+ # LOCKED VIEW in the Customer rail's "Cohorts" section (wave-15 C-LOCK), so the separate
79
+ # nav destination is gone. ALL cohort machinery stays: `scope=cohort` still works
80
+ # (routes_grid._SCOPES, storage keys, events), page_cohort remains in app.py, and
81
+ # _LEGACY_KEYS maps cohort→customer_data so grants + ?page= deep links land on the grid
82
+ # that now hosts the cohorts.
83
+ {'key': 'cohort', 'label': 'Cohort', 'brand': True, 'hq': False, 'validate': False, 'source': 'Odoo', 'parent': 'customers', 'archived': True,
84
+ 'note': 'Hand-curated, unchanging customer lists β€” folded into the Customer rail as '
85
+ 'locked views (wave 16). The set is fixed: it changes only when someone adds '
86
+ 'or removes a member. Open them from Customer > Views > Cohorts.'},
87
+ # ARCHIVED wave 16 (owner item 7, R11, 2026-08-02) beside Sales. The agent DRAWER and the
88
+ # data layer (modules/agent.py, agent_* caches) STAY β€” agent entities still open from
89
+ # customer surfaces; an own-book agent login's home is the Customer grid narrowed by the
90
+ # R1 permanent filter ("Agent is X"), not this page.
91
+ {'key': 'agent', 'label': 'Agents', 'brand': True, 'hq': False, 'validate': True, 'source': 'Odoo', 'archived': True,
92
+ 'note': 'Per-agent book: sales (custom dates), returns, top SKUs, full customer list incl. inactive. '
93
+ 'Retired wave 16: agent drawers + the R1 own-book filter carry the use case.'},
94
+ # Wave 16 C-TOPIC (owner items 9+10, R4): the PRODUCT table family β€” the second object on
95
+ # the table-page factory. `products_family` is the folder head (the `customers` pattern:
96
+ # group_only, never a destination); `product_data` is the grid over the SKU dataset, with
97
+ # its OWN workspace bucket ('product_table_workspace') and the /products + scope=product
98
+ # seams. The archived Streamlit `products` (SKU) row below stays archived and untouched,
99
+ # exactly as R4 rules.
100
+ {'key': 'products_family', 'label': 'Products', 'brand': True, 'hq': False, 'validate': False,
101
+ 'group_only': True,
102
+ 'note': 'Folder for the product surfaces (Product table). The archived SKU dashboard is '
103
+ 'not part of this family.'},
104
+ {'key': 'product_data', 'label': 'Product', 'brand': True, 'hq': False, 'validate': True, 'source': 'Odoo', 'parent': 'products_family',
105
+ 'note': 'The SKU catalogue as a grid: per-product revenue, units and (consolidated) '
106
+ 'stock columns, with saved views and custom fields. Identity = the SKU code.'},
107
  {'key': 'products', 'label': 'SKU', 'brand': True, 'hq': False, 'validate': True, 'archived': True,
108
  'note': 'SKU movers, zombies, velocity, coverage, drawers β€” by BU (sales-derived).'},
109
  {'key': 'assortment', 'label': 'Assortment', 'brand': True, 'hq': False, 'validate': True, 'archived': True,
royalimports_os/core/users.py CHANGED
@@ -17,16 +17,29 @@ import core.store as store
17
  BU_LABELS = {5: 'Fisch', 6: 'Royal'}
18
  _ITER = 200_000
19
 
 
 
 
 
20
 
21
  def _hash(pw, salt):
22
  return hashlib.pbkdf2_hmac('sha256', str(pw).encode('utf-8'), bytes.fromhex(salt), _ITER).hex()
23
 
24
 
25
- def _record(pw, name, role, bus, active=True, modules='all', agent=None, email=None):
 
26
  salt = secrets.token_hex(16)
27
- return {'salt': salt, 'hash': _hash(pw, salt), 'name': name, 'role': role,
28
- 'bus': bus, 'active': active, 'modules': modules,
29
- 'agent': agent or None, 'email': email or None}
 
 
 
 
 
 
 
 
30
 
31
 
32
  def registry():
@@ -69,6 +82,17 @@ def _public(username, u):
69
  # to every grid session via the workspace map); without it here the API session's
70
  # user record silently drops it and /me can never show your own photo.
71
  'avatar': u.get('avatar') or None,
 
 
 
 
 
 
 
 
 
 
 
72
  'epoch': int(u.get('epoch') or 0)}
73
 
74
 
@@ -201,7 +225,7 @@ def set_active(username, active):
201
 
202
 
203
  def set_access(username, role=None, bus=None, modules=None, agent=None, email=None,
204
- name=None):
205
  """Update access fields. agent/email: pass '' to clear, None to leave unchanged β€”
206
  the user↔agent link scopes the Customer List page / digests to that agent's book.
207
 
@@ -226,6 +250,13 @@ def set_access(username, role=None, bus=None, modules=None, agent=None, email=No
226
  u['agent'] = agent or None
227
  if email is not None:
228
  u['email'] = email or None
 
 
 
 
 
 
 
229
  return reg
230
  store.update('users', _set)
231
 
 
17
  BU_LABELS = {5: 'Fisch', 6: 'Royal'}
18
  _ITER = 200_000
19
 
20
+ #: Wave 15 C-PERM β€” the explicit-resolution marker. Mirrors `core.perm_scope.PERMS_VERSION`;
21
+ #: kept as a literal here so `users` does not import the permission layer it is read by.
22
+ PERMS_VERSION = 1
23
+
24
 
25
  def _hash(pw, salt):
26
  return hashlib.pbkdf2_hmac('sha256', str(pw).encode('utf-8'), bytes.fromhex(salt), _ITER).hex()
27
 
28
 
29
+ def _record(pw, name, role, bus, active=True, modules='all', agent=None, email=None,
30
+ perms=None):
31
  salt = secrets.token_hex(16)
32
+ rec = {'salt': salt, 'hash': _hash(pw, salt), 'name': name, 'role': role,
33
+ 'bus': bus, 'active': active, 'modules': modules,
34
+ 'agent': agent or None, 'email': email or None}
35
+ if perms is not None:
36
+ # Wave 15 C-PERM. A record written WITH perms is migrated by construction β€” the marker
37
+ # and the block are set together, here, so no writer can create one without the other.
38
+ # (`core.perm_scope` reads an unmarked record as legacy, so a block without its marker
39
+ # would be silently ignored; a marker without a block would deny everything.)
40
+ rec['perms'] = perms
41
+ rec['perms_v'] = PERMS_VERSION
42
+ return rec
43
 
44
 
45
  def registry():
 
82
  # to every grid session via the workspace map); without it here the API session's
83
  # user record silently drops it and /me can never show your own photo.
84
  'avatar': u.get('avatar') or None,
85
+ # β›” WAVE 15 C-PERM β€” THE WALL TRAVELS ON THIS PROJECTION OR IT DOES NOT TRAVEL.
86
+ # `deps._user_for` builds every API session from `_public()`, so a `perms` block
87
+ # dropped here is a restricted account served as an unrestricted one β€” silently, on
88
+ # every route, with nothing to notice. `perms_v` must ride ALONG WITH it and for the
89
+ # same reason inverted: the marker without the block denies everything, the block
90
+ # without the marker is ignored. Two keys, one fact, never separated.
91
+ # `verify_api` asserts a restricted user's SESSION OBJECT carries both, at the mount
92
+ # rather than by grep β€” a projection is exactly the kind of wiring that looks
93
+ # present in three files and is absent in the one that runs.
94
+ **({'perms': u['perms']} if isinstance(u.get('perms'), dict) else {}),
95
+ **({'perms_v': int(u['perms_v'] or 0)} if u.get('perms_v') else {}),
96
  'epoch': int(u.get('epoch') or 0)}
97
 
98
 
 
225
 
226
 
227
  def set_access(username, role=None, bus=None, modules=None, agent=None, email=None,
228
+ name=None, perms=None):
229
  """Update access fields. agent/email: pass '' to clear, None to leave unchanged β€”
230
  the user↔agent link scopes the Customer List page / digests to that agent's book.
231
 
 
250
  u['agent'] = agent or None
251
  if email is not None:
252
  u['email'] = email or None
253
+ if perms is not None:
254
+ # Wave 15 C-PERM. Writing perms MIGRATES the record: the marker goes on in the
255
+ # same read-modify-write, so a record can never end up with one and not the
256
+ # other (see `_record`). Whole-block replace, matching the PUT route's shape β€”
257
+ # a merge would make "remove this restriction" unexpressible.
258
+ u['perms'] = perms
259
+ u['perms_v'] = PERMS_VERSION
260
  return reg
261
  store.update('users', _set)
262
 
royalimports_os/harness/analyst.py CHANGED
@@ -198,10 +198,63 @@ def _live_chat(messages, tools, model, tool_choice="auto"):
198
  raise RuntimeError(f"all LLM providers failed (last: {last_err})")
199
 
200
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
201
  def ask(question, history=None, chat_fn=None, model=DEFAULT_MODEL, max_iters=MAX_ITERS,
202
- telemetry_kind="analyst"):
203
  """Run one Analyst turn. Returns {answer, artifacts, tool_trace, iterations, exhausted,
204
- usage}. chat_fn(messages, tools, model) -> (assistant_message_dict, usage_dict)."""
 
 
 
 
 
 
 
 
 
 
 
205
  chat = chat_fn or _live_chat
206
  tools = T.openai_tools()
207
  messages = [{"role": "system", "content": system_prompt()}]
 
198
  raise RuntimeError(f"all LLM providers failed (last: {last_err})")
199
 
200
 
201
+ #: Wave 15 R2 β€” what a restricted account is told instead of an answer.
202
+ ANALYST_DENIED = ("The Analyst is not available on your account. It answers from the full "
203
+ "governed model, which is wider than what your account is permitted to see.")
204
+
205
+
206
+ def may_ask(user):
207
+ """β›” R2 β€” THE AI WALL, AND IT IS DELIBERATELY BLUNT.
208
+
209
+ Owner, verbatim: *"If the AI is triggered by a user, the AI ITSELF should not be able to see
210
+ the data."* Today the Analyst's tools run UNSCOPED β€” `harness/tools.run_semantic_query` takes
211
+ no subject and no filter, so every question it answers is answered over the whole tenant.
212
+ A restricted account asking "what were our top customers?" would therefore receive, in prose,
213
+ precisely the rows the grid's permanent filter exists to withhold. Prose is not a lesser leak
214
+ than a table; it is a harder one to notice.
215
+
216
+ So the wall is REFUSAL, not narrowing: an account with ANY declared restriction β€” or any
217
+ non-admin on a migrated record β€” does not reach the model at all. An AI that never runs
218
+ cannot leak what it never read. Fail-closed on an unreadable record for the same reason.
219
+
220
+ β­’ NAMED DEBT, owner-mandated (R2, doc Β§Debt, log 2026-08-02). The RIGHT answer is to thread
221
+ the subject's permanent filter into every semantic query the Analyst runs β€” `filter_sql`
222
+ already compiles that tree to SQL, so the shape exists; what does not exist is a per-subject
223
+ query path through `harness/semantic.py`, which takes `team_id` and nothing else. Until that
224
+ lands this refusal is the whole enforcement, and it must NOT be relaxed into "narrow the
225
+ prompt" or "tell the model what it may not say" β€” a prompt is not a permission boundary.
226
+ """
227
+ import core.perms as perms
228
+ import core.perm_scope as perm_scope
229
+
230
+ if not isinstance(user, dict):
231
+ return False # no identity resolved -> no Analyst
232
+ if perms.is_admin(user):
233
+ return True
234
+ if perm_scope.is_migrated(user):
235
+ # Migrated and not an admin: the account is governed by a wall the Analyst cannot honour.
236
+ return False
237
+ # Legacy record: restricted the old way is still restricted.
238
+ return (perms.allowed_modules(user) is None
239
+ and perms.scope_team_id(user) is None
240
+ and not perms.scope_agent(user))
241
+
242
+
243
  def ask(question, history=None, chat_fn=None, model=DEFAULT_MODEL, max_iters=MAX_ITERS,
244
+ telemetry_kind="analyst", user=None):
245
  """Run one Analyst turn. Returns {answer, artifacts, tool_trace, iterations, exhausted,
246
+ usage}. chat_fn(messages, tools, model) -> (assistant_message_dict, usage_dict).
247
+
248
+ `user` is the SUBJECT asking. Passing it engages the R2 wall (`may_ask`); omitting it keeps
249
+ the unscoped behaviour that `harness/evals.py` and `harness/routines.py` rely on β€” those run
250
+ as the SYSTEM, not on behalf of a person, and gating them on a user record they do not have
251
+ would break the eval ladder to no security benefit. Every call that IS on behalf of somebody
252
+ passes it, and `app.py`'s chat entry point does.
253
+ """
254
+ if user is not None and not may_ask(user):
255
+ return {"answer": ANALYST_DENIED, "artifacts": [], "tool_trace": [],
256
+ "iterations": 0, "exhausted": False, "denied": True,
257
+ "usage": {"prompt_tokens": 0, "completion_tokens": 0}}
258
  chat = chat_fn or _live_chat
259
  tools = T.openai_tools()
260
  messages = [{"role": "system", "content": system_prompt()}]
royalimports_os/harness/filter_eval.py ADDED
@@ -0,0 +1,485 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """harness/filter_eval.py β€” the filter tree evaluated against ROWS, in Python (wave 15, C-EVAL).
2
+
3
+ THE THIRD ENGINE, and the one with a different job. There are now three readers of the same
4
+ filter tree and it is worth being precise about why:
5
+
6
+ * `customer-grid/useVisibleRows.ts` β€” the CLIENT, over in-memory rows. The reference.
7
+ * `harness/filter_sql.py` β€” compiles the tree to SQL for the DuckDB semantic tables.
8
+ * **this module** β€” evaluates the tree against wire-shaped row dicts in the
9
+ API/host process, where there is no SQL and the rows are
10
+ already in hand.
11
+
12
+ It exists because a PERMANENT (permission) filter has to be applied server-side, to rows the
13
+ server is about to send, on a surface whose columns are not a DuckDB table. Neither existing
14
+ engine can do that: the client one is TypeScript, and the SQL one needs a table.
15
+
16
+ β›” TWO ENTRY POINTS, OPPOSITE DEFAULTS, AND THE DIFFERENCE IS THE WHOLE POINT.
17
+
18
+ matches(...) DISPLAY semantics. A faithful mirror of the client, including the places
19
+ where the client IGNORES a leaf. Refereed against the client by
20
+ `aios-web/verify_filter_parity.py` β€” if this disagrees with the browser about
21
+ one row, a saved view means two different things in two places.
22
+
23
+ permits(...) PERMISSION semantics. Same evaluator, `strict=True`: anything the display
24
+ engine would IGNORE, this DENIES.
25
+
26
+ Why they cannot be the same function (C-EVAL amendment 1, and the reason this module has a
27
+ docstring this long). The client engine is TRI-STATE β€” `True` / `False` / `None`, where `None`
28
+ means "this leaf is INACTIVE, parent ignores it entirely". A leaf naming a column that does not
29
+ exist returns `None` (`useVisibleRows.ts:318`), and a group whose children are all inactive is
30
+ itself inactive (:273). For a DISPLAY filter that is exactly right: a half-built condition must
31
+ not zero the grid, and a stale column reference must not either.
32
+
33
+ For a PERMISSION filter it is a catastrophe. `agent is Tara` is the only thing standing between
34
+ a sales rep and the whole book; rename or delete the `agent` field and that leaf becomes
35
+ `None` β€” ignored β€” and the rep silently receives every customer. The wall would be one field
36
+ rename away from open, and nothing would go red. So `permits()` inverts every ignore into a
37
+ denial: an unanswerable permission filter is an OUTAGE, not a licence.
38
+
39
+ The asymmetry is a PARAMETER (`strict`) rather than a second implementation, deliberately: a
40
+ mirror must copy the original's asymmetries, and the only way to be sure it still does next
41
+ month is for both behaviours to come out of the same walk.
42
+
43
+ ⚠ WHAT THIS MODULE DOES NOT RE-IMPLEMENT. Activeness (`is_rule_active`), the JS-`Number`
44
+ coercion (`to_num`), the op vocabularies, cohort-id parsing and the date-window/anchor resolvers
45
+ all already exist in `filter_sql.py` and `windows.py`, and are already held against the client by
46
+ `verify_filter_engine.py` (525 checks) and `verify_windows.py` (123). Importing them is not
47
+ laziness β€” a second copy of "what counts as an active rule" is precisely the drift those gates
48
+ exist to catch, and it would be a copy the gates do not cover.
49
+ """
50
+ from harness.filter_sql import ( # noqa: F401 (COHORT_OPS re-exported for callers)
51
+ COHORT_FIELD, COHORT_OPS, COHORT_OP_ALIASES, FILTER_OPS, RANK_OPS,
52
+ is_rule_active, parse_cohort_ids, to_num, _resolve_anchor, _window_bounds,
53
+ )
54
+
55
+ #: The CLIENT's numeric family, which is WIDER than `filter_sql.NUMERIC_TYPES`. `rating` (an
56
+ #: integer 1..max) and `formula` (computed in the browser and injected at the field's key) compare
57
+ #: as numbers here because this engine sees the same assembled row the client does. They are
58
+ #: absent from the SQL port for a good reason β€” they are client-only strata that can never reach a
59
+ #: DuckDB table β€” so the two lists differing is correct, not drift. Mirrors `isNumericType`.
60
+ NUMERIC_TYPES = frozenset({'currency', 'int', 'pct', 'rating', 'formula'})
61
+
62
+ #: `created_time` is a DATETIME rendered read-only, and it filters as a DATE (truncated to the
63
+ #: day below). Mirrors `isDateType`.
64
+ DATE_TYPES = frozenset({'date', 'created_time'})
65
+
66
+ #: The date ops that actually compare against an ANCHOR. Everything else falls to the
67
+ #: active-and-always-true default WITHOUT resolving one β€” ordering matters, see `_match_date`.
68
+ DATE_CMP_OPS = frozenset({'eq', 'neq', 'lt', 'lte', 'gt', 'gte'})
69
+
70
+
71
+ class EvalCtx:
72
+ """Everything the engine needs besides the row and the columns.
73
+
74
+ All four members share one property β€” each is an answer a single ROW cannot compute β€” and
75
+ therefore share one failure mode: absent, the condition matches NOTHING rather than
76
+ everything. That is the widening sin the cohort/measure/rank leaves are each written to
77
+ avoid, and it is why none of these defaults to a permissive value.
78
+ """
79
+
80
+ __slots__ = ('cohort_sets', 'measure_sets', 'rank_sets', 'today')
81
+
82
+ def __init__(self, cohort_sets=None, measure_sets=None, rank_sets=None, today=None):
83
+ #: {cohort_id: set(pid)} β€” the cohorts THIS reader may see.
84
+ self.cohort_sets = cohort_sets or {}
85
+ #: {rule_id: set(pid)} β€” resolved measure conditions (CG-8).
86
+ self.measure_sets = measure_sets or {}
87
+ #: {id(leaf) or leaf-key: set(pid)} β€” resolved rank slices (C-OPS).
88
+ self.rank_sets = rank_sets or {}
89
+ #: The TENANT's today, ISO. Never the server clock at call time β€” a date filter that
90
+ #: means something different per process is not a filter.
91
+ self.today = today
92
+
93
+
94
+ _EMPTY_CTX = EvalCtx()
95
+
96
+
97
+ def _is_group(node):
98
+ return isinstance(node, dict) and isinstance(node.get('children'), list)
99
+
100
+
101
+ def _is_cohort(node):
102
+ return isinstance(node, dict) and node.get('colId') == COHORT_FIELD
103
+
104
+
105
+ def _is_measure(node):
106
+ """Mirrors `isMeasureRule`: a leaf carrying a `window` IS a measure condition."""
107
+ return isinstance(node, dict) and node.get('window') is not None
108
+
109
+
110
+ def _rhs_col(rhs):
111
+ """Mirrors `rhsColId`: a STATISTIC names no column."""
112
+ if not isinstance(rhs, dict) or rhs.get('kind') == 'stat':
113
+ return None
114
+ return rhs.get('colId')
115
+
116
+
117
+ def _as_text(v):
118
+ """The client's `String(raw ?? "").toLowerCase()`. `None` becomes '' (never 'None')."""
119
+ return ('' if v is None else str(v)).lower()
120
+
121
+
122
+ def _as_day(v):
123
+ """Day-granularity truncation. A `created_time` cell is a DATETIME and every comparand in
124
+ this vocabulary is a DATE β€” lexically the longer string sorts AFTER its own day, so without
125
+ this `on or before <today>` would silently exclude today's rows. Identity for a pure date."""
126
+ return ('' if v is None else str(v))[:10]
127
+
128
+
129
+ def _cmp_num(op, a, b):
130
+ """`default: True` is the documented ACTIVE-and-always-true case β€” an operator that exists
131
+ but does not apply to this type (`contains` on a number) narrows nothing and asks nothing.
132
+ An operator in NO vocabulary never reaches here; `_eval` refuses it first."""
133
+ if op == 'gt':
134
+ return a > b
135
+ if op == 'gte':
136
+ return a >= b
137
+ if op == 'lt':
138
+ return a < b
139
+ if op == 'lte':
140
+ return a <= b
141
+ if op == 'eq':
142
+ return a == b
143
+ if op == 'neq':
144
+ return a != b
145
+ return True
146
+
147
+
148
+ def _cmp_str(op, a, v):
149
+ if op == 'eq':
150
+ return a == v
151
+ if op == 'neq':
152
+ return a != v
153
+ if op == 'lt':
154
+ return a < v
155
+ if op == 'lte':
156
+ return a <= v
157
+ if op == 'gt':
158
+ return a > v
159
+ if op == 'gte':
160
+ return a >= v
161
+ return True
162
+
163
+
164
+ def _cmp_text(op, a, v):
165
+ if op == 'contains':
166
+ return v in a
167
+ if op == 'doesNotContain':
168
+ return v not in a
169
+ if op == 'eq':
170
+ return a == v
171
+ if op == 'neq':
172
+ return a != v
173
+ return True
174
+
175
+
176
+ def _is_blank(raw):
177
+ """Blank = None or ''. A numeric 0 is NOT blank β€” `isEmpty` must not swallow a real zero,
178
+ and the wire preserves null for a missing value."""
179
+ return raw is None or raw == ''
180
+
181
+
182
+ def _match_numeric(rule, raw, other, has_rhs):
183
+ a = to_num(raw)
184
+ op = rule.get('op')
185
+ if has_rhs:
186
+ return _cmp_num(op, a, to_num(other))
187
+ if op == 'between':
188
+ v, v2 = rule.get('value'), rule.get('value2')
189
+ if v == '' or v2 is None or v2 == '':
190
+ return True # both bounds required
191
+ lo, hi = to_num(v), to_num(v2)
192
+ if lo > hi:
193
+ lo, hi = hi, lo
194
+ return lo <= a <= hi
195
+ if rule.get('value') == '':
196
+ return True # inactive until a value is typed
197
+ return _cmp_num(op, a, to_num(rule.get('value')))
198
+
199
+
200
+ def _match_date(rule, raw, other, has_rhs, today):
201
+ a = _as_day(raw)
202
+ op = rule.get('op')
203
+
204
+ # "is within [the past month]" β€” a RANGE test, and the only date op reading `dateWindow`.
205
+ if op == 'within':
206
+ if not today:
207
+ return False
208
+ bounds = _window_bounds(rule.get('dateWindow'), today)
209
+ if not bounds:
210
+ return False # unresolvable range -> matches nothing
211
+ if a == '':
212
+ # A blank date is not "within" any range. Without this, '' >= a null lower bound is
213
+ # vacuously true and every never-ordered customer lands inside every window.
214
+ return False
215
+ lo, hi = bounds
216
+ return (lo is None or a >= lo) and (hi is None or a <= hi)
217
+
218
+ if has_rhs:
219
+ return _cmp_str(op, a, _as_day(other))
220
+ if op == 'between':
221
+ v, v2 = rule.get('value'), rule.get('value2')
222
+ if v == '' or v2 is None or v2 == '':
223
+ return True
224
+ lo, hi = (v, v2) if v < v2 else (v2, v)
225
+ return lo <= a <= hi
226
+
227
+ # An op that does not apply to a date (`contains`) is ACTIVE-and-always-true, decided BEFORE
228
+ # any anchor is resolved β€” there is no date in that question to resolve. Ordering this after
229
+ # the anchor would turn `contains` on a date from always-true into matches-nothing, which is
230
+ # a different answer under `or`.
231
+ if op not in DATE_CMP_OPS:
232
+ return True
233
+ if not rule.get('dateMode') and rule.get('value') == '':
234
+ return True # inactive until a value is typed
235
+ mode = rule.get('dateMode') or 'exact'
236
+ # `today` is required by a RELATIVE anchor and by nothing else, which is what keeps every
237
+ # pre-anchor saved view working in a payload that carries no today.
238
+ if mode != 'exact' and not today:
239
+ return False
240
+ v = _resolve_anchor(mode, rule.get('value'), today or '1970-01-01')
241
+ if v is None:
242
+ # Unresolvable (junk date, missing N) -> matches nothing. The honest answer to a
243
+ # question with no date in it.
244
+ return False
245
+ return _cmp_str(op, a, v)
246
+
247
+
248
+ def _match_filter(rule, row, columns, today):
249
+ """One LEAF against one row, dispatched on the field's declared type.
250
+
251
+ `isEmpty`/`isNotEmpty` are handled FIRST and type-independently: they must never fall
252
+ through to the "blank value -> inactive" guards below, which would turn them into
253
+ always-true no-ops.
254
+ """
255
+ field = columns.get(rule.get('colId')) or {}
256
+ ftype = field.get('type')
257
+ raw = row.get(rule.get('colId'))
258
+ op = rule.get('op')
259
+
260
+ if op == 'isEmpty':
261
+ return _is_blank(raw)
262
+ if op == 'isNotEmpty':
263
+ return not _is_blank(raw)
264
+
265
+ # A RANK op can never be answered from one row. `_eval` routes rank leaves to their resolved
266
+ # set and one should never arrive here; this is the SECOND layer, and it exists because of
267
+ # what the first layer's absence would do β€” `_cmp_num`'s `default: True` would make `topN`
268
+ # match EVERY row, a filter that widens under a count that agrees with it.
269
+ if op in RANK_OPS:
270
+ return False
271
+
272
+ rhs = rule.get('rhs')
273
+ has_rhs = rhs is not None
274
+ other = row.get(_rhs_col(rhs) or '') if has_rhs else None
275
+
276
+ if ftype in NUMERIC_TYPES:
277
+ return _match_numeric(rule, raw, other, has_rhs)
278
+ if ftype in DATE_TYPES:
279
+ return _match_date(rule, raw, other, has_rhs, today)
280
+
281
+ a = _as_text(raw)
282
+ if has_rhs:
283
+ return _cmp_text(op, a, _as_text(other))
284
+ if rule.get('value') == '':
285
+ return True
286
+ return _cmp_text(op, a, _as_text(rule.get('value')))
287
+
288
+
289
+ def _eval(node, row, columns, ctx, strict):
290
+ """One node against one row. `True` / `False` / `None`, where `None` = INACTIVE.
291
+
292
+ `strict` is the permission mode: every `None` this function would return becomes `False`
293
+ instead. Read the two behaviours side by side rather than trusting either alone β€” the
294
+ difference between them IS the security property (see the module docstring).
295
+ """
296
+ ignore = False if strict else None
297
+
298
+ if _is_group(node):
299
+ saw_active = False
300
+ all_true = True
301
+ any_true = False
302
+ for child in node['children']:
303
+ v = _eval(child, row, columns, ctx, strict)
304
+ if v is None:
305
+ continue # inactive -> ignored entirely
306
+ saw_active = True
307
+ all_true = all_true and v
308
+ any_true = any_true or v
309
+ if not saw_active:
310
+ # A group with no active children is itself inactive. In strict mode an empty or
311
+ # wholly-unanswerable permission group DENIES: a wall that evaluates to "nothing to
312
+ # say" must not mean "let them through".
313
+ return ignore
314
+ return any_true if node.get('conj') == 'or' else all_true
315
+
316
+ if not isinstance(node, dict):
317
+ return ignore
318
+
319
+ # A COHORT leaf, BEFORE the column lookup: `__cohort__` is not a column, so the lookup below
320
+ # would call it INACTIVE β€” and inactive means every row on screen under a count nobody doubts.
321
+ if _is_cohort(node):
322
+ if not is_rule_active(node, columns):
323
+ return ignore
324
+ ids = parse_cohort_ids(node.get('value'))
325
+ sets = [ctx.cohort_sets.get(cid) for cid in ids]
326
+ # ANY named cohort we were given no membership for makes the WHOLE condition
327
+ # unanswerable, and unanswerable matches nothing β€” for `is none of` as well. Answering
328
+ # "everything" to `is none of [a cohort we cannot see]` is the widening sin wearing a
329
+ # plausible face, and PARTIAL evaluation is worse: `is none of [A, B]` quietly becoming
330
+ # `is none of [A]` would show every row in B under a count nobody would doubt.
331
+ if any(s is None for s in sets):
332
+ return False
333
+ pid = row.get('pid')
334
+ op = node.get('op')
335
+ op = op if op in COHORT_OPS else COHORT_OP_ALIASES.get(op, 'anyOf')
336
+ if op == 'allOf':
337
+ return all(pid in s for s in sets)
338
+ in_any = any(pid in s for s in sets)
339
+ return (not in_any) if op == 'noneOf' else in_any
340
+
341
+ # A MEASURE leaf, also before the column lookup and for the same reason: a measure's colId
342
+ # ("revenue") is not a column of this table. An ACTIVE rule whose set has not been resolved
343
+ # is PENDING and matches NOTHING β€” never everything.
344
+ if _is_measure(node):
345
+ if not is_rule_active(node, columns):
346
+ return ignore
347
+ s = ctx.measure_sets.get(node.get('id')) if node.get('id') else None
348
+ if s is None:
349
+ return False
350
+ return row.get('pid') in s
351
+
352
+ # ── a column leaf ────────────────────────────────────────────────────────────────────────
353
+ if node.get('colId') not in columns:
354
+ # THE LEAF THIS WHOLE MODULE'S `strict` FLAG EXISTS FOR. Display: ignore it. Permission:
355
+ # deny β€” see the module docstring's field-rename walkthrough.
356
+ return ignore
357
+ if node.get('rhs') is not None and _rhs_col(node['rhs']) not in columns:
358
+ # An rhs naming a column this table does not have is ignored by the SAME rule as an
359
+ # unknown LEFT column. Treating one side as "ignore" and the other as "match nothing"
360
+ # would make `a > deleted` behave differently from `deleted > a`.
361
+ return ignore
362
+ if not is_rule_active(node, columns):
363
+ return ignore
364
+
365
+ # A RANK leaf is a MEMBERSHIP test, like a cohort or a measure: the set was computed in a
366
+ # prior pass over the other rows. No set = REFUSE, never "ignore" and never "true" β€” both of
367
+ # those SHOW rows.
368
+ if node.get('op') in RANK_OPS:
369
+ s = ctx.rank_sets.get(_rank_key(node))
370
+ return (row.get('pid') in s) if s is not None else False
371
+
372
+ # An operator in NO vocabulary at all. The comparators end in `default: True`, right for an
373
+ # operator that exists but does not apply to this type; NOT right for one that exists
374
+ # nowhere (`inTertile` out of a stale saved view), which would match every row.
375
+ if node.get('op') not in FILTER_OPS:
376
+ return False
377
+
378
+ return _match_filter(node, row, columns, ctx.today)
379
+
380
+
381
+ def _rank_key(node):
382
+ """The client keys `rankSets` by leaf IDENTITY (a Map keyed on the node object). Python
383
+ dicts cannot key on a dict, so the caller that resolves rank sets and this evaluator agree
384
+ on a derived key. Kept in ONE place so the two cannot drift apart."""
385
+ return (node.get('id') or '', node.get('colId') or '', node.get('op') or '',
386
+ str(node.get('value') if node.get('value') is not None else ''))
387
+
388
+
389
+ def _columns_map(fields):
390
+ """`[{key,type,…}]` -> `{key: field}`. Accepts a mapping unchanged, so callers holding
391
+ either shape need no adapter."""
392
+ if isinstance(fields, dict):
393
+ return fields
394
+ out = {}
395
+ for f in fields or ():
396
+ if isinstance(f, dict) and f.get('key'):
397
+ out[f['key']] = f
398
+ return out
399
+
400
+
401
+ def evaluate(tree, row, fields, ctx=None):
402
+ """The TRI-STATE the client actually has: `True` / `False` / `None`, where `None` means the
403
+ tree is INACTIVE β€” it asks nothing, so it narrows nothing.
404
+
405
+ Exposed because collapsing `None` into `True` (which `matches` does, correctly, for its own
406
+ purpose) destroys a distinction some callers must keep. The `memberPids` union is the one
407
+ that bit: the client's rule is `members.has(pid) || matchFilterTree(…)` and that union sits
408
+ INSIDE `if (filters.length)`, so an INACTIVE tree must show every row and ignore the member
409
+ list β€” whereas an ACTIVE tree that merely fails must still admit hand-picked members. A
410
+ caller holding only `matches` cannot tell those two apart and will narrow an inactive view
411
+ down to its hand-picked rows. (`filter_sql.compile_filter_tree` keeps the same distinction
412
+ by returning None rather than a predicate; this is the row-engine's equivalent.)
413
+
414
+ Activeness is ROW-INDEPENDENT β€” every `None` here comes from `is_rule_active` or an empty
415
+ group, none of which reads the row β€” so a caller may compute it once per tree if it wishes.
416
+ """
417
+ columns = _columns_map(fields)
418
+ nodes, conj = tree_parts(tree)
419
+ return _eval({'conj': conj, 'children': nodes}, row, columns, ctx or _EMPTY_CTX, False)
420
+
421
+
422
+ def matches(tree, row, fields, ctx=None):
423
+ """DISPLAY semantics β€” does `row` survive this filter tree? Mirrors the client exactly.
424
+
425
+ A wholly INACTIVE tree returns True: no narrowing, every row shows. That is what the browser
426
+ does with a half-built condition, and this function's whole job is to agree with the browser.
427
+ Use `evaluate()` instead when you need to tell "inactive" from "matched" (see its docstring).
428
+ """
429
+ v = evaluate(tree, row, fields, ctx)
430
+ return True if v is None else bool(v)
431
+
432
+
433
+ def visible_pids(tree, rows, fields, ctx=None, member_pids=None):
434
+ """The client's whole row pipeline for one tree, member union included β€” the shape a caller
435
+ should reach for instead of assembling `matches` in a loop.
436
+
437
+ Mirrors `useVisibleRows`: an INACTIVE tree yields every row (and IGNORES `member_pids`,
438
+ because the union lives inside `if (filters.length)`); an ACTIVE tree yields the rows it
439
+ matches UNION the hand-picked members.
440
+ """
441
+ ctx = ctx or _EMPTY_CTX
442
+ members = set(member_pids or ())
443
+ out, active = [], False
444
+ verdicts = []
445
+ for r in rows:
446
+ v = evaluate(tree, r, fields, ctx)
447
+ if v is not None:
448
+ active = True
449
+ verdicts.append((r, v))
450
+ for r, v in verdicts:
451
+ if not active:
452
+ out.append(r.get('pid'))
453
+ elif v or (members and r.get('pid') in members):
454
+ out.append(r.get('pid'))
455
+ return out
456
+
457
+
458
+ def permits(tree, row, fields, ctx=None):
459
+ """PERMISSION semantics β€” may this reader SEE `row` under this permanent filter?
460
+
461
+ Same evaluator, every ignore inverted into a denial. An empty/absent tree means "no
462
+ restriction declared" and admits (the caller decides whether a module with no entry is
463
+ reachable at all β€” that is `perm_scope`'s question, not this one); anything PRESENT but
464
+ unanswerable DENIES.
465
+ """
466
+ nodes, conj = tree_parts(tree)
467
+ if not nodes:
468
+ return True # nothing declared -> nothing to enforce here
469
+ columns = _columns_map(fields)
470
+ v = _eval({'conj': conj, 'children': nodes}, row, columns, ctx or _EMPTY_CTX, True)
471
+ return bool(v)
472
+
473
+
474
+ def tree_parts(tree):
475
+ """Read C-PERM amendment 2's `FilterTree` β€” `{conj?, nodes}` β€” into `(nodes, conj)`.
476
+
477
+ Accepts a BARE LIST too, because that is what `ViewConfig.filters` is and what
478
+ `clean_filter_tree` returns; an absent conj is `'and'`, mirroring `ViewConfig.filterConj`.
479
+ One reader, so the absent-conj default lives here instead of at every call site.
480
+ """
481
+ if isinstance(tree, dict):
482
+ nodes = tree.get('nodes')
483
+ conj = 'or' if tree.get('conj') == 'or' else 'and'
484
+ return (nodes if isinstance(nodes, list) else []), conj
485
+ return (tree if isinstance(tree, list) else []), 'and'
royalimports_os/modules/customer_data.py CHANGED
@@ -544,6 +544,10 @@ def delete_list(username, name):
544
  # A NEW table object gets its own `core.table_store.make('<its>_table_workspace')`.
545
  _TSTORE = table_store.make(TABLE_KEY)
546
 
 
 
 
 
547
  table_workspace = _TSTORE.workspace
548
  shared_table_views = _TSTORE.shared_views # wave-9 I17: views shared WITH this viewer
549
  shared_table_view = _TSTORE.shared_view # ...and one raw, for authorisation only
 
544
  # A NEW table object gets its own `core.table_store.make('<its>_table_workspace')`.
545
  _TSTORE = table_store.make(TABLE_KEY)
546
 
547
+ #: Wave 16 C-TOPIC β€” the ops OBJECT, for callers that select a table by TOPIC (grid_events'
548
+ #: `EventCtx.table`). The module-level re-exports below stay for every existing caller.
549
+ TABLE_OPS = _TSTORE
550
+
551
  table_workspace = _TSTORE.workspace
552
  shared_table_views = _TSTORE.shared_views # wave-9 I17: views shared WITH this viewer
553
  shared_table_view = _TSTORE.shared_view # ...and one raw, for authorisation only
royalimports_os/modules/digest.py CHANGED
@@ -117,8 +117,11 @@ def build(user, t=None):
117
  rows.append(_line(r.get('customer', '?'), href, meta))
118
  if y_orders:
119
  rows.append(_sec('Yesterday'))
 
 
 
120
  rows.append(_line(f"{y_orders} orders Β· {_m(y_rev)}",
121
- links.deeplink('sales', src='digest')))
122
 
123
  scope = f"{agent}'s book" if agent else 'the whole book'
124
  list_url = links.deeplink('customer_data', src='digest')
 
117
  rows.append(_line(r.get('customer', '?'), href, meta))
118
  if y_orders:
119
  rows.append(_sec('Yesterday'))
120
+ # Wave 16: the Sales page is retired (registry row archived) β€” yesterday's orders now
121
+ # link to the Customer grid, the surface that carries the book. A link to an archived
122
+ # page would fall through to the landing and read as a broken link.
123
  rows.append(_line(f"{y_orders} orders Β· {_m(y_rev)}",
124
+ links.deeplink('customer_data', src='digest')))
125
 
126
  scope = f"{agent}'s book" if agent else 'the whole book'
127
  list_url = links.deeplink('customer_data', src='digest')
royalimports_os/modules/product_data.py ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """modules/product_data.py β€” the PRODUCT table's pool (wave 15 item 9/10, contract C-TOPIC).
2
+
3
+ The second object on the table-page factory: same grid, same engine, same permission wall β€” the
4
+ only difference is the field schema and the identity. `modules/customer_data.pool()` is the
5
+ template and this deliberately mirrors its signature and its row shape.
6
+
7
+ β›” THREE DECISIONS THIS FILE HAD TO MAKE, EACH RECORDED BECAUSE A LATER READER WILL WONDER.
8
+
9
+ 1. **THE IDENTITY IS A SKU CODE, WHICH IS A STRING, AND THE GRID WANTS AN INTEGER `pid`.**
10
+ Cohort membership, `allowed_pids`, the measure channel and `rows_from_pool` all key on an
11
+ integer. So each row carries BOTH: `pid` (a stable CRC32 of the code, so the same SKU gets the
12
+ same id on every pull and across processes β€” never an enumeration index, which would reshuffle
13
+ whenever the catalogue changes) and `code`, the real business key, as a visible column.
14
+ `_assert_no_pid_collision` fails the BUILD rather than the read: two SKUs sharing a pid would
15
+ silently merge in every downstream set operation, and a loud build failure is the only version
16
+ of that anyone would notice.
17
+
18
+ 2. **THE SCOPE RULE β€” inventory columns are CONSOLIDATED and are therefore OMITTED for a
19
+ BU-scoped caller.** `products.directory(t, team_id)` is brand-shaped; `inventory.sku_inventory`
20
+ is explicitly NOT (its own docstring: "on-hand stock is one physical warehouse, not
21
+ brand-tagged"). Joining them for a Fisch-only user would put BU-shaped revenue beside
22
+ company-wide stock IN THE SAME ROW β€” the mixed-scope value defect wave 15's amendment 3 exists
23
+ for, arriving through a different door. The honest options were "omit" or "label the columns
24
+ company-wide"; omit is the fail-closed one, and a column that is absent asks a question,
25
+ whereas a column that is silently company-wide answers one wrongly.
26
+
27
+ 3. **WHAT IS NOT HERE, NAMED RATHER THAN QUIETLY MISSING.** R4 lists ~20 fields. Vendor and
28
+ COUNTRY are not in Odoo at all β€” they live in the inventory WORKBOOK
29
+ ([[odoo-vendor-country-origin]]) and need a loader this module deliberately does not invent.
30
+ Margin % comes from `modules/pricing.table`, which is a heavier build (channel-rate cost
31
+ allocation) and is left for the wave that needs it. `validate()` reconciles what SHIPS; it
32
+ does not pretend to cover columns that are absent.
33
+ """
34
+ import zlib
35
+
36
+ import core.periods as P
37
+ import core.table_store as table_store
38
+ import modules.products as products
39
+
40
+ #: Columns that exist ONLY on a consolidated pull. See decision 2.
41
+ CONSOLIDATED_ONLY = ("on_hand", "unit_cost", "inv_value", "qty_ltm", "dos", "stock_bucket")
42
+
43
+ #: Wave 16 C-TOPIC β€” the PRODUCT table's OWN workspace bucket. β›” Never the customer one:
44
+ #: product pids are CRC32 hashes of SKU codes and customer pids are Odoo partner ids, so in a
45
+ #: SHARED overlay bucket a hash collision would silently write a product note onto somebody's
46
+ #: customer (or the reverse). Separate store keys make that structurally impossible, which is
47
+ #: the whole reason the table-page factory exists ("a new table object gets its own
48
+ #: table_store.make('<its>_table_workspace')").
49
+ TABLE_KEY = 'product_table_workspace'
50
+ TABLE_OPS = table_store.make(TABLE_KEY)
51
+
52
+
53
+ def sku_pid(code):
54
+ """A stable integer id for a SKU code. CRC32, masked to 31 bits so it is always positive and
55
+ always JSON-safe. Stable across processes and pulls, which an enumeration index is not."""
56
+ return zlib.crc32(str(code).encode("utf-8")) & 0x7FFFFFFF
57
+
58
+
59
+ def _assert_no_pid_collision(rows):
60
+ """Two SKUs sharing a pid would MERGE in every set operation downstream β€” cohort membership,
61
+ allowed_pids, the measure channel β€” and nothing would report it. Fail the build instead."""
62
+ seen = {}
63
+ for r in rows:
64
+ prior = seen.get(r["pid"])
65
+ if prior is not None and prior != r["code"]:
66
+ raise ValueError(
67
+ f"product_data: pid collision β€” {prior!r} and {r['code']!r} both hash to "
68
+ f"{r['pid']}. Downstream set operations would merge them silently; widen the id "
69
+ f"before shipping this catalogue.")
70
+ seen[r["pid"]] = r["code"]
71
+
72
+
73
+ def _inventory_by_code(t):
74
+ """`{code: {...}}` from the inventory module, or `{}` if it cannot be read.
75
+
76
+ Degrades to empty rather than raising, matching `customer_data._pool_build`'s treatment of
77
+ its own slow families: a product table that will not render because inventory is momentarily
78
+ unreachable is a worse failure than one with blank stock columns.
79
+ """
80
+ try:
81
+ import modules.inventory as inventory
82
+ return inventory.sku_inventory(t=t) or {}
83
+ except Exception:
84
+ return {}
85
+
86
+
87
+ def pool(team_id=None, t=None):
88
+ """One row per SKU across the scoped book β€” the PRODUCT analogue of `customer_data.pool`.
89
+
90
+ `team_id` shapes the revenue columns exactly as it does for customers (`products.directory`
91
+ passes it into `_sku_rev`), which is why `core.perm_scope.derive_pool_scope` must keep
92
+ driving it rather than a post-filter deciding the BU.
93
+ """
94
+ t = t or P.today()
95
+ consolidated = team_id is None
96
+ inv = _inventory_by_code(t) if consolidated else {}
97
+
98
+ rows = []
99
+ for r in products.directory(t=t, team_id=team_id):
100
+ code = r["code"]
101
+ row = {
102
+ "pid": sku_pid(code),
103
+ "code": code,
104
+ "product": r.get("product") or code,
105
+ "category": r.get("category") or "(uncategorized)",
106
+ "rev_ytd": r.get("rev_ytd", 0.0),
107
+ "rev_ly": r.get("rev_ly", 0.0),
108
+ "yoy_pct": r.get("yoy_pct"),
109
+ "qty_ytd": r.get("qty_ytd", 0.0),
110
+ "orders_ytd": r.get("orders_ytd", 0),
111
+ }
112
+ if consolidated:
113
+ e = inv.get(code) or {}
114
+ row.update({
115
+ "on_hand": e.get("on_hand"),
116
+ "unit_cost": e.get("unit_cost"),
117
+ "inv_value": e.get("inv_value"),
118
+ "qty_ltm": e.get("qty_ltm"),
119
+ "dos": e.get("dos"),
120
+ "stock_bucket": e.get("bucket"),
121
+ })
122
+ rows.append(row)
123
+
124
+ rows.sort(key=lambda r: -(r["rev_ytd"] or 0.0))
125
+ _assert_no_pid_collision(rows)
126
+ return rows
127
+
128
+
129
+ def validate(team_id=None, t=None):
130
+ """Reconcile what SHIPS to an independent aggregate β€” the platform's own rule that a number
131
+ which does not tie to Odoo does not ship.
132
+
133
+ The check is deliberately narrow and says so: Ξ£ per-SKU YTD revenue must equal the SKU
134
+ module's own YTD total over the same scope. It does NOT cover the inventory columns (they are
135
+ a different module's reconciliation, and they are absent on a scoped pull anyway).
136
+ """
137
+ t = t or P.today()
138
+ rows = pool(team_id=team_id, t=t)
139
+ ours = round(sum(r["rev_ytd"] or 0.0 for r in rows), 2)
140
+ yf, yt = P.ytd(t)
141
+ theirs = round(sum(v.get("rev", 0.0)
142
+ for v in (products._sku_rev(yf, yt, team_id) or {}).values()), 2)
143
+ return [{
144
+ "check": "Ξ£ per-SKU YTD revenue == modules.products._sku_rev over the same window",
145
+ "ours": ours, "theirs": theirs, "ok": abs(ours - theirs) < 0.01,
146
+ }]
web/dist-embed/index.html CHANGED
The diff for this file is too large to render. See raw diff
 
web/src/customer-grid/ColumnMenu.tsx CHANGED
The diff for this file is too large to render. See raw diff
 
web/src/customer-grid/CustomerGrid.tsx CHANGED
The diff for this file is too large to render. See raw diff
 
web/src/customer-grid/Toolbar.tsx CHANGED
The diff for this file is too large to render. See raw diff
 
web/src/customer-grid/ViewSidebar.tsx CHANGED
The diff for this file is too large to render. See raw diff
 
web/src/customer-grid/apiBridge.ts CHANGED
@@ -50,7 +50,8 @@ import {
50
  signal,
51
  } from "../apiContract";
52
  import { setStandaloneSink } from "./hostBridge";
53
- import type { CustomersPayload, GridWorkspace, HostEvent, Row } from "./types";
 
54
  import type { TsPayload, TsRequest } from "./timeSeriesData";
55
 
56
  const JSON_HEADERS = { "Content-Type": "application/json" };
@@ -65,11 +66,11 @@ async function readJson(res: Response): Promise<unknown> {
65
 
66
  /** 401 is the one status that is never a data problem. Raised once, centrally,
67
  * so every call site cannot forget to. Returns true when it handled it.
68
- * The customers cache dies with the session β€” the next signed-in user may not
69
  * be the same person, and a cached book must never cross that boundary. */
70
  function handledUnauthorized(status: number): boolean {
71
  if (status !== 401) return false;
72
- customersCache = null;
73
  signal(UNAUTHORIZED_EVENT);
74
  return true;
75
  }
@@ -94,27 +95,30 @@ function handledUnauthorized(status: number): boolean {
94
  * the edit, not the pre-edit pull.
95
  */
96
  const CUSTOMERS_FRESH_MS = 5 * 60_000;
97
- let customersCache: { at: number; payload: CustomersPayload } | null = null;
 
 
98
 
99
  export function clearCustomersCache(): void {
100
- customersCache = null;
101
  }
102
 
103
  /**
104
- * X2 `GET /api/v1/customers` β†’ `{fields, rows, today, pulled_at}`, rows already
105
  * scoped to the session's BU pool (EXIT-3b). The cookie replaces HTTP Basic.
106
  *
107
  * Returns null on ANY failure, having raised the matching signal. A null is not
108
  * an empty table: the frame renders a failure, not "this tenant has no
109
- * customers", because those two look identical and only one of them is true.
110
  */
111
- export async function fetchCustomers(): Promise<CustomersPayload | null> {
112
- if (customersCache && Date.now() - customersCache.at < CUSTOMERS_FRESH_MS) {
113
- return customersCache.payload;
 
114
  }
115
  let res: Response;
116
  try {
117
- res = await fetch(`${API_V1}/customers`, { credentials: CREDENTIALS });
118
  } catch {
119
  signal(DATA_ERROR_EVENT, "Cannot reach the server.");
120
  return null;
@@ -129,10 +133,16 @@ export async function fetchCustomers(): Promise<CustomersPayload | null> {
129
  signal(DATA_ERROR_EVENT, "The server sent an unreadable payload.");
130
  return null;
131
  }
132
- customersCache = { at: Date.now(), payload: body };
133
  return body;
134
  }
135
 
 
 
 
 
 
 
136
  /**
137
  * `GET /api/v1/workspace` β€” the saved views, custom fields, folders and cohorts
138
  * for the session user (S1's amendment, 2026-07-30). It exists because X2 pins
@@ -167,28 +177,33 @@ export async function fetchWorkspace(
167
  }
168
 
169
  /**
170
- * X2 `PATCH /api/v1/customers/{pid}` β€” the overlay stratum only (Odoo is never
171
  * written). Kept as its own route rather than folded into the events log
172
  * because X2 keeps it: cell edits are the one write with a per-row identity and
173
  * a rollback the caller already implements.
174
  */
175
- export async function patchCustomer(pid: number, updates: Partial<Row>): Promise<boolean> {
 
 
 
 
176
  try {
177
- const res = await fetch(`${API_V1}/customers/${pid}`, {
178
  method: "PATCH",
179
  credentials: CREDENTIALS,
180
  headers: JSON_HEADERS,
181
  body: JSON.stringify(updates),
182
  });
183
  if (handledUnauthorized(res.status)) return false;
184
- if (res.ok && customersCache) {
 
185
  // Write the ACCEPTED values (the server's own report, not the request)
186
  // through into the cached rows, so a remount within the cache window
187
  // shows this edit instead of the pre-edit pull.
188
  const body = (await readJson(res)) as { updates?: Record<string, unknown> } | null;
189
  const accepted = body?.updates;
190
  if (accepted && typeof accepted === "object") {
191
- const row = customersCache.payload.rows.find((r) => r.pid === pid);
192
  if (row) Object.assign(row, accepted);
193
  }
194
  }
@@ -198,6 +213,11 @@ export async function patchCustomer(pid: number, updates: Partial<Row>): Promise
198
  }
199
  }
200
 
 
 
 
 
 
201
  /**
202
  * Item 7 (contract C-TS) β€” `POST /api/v1/grid/timeseries`.
203
  *
@@ -254,16 +274,17 @@ let pending: HostEvent[] = [];
254
  let inFlight = false;
255
 
256
  /**
257
- * Which SURFACE this grid is drawing β€” `customer` (the whole scoped pool) or
258
- * `cohort` (hand-curated sets). It lives at module scope beside the queue on
259
- * purpose: the queue is already module-level, and an event must carry the scope
260
- * it was CREATED under even if it drains after a route change.
 
261
  *
262
  * ⚠ The server refuses an unknown value rather than defaulting it, so this is
263
  * never a free-text field. Read and write must agree on what a scope is: the
264
  * grid asks `/workspace?scope=X` and every event it then emits says `X`.
265
  */
266
- export type SurfaceScope = "customer" | "cohort";
267
  let surfaceScope: SurfaceScope = "customer";
268
 
269
  export function setSurfaceScope(scope: SurfaceScope): void {
 
50
  signal,
51
  } from "../apiContract";
52
  import { setStandaloneSink } from "./hostBridge";
53
+ import { CUSTOMER_TOPIC } from "./types";
54
+ import type { CustomersPayload, GridWorkspace, HostEvent, Row, TopicConfig } from "./types";
55
  import type { TsPayload, TsRequest } from "./timeSeriesData";
56
 
57
  const JSON_HEADERS = { "Content-Type": "application/json" };
 
66
 
67
  /** 401 is the one status that is never a data problem. Raised once, centrally,
68
  * so every call site cannot forget to. Returns true when it handled it.
69
+ * The rows caches die with the session β€” the next signed-in user may not
70
  * be the same person, and a cached book must never cross that boundary. */
71
  function handledUnauthorized(status: number): boolean {
72
  if (status !== 401) return false;
73
+ rowsCache.clear();
74
  signal(UNAUTHORIZED_EVENT);
75
  return true;
76
  }
 
95
  * the edit, not the pre-edit pull.
96
  */
97
  const CUSTOMERS_FRESH_MS = 5 * 60_000;
98
+ // Wave 16 C-TOPIC: ONE cache map keyed by the topic's rows path, so the product pull and the
99
+ // customer pull each get the same 5-minute remount window without ever serving each other.
100
+ const rowsCache = new Map<string, { at: number; payload: CustomersPayload }>();
101
 
102
  export function clearCustomersCache(): void {
103
+ rowsCache.clear();
104
  }
105
 
106
  /**
107
+ * X2 `GET /api/v1/<topic.rowsPath>` β†’ `{fields, rows, today, pulled_at}`, rows already
108
  * scoped to the session's BU pool (EXIT-3b). The cookie replaces HTTP Basic.
109
  *
110
  * Returns null on ANY failure, having raised the matching signal. A null is not
111
  * an empty table: the frame renders a failure, not "this tenant has no
112
+ * records", because those two look identical and only one of them is true.
113
  */
114
+ export async function fetchTopicRows(topic: TopicConfig): Promise<CustomersPayload | null> {
115
+ const cached = rowsCache.get(topic.rowsPath);
116
+ if (cached && Date.now() - cached.at < CUSTOMERS_FRESH_MS) {
117
+ return cached.payload;
118
  }
119
  let res: Response;
120
  try {
121
+ res = await fetch(`${API_V1}/${topic.rowsPath}`, { credentials: CREDENTIALS });
122
  } catch {
123
  signal(DATA_ERROR_EVENT, "Cannot reach the server.");
124
  return null;
 
133
  signal(DATA_ERROR_EVENT, "The server sent an unreadable payload.");
134
  return null;
135
  }
136
+ rowsCache.set(topic.rowsPath, { at: Date.now(), payload: body });
137
  return body;
138
  }
139
 
140
+ /** The customer topic's fetch β€” kept under its own name because half the write-path notes in
141
+ * this repo cite it; it IS `fetchTopicRows(CUSTOMER_TOPIC)`. */
142
+ export function fetchCustomers(): Promise<CustomersPayload | null> {
143
+ return fetchTopicRows(CUSTOMER_TOPIC);
144
+ }
145
+
146
  /**
147
  * `GET /api/v1/workspace` β€” the saved views, custom fields, folders and cohorts
148
  * for the session user (S1's amendment, 2026-07-30). It exists because X2 pins
 
177
  }
178
 
179
  /**
180
+ * X2 `PATCH /api/v1/<topic.rowsPath>/{pid}` β€” the overlay stratum only (Odoo is never
181
  * written). Kept as its own route rather than folded into the events log
182
  * because X2 keeps it: cell edits are the one write with a per-row identity and
183
  * a rollback the caller already implements.
184
  */
185
+ export async function patchTopicRow(
186
+ topic: TopicConfig,
187
+ pid: number,
188
+ updates: Partial<Row>,
189
+ ): Promise<boolean> {
190
  try {
191
+ const res = await fetch(`${API_V1}/${topic.rowsPath}/${pid}`, {
192
  method: "PATCH",
193
  credentials: CREDENTIALS,
194
  headers: JSON_HEADERS,
195
  body: JSON.stringify(updates),
196
  });
197
  if (handledUnauthorized(res.status)) return false;
198
+ const cached = rowsCache.get(topic.rowsPath);
199
+ if (res.ok && cached) {
200
  // Write the ACCEPTED values (the server's own report, not the request)
201
  // through into the cached rows, so a remount within the cache window
202
  // shows this edit instead of the pre-edit pull.
203
  const body = (await readJson(res)) as { updates?: Record<string, unknown> } | null;
204
  const accepted = body?.updates;
205
  if (accepted && typeof accepted === "object") {
206
+ const row = cached.payload.rows.find((r) => r.pid === pid);
207
  if (row) Object.assign(row, accepted);
208
  }
209
  }
 
213
  }
214
  }
215
 
216
+ /** The customer topic's patch, by its historical name. */
217
+ export function patchCustomer(pid: number, updates: Partial<Row>): Promise<boolean> {
218
+ return patchTopicRow(CUSTOMER_TOPIC, pid, updates);
219
+ }
220
+
221
  /**
222
  * Item 7 (contract C-TS) β€” `POST /api/v1/grid/timeseries`.
223
  *
 
274
  let inFlight = false;
275
 
276
  /**
277
+ * Which SURFACE this grid is drawing β€” `customer` (the whole scoped pool),
278
+ * `cohort` (hand-curated sets) or `product` (the SKU table β€” wave 16 C-TOPIC).
279
+ * It lives at module scope beside the queue on purpose: the queue is already
280
+ * module-level, and an event must carry the scope it was CREATED under even if
281
+ * it drains after a route change.
282
  *
283
  * ⚠ The server refuses an unknown value rather than defaulting it, so this is
284
  * never a free-text field. Read and write must agree on what a scope is: the
285
  * grid asks `/workspace?scope=X` and every event it then emits says `X`.
286
  */
287
+ export type SurfaceScope = "customer" | "cohort" | "product";
288
  let surfaceScope: SurfaceScope = "customer";
289
 
290
  export function setSurfaceScope(scope: SurfaceScope): void {
web/src/customer-grid/clipboard.ts CHANGED
@@ -116,10 +116,65 @@ export interface FieldPastePatch {
116
  value: string;
117
  }
118
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
119
  /**
120
  * The whole paste policy as a pure, atomic plan. CustomerGrid supplies the actual target row
121
- * pids (null for a group/header row), then applies the returned patches only when every value
122
- * passed. `null` means apply nothing.
 
 
 
 
 
123
  */
124
  export function planFieldPaste({
125
  field,
@@ -138,11 +193,17 @@ export function planFieldPaste({
138
  }): FieldPastePatch[] | null {
139
  if (!editable || !isSingleColumnClipboard(values)) return null;
140
  if (sourceFieldKey && sourceFieldKey !== field.key) return null;
141
- if (targetPids.length !== values.length || targetPids.some((pid) => pid == null))
 
 
 
 
 
142
  return null;
143
  const patches: FieldPastePatch[] = [];
144
- for (let index = 0; index < values.length; index += 1) {
145
- const value = coerceClipboardValue(field, values[index][0], allowedChoices);
 
146
  const pid = targetPids[index];
147
  if (value === undefined || pid == null) return null;
148
  patches.push({ pid, value });
 
116
  value: string;
117
  }
118
 
119
+ /**
120
+ * The selected RECTANGLE, in glide's own coordinates (`GridSelection.current.range`).
121
+ * `width`/`height` are counts of columns/rows, so a single clicked cell is 1Γ—1.
122
+ */
123
+ export interface PasteSelection {
124
+ x: number;
125
+ y: number;
126
+ width: number;
127
+ height: number;
128
+ }
129
+
130
+ /**
131
+ * Wave-15 item 3 (R8) β€” HOW MANY ROWS a paste writes.
132
+ *
133
+ * The defect this replaces: the target rows were walked down from the anchor for exactly
134
+ * `values.length` rows and THE SELECTION WAS NEVER CONSULTED. So copying one cell, selecting
135
+ * fifty rows and pasting wrote ONE β€” the fifty-row selection was painted, obeyed by nothing, and
136
+ * the user had no way to tell the difference between "it filled" and "it filled the first row"
137
+ * without scrolling.
138
+ *
139
+ * R8: the clipboard TILES TO FILL the selection. A pattern of K repeats top-to-bottom until N
140
+ * rows are covered (`planFieldPaste` takes `values[i % K]`), and N need not be a multiple of K β€”
141
+ * Excel refuses that, Airtable tiles, and the owner asked for tiling. A clipboard LARGER than
142
+ * the selection is not truncated either: it pastes from the anchor downward, past the selection
143
+ * end, because the rows the user copied are the thing they chose and silently dropping the tail
144
+ * would be the same class of quiet lie as the bug above.
145
+ *
146
+ * ⚠ `target` IS the selection origin whenever there is a selection β€” glide's `onPasteInternal`
147
+ * computes `target = [current.range.x, current.range.y]` (data-editor.tsx:3361), MEASURED, not
148
+ * assumed. The equality guards below are therefore normally trivially true; they earn their
149
+ * place by covering glide's OTHER two target branches (a whole-column or whole-row selection
150
+ * with no `current`), where `range` is undefined and the honest answer is today's behaviour.
151
+ */
152
+ export function pasteRowCount(
153
+ clipboardRows: number,
154
+ selection: PasteSelection | undefined,
155
+ target: { col: number; row: number }
156
+ ): number {
157
+ if (clipboardRows <= 0) return 0;
158
+ // No rectangle to fill: paste the clipboard as it comes, from the anchor down.
159
+ if (!selection) return clipboardRows;
160
+ // Same-field VERTICAL paste only, exactly as today (`isSingleColumnClipboard` is the other
161
+ // half). A selection spanning columns describes a matrix this product deliberately refuses,
162
+ // so filling it would invent a policy nobody asked for.
163
+ if (selection.width !== 1) return clipboardRows;
164
+ // The paste has to be landing IN the selection for the selection to mean anything.
165
+ if (selection.x !== target.col || selection.y !== target.row) return clipboardRows;
166
+ return Math.max(clipboardRows, selection.height);
167
+ }
168
+
169
  /**
170
  * The whole paste policy as a pure, atomic plan. CustomerGrid supplies the actual target row
171
+ * pids (null for a group/header row) β€” `pasteRowCount` of them β€” then applies the returned
172
+ * patches only when every value passed. `null` means apply nothing.
173
+ *
174
+ * ⚠ ONE PATCH PER TARGET ROW, not per clipboard row (wave-15 R8). The clipboard is a PATTERN
175
+ * that repeats: row i takes `values[i % values.length]`. With one copied cell and fifty targets
176
+ * that is fifty identical patches; with a two-row pattern and seven targets it is
177
+ * A B A B A B A.
178
  */
179
  export function planFieldPaste({
180
  field,
 
193
  }): FieldPastePatch[] | null {
194
  if (!editable || !isSingleColumnClipboard(values)) return null;
195
  if (sourceFieldKey && sourceFieldKey !== field.key) return null;
196
+ // ⚠ This was `!==` until wave 15, and the change is deliberate rather than a loosening.
197
+ // FEWER targets than clipboard rows still refuses β€” that would drop copied rows on the floor
198
+ // silently. MORE is now legal, because that IS the tile-to-fill case. The null test is
199
+ // untouched and is what keeps the whole operation ATOMIC: a selection running past the last
200
+ // record, or over a group header, refuses everything rather than half-writing.
201
+ if (targetPids.length < values.length || targetPids.some((pid) => pid == null))
202
  return null;
203
  const patches: FieldPastePatch[] = [];
204
+ for (let index = 0; index < targetPids.length; index += 1) {
205
+ const value = coerceClipboardValue(
206
+ field, values[index % values.length][0], allowedChoices);
207
  const pid = targetPids[index];
208
  if (value === undefined || pid == null) return null;
209
  patches.push({ pid, value });
web/src/customer-grid/cohortRail.ts ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // ---------------------------------------------------------------------------
2
+ // customer-grid / cohortRail.ts β€” wave-15 item 5 (contract C-LOCK, owner R10).
3
+ //
4
+ // THE COHORT MODULE IS GONE, AND ITS COHORTS ARE NOT. R10: every cohort
5
+ // auto-projects as a LOCKED VIEW in a "Cohorts" section of the Customer rail,
6
+ // the `#/cohort` route disappears, and all the cohort machinery stays reachable
7
+ // from Customer. This is the projection β€” cohort list in, rail rows out.
8
+ //
9
+ // Pure, and separate from ViewSidebar, for the reason every projection in this
10
+ // tree is: the rail is a React component no node gate can mount, and the thing
11
+ // that must not regress is WHAT THE ROWS SAY β€” particularly a set the reader
12
+ // cannot see, which is a permission surface rather than a display convenience.
13
+ // `verify_cohort_lock.py` drives this directly.
14
+ // ---------------------------------------------------------------------------
15
+
16
+ /** The cohort shape the host already puts on `/workspace?scope=customer`
17
+ * (`types.ts` WorkspaceWire.lists β€” verified against the shipped wire, not assumed). */
18
+ export interface CohortWire {
19
+ id: string;
20
+ name: string;
21
+ pids?: number[];
22
+ missing?: number;
23
+ folderId?: string | null;
24
+ }
25
+
26
+ export interface CohortRailRow {
27
+ /** The cohort's own id. NOT a view id β€” these rows are projected, never saved. */
28
+ id: string;
29
+ name: string;
30
+ /**
31
+ * Members this reader can actually see, or `null` when the set was served without
32
+ * membership. ⚠ `null` is NOT 0: "a list with nobody in it" and "a list I am not allowed to
33
+ * count" are different sentences, and the engine already treats the second as unanswerable
34
+ * (it matches NOTHING). A row that printed 0 for both would describe a set it must not
35
+ * describe.
36
+ */
37
+ count: number | null;
38
+ /** Members the host knows exist but did not send β€” disclosed, never folded into `count`. */
39
+ missing: number;
40
+ /** True while the grid is showing this cohort, so the rail can mark it the way it marks the
41
+ * active view. */
42
+ active: boolean;
43
+ /** Always true. Present so the row renders through the same `cg-view-lockset` vocabulary a
44
+ * saved locked view uses β€” one lock mark in the product, not two that drift. */
45
+ locked: true;
46
+ }
47
+
48
+ /**
49
+ * Project the cohorts onto rail rows.
50
+ *
51
+ * Ordering is BY NAME, deliberately, and not by size: the rail is how somebody finds a list
52
+ * they already have in mind, and a size order re-arranges itself every time the data moves.
53
+ * `localeCompare` so accented names file where a reader expects.
54
+ */
55
+ export function cohortRailRows(
56
+ lists: readonly CohortWire[] | undefined,
57
+ activeCohortId: string | null | undefined
58
+ ): CohortRailRow[] {
59
+ return [...(lists ?? [])]
60
+ .filter((c) => !!c && typeof c.id === "string" && c.id !== "")
61
+ .sort((a, b) => a.name.localeCompare(b.name))
62
+ .map((c) => ({
63
+ id: c.id,
64
+ name: c.name,
65
+ // `pids` ABSENT = no membership was served. An empty array is a real, countable empty set.
66
+ count: Array.isArray(c.pids) ? c.pids.length : null,
67
+ missing: typeof c.missing === "number" && c.missing > 0 ? c.missing : 0,
68
+ active: !!activeCohortId && c.id === activeCohortId,
69
+ locked: true,
70
+ }));
71
+ }
72
+
73
+ /**
74
+ * What the TOOLBAR chip says while a cohort lock is in force (item 5c: "the toolbar shows the
75
+ * locked state near Filter/Sort/Group"). Until this wave the lock was stated only INSIDE the
76
+ * filter popover, which meant the one control that explains a narrowed table was invisible
77
+ * until you opened something.
78
+ *
79
+ * Three sentences, because there are three genuinely different states and only one of them is
80
+ * ordinary:
81
+ * - a set we can see -> name it, and say how many are in it
82
+ * - a set we cannot see -> say THAT, because the table is empty for a reason that is not
83
+ * a filter and the reader would otherwise hunt for one
84
+ * - no lock -> no chip at all
85
+ */
86
+ export function cohortLockChipText(row: Pick<CohortRailRow, "name" | "count"> | null): string | null {
87
+ if (!row) return null;
88
+ if (row.count == null) return "Locked to a list you cannot see";
89
+ return `${row.name} Β· ${row.count.toLocaleString()} ${
90
+ row.count === 1 ? "customer" : "customers"
91
+ }`;
92
+ }
web/src/customer-grid/iconShapes.ts CHANGED
@@ -149,7 +149,7 @@ export const MODE_SHAPES: Record<DisplayMode, IconShape[]> = {
149
  * The key type is a string union declared here rather than imported from chartData.ts: this
150
  * module is a leaf (types + theme only) and chartData imports IT, not the reverse.
151
  */
152
- export type ChartKindKey = "bar" | "line" | "area" | "donut" | "kpi";
153
  export const CHART_KIND_SHAPES: Record<ChartKindKey, IconShape[]> = {
154
  bar: [{ d: "M3.2 12.8V7.4M6.4 12.8V4.2M9.6 12.8V8.8M12.8 12.8V5.8" }],
155
  line: [
@@ -165,6 +165,12 @@ export const CHART_KIND_SHAPES: Record<ChartKindKey, IconShape[]> = {
165
  // A single big number: the KPI card. Drawn as a framed value rather than a glyph, so it
166
  // reads as "one number" beside four marks that all read as "a distribution".
167
  kpi: [{ d: "M2.6 3.8h10.8v8.4H2.6z" }, { d: "M5.4 9.6V6.4l1.9 3.2V6.4M9.4 6.4v3.2h1.8" }],
 
 
 
 
 
 
168
  };
169
 
170
  export const CHART_KIND_LABELS: Record<ChartKindKey, string> = {
@@ -173,6 +179,7 @@ export const CHART_KIND_LABELS: Record<ChartKindKey, string> = {
173
  area: "Area",
174
  donut: "Donut",
175
  kpi: "Single value",
 
176
  };
177
 
178
  /** I16 β€” the pastel each chart kind wears, same family rule as MODE_TONE. */
@@ -182,6 +189,7 @@ export const CHART_KIND_TONE: Record<ChartKindKey, FolderTone> = {
182
  area: "green",
183
  donut: "yellow",
184
  kpi: "neutral",
 
185
  };
186
 
187
  /**
 
149
  * The key type is a string union declared here rather than imported from chartData.ts: this
150
  * module is a leaf (types + theme only) and chartData imports IT, not the reverse.
151
  */
152
+ export type ChartKindKey = "bar" | "line" | "area" | "donut" | "kpi" | "table";
153
  export const CHART_KIND_SHAPES: Record<ChartKindKey, IconShape[]> = {
154
  bar: [{ d: "M3.2 12.8V7.4M6.4 12.8V4.2M9.6 12.8V8.8M12.8 12.8V5.8" }],
155
  line: [
 
165
  // A single big number: the KPI card. Drawn as a framed value rather than a glyph, so it
166
  // reads as "one number" beside four marks that all read as "a distribution".
167
  kpi: [{ d: "M2.6 3.8h10.8v8.4H2.6z" }, { d: "M5.4 9.6V6.4l1.9 3.2V6.4M9.4 6.4v3.2h1.8" }],
168
+ // Wave-16 C-CHARTCAP: a group-by aggregate table. Framed like the KPI (it is a card of
169
+ // values, not a distribution), with a header band and a column rule.
170
+ table: [
171
+ { d: "M2.6 3.4h10.8v9.2H2.6z" },
172
+ { d: "M2.6 6.2h10.8M7.2 6.2v6.4M2.6 9.4h10.8" },
173
+ ],
174
  };
175
 
176
  export const CHART_KIND_LABELS: Record<ChartKindKey, string> = {
 
179
  area: "Area",
180
  donut: "Donut",
181
  kpi: "Single value",
182
+ table: "Table",
183
  };
184
 
185
  /** I16 β€” the pastel each chart kind wears, same family rule as MODE_TONE. */
 
189
  area: "green",
190
  donut: "yellow",
191
  kpi: "neutral",
192
+ table: "neutral",
193
  };
194
 
195
  /**
web/src/customer-grid/icons.tsx CHANGED
@@ -172,7 +172,8 @@ export function ChartKindIcon({
172
  // Same rule as ToneModeIcon: the FIRST path is the shape's body, so it takes the
173
  // pastel fill and the rest stay strokes over it. Bar/line are pure strokes, so
174
  // their first path has no interior to fill and this is a no-op for them.
175
- fill={i === 0 && (kind === "area" || kind === "donut" || kind === "kpi")
 
176
  ? paint.fill
177
  : "none"}
178
  stroke={paint.stroke}
 
172
  // Same rule as ToneModeIcon: the FIRST path is the shape's body, so it takes the
173
  // pastel fill and the rest stay strokes over it. Bar/line are pure strokes, so
174
  // their first path has no interior to fill and this is a no-op for them.
175
+ fill={i === 0 &&
176
+ (kind === "area" || kind === "donut" || kind === "kpi" || kind === "table")
177
  ? paint.fill
178
  : "none"}
179
  stroke={paint.stroke}
web/src/customer-grid/theme.ts CHANGED
@@ -191,68 +191,112 @@ export const ACTIVE_ROW_NEUTRAL = ROW_HIGHLIGHT_NEUTRAL;
191
  * pair, "Filter Β· 2" on a 20-column table still leaves the user hunting for the two columns it
192
  * means.
193
  *
194
- * The tone is still resolved per control (`useGridColumns.columnTones`, filter > group > sort)
195
- * because PANEL's toolbar chips still hue-code β€” but as of wave-14 R4 it no longer changes what
196
- * this table paints. See `COLUMN_TONE_THEME`.
197
  */
198
  export type ControlTone = "filter" | "sort" | "group";
199
 
200
  /**
201
- * ⭐ Wave-14 items 1 + 2 + 10 (owner rulings R4 + R11) β€” **ONE uniform, faint, warm-grey wash for
202
- * any involved column, whichever control involves it.** Hue coding now lives ONLY in the toolbar
203
- * chips.
204
  *
205
- * What was wrong, all three at once, and why one object fixes all of them:
 
 
 
206
  *
207
- * 1. **The tint vanished on click (item 1).** The old table set `bgHeader` + `bgHeaderHovered`
208
- * and NOT `bgHeaderHasFocus`, so the moment a cell in that column was selected glide painted
209
- * the base `bgHeaderHasFocus: LP_BLUE_TINT` straight over the tone
210
- * (`data-grid-render.header.js:48,59`). All three keys are set here, to the same colour, so
211
- * there is no state in which the header changes identity.
212
- * 2. **The bold was already gone (item 2), and NOT because of a font setting.** glide's
213
- * `drawGridHeaders` does `if (theme !== outerTheme) ctx.font = theme.baseFontFull` before
214
- * drawing a header β€” the CELL font β€” so ANY column carrying a `themeOverride` painted its
215
- * title at "13px" regular instead of "600 13px". Setting `headerFontStyle` alone would have
216
- * changed nothing; `CustomerGrid.drawGridHeader` re-asserts the header font on the ctx, and
217
- * that is what makes the 700 below actually reach the screen. The two must ship together.
218
- * 3. **The saturated pastels were the "too loud" complaint (item 10).** `Airtable 11.png` shows
219
- * involved columns carrying a barely-there wash and headers that read as ordinary headers;
220
- * #F1F0ED is one warm step off the base `LP_WASH` header β€” visible when you compare two
221
- * columns, invisible as noise.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
222
  *
223
- * ⚠ `bgCell` is rgba, NOT a hex, and that is load-bearing: `mergeAndRealizeTheme` alpha-BLENDS
224
- * `bgCell` and hard-replaces every other key (glide `common/styles.js`). An opaque tint here
225
- * would ERASE a colour-by row's status wash wherever the two met β€” which is what the outgoing
226
- * `LP_*_TINT` values did. Same warm family as the header, at a third of its strength.
227
  *
228
- * ⚠ Literal hex/rgba, mirroring the CSS tokens: glide's theme is a canvas theme and cannot read
229
- * a CSS variable. That duplication is deliberate and is what `verify_icons`' I7c parity check
230
- * exists to police β€” do not "fix" it by reaching for `getComputedStyle`.
 
 
 
 
 
 
 
231
  */
232
- export const INVOLVED_COLUMN_THEME: Partial<Theme> = {
233
- // The same value in all three header states β€” see reason 1 above.
234
- bgHeader: "#F1F0ED",
235
- bgHeaderHovered: "#F1F0ED",
236
- bgHeaderHasFocus: "#F1F0ED",
237
- // #F1F0ED is rgb(115,105,75) at 10% over white; this is the same ink at 5%, i.e. β‰ˆ #F8F8F6.
238
- bgCell: "rgba(115, 105, 75, 0.05)",
239
- // Item 2 β€” bold. Only reaches the canvas because drawGridHeader re-asserts the header font.
240
- headerFontStyle: "700 13px",
 
 
 
 
 
 
 
 
 
 
 
 
 
241
  };
242
 
243
  /**
244
- * R4 β€” all three controls, ONE theme, by identity rather than by three equal literals: "the tint
245
- * does not depend on which control" is then a property of this module and cannot drift.
246
  *
247
- * The `Record<ControlTone, …>` shape is kept deliberately. `columnTones` still resolves exactly
248
- * one tone per column with the documented filter > group > sort precedence β€” that precedence is
249
- * now INERT for paint, but it is still what PANEL's chips and any future per-control affordance
250
- * read, and collapsing the type here would ripple into both for no gain.
 
 
 
 
 
 
 
 
251
  */
252
- export const COLUMN_TONE_THEME: Record<ControlTone, Partial<Theme>> = {
253
- filter: INVOLVED_COLUMN_THEME,
254
- sort: INVOLVED_COLUMN_THEME,
255
- group: INVOLVED_COLUMN_THEME,
256
  };
257
 
258
  /**
 
191
  * pair, "Filter Β· 2" on a 20-column table still leaves the user hunting for the two columns it
192
  * means.
193
  *
194
+ * The tone is resolved per control by `useGridColumns.columnTones`, whose precedence is
195
+ * **filter > sort > group** (owner R6, wave 15 β€” it was filter > group > sort until then), and
196
+ * as of wave-15 R5 it drives what this table paints again. See `COLUMN_TONE_THEME`.
197
  */
198
  export type ControlTone = "filter" | "sort" | "group";
199
 
200
  /**
201
+ * The header weight an INVOLVED column paints at.
 
 
202
  *
203
+ * ⚠ Named once, and read by `useGridColumns.measureHeaderText` rather than retyped there: an
204
+ * involved header is measured at the weight it is actually PAINTED at, and a second literal is
205
+ * how those two silently diverge (see that function's own warning β€” the bug it describes
206
+ * survived a fix that looked correct in the diff).
207
  *
208
+ * ⚠ It only reaches the canvas at all because `CustomerGrid.drawGridHeader` re-asserts the
209
+ * header font on the ctx. glide's `drawGridHeaders` does
210
+ * `if (theme !== outerTheme) ctx.font = theme.baseFontFull` before drawing a header β€” the CELL
211
+ * font β€” so ANY column carrying a `themeOverride` would otherwise paint its title at plain
212
+ * "13px". Setting `headerFontStyle` alone changes nothing; the two must ship together.
213
+ */
214
+ export const INVOLVED_HEADER_FONT = "700 13px";
215
+
216
+ /**
217
+ * `#RRGGBB` β†’ `rgba(r, g, b, a)`.
218
+ *
219
+ * Exists so a wash below is DERIVED from the palette constant it belongs to instead of being a
220
+ * second hand-written copy of the same hue. `verify_icons`' I7c parity diffs the `LP_*` hexes in
221
+ * this file against the `--lp-*` custom properties in index.css β€” a literal `rgba(53, 117, 78,
222
+ * …)` beside `LP_GREEN_DEEP` would sit OUTSIDE that check and could drift from the token the
223
+ * toolbar chip reads while both still looked right in isolation. Derivation puts the wash under
224
+ * the gate that already exists.
225
+ */
226
+ function washOf(hex: string, alpha: number): string {
227
+ const n = parseInt(hex.slice(1), 16);
228
+ return `rgba(${(n >> 16) & 255}, ${(n >> 8) & 255}, ${n & 255}, ${alpha})`;
229
+ }
230
+
231
+ /**
232
+ * ⭐ Wave-15 item 8 (owner rulings R5 + R6) β€” **an involved column wears ITS OWN CONTROL'S HUE
233
+ * again: filter = green, sort = yellow, group = purple, the same three the toolbar chips wear.**
234
+ *
235
+ * This REVERSES wave-14 R4, which collapsed all three to one warm grey after the saturated
236
+ * pastels read as "too loud". Both instructions came from the owner and both were about the same
237
+ * thing β€” R4 objected to the LOUDNESS, R5 asks for the LINK β€” so what changed is the strength,
238
+ * not the idea: the header takes the chip's own pale tint (`--lp-*-tint`, which is what the chip
239
+ * paints, so the eye connects the two without being told), and the cell takes the chip's INK at
240
+ * 6%, which is a whisper. What is gone is the wave-14 claim that hue coding "lives ONLY in the
241
+ * toolbar chips".
242
  *
243
+ * Three properties carried over from R4's version, each of which was a bug fix:
 
 
 
244
  *
245
+ * 1. **All THREE header states carry the tint.** Setting `bgHeader` + `bgHeaderHovered` and not
246
+ * `bgHeaderHasFocus` is why the tint used to VANISH the moment a cell in that column was
247
+ * selected β€” glide paints the base `bgHeaderHasFocus: LP_BLUE_TINT` straight over the tone
248
+ * (`data-grid-render.header.js:48,59`). There must be no state in which the header changes
249
+ * identity.
250
+ * 2. **The bold** (`INVOLVED_HEADER_FONT`, see its note β€” it needs drawGridHeader's help).
251
+ * 3. **`bgCell` is rgba, NOT a hex, and that is load-bearing.** `mergeAndRealizeTheme`
252
+ * alpha-BLENDS `bgCell` and hard-replaces every other key (glide `common/styles.js`). An
253
+ * opaque tint here would ERASE a colour-by row's status wash wherever the two met β€” which is
254
+ * exactly what the pre-wave-14 `LP_*_TINT` cell values did.
255
  */
256
+ export const COLUMN_TONE_THEME: Record<ControlTone, Partial<Theme>> = {
257
+ filter: {
258
+ bgHeader: LP_GREEN_TINT,
259
+ bgHeaderHovered: LP_GREEN_TINT,
260
+ bgHeaderHasFocus: LP_GREEN_TINT,
261
+ bgCell: washOf(LP_GREEN_DEEP, 0.06),
262
+ headerFontStyle: INVOLVED_HEADER_FONT,
263
+ },
264
+ sort: {
265
+ bgHeader: LP_YELLOW_TINT,
266
+ bgHeaderHovered: LP_YELLOW_TINT,
267
+ bgHeaderHasFocus: LP_YELLOW_TINT,
268
+ bgCell: washOf(LP_YELLOW_DEEP, 0.06),
269
+ headerFontStyle: INVOLVED_HEADER_FONT,
270
+ },
271
+ group: {
272
+ bgHeader: LP_PURPLE_TINT,
273
+ bgHeaderHovered: LP_PURPLE_TINT,
274
+ bgHeaderHasFocus: LP_PURPLE_TINT,
275
+ bgCell: washOf(LP_PURPLE_DEEP, 0.06),
276
+ headerFontStyle: INVOLVED_HEADER_FONT,
277
+ },
278
  };
279
 
280
  /**
281
+ * R5's second half β€” **a subtle row band while ANY control is active.**
 
282
  *
283
+ * The columns say WHICH FIELD a control is about; this says, from anywhere on the table, THAT
284
+ * one is on. Alternating rows only, in the hue of the winning control (R6's
285
+ * filter > sort > group), and fainter than the column wash β€” it covers half the table, so the
286
+ * same 6% would read as a texture rather than a hint.
287
+ *
288
+ * ⚠ Banded by DATA-ROW ORDINAL, never by display index (`CustomerGrid.bandMask`): group headers
289
+ * occupy display indices too, so index parity would flip the stripe at every group boundary and
290
+ * put two banded rows side by side.
291
+ *
292
+ * ⚠ Not painted on a colour-by table, on the hovered row, or on the active row β€” each of those
293
+ * already carries a wash the user asked for, and stacking a second one blends two hues into a
294
+ * third that means neither.
295
  */
296
+ export const CONTROL_BAND_THEME: Record<ControlTone, Partial<Theme>> = {
297
+ filter: { bgCell: washOf(LP_GREEN_DEEP, 0.035) },
298
+ sort: { bgCell: washOf(LP_YELLOW_DEEP, 0.035) },
299
+ group: { bgCell: washOf(LP_PURPLE_DEEP, 0.035) },
300
  };
301
 
302
  /**
web/src/customer-grid/timeSeriesData.ts CHANGED
@@ -604,6 +604,56 @@ export function buildTsDeltas(
604
  return out;
605
  }
606
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
607
  // ------------------------------------------------------------------ styles (item 17)
608
 
609
  /**
@@ -900,6 +950,68 @@ export function tsRowToChartModel(row: TsTableRow, columns: TsColumn[]): ChartMo
900
  };
901
  }
902
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
903
  // --------------------------------------------------------------------- CSV
904
 
905
  function csvCell(v: string): string {
 
604
  return out;
605
  }
606
 
607
+ // ------------------------------------------- wave-15 C-CHARTCAP (a): the COMPARE series ----
608
+
609
+ /**
610
+ * The SAME metric one year earlier, aligned to the current buckets β€” the second series of a
611
+ * year-over-year trend (`pages_sales._trend_block`'s "This year" / "Last year").
612
+ *
613
+ * ⚠ Derived from the row it already has, NOT fetched again. "The same measure over a prior-year
614
+ * window" is, on a bucketed series, the same series read `TS_YOY_BACK[bucket]` columns to the
615
+ * left β€” so cell i of the compare series is cell `i - back` of the row. No second query, no
616
+ * second window to keep in step with the first, and the two series cannot disagree about what a
617
+ * bucket means because they ARE the same buckets.
618
+ *
619
+ * ⚠ It REFUSES rather than drawing a short series. A 12-month span has no month a year before
620
+ * its first month, so every compare cell would be null and the card would show one real line
621
+ * against an empty one that reads as "we sold nothing last year". Same refusal, same wording
622
+ * shape, as `buildTsDeltas`' `yoy` row β€” one law, stated once, two consumers.
623
+ *
624
+ * `partial` rides along from the source bucket: an in-progress period compared against a
625
+ * complete one is the comparison the whole partial flag exists to mark.
626
+ */
627
+ export interface TsCompareSeries {
628
+ label: string;
629
+ cells: TsCell[];
630
+ /** How many buckets back the comparison reaches β€” 12 months, 52 weeks, 4 quarters, 1 year. */
631
+ back: number;
632
+ /** Set when the span cannot answer the comparison at all; the caller renders it once. */
633
+ refusal?: string;
634
+ }
635
+
636
+ export function buildTsCompare(
637
+ row: Pick<TsTableRow, "cells" | "label">,
638
+ bucket: TsBucket
639
+ ): TsCompareSeries {
640
+ const back = TS_YOY_BACK[bucket] ?? 12;
641
+ const blank: TsCell = { value: null, delta: null, partial: false };
642
+ const cells = row.cells.map((_, i) => (i >= back ? row.cells[i - back] : blank));
643
+ const refusal =
644
+ row.cells.length <= back
645
+ ? "This span is shorter than a year, so there is no earlier period to compare against."
646
+ : undefined;
647
+ return {
648
+ label: `${row.label} (last year)`,
649
+ // A refused comparison carries NO cells rather than a column of blanks: an empty series is
650
+ // absent from the chart, where a null-filled one is a flat line at zero that looks like data.
651
+ cells: refusal ? [] : cells,
652
+ back,
653
+ refusal,
654
+ };
655
+ }
656
+
657
  // ------------------------------------------------------------------ styles (item 17)
658
 
659
  /**
 
950
  };
951
  }
952
 
953
+ /**
954
+ * Wave-16 C-CHARTCAP β€” one metric row β†’ a TWO-SERIES `ChartModel`: the metric, and the same
955
+ * metric a year earlier (`buildTsCompare`), both trimmed to the last `lastN` columns.
956
+ *
957
+ * ⚠ THE FETCH IS WIDER THAN THE PICTURE, and this function is where the two meet. The card
958
+ * asks for `lastN` buckets on screen; its request fetched `lastN + TS_YOY_BACK[bucket]` so
959
+ * every DRAWN bucket has a companion a year back. Drawing the whole fetched span instead
960
+ * would show a chart where the oldest year has no companion line β€” which reads as "we sold
961
+ * nothing back then", the exact lie `buildTsCompare`'s refusal exists to prevent. So the trim
962
+ * is not cosmetic: it is what makes every visible bucket comparable.
963
+ *
964
+ * Still ONE query: the compare series is derived from the same row (`cells[i - back]`), so
965
+ * the two series cannot disagree about what a bucket means.
966
+ *
967
+ * The compare series keeps the engine's own label (`"<metric> (last year)"`) and sits SECOND
968
+ * in `seriesOrder`, so the current year takes the palette's first colour on every card.
969
+ * If the row is somehow too short to compare (defensive β€” the widened fetch prevents it),
970
+ * the model falls back to the single current series rather than drawing against blanks.
971
+ */
972
+ export function tsCompareChartModel(
973
+ row: TsTableRow,
974
+ columns: TsColumn[],
975
+ bucket: TsBucket,
976
+ lastN: number
977
+ ): ChartModel {
978
+ const compare = buildTsCompare(row, bucket);
979
+ const keep = Math.max(1, Math.min(Math.round(lastN), columns.length));
980
+ const start = columns.length - keep;
981
+ const cols = columns.slice(start);
982
+ const priorKey = `${row.field}::prior_year`;
983
+
984
+ const pointsOf = (cells: TsCell[], seriesKey: string, seriesLabel: string) =>
985
+ cols
986
+ .map((col, i) => ({ col, cell: cells[start + i] }))
987
+ .filter((p) => p.cell && p.cell.value != null)
988
+ .map((p) => ({
989
+ key: p.col.key,
990
+ label: p.col.label,
991
+ value: p.cell.value as number,
992
+ n: 1,
993
+ seriesKey,
994
+ seriesLabel,
995
+ }));
996
+
997
+ const current = pointsOf(row.cells, row.field, row.label);
998
+ const prior = compare.refusal ? [] : pointsOf(compare.cells, priorKey, compare.label);
999
+ return {
1000
+ points: [...current, ...prior],
1001
+ xOrder: cols.map((c) => c.key),
1002
+ seriesOrder: compare.refusal ? [row.field] : [row.field, priorKey],
1003
+ omitted: 0,
1004
+ omittedValue: 0,
1005
+ omittedSeries: 0,
1006
+ omittedSeriesValue: 0,
1007
+ blanks: row.cells.slice(start).filter((c) => c.value == null).length,
1008
+ missingY: 0,
1009
+ rows: current.length,
1010
+ nonPositive: 0,
1011
+ nonPositiveValue: 0,
1012
+ };
1013
+ }
1014
+
1015
  // --------------------------------------------------------------------- CSV
1016
 
1017
  function csvCell(v: string): string {
web/src/customer-grid/types.ts CHANGED
@@ -242,6 +242,10 @@ export interface DisplaySpec {
242
  /** R3 β€” how far back the trend runs. `lastN` is 1..TS_MAX_LAST_N and is meaningful only
243
  * beside `bucket`; alone it is inert rather than invalid (the picker writes them together). */
244
  span?: { lastN?: number };
 
 
 
 
245
  }[];
246
  /**
247
  * Wave 2026-08-02 item 3 (C-DISP) β€” kanban card clamp. **Stored ONLY as the literal `false`.**
@@ -1298,6 +1302,39 @@ export function isFilterGroup(node: FilterNode): node is FilterGroup {
1298
  return node != null && Array.isArray((node as FilterGroup).children);
1299
  }
1300
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1301
  export type RowHeightMode = "short" | "medium" | "tall";
1302
  export type ThemeMode = "light" | "dark";
1303
 
@@ -1406,6 +1443,55 @@ export interface SavedView {
1406
  * no entry at all, because it reads as success.
1407
  */
1408
  export const UNDELETABLE_VIEW_IDS = new Set(["all-customers"]);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1409
  export function isUndeletableView(view: Pick<SavedView, "id">): boolean {
1410
  return UNDELETABLE_VIEW_IDS.has(view.id);
1411
  }
 
242
  /** R3 β€” how far back the trend runs. `lastN` is 1..TS_MAX_LAST_N and is meaningful only
243
  * beside `bucket`; alone it is inert rather than invalid (the picker writes them together). */
244
  span?: { lastN?: number };
245
+ /** Wave-16 C-CHARTCAP β€” the YoY companion ("prior_year"). Loose-typed like `agg`/`bucket`
246
+ * above and for the same reason: the vocabulary lives in chartData.ts and the host, and
247
+ * `cleanCharts`/`_clean_chart` are what enforce membership. Passes through here untouched. */
248
+ compare?: string;
249
  }[];
250
  /**
251
  * Wave 2026-08-02 item 3 (C-DISP) β€” kanban card clamp. **Stored ONLY as the literal `false`.**
 
1302
  return node != null && Array.isArray((node as FilterGroup).children);
1303
  }
1304
 
1305
+ /**
1306
+ * Wave-15 (C-KIT / C-PERM) β€” A WHOLE FILTER, as one value.
1307
+ *
1308
+ * ⚠ This type is NEW, and its absence was a live hazard rather than an inconvenience. A filter
1309
+ * has always been TWO things here β€” `ViewConfig.filters` (the node list) and
1310
+ * `ViewConfig.filterConj` (how the ROOT list is joined) β€” carried as two separate members
1311
+ * because that is how a view persists them. Nothing wrong with that inside a view; the problem
1312
+ * is everywhere a filter has to travel as ONE value: a permission record, a route body, a panel
1313
+ * prop. Passing the nodes alone loses the root and/or SILENTLY, and `[A, B]` joined by `or` is a
1314
+ * different question from `[A, B]` joined by `and` β€” the drop is invisible in the payload, in
1315
+ * the UI, and in any count you would think to check.
1316
+ *
1317
+ * `conj` is OPTIONAL and absent means `"and"`, mirroring `ViewConfig.filterConj` exactly, so a
1318
+ * tree persisted as `{nodes: [...]}` reads as every view saved before this type existed.
1319
+ *
1320
+ * ⚠ The SERVER validator takes the NODES, not this object: `clean_filter_tree` (aios_grid.py)
1321
+ * walks a node list and would drop this wrapper as an unrecognised node. Hand it `tree.nodes`.
1322
+ */
1323
+ export interface FilterTree {
1324
+ conj?: Conjunction;
1325
+ nodes: FilterNode[];
1326
+ }
1327
+
1328
+ /** The nodes of a tree that may be absent/null β€” one place for the empty default. */
1329
+ export function filterTreeNodes(tree: FilterTree | null | undefined): FilterNode[] {
1330
+ return Array.isArray(tree?.nodes) ? tree.nodes : [];
1331
+ }
1332
+
1333
+ /** The root conjunction of a tree that may be absent/null. Absent = "and" (see FilterTree). */
1334
+ export function filterTreeConj(tree: FilterTree | null | undefined): Conjunction {
1335
+ return tree?.conj === "or" ? "or" : "and";
1336
+ }
1337
+
1338
  export type RowHeightMode = "short" | "medium" | "tall";
1339
  export type ThemeMode = "light" | "dark";
1340
 
 
1443
  * no entry at all, because it reads as success.
1444
  */
1445
  export const UNDELETABLE_VIEW_IDS = new Set(["all-customers"]);
1446
+
1447
+ // ─────────────────────────────────────────────── wave 16 C-TOPIC: the grid's TOPIC
1448
+ /**
1449
+ * ONE grid engine, N table objects (owner items 9+10). A topic names everything that differs
1450
+ * between the Customer table and the Product table β€” and NOTHING else differs:
1451
+ * `key` the registry key (what the nav and grants speak);
1452
+ * `scope` the surface scope the workspace/events routes take (`?scope=`,
1453
+ * `scopeKey` on every event) β€” `cohort` shares the customer topic;
1454
+ * `rowsPath` the REST segment: GET /api/v1/<rowsPath>, PATCH /api/v1/<rowsPath>/{pid};
1455
+ * `noun`/`nouns` the user-facing word ("customer(s)" / "product(s)") for copy that names
1456
+ * what a row IS;
1457
+ * `measures` whether the user-measure channel exists at this grain β€” false hides the
1458
+ * Insert-field metric option and the time-series mode (the server refuses
1459
+ * both regardless; the client simply does not offer a dead door).
1460
+ *
1461
+ * ⚠ Derived from the SCOPE, never carried beside it: two props describing one surface is how
1462
+ * a read and a write end up talking about different tables.
1463
+ */
1464
+ export interface TopicConfig {
1465
+ key: string;
1466
+ scope: string;
1467
+ rowsPath: string;
1468
+ noun: string;
1469
+ nouns: string;
1470
+ measures: boolean;
1471
+ }
1472
+
1473
+ export const CUSTOMER_TOPIC: TopicConfig = {
1474
+ key: "customer_data",
1475
+ scope: "customer",
1476
+ rowsPath: "customers",
1477
+ noun: "customer",
1478
+ nouns: "customers",
1479
+ measures: true,
1480
+ };
1481
+
1482
+ export const PRODUCT_TOPIC: TopicConfig = {
1483
+ key: "product_data",
1484
+ scope: "product",
1485
+ rowsPath: "products",
1486
+ noun: "product",
1487
+ nouns: "products",
1488
+ measures: false,
1489
+ };
1490
+
1491
+ /** The topic a surface scope draws β€” `cohort` IS the customer topic over fixed sets. */
1492
+ export function topicForScope(scope: string): TopicConfig {
1493
+ return scope === "product" ? PRODUCT_TOPIC : CUSTOMER_TOPIC;
1494
+ }
1495
  export function isUndeletableView(view: Pick<SavedView, "id">): boolean {
1496
  return UNDELETABLE_VIEW_IDS.has(view.id);
1497
  }
web/src/customer-grid/useCustomerData.ts CHANGED
@@ -24,8 +24,9 @@
24
 
25
  import { useCallback, useEffect, useRef, useState } from "react";
26
  import type { Dispatch, SetStateAction } from "react";
 
27
  import type { CustomersPayload, Field, GridWorkspace, Row } from "./types";
28
- import { fetchCustomers, fetchWorkspace, patchCustomer, setSurfaceScope } from "./apiBridge";
29
  import { WORKSPACE_STALE_EVENT } from "../apiContract";
30
  import type { SurfaceScope } from "./apiBridge";
31
  import {
@@ -152,6 +153,10 @@ export function useCustomerData(scope: SurfaceScope = "customer"): CustomerData
152
  // would be posted as `customer` from the Cohort surface. Module scope + a synchronous set is
153
  // what keeps the read and the write talking about the same surface.
154
  setSurfaceScope(scope);
 
 
 
 
155
  // Lazy initializer: in embed mode the data is already on the page, so seed it
156
  // synchronously β€” `loading` is false on the very first render (no flash).
157
  const [data, setData] = useState<CustomersPayload | null>(() => readInitialPayload());
@@ -208,7 +213,10 @@ export function useCustomerData(scope: SurfaceScope = "customer"): CustomerData
208
  // today rather than failing the read. Parallel, not sequential β€” the table
209
  // must not wait on the smaller call.
210
  async function load() {
211
- const [payload, workspace] = await Promise.all([fetchCustomers(), fetchWorkspace(scope)]);
 
 
 
212
  if (cancelled || !payload) return;
213
  setData(workspace ? withWorkspace(payload, workspace) : payload);
214
  }
@@ -234,7 +242,8 @@ export function useCustomerData(scope: SurfaceScope = "customer"): CustomerData
234
  cancelled = true;
235
  if (typeof window !== "undefined") window.removeEventListener(WORKSPACE_STALE_EVENT, onStale);
236
  };
237
- }, [scope]);
 
238
 
239
  // Optimistic overlay write: apply the edit immediately (so the grid cell and
240
  // the detail panel reflect it at once), snapshot the pre-edit entry, then
@@ -278,8 +287,9 @@ export function useCustomerData(scope: SurfaceScope = "customer"): CustomerData
278
  if (EMBEDDED_HTML) return;
279
 
280
  // CP-B: the v1 route, carrying the session cookie. Rollback semantics are
281
- // unchanged β€” the UI never keeps a value the server refused.
282
- void patchCustomer(pid, updates).then((ok) => {
 
283
  if (ok) return;
284
  console.warn(`customer-grid: overlay PATCH failed for pid ${pid}; rolling back`);
285
  setOverlayEdits((prev) => {
@@ -289,7 +299,7 @@ export function useCustomerData(scope: SurfaceScope = "customer"): CustomerData
289
  return next;
290
  });
291
  });
292
- }, []);
293
 
294
  return {
295
  fields: data?.fields ?? [],
 
24
 
25
  import { useCallback, useEffect, useRef, useState } from "react";
26
  import type { Dispatch, SetStateAction } from "react";
27
+ import { topicForScope } from "./types";
28
  import type { CustomersPayload, Field, GridWorkspace, Row } from "./types";
29
+ import { fetchTopicRows, fetchWorkspace, patchTopicRow, setSurfaceScope } from "./apiBridge";
30
  import { WORKSPACE_STALE_EVENT } from "../apiContract";
31
  import type { SurfaceScope } from "./apiBridge";
32
  import {
 
153
  // would be posted as `customer` from the Cohort surface. Module scope + a synchronous set is
154
  // what keeps the read and the write talking about the same surface.
155
  setSurfaceScope(scope);
156
+ // Wave 16 C-TOPIC: the topic is DERIVED from the scope (cohort = the customer topic), so
157
+ // the rows fetch, the patch route and the workspace scope can never disagree about which
158
+ // table this is.
159
+ const topic = topicForScope(scope);
160
  // Lazy initializer: in embed mode the data is already on the page, so seed it
161
  // synchronously β€” `loading` is false on the very first render (no flash).
162
  const [data, setData] = useState<CustomersPayload | null>(() => readInitialPayload());
 
213
  // today rather than failing the read. Parallel, not sequential β€” the table
214
  // must not wait on the smaller call.
215
  async function load() {
216
+ const [payload, workspace] = await Promise.all([
217
+ fetchTopicRows(topic),
218
+ fetchWorkspace(scope),
219
+ ]);
220
  if (cancelled || !payload) return;
221
  setData(workspace ? withWorkspace(payload, workspace) : payload);
222
  }
 
242
  cancelled = true;
243
  if (typeof window !== "undefined") window.removeEventListener(WORKSPACE_STALE_EVENT, onStale);
244
  };
245
+ // `topic` is a stable module constant per scope (topicForScope), so this cannot loop.
246
+ }, [scope, topic]);
247
 
248
  // Optimistic overlay write: apply the edit immediately (so the grid cell and
249
  // the detail panel reflect it at once), snapshot the pre-edit entry, then
 
287
  if (EMBEDDED_HTML) return;
288
 
289
  // CP-B: the v1 route, carrying the session cookie. Rollback semantics are
290
+ // unchanged β€” the UI never keeps a value the server refused. The TOPIC picks
291
+ // the route, so a product edit can never land on a customer pid (wave 16).
292
+ void patchTopicRow(topic, pid, updates).then((ok) => {
293
  if (ok) return;
294
  console.warn(`customer-grid: overlay PATCH failed for pid ${pid}; rolling back`);
295
  setOverlayEdits((prev) => {
 
299
  return next;
300
  });
301
  });
302
+ }, [topic]);
303
 
304
  return {
305
  fields: data?.fields ?? [],
web/src/customer-grid/useGridColumns.ts CHANGED
@@ -1,327 +1,349 @@
1
- import { useCallback, useMemo } from "react";
2
- import type { GridColumn, Theme } from "@glideapps/glide-data-grid";
3
- import type { Field, FilterNode, ViewConfig } from "./types";
4
- import { isFilterGroup, isRuleActive } from "./types";
5
- import { typeIconName } from "./iconShapes";
6
- import { fitHeaderTitle, headerLabelSpace, headerMarkSizes } from "./overlayPlacement";
7
- import { COLUMN_TONE_THEME, INVOLVED_COLUMN_THEME, lightTheme } from "./theme";
8
- import type { ControlTone } from "./theme";
9
-
10
- const DEFAULT_WIDTH = 150;
11
-
12
- /**
13
- * Owner item 16 β€” measure header text in GLIDE'S OWN HEADER FONT.
14
- *
15
- * ⚠ NOT the cell font. Glide's `headerFontStyle` is "600 13px" and its `baseFontStyle` is
16
- * "13px" (`common/styles.js:73-75`); semibold is materially wider, so measuring with the cell
17
- * font under-measures, under-truncates, and leaves the label running under the (i) β€” the exact
18
- * defect this item is about, surviving a fix that looked correct in the diff.
19
- *
20
- * ⚠⚠ Wave-14 item 2 adds the SAME trap one weight up. An involved column now paints its header
21
- * at **700** (`INVOLVED_COLUMN_THEME.headerFontStyle`), so measuring every column at 600 would
22
- * under-truncate exactly the filtered/sorted/grouped columns β€” the ones the owner is looking at.
23
- * Hence TWO cached contexts, and both font strings are read off the theme objects rather than
24
- * retyped here: a literal in this file is a copy that can drift from the one glide actually
25
- * paints with, which is the whole failure mode above.
26
- *
27
- * One lazily-built offscreen context per weight, the same shape as CustomerGrid's
28
- * `measureCellText`. A context can legitimately be null (a headless canvas, a locked-down
29
- * embed); 0 then measures as "everything fits" and no title is truncated, which is the safe
30
- * direction to fail β€” a title that slightly overlaps beats one silently cut to "C…".
31
- */
32
- const _hdrCtx: Record<"base" | "bold", CanvasRenderingContext2D | null | undefined> = {
33
- base: undefined,
34
- bold: undefined,
35
- };
36
- function measureHeaderText(text: string, bold = false): number {
37
- const slot = bold ? "bold" : "base";
38
- if (_hdrCtx[slot] === undefined) {
39
- const ctx = document.createElement("canvas").getContext("2d");
40
- if (ctx) {
41
- const style =
42
- (bold ? INVOLVED_COLUMN_THEME.headerFontStyle : lightTheme.headerFontStyle) ??
43
- "600 13px";
44
- ctx.font = `${style} ${lightTheme.fontFamily ?? "Inter, sans-serif"}`;
45
- }
46
- _hdrCtx[slot] = ctx;
47
- }
48
- const ctx = _hdrCtx[slot];
49
- return ctx ? ctx.measureText(text).width : 0;
50
- }
51
-
52
- /** The (i) is drawn for exactly this condition β€” `CustomerGrid.drawGridHeader` resolves the
53
- * same one from the same field, so the reserve and the mark can never disagree. */
54
- function hasInfoMark(field: Field): boolean {
55
- return !!(field.note || field.description);
56
- }
57
-
58
- /** Every column key an ACTIVE filter rule names, anywhere in the tree. Inactive (half-typed)
59
- * rules are skipped: a rule that is not narrowing anything must not tint a column as though
60
- * it were β€” that is the same "it looks like it is working" lie the engine refuses to tell. */
61
- function filteredKeys(nodes: FilterNode[], out: Set<string>): void {
62
- for (const node of nodes ?? []) {
63
- if (isFilterGroup(node)) {
64
- filteredKeys(node.children, out);
65
- continue;
66
- }
67
- if (isRuleActive(node)) out.add(node.colId);
68
- }
69
- }
70
-
71
- /**
72
- * Owner item 22 β€” key β†’ which control involves it, or absent.
73
- *
74
- * ⚠ ONE tone per column, and the precedence is a decision, not an accident:
75
- * **filter > group > sort.** A filter changes WHICH ROWS you are looking at, grouping changes
76
- * the table's structure, a sort only reorders what was already there β€” so when a column is
77
- * doing two jobs the header names the most consequential one. Blending two tints would produce
78
- * a third colour that matches no chip in the toolbar, which is worse than picking.
79
- */
80
- /**
81
- * The column's theme override, or `undefined` β€” glide's fast path for "no override" is an absent
82
- * object, so an empty `{}` would cost a ~35-key theme merge per column per frame.
83
- *
84
- * ⚠ Wave-14 item 1 (R11): a user-created field NO LONGER contributes a theme at all. Its yellow
85
- * header wash is dead and its replacement is a painted DOT, not a background β€” so the only thing
86
- * that can put a themeOverride on a column now is being INVOLVED in a control, and the returned
87
- * object is the one shared `INVOLVED_COLUMN_THEME` reference (stable across columns and frames,
88
- * which is what keeps glide's merge cache-friendly).
89
- *
90
- * That the tone is resolved and then discarded is deliberate, not dead code: `columnTones`'
91
- * filter > group > sort precedence still names WHICH control owns the column for anything that
92
- * wants it, and R4 is a decision about paint, not about the model.
93
- */
94
- function columnTheme(tone: ControlTone | undefined): Partial<Theme> | undefined {
95
- return tone ? COLUMN_TONE_THEME[tone] : undefined;
96
- }
97
-
98
- function columnTones(config: ViewConfig): Map<string, ControlTone> {
99
- const out = new Map<string, ControlTone>();
100
- for (const s of config.sorts ?? []) out.set(s.colId, "sort");
101
- if (config.groupBy) out.set(config.groupBy, "group");
102
- const filtered = new Set<string>();
103
- filteredKeys(config.filters ?? [], filtered);
104
- for (const key of filtered) out.set(key, "filter");
105
- return out;
106
- }
107
-
108
- function isDefaultVisible(field: Field): boolean {
109
- return field.default !== false || field.source === "overlay";
110
- }
111
-
112
- export function defaultViewConfig(fields: Field[]): ViewConfig {
113
- const shown = fields.filter(isDefaultVisible).map((field) => field.key);
114
- const hidden = fields.filter((field) => !isDefaultVisible(field)).map((field) => field.key);
115
- return {
116
- filters: [],
117
- filterConj: "and",
118
- sorts: [],
119
- groupBy: null,
120
- colorBy: null,
121
- rowHeightMode: "short",
122
- order: [...shown, ...hidden],
123
- visible: shown,
124
- widths: {},
125
- memberPids: [],
126
- };
127
- }
128
-
129
- function reconcileOrder(order: string[], fields: Field[]): string[] {
130
- const valid = new Set(fields.map((field) => field.key));
131
- const kept = order.filter((key, index) => valid.has(key) && order.indexOf(key) === index);
132
- for (const field of fields) if (!kept.includes(field.key)) kept.push(field.key);
133
- const locked = fields.find((field) => field.pinned)?.key ?? fields[0]?.key;
134
- if (locked && kept[0] !== locked) {
135
- const without = kept.filter((key) => key !== locked);
136
- return [locked, ...without];
137
- }
138
- return kept;
139
- }
140
-
141
- function reconcileVisible(visible: string[], fields: Field[], lockedKey: string): Set<string> {
142
- const valid = new Set(fields.map((field) => field.key));
143
- const out = new Set(visible.filter((key) => valid.has(key)));
144
- if (out.size === 0) {
145
- for (const field of fields) if (isDefaultVisible(field)) out.add(field.key);
146
- }
147
- if (lockedKey) out.add(lockedKey);
148
- return out;
149
- }
150
-
151
- export interface GridColumnsApi {
152
- visibleCols: GridColumn[];
153
- fieldByKey: Map<string, Field>;
154
- order: string[];
155
- visible: Set<string>;
156
- widths: Record<string, number>;
157
- lockedKey: string;
158
- onColumnResize: (col: GridColumn, newSize: number) => void;
159
- onColumnMoved: (from: number, to: number) => void;
160
- onColumnProposeMove: (from: number, to: number) => boolean;
161
- setColumnVisible: (key: string, show: boolean) => void;
162
- insertColumn: (key: string, anchorKey: string | null, side: "left" | "right" | "end") => void;
163
- }
164
-
165
- /**
166
- * Controlled column adapter. ViewConfig is the durable source of truth, so
167
- * choosing a saved view is one atomic state change instead of a chain of hook
168
- * setters that can flash or overwrite one another.
169
- */
170
- export function useGridColumns(
171
- fields: Field[],
172
- config: ViewConfig,
173
- onConfig: (next: ViewConfig) => void
174
- ): GridColumnsApi {
175
- const fieldByKey = useMemo(
176
- () => new Map(fields.map((field) => [field.key, field])),
177
- [fields]
178
- );
179
- const lockedKey = useMemo(
180
- () => fields.find((field) => field.pinned)?.key ?? fields[0]?.key ?? "",
181
- [fields]
182
- );
183
- const order = useMemo(() => reconcileOrder(config.order, fields), [config.order, fields]);
184
- const visible = useMemo(
185
- () => reconcileVisible(config.visible, fields, lockedKey),
186
- [config.visible, fields, lockedKey]
187
- );
188
-
189
- // Item 22 β€” recomputed only when the three controls move, not on every width drag.
190
- const tones = useMemo(
191
- () => columnTones(config),
192
- [config.filters, config.sorts, config.groupBy] // eslint-disable-line react-hooks/exhaustive-deps
193
- );
194
-
195
- const visibleCols = useMemo<GridColumn[]>(
196
- () =>
197
- order
198
- .filter((key) => visible.has(key))
199
- .map((key) => {
200
- const field = fieldByKey.get(key)!;
201
- const width = config.widths[key] ?? DEFAULT_WIDTH;
202
- // Wave-14 item 2 β€” an INVOLVED column's header paints at 700, so it must be MEASURED
203
- // at 700. `tones` is already a dep of this memo, so this costs nothing.
204
- const involved = tones.has(key);
205
- // R11 β€” the marks this header carries, in the strip's canonical order. Both this
206
- // reserve and `CustomerGrid.drawGridHeader`'s painting read `headerMarkSizes`, so a
207
- // column can never reserve room for one mark and then be given two.
208
- const marks = headerMarkSizes(hasInfoMark(field), field.source === "overlay");
209
- return {
210
- id: key,
211
- // Owner item 16 β€” ELLIPSISED so the title can never run under the (i). Glide
212
- // truncates nothing: `drawHeaderInner` calls `fillText(c.title, …)` with no clip
213
- // and no max width, so on a narrow column the name simply painted through the
214
- // mark. Shortening the title glide is given is the whole fix β€” the alternative,
215
- // clipping inside `drawHeader`, cuts mid-glyph with no ellipsis to say it did.
216
- // The FULL name stays reachable: CustomerGrid's header tip leads with it whenever
217
- // this returns something shorter than `field.label`.
218
- title: fitHeaderTitle(
219
- field.label,
220
- headerLabelSpace(width, marks),
221
- (text) => measureHeaderText(text, involved)
222
- ),
223
- width,
224
- hasMenu: true,
225
- menuIcon: "dots",
226
- // Wave-8 I20 β€” the field-TYPE mark leads every header, so the column says what
227
- // KIND of thing it holds before you read a single cell (same geometry as the
228
- // Fields panel's rows β€” icons.tsx).
229
- icon: typeIconName(field.type),
230
- // Wave-9 I3 β€” the (i) is NO LONGER `overlayIcon`. Glide draws an overlay at a
231
- // hard-coded offset from the TYPE mark (drawHeaderInner: `drawX + 9`), i.e.
232
- // pinned to the far LEFT of the header, and no prop moves it; the owner asked
233
- // for it right-aligned and centred with the field name. It is drawn instead by
234
- // CustomerGrid's `drawHeader` callback, which resolves the same
235
- // `field.note || field.description` condition from the field itself.
236
- // The hover text is still CustomerGrid's floating tip (pointer-events: none β€”
237
- // a tooltip must never swallow the next click, [[ui-invisible-to-assertions]]).
238
- // Wave-14 R4 β€” being INVOLVED in a filter/sort/group is the only thing that tints a
239
- // column now, and all three tint it the same faint warm grey; the hue that says
240
- // WHICH control lives on the toolbar chip. User-created ownership moved out of the
241
- // theme entirely and is the dot drawn in the mark strip (R11).
242
- themeOverride: columnTheme(tones.get(key)),
243
- };
244
- }),
245
- [order, visible, config.widths, fieldByKey, tones]
246
- );
247
-
248
- const onColumnResize = useCallback(
249
- (column: GridColumn, newSize: number) => {
250
- if (!column.id) return;
251
- onConfig({
252
- ...config,
253
- widths: { ...config.widths, [column.id]: Math.round(newSize) },
254
- });
255
- },
256
- [config, onConfig]
257
- );
258
-
259
- const onColumnMoved = useCallback(
260
- (from: number, to: number) => {
261
- if (from === 0 || to === 0) return;
262
- const visibleKeys = order.filter((key) => visible.has(key));
263
- if (
264
- from < 0 ||
265
- from >= visibleKeys.length ||
266
- to < 0 ||
267
- to >= visibleKeys.length
268
- )
269
- return;
270
- const movedKeys = visibleKeys.slice();
271
- const [moved] = movedKeys.splice(from, 1);
272
- movedKeys.splice(to, 0, moved);
273
- let index = 0;
274
- const nextOrder = order.map((key) =>
275
- visible.has(key) ? movedKeys[index++] : key
276
- );
277
- onConfig({ ...config, order: nextOrder });
278
- },
279
- [config, onConfig, order, visible]
280
- );
281
-
282
- const onColumnProposeMove = useCallback(
283
- (from: number, to: number) => from !== 0 && to !== 0,
284
- []
285
- );
286
-
287
- const setColumnVisible = useCallback(
288
- (key: string, show: boolean) => {
289
- if (!show && key === lockedKey) return;
290
- const next = new Set(visible);
291
- if (show) next.add(key);
292
- else next.delete(key);
293
- onConfig({ ...config, visible: [...next] });
294
- },
295
- [config, lockedKey, onConfig, visible]
296
- );
297
-
298
- const insertColumn = useCallback(
299
- (key: string, anchorKey: string | null, side: "left" | "right" | "end") => {
300
- const nextOrder = order.filter((item) => item !== key);
301
- if (side === "end" || !anchorKey) {
302
- nextOrder.push(key);
303
- } else {
304
- const anchor = Math.max(0, nextOrder.indexOf(anchorKey));
305
- nextOrder.splice(anchor + (side === "right" ? 1 : 0), 0, key);
306
- }
307
- const nextVisible = new Set(visible);
308
- nextVisible.add(key);
309
- onConfig({ ...config, order: nextOrder, visible: [...nextVisible] });
310
- },
311
- [config, onConfig, order, visible]
312
- );
313
-
314
- return {
315
- visibleCols,
316
- fieldByKey,
317
- order,
318
- visible,
319
- widths: config.widths,
320
- lockedKey,
321
- onColumnResize,
322
- onColumnMoved,
323
- onColumnProposeMove,
324
- setColumnVisible,
325
- insertColumn,
326
- };
327
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { useCallback, useMemo } from "react";
2
+ import type { GridColumn, Theme } from "@glideapps/glide-data-grid";
3
+ import type { Field, FilterNode, ViewConfig } from "./types";
4
+ import { isFilterGroup, isRuleActive } from "./types";
5
+ import { typeIconName } from "./iconShapes";
6
+ import { fitHeaderTitle, headerLabelSpace, headerMarkSizes } from "./overlayPlacement";
7
+ import { COLUMN_TONE_THEME, INVOLVED_HEADER_FONT, lightTheme } from "./theme";
8
+ import type { ControlTone } from "./theme";
9
+
10
+ const DEFAULT_WIDTH = 150;
11
+
12
+ /**
13
+ * Owner item 16 β€” measure header text in GLIDE'S OWN HEADER FONT.
14
+ *
15
+ * ⚠ NOT the cell font. Glide's `headerFontStyle` is "600 13px" and its `baseFontStyle` is
16
+ * "13px" (`common/styles.js:73-75`); semibold is materially wider, so measuring with the cell
17
+ * font under-measures, under-truncates, and leaves the label running under the (i) β€” the exact
18
+ * defect this item is about, surviving a fix that looked correct in the diff.
19
+ *
20
+ * ⚠⚠ Wave-14 item 2 adds the SAME trap one weight up. An involved column paints its header at
21
+ * **700** (`INVOLVED_HEADER_FONT`), so measuring every column at 600 would under-truncate
22
+ * exactly the filtered/sorted/grouped columns β€” the ones the owner is looking at. Hence TWO
23
+ * cached contexts, and both font strings are read off the theme layer rather than retyped here:
24
+ * a literal in this file is a copy that can drift from the one glide actually paints with, which
25
+ * is the whole failure mode above.
26
+ *
27
+ * ⚠ Wave-15 R5 gave each control its OWN hue, so there are now three involved-column themes
28
+ * instead of one. They deliberately share `INVOLVED_HEADER_FONT`, so ONE bold context still
29
+ * measures all three correctly β€” but the constant, not any one of the three theme objects, is
30
+ * what this reads. Picking `COLUMN_TONE_THEME.filter.headerFontStyle` would have measured every
31
+ * involved column against whichever tone happened to be listed first.
32
+ *
33
+ * One lazily-built offscreen context per weight, the same shape as CustomerGrid's
34
+ * `measureCellText`. A context can legitimately be null (a headless canvas, a locked-down
35
+ * embed); 0 then measures as "everything fits" and no title is truncated, which is the safe
36
+ * direction to fail β€” a title that slightly overlaps beats one silently cut to "C…".
37
+ */
38
+ const _hdrCtx: Record<"base" | "bold", CanvasRenderingContext2D | null | undefined> = {
39
+ base: undefined,
40
+ bold: undefined,
41
+ };
42
+ function measureHeaderText(text: string, bold = false): number {
43
+ const slot = bold ? "bold" : "base";
44
+ if (_hdrCtx[slot] === undefined) {
45
+ const ctx = document.createElement("canvas").getContext("2d");
46
+ if (ctx) {
47
+ const style =
48
+ (bold ? INVOLVED_HEADER_FONT : lightTheme.headerFontStyle) ?? "600 13px";
49
+ ctx.font = `${style} ${lightTheme.fontFamily ?? "Inter, sans-serif"}`;
50
+ }
51
+ _hdrCtx[slot] = ctx;
52
+ }
53
+ const ctx = _hdrCtx[slot];
54
+ return ctx ? ctx.measureText(text).width : 0;
55
+ }
56
+
57
+ /** The (i) is drawn for exactly this condition β€” `CustomerGrid.drawGridHeader` resolves the
58
+ * same one from the same field, so the reserve and the mark can never disagree. */
59
+ function hasInfoMark(field: Field): boolean {
60
+ return !!(field.note || field.description);
61
+ }
62
+
63
+ /** Every column key an ACTIVE filter rule names, anywhere in the tree. Inactive (half-typed)
64
+ * rules are skipped: a rule that is not narrowing anything must not tint a column as though
65
+ * it were β€” that is the same "it looks like it is working" lie the engine refuses to tell. */
66
+ function filteredKeys(nodes: FilterNode[], out: Set<string>): void {
67
+ for (const node of nodes ?? []) {
68
+ if (isFilterGroup(node)) {
69
+ filteredKeys(node.children, out);
70
+ continue;
71
+ }
72
+ if (isRuleActive(node)) out.add(node.colId);
73
+ }
74
+ }
75
+
76
+ /**
77
+ * The column's theme override, or `undefined` β€” glide's fast path for "no override" is an absent
78
+ * object, so an empty `{}` would cost a ~35-key theme merge per column per frame.
79
+ *
80
+ * ⚠ Wave-14 item 1 (R11): a user-created field contributes no theme. Its yellow header wash is
81
+ * dead and its replacement is a painted DOT, not a background β€” so the only thing that can put a
82
+ * themeOverride on a column is being INVOLVED in a control.
83
+ *
84
+ * ⚠ Wave-15 R5: the returned object is one of the three SHARED `COLUMN_TONE_THEME` references
85
+ * (never a fresh object), which is what keeps glide's theme merge cache-friendly across frames.
86
+ */
87
+ function columnTheme(tone: ControlTone | undefined): Partial<Theme> | undefined {
88
+ return tone ? COLUMN_TONE_THEME[tone] : undefined;
89
+ }
90
+
91
+ /**
92
+ * Owner item 22 β€” key β†’ which control involves it, or absent.
93
+ *
94
+ * ⚠ ONE tone per column, and the precedence is a decision, not an accident: **filter > sort >
95
+ * group** (owner R6, wave 15). A filter changes WHICH ROWS you are looking at; when a column is
96
+ * doing two jobs the header names the most consequential one. Blending two tints would produce a
97
+ * third colour that matches no chip in the toolbar, which is worse than picking.
98
+ *
99
+ * ⚠ THE PRECEDENCE IS THE WRITE ORDER BELOW, and it reads backwards: later `set` calls WIN, so
100
+ * the least important control is written FIRST. It was `sort, group, filter` β€” i.e. filter >
101
+ * group > sort β€” until R6 named the order explicitly; getting this wrong is a one-line edit that
102
+ * changes a colour on screen and nothing else, so it is stated here rather than left to be
103
+ * re-derived from the sequence.
104
+ */
105
+ function columnTones(config: ViewConfig): Map<string, ControlTone> {
106
+ const out = new Map<string, ControlTone>();
107
+ if (config.groupBy) out.set(config.groupBy, "group");
108
+ for (const s of config.sorts ?? []) out.set(s.colId, "sort");
109
+ const filtered = new Set<string>();
110
+ filteredKeys(config.filters ?? [], filtered);
111
+ for (const key of filtered) out.set(key, "filter");
112
+ return out;
113
+ }
114
+
115
+ /**
116
+ * R5's second half β€” the WINNING control for the whole table, or undefined when none is active.
117
+ *
118
+ * Same precedence as `columnTones`, stated once here rather than re-derived: the row band and
119
+ * the involved columns must agree about which control is "the" one, or the table would band in
120
+ * green while its only hued column was yellow.
121
+ */
122
+ export function activeControlTone(config: ViewConfig): ControlTone | undefined {
123
+ const filtered = new Set<string>();
124
+ filteredKeys(config.filters ?? [], filtered);
125
+ if (filtered.size > 0) return "filter";
126
+ if ((config.sorts ?? []).length > 0) return "sort";
127
+ return config.groupBy ? "group" : undefined;
128
+ }
129
+
130
+ function isDefaultVisible(field: Field): boolean {
131
+ return field.default !== false || field.source === "overlay";
132
+ }
133
+
134
+ export function defaultViewConfig(fields: Field[]): ViewConfig {
135
+ const shown = fields.filter(isDefaultVisible).map((field) => field.key);
136
+ const hidden = fields.filter((field) => !isDefaultVisible(field)).map((field) => field.key);
137
+ return {
138
+ filters: [],
139
+ filterConj: "and",
140
+ sorts: [],
141
+ groupBy: null,
142
+ colorBy: null,
143
+ rowHeightMode: "short",
144
+ order: [...shown, ...hidden],
145
+ visible: shown,
146
+ widths: {},
147
+ memberPids: [],
148
+ };
149
+ }
150
+
151
+ function reconcileOrder(order: string[], fields: Field[]): string[] {
152
+ const valid = new Set(fields.map((field) => field.key));
153
+ const kept = order.filter((key, index) => valid.has(key) && order.indexOf(key) === index);
154
+ for (const field of fields) if (!kept.includes(field.key)) kept.push(field.key);
155
+ const locked = fields.find((field) => field.pinned)?.key ?? fields[0]?.key;
156
+ if (locked && kept[0] !== locked) {
157
+ const without = kept.filter((key) => key !== locked);
158
+ return [locked, ...without];
159
+ }
160
+ return kept;
161
+ }
162
+
163
+ function reconcileVisible(visible: string[], fields: Field[], lockedKey: string): Set<string> {
164
+ const valid = new Set(fields.map((field) => field.key));
165
+ const out = new Set(visible.filter((key) => valid.has(key)));
166
+ if (out.size === 0) {
167
+ for (const field of fields) if (isDefaultVisible(field)) out.add(field.key);
168
+ }
169
+ if (lockedKey) out.add(lockedKey);
170
+ return out;
171
+ }
172
+
173
+ export interface GridColumnsApi {
174
+ visibleCols: GridColumn[];
175
+ fieldByKey: Map<string, Field>;
176
+ order: string[];
177
+ visible: Set<string>;
178
+ widths: Record<string, number>;
179
+ lockedKey: string;
180
+ onColumnResize: (col: GridColumn, newSize: number) => void;
181
+ onColumnMoved: (from: number, to: number) => void;
182
+ onColumnProposeMove: (from: number, to: number) => boolean;
183
+ setColumnVisible: (key: string, show: boolean) => void;
184
+ insertColumn: (key: string, anchorKey: string | null, side: "left" | "right" | "end") => void;
185
+ }
186
+
187
+ /**
188
+ * Controlled column adapter. ViewConfig is the durable source of truth, so
189
+ * choosing a saved view is one atomic state change instead of a chain of hook
190
+ * setters that can flash or overwrite one another.
191
+ */
192
+ export function useGridColumns(
193
+ fields: Field[],
194
+ config: ViewConfig,
195
+ onConfig: (next: ViewConfig) => void
196
+ ): GridColumnsApi {
197
+ const fieldByKey = useMemo(
198
+ () => new Map(fields.map((field) => [field.key, field])),
199
+ [fields]
200
+ );
201
+ const lockedKey = useMemo(
202
+ () => fields.find((field) => field.pinned)?.key ?? fields[0]?.key ?? "",
203
+ [fields]
204
+ );
205
+ const order = useMemo(() => reconcileOrder(config.order, fields), [config.order, fields]);
206
+ const visible = useMemo(
207
+ () => reconcileVisible(config.visible, fields, lockedKey),
208
+ [config.visible, fields, lockedKey]
209
+ );
210
+
211
+ // Item 22 β€” recomputed only when the three controls move, not on every width drag.
212
+ const tones = useMemo(
213
+ () => columnTones(config),
214
+ [config.filters, config.sorts, config.groupBy] // eslint-disable-line react-hooks/exhaustive-deps
215
+ );
216
+
217
+ const visibleCols = useMemo<GridColumn[]>(
218
+ () =>
219
+ order
220
+ .filter((key) => visible.has(key))
221
+ .map((key) => {
222
+ const field = fieldByKey.get(key)!;
223
+ const width = config.widths[key] ?? DEFAULT_WIDTH;
224
+ // Wave-14 item 2 β€” an INVOLVED column's header paints at 700, so it must be MEASURED
225
+ // at 700. `tones` is already a dep of this memo, so this costs nothing.
226
+ const involved = tones.has(key);
227
+ // R11 β€” the marks this header carries, in the strip's canonical order. Both this
228
+ // reserve and `CustomerGrid.drawGridHeader`'s painting read `headerMarkSizes`, so a
229
+ // column can never reserve room for one mark and then be given two.
230
+ const marks = headerMarkSizes(hasInfoMark(field), field.source === "overlay");
231
+ return {
232
+ id: key,
233
+ // Owner item 16 β€” ELLIPSISED so the title can never run under the (i). Glide
234
+ // truncates nothing: `drawHeaderInner` calls `fillText(c.title, …)` with no clip
235
+ // and no max width, so on a narrow column the name simply painted through the
236
+ // mark. Shortening the title glide is given is the whole fix β€” the alternative,
237
+ // clipping inside `drawHeader`, cuts mid-glyph with no ellipsis to say it did.
238
+ // The FULL name stays reachable: CustomerGrid's header tip leads with it whenever
239
+ // this returns something shorter than `field.label`.
240
+ title: fitHeaderTitle(
241
+ field.label,
242
+ headerLabelSpace(width, marks),
243
+ (text) => measureHeaderText(text, involved)
244
+ ),
245
+ width,
246
+ hasMenu: true,
247
+ menuIcon: "dots",
248
+ // Wave-8 I20 β€” the field-TYPE mark leads every header, so the column says what
249
+ // KIND of thing it holds before you read a single cell (same geometry as the
250
+ // Fields panel's rows β€” icons.tsx).
251
+ icon: typeIconName(field.type),
252
+ // Wave-9 I3 β€” the (i) is NO LONGER `overlayIcon`. Glide draws an overlay at a
253
+ // hard-coded offset from the TYPE mark (drawHeaderInner: `drawX + 9`), i.e.
254
+ // pinned to the far LEFT of the header, and no prop moves it; the owner asked
255
+ // for it right-aligned and centred with the field name. It is drawn instead by
256
+ // CustomerGrid's `drawHeader` callback, which resolves the same
257
+ // `field.note || field.description` condition from the field itself.
258
+ // The hover text is still CustomerGrid's floating tip (pointer-events: none β€”
259
+ // a tooltip must never swallow the next click, [[ui-invisible-to-assertions]]).
260
+ // Wave-14 R4 β€” being INVOLVED in a filter/sort/group is the only thing that tints a
261
+ // column now, and all three tint it the same faint warm grey; the hue that says
262
+ // WHICH control lives on the toolbar chip. User-created ownership moved out of the
263
+ // theme entirely and is the dot drawn in the mark strip (R11).
264
+ themeOverride: columnTheme(tones.get(key)),
265
+ };
266
+ }),
267
+ [order, visible, config.widths, fieldByKey, tones]
268
+ );
269
+
270
+ const onColumnResize = useCallback(
271
+ (column: GridColumn, newSize: number) => {
272
+ if (!column.id) return;
273
+ onConfig({
274
+ ...config,
275
+ widths: { ...config.widths, [column.id]: Math.round(newSize) },
276
+ });
277
+ },
278
+ [config, onConfig]
279
+ );
280
+
281
+ const onColumnMoved = useCallback(
282
+ (from: number, to: number) => {
283
+ if (from === 0 || to === 0) return;
284
+ const visibleKeys = order.filter((key) => visible.has(key));
285
+ if (
286
+ from < 0 ||
287
+ from >= visibleKeys.length ||
288
+ to < 0 ||
289
+ to >= visibleKeys.length
290
+ )
291
+ return;
292
+ const movedKeys = visibleKeys.slice();
293
+ const [moved] = movedKeys.splice(from, 1);
294
+ movedKeys.splice(to, 0, moved);
295
+ let index = 0;
296
+ const nextOrder = order.map((key) =>
297
+ visible.has(key) ? movedKeys[index++] : key
298
+ );
299
+ onConfig({ ...config, order: nextOrder });
300
+ },
301
+ [config, onConfig, order, visible]
302
+ );
303
+
304
+ const onColumnProposeMove = useCallback(
305
+ (from: number, to: number) => from !== 0 && to !== 0,
306
+ []
307
+ );
308
+
309
+ const setColumnVisible = useCallback(
310
+ (key: string, show: boolean) => {
311
+ if (!show && key === lockedKey) return;
312
+ const next = new Set(visible);
313
+ if (show) next.add(key);
314
+ else next.delete(key);
315
+ onConfig({ ...config, visible: [...next] });
316
+ },
317
+ [config, lockedKey, onConfig, visible]
318
+ );
319
+
320
+ const insertColumn = useCallback(
321
+ (key: string, anchorKey: string | null, side: "left" | "right" | "end") => {
322
+ const nextOrder = order.filter((item) => item !== key);
323
+ if (side === "end" || !anchorKey) {
324
+ nextOrder.push(key);
325
+ } else {
326
+ const anchor = Math.max(0, nextOrder.indexOf(anchorKey));
327
+ nextOrder.splice(anchor + (side === "right" ? 1 : 0), 0, key);
328
+ }
329
+ const nextVisible = new Set(visible);
330
+ nextVisible.add(key);
331
+ onConfig({ ...config, order: nextOrder, visible: [...nextVisible] });
332
+ },
333
+ [config, onConfig, order, visible]
334
+ );
335
+
336
+ return {
337
+ visibleCols,
338
+ fieldByKey,
339
+ order,
340
+ visible,
341
+ widths: config.widths,
342
+ lockedKey,
343
+ onColumnResize,
344
+ onColumnMoved,
345
+ onColumnProposeMove,
346
+ setColumnVisible,
347
+ insertColumn,
348
+ };
349
+ }
web/src/customer-grid/viewModes.tsx CHANGED
@@ -1,831 +1,831 @@
1
- // ---------------------------------------------------------------------------
2
- // customer-grid / viewModes.tsx
3
- // Wave-6 item 10 β€” the three DISPLAY MODES beside the grid: List Β· Calendar Β·
4
- // Kanban, plus the switcher the toolbar hosts. All three render the SAME
5
- // pipeline output the grid paints (filter β†’ search β†’ sort β†’ group), so the
6
- // toolbar count, the filters and the sorts mean exactly what they mean on the
7
- // grid; only the projection changes.
8
- //
9
- // Honesty rules carried over:
10
- // - Calendar: records without a date are NEVER silently hidden β€” a
11
- // "N without a date" pill discloses them (rule 8b). Other months are not
12
- // "hidden" either; they are navigable.
13
- // - Kanban: stack counts are the FULL bucket counts; the per-stack render
14
- // cap is stated beside the control that lifts it. A `status` board is
15
- // read-only and says so β€” cards move only on an editable overlay select,
16
- // through the same overlay_patch every other edit door uses.
17
- // - List: grouping renders as real section headers with the group's count;
18
- // the display cap stays the grid's own "Showing first N" bar.
19
- // ---------------------------------------------------------------------------
20
-
21
- import { memo, useMemo, useRef, useState } from "react";
22
- import type { DragEvent } from "react";
23
- import { choiceOptions } from "./types";
24
- import type { DisplayMode, Field, Row, VisibleRow } from "./types";
25
- // Item 4 (C-DISP) β€” the calendar's summary aggregates come from the SAME functions the charts
26
- // use, so a sum in a day cell and a sum in a bar mean the same thing.
27
- import { CHART_AGGS, aggregateOrNull, asChartNumber } from "../viz/chartData";
28
- import type { ChartAgg } from "../viz/chartData";
29
- import { MAX_CALENDAR_METRICS } from "./types";
30
-
31
- /** Item 4 β€” plain words for the aggregates. "avg" is jargon in a picker aimed at a day cell. */
32
- const AGG_LABELS: Record<ChartAgg, string> = {
33
- sum: "Total",
34
- avg: "Average",
35
- count: "Count",
36
- min: "Lowest",
37
- max: "Highest",
38
- };
39
- import { formatDisplay } from "./cells";
40
- import { optionTint } from "./choiceColors";
41
- import { CREATABLE_MODES, MODE_LABELS } from "./iconShapes";
42
- import { LockMark, ModeIcon } from "./icons";
43
- import { FieldSelectButton } from "./FieldSelect";
44
- import { Popover } from "./Toolbar";
45
-
46
- /** Stacks render this many cards before offering "Show all" β€” a stated cap,
47
- * never a silent one (the stack header always carries the full count). */
48
- const KANBAN_PAGE = 50;
49
-
50
- // ------------------------------------------------------------- the switcher
51
-
52
- export function ModeSwitch({
53
- mode,
54
- onMode,
55
- locked = false,
56
- dateField,
57
- dateChoices,
58
- stackField,
59
- stackChoices,
60
- colorField,
61
- colorChoices,
62
- sizeField,
63
- sizeChoices,
64
- onPickField,
65
- clamped = true,
66
- onClamp,
67
- calendarMode = "records",
68
- onCalendarMode,
69
- calendarMetrics = [],
70
- metricChoices = [],
71
- onCalendarMetrics,
72
- }: {
73
- mode: DisplayMode;
74
- onMode: (m: DisplayMode) => void;
75
- /**
76
- * Wave-9 contract C3 (I12) β€” this view's display mode is FROZEN. The trigger stops being a
77
- * dropdown and becomes a label that says so. The field selects below it stay live: C3
78
- * freezes the MODE, and a kanban's stack field is configuration ("filters/sorts/columns
79
- * stay editable"), so removing those too would be a broader lock than the contract grants.
80
- */
81
- locked?: boolean;
82
- /** The calendar's effective date field (resolved by the caller). */
83
- dateField?: Field;
84
- dateChoices: Field[];
85
- /** The kanban's effective stack field (resolved by the caller). */
86
- stackField?: Field;
87
- stackChoices: Field[];
88
- /** Wave-8 I3/I5 β€” the map's encodings, resolved by the caller from the VIEW
89
- * DEF exactly like the two above (never from component state that dies on
90
- * unmount). Both are optional encodings, so both offer a "no encoding" row β€”
91
- * which is why their `<select>`s carry an explicit empty option instead of
92
- * relying on a first option, the wave-7 trap. */
93
- colorField?: Field;
94
- colorChoices: Field[];
95
- sizeField?: Field;
96
- sizeChoices: Field[];
97
- onPickField: (k: "dateField" | "stackField" | "colorField" | "sizeField", key: string) => void;
98
- /** Item 3 (C-DISP) β€” cards are clamped unless the view stored the literal `false`. */
99
- clamped?: boolean;
100
- /** `false` = opt out of the clamp; `undefined` = back to the default (the key comes OFF). */
101
- onClamp?: (next: false | undefined) => void;
102
- /** Item 4 (C-DISP) β€” calendar days list records (default) or show aggregates. */
103
- calendarMode?: "records" | "summary";
104
- onCalendarMode?: (next: "records" | "summary") => void;
105
- /** Item 4 β€” the chosen per-day totals, and the numeric-family fields on offer. */
106
- calendarMetrics?: { id: string; field: string; agg: string }[];
107
- metricChoices?: Field[];
108
- onCalendarMetrics?: (next: { id: string; field: string; agg: string }[]) => void;
109
- }) {
110
- // Wave-7 item W12: the switcher is a DROPDOWN in the toolbar-button family β€” the
111
- // same Popover component Fields/Filter/Sort use, radio rows inside (the Rows/Color
112
- // panel pattern), with the current mode named on the trigger chip.
113
- return (
114
- <span className="cg-modes">
115
- {/* Wave-8 I18 β€” the trigger wears the CURRENT mode's own mark (not a generic
116
- layout glyph), and every row in the list carries its own, so the switcher
117
- is readable at a glance instead of only by its text. */}
118
- {locked ? (
119
- // I12 β€” NOT a disabled button. A greyed dropdown invites a click and then does
120
- // nothing, which reads as broken; this states the fact instead. The title explains
121
- // what is frozen and what is not, because "locked" alone would imply the filters and
122
- // sorts are frozen too, and they are not.
123
- <span
124
- className="cg-modes-locked"
125
- title={`This view is locked as ${MODE_LABELS[mode]}. Filters, sorts and columns are still editable β€” its creator or an admin can unlock it from the view menu.`}
126
- >
127
- <ModeIcon mode={mode} />
128
- <span>View Β· {MODE_LABELS[mode]}</span>
129
- <LockMark />
130
- </span>
131
- ) : (
132
- <Popover
133
- label={`View Β· ${MODE_LABELS[mode]}`}
134
- icon={<ModeIcon mode={mode} />}
135
- active={mode !== "grid"}
136
- >
137
- {(close) => (
138
- <div className="cg-pop-body">
139
- <div className="cg-pop-title">View as</div>
140
- {CREATABLE_MODES.map((m) => (
141
- <label key={m} className="cg-radio-row">
142
- <input
143
- type="radio"
144
- name="cg-viewmode"
145
- checked={mode === m}
146
- onChange={() => {
147
- onMode(m);
148
- close();
149
- }}
150
- />
151
- <ModeIcon mode={m} />
152
- <span>{MODE_LABELS[m]}</span>
153
- </label>
154
- ))}
155
- </div>
156
- )}
157
- </Popover>
158
- )}
159
- {/* Item 20 (C-FLDSEL) β€” the mode bar's field pickers wear the type mark, same control
160
- as the filter and sort rows. These two have no "none" state: a calendar without a
161
- date field and a board without a stack field are not modes, so the picker is never
162
- in its placeholder state here unless the view names a field the table has lost β€”
163
- which it now SHOWS rather than silently replacing with the first choice. */}
164
- {mode === "calendar" && dateChoices.length > 0 && (
165
- <FieldSelectButton
166
- className="cg-mode-field"
167
- ariaLabel="Calendar date field"
168
- value={dateField?.key}
169
- onChange={(key) => onPickField("dateField", key)}
170
- fields={dateChoices.map((f) => ({ key: f.key, label: f.label, type: f.type }))}
171
- />
172
- )}
173
- {mode === "kanban" && stackChoices.length > 0 && (
174
- <FieldSelectButton
175
- className="cg-mode-field"
176
- ariaLabel="Kanban stack field"
177
- value={stackField?.key}
178
- onChange={(key) => onPickField("stackField", key)}
179
- fields={stackChoices.map((f) => ({ key: f.key, label: f.label, type: f.type }))}
180
- />
181
- )}
182
- {/* Owner item 3 (C-DISP) β€” the card-length toggle, beside the stack-field select the
183
- contract names. Cards are CLAMPED by default now (that is the "standardized" the
184
- owner asked for: a lane of same-height cards is scannable, a lane of ragged ones is
185
- not), so this button is the opt-out.
186
-
187
- ⚠ The stored value is the literal `false` and ONLY `false` β€” absent means clamped.
188
- `true` would be a second spelling of the default, and two spellings of one state is
189
- how a save starts churning. That is why the handler sends `false` or `undefined`
190
- rather than a boolean. */}
191
- {mode === "kanban" && onClamp && (
192
- <button
193
- type="button"
194
- className={"cg-tb-btn cg-mode-field" + (clamped ? " is-on" : "")}
195
- aria-pressed={clamped}
196
- onClick={() => onClamp(clamped ? false : undefined)}
197
- title={
198
- clamped
199
- ? "Cards are trimmed to a standard height. Click to let them grow to their content."
200
- : "Cards grow to their content. Click to trim them to a standard height."
201
- }
202
- >
203
- {clamped ? "Short cards" : "Full cards"}
204
- </button>
205
- )}
206
- {/* Owner item 4 (C-DISP) β€” records vs summaries. A toggle rather than a select: there
207
- are exactly two states and the button can say which one you are in. */}
208
- {mode === "calendar" && onCalendarMode && (
209
- <button
210
- type="button"
211
- className={"cg-tb-btn cg-mode-field" + (calendarMode === "summary" ? " is-on" : "")}
212
- aria-pressed={calendarMode === "summary"}
213
- onClick={() => onCalendarMode(calendarMode === "summary" ? "records" : "summary")}
214
- title={
215
- calendarMode === "summary"
216
- ? "Each day shows totals. Click to list the records instead."
217
- : "Each day lists its records. Click to show totals instead."
218
- }
219
- >
220
- {calendarMode === "summary" ? "Summaries" : "Records"}
221
- </button>
222
- )}
223
- {/* Item 4 β€” the metric PICKER, and it is what makes the item's "count/sum/avg" true.
224
- Without it `summaryMetrics` can only ever be the always-on Records count, so a
225
- summary day could say "Records: 3" and nothing else β€” the renderer would be right and
226
- the feature would be half-delivered.
227
-
228
- Only shown in summary mode: a picker for a thing that is not on screen is noise. */}
229
- {mode === "calendar" && calendarMode === "summary" && onCalendarMetrics && (
230
- <Popover
231
- label={`Totals Β· ${calendarMetrics.length + 1}`}
232
- icon={<ModeIcon mode="chart" />}
233
- active={calendarMetrics.length > 0}
234
- >
235
- {() => (
236
- <div className="cg-pop-body">
237
- <div className="cg-pop-title">Totals per day</div>
238
- <div className="cg-pop-note">
239
- Records is always counted β€” every other figure in the cell is computed over it.
240
- Up to {MAX_CALENDAR_METRICS} more.
241
- </div>
242
- {metricChoices.length === 0 && (
243
- <div className="cg-pop-note">
244
- This table has no numeric fields to total.
245
- </div>
246
- )}
247
- {metricChoices.map((f) => {
248
- const chosen = calendarMetrics.find((m) => m.field === f.key);
249
- const full = calendarMetrics.length >= MAX_CALENDAR_METRICS;
250
- return (
251
- <div key={f.key} className="cg-cal-pick">
252
- <label className="cg-check-row">
253
- <input
254
- type="checkbox"
255
- checked={!!chosen}
256
- disabled={!chosen && full}
257
- onChange={() => {
258
- const next = chosen
259
- ? calendarMetrics.filter((m) => m.field !== f.key)
260
- : [
261
- ...calendarMetrics,
262
- { id: `cm_${f.key}`, field: f.key, agg: "sum" },
263
- ];
264
- onCalendarMetrics(next);
265
- }}
266
- />
267
- <span className="cg-check-label">{f.label}</span>
268
- </label>
269
- {chosen && (
270
- <select
271
- className="cg-select"
272
- value={chosen.agg}
273
- aria-label={`How to total ${f.label}`}
274
- onChange={(e) =>
275
- onCalendarMetrics(
276
- calendarMetrics.map((m) =>
277
- m.field === f.key ? { ...m, agg: e.target.value } : m
278
- )
279
- )
280
- }
281
- >
282
- {CHART_AGGS.filter((a) => a !== "count").map((a) => (
283
- <option key={a} value={a}>
284
- {AGG_LABELS[a]}
285
- </option>
286
- ))}
287
- </select>
288
- )}
289
- </div>
290
- );
291
- })}
292
- </div>
293
- )}
294
- </Popover>
295
- )}
296
- {/* The map's two encodings are OPTIONAL, so "none" is a real choice and not merely the
297
- absence of one: it is a row in the list AND the placeholder the button falls back to,
298
- which is the same state said twice on purpose β€” you can see what you would return to
299
- before you pick it. The "Colour: " prefix lived on every option because a native
300
- select had nowhere else to say which encoding it was; the aria-label and the row
301
- carry that now, so the labels are just the field names. */}
302
- {mode === "map" && colorChoices.length > 0 && (
303
- <FieldSelectButton
304
- className="cg-mode-field"
305
- ariaLabel="Colour pins by"
306
- placeholder="Colour: none"
307
- // `?? ""` on purpose: "" is the key of the explicit "No colour" row, so the none
308
- // state MARKS itself in the list instead of leaving every row unmarked.
309
- value={colorField?.key ?? ""}
310
- onChange={(key) => onPickField("colorField", key)}
311
- fields={[
312
- { key: "", label: "No colour", type: undefined },
313
- ...colorChoices.map((f) => ({
314
- key: f.key, label: `Colour: ${f.label}`, type: f.type,
315
- })),
316
- ]}
317
- />
318
- )}
319
- {mode === "map" && sizeChoices.length > 0 && (
320
- <FieldSelectButton
321
- className="cg-mode-field"
322
- ariaLabel="Size pins by"
323
- placeholder="Size: none"
324
- value={sizeField?.key ?? ""}
325
- onChange={(key) => onPickField("sizeField", key)}
326
- fields={[
327
- { key: "", label: "No size", type: undefined },
328
- ...sizeChoices.map((f) => ({
329
- key: f.key, label: `Size: ${f.label}`, type: f.type,
330
- })),
331
- ]}
332
- />
333
- )}
334
- </span>
335
- );
336
- }
337
-
338
- // ------------------------------------------------------------------- list
339
-
340
- /** Item 1 β€” memoised on the same argument; `onToggleGroup` was an inline arrow at the call
341
- * site and is now a useCallback, without which this memo could never bail. */
342
- export const ListView = memo(function ListView({
343
- rows,
344
- fieldByKey,
345
- visibleKeys,
346
- titleKey,
347
- onOpen,
348
- onToggleGroup,
349
- }: {
350
- /** The CAPPED display slice, exactly what the grid would paint β€” the
351
- * "Showing first N" bar below stays the single statement of the cap. */
352
- rows: VisibleRow[];
353
- fieldByKey: Map<string, Field>;
354
- visibleKeys: string[];
355
- titleKey: string;
356
- onOpen: (pid: number) => void;
357
- onToggleGroup: (groupKey: string) => void;
358
- }) {
359
- const inlineKeys = visibleKeys.filter((k) => k !== titleKey);
360
- return (
361
- <div className="cg-listview">
362
- {rows.map((vr, i) => {
363
- if (vr.kind === "group-footer") return null;
364
- if (vr.kind === "group-header") {
365
- return (
366
- <button
367
- type="button"
368
- key={`g:${vr.groupKey}:${i}`}
369
- className="cg-lv-group"
370
- onClick={() => onToggleGroup(vr.groupKey)}
371
- aria-expanded={!vr.collapsed}
372
- >
373
- <span className="cg-lv-chev">{vr.collapsed ? "β–Ά" : "β–Ό"}</span>
374
- <span className="cg-lv-group-label">{vr.label}</span>
375
- <span className="cg-lv-count">{vr.count.toLocaleString()}</span>
376
- </button>
377
- );
378
- }
379
- const r = vr.record;
380
- return (
381
- <button
382
- type="button"
383
- key={`r:${r.pid}:${i}`}
384
- className="cg-lv-row"
385
- onClick={() => onOpen(r.pid)}
386
- >
387
- <span className="cg-lv-title">{String(r[titleKey] ?? "")}</span>
388
- <span className="cg-lv-cells">
389
- {inlineKeys.map((k) => {
390
- const f = fieldByKey.get(k);
391
- if (!f) return null;
392
- const text = formatDisplay(f, r[k]);
393
- if (!text) return null;
394
- return (
395
- <span key={k} className="cg-lv-cell">
396
- <span className="cg-lv-k">{f.label}</span>
397
- <span className="cg-lv-v">{text}</span>
398
- </span>
399
- );
400
- })}
401
- </span>
402
- </button>
403
- );
404
- })}
405
- {rows.length === 0 && (
406
- <div className="cg-mode-empty">No records match this view.</div>
407
- )}
408
- </div>
409
- );
410
- });
411
-
412
- // --------------------------------------------------------------- calendar
413
-
414
- /** "YYYY-MM" arithmetic without a clock: month navigation is pure string/UTC
415
- * math over the anchor the caller supplied (the tenant's today, never
416
- * `new Date()` β€” the [[date-window-vocabulary]] rule). */
417
- function shiftMonth(month: string, delta: number): string {
418
- const y = Number(month.slice(0, 4));
419
- const m = Number(month.slice(5, 7));
420
- const d = new Date(Date.UTC(y, m - 1 + delta, 1));
421
- return d.toISOString().slice(0, 7);
422
- }
423
-
424
- function monthTitle(month: string): string {
425
- const y = Number(month.slice(0, 4));
426
- const m = Number(month.slice(5, 7));
427
- return new Date(Date.UTC(y, m - 1, 1)).toLocaleDateString(undefined, {
428
- month: "long",
429
- year: "numeric",
430
- timeZone: "UTC",
431
- });
432
- }
433
-
434
- /** Item 1 β€” memoised for the same reason as KanbanView below: a whole month of chips must not
435
- * be reconciled again just because the record modal opened. All five props are already
436
- * stable at the call site (`rows` is the `modeDataRows` useMemo, `field` comes out of
437
- * `dateFieldChoices`, `onOpen` is a setState), so this one needed no call-site change. */
438
- export const CalendarView = memo(function CalendarView({
439
- rows,
440
- field,
441
- today,
442
- titleKey,
443
- mode = "records",
444
- metrics,
445
- fieldByKey,
446
- onOpen,
447
- }: {
448
- /** DISTINCT data rows from the full pipeline (never the display slice β€” a
449
- * month is its own bound). */
450
- rows: Row[];
451
- field: Field;
452
- /** The tenant's today, from the payload. Absent = anchor on the data. */
453
- today?: string;
454
- titleKey: string;
455
- /** Item 4 (C-DISP) β€” chips (default) or per-day aggregates. */
456
- mode?: "records" | "summary";
457
- /** The aggregates a summary day shows. Count of records is always shown first. */
458
- metrics?: { id: string; field: string; agg: string }[];
459
- fieldByKey?: Map<string, Field>;
460
- onOpen: (pid: number) => void;
461
- }) {
462
- const entries = useMemo(
463
- () =>
464
- rows.map((r) => ({
465
- pid: r.pid,
466
- title: String(r[titleKey] ?? ""),
467
- day: String(r[field.key] ?? "").slice(0, 10),
468
- row: r,
469
- })),
470
- [rows, field.key, titleKey]
471
- );
472
- const dated = useMemo(
473
- () => entries.filter((e) => /^\d{4}-\d{2}-\d{2}$/.test(e.day)),
474
- [entries]
475
- );
476
- const noDate = entries.length - dated.length;
477
- const anchorMonth = useMemo(() => {
478
- if (today && /^\d{4}-\d{2}/.test(today)) return today.slice(0, 7);
479
- const months = dated.map((e) => e.day.slice(0, 7)).sort();
480
- return months.length ? months[months.length - 1] : null;
481
- }, [today, dated]);
482
- const [month, setMonth] = useState<string | null>(anchorMonth);
483
- const shown = month ?? anchorMonth;
484
-
485
- const byDay = useMemo(() => {
486
- const m = new Map<string, { pid: number; title: string; row: Row }[]>();
487
- if (!shown) return m;
488
- for (const e of dated) {
489
- if (!e.day.startsWith(shown)) continue;
490
- const bucket = m.get(e.day) ?? [];
491
- bucket.push({ pid: e.pid, title: e.title, row: e.row });
492
- m.set(e.day, bucket);
493
- }
494
- return m;
495
- }, [dated, shown]);
496
-
497
- /**
498
- * Item 4 (C-DISP) β€” the aggregates each summary day shows.
499
- *
500
- * Count is ALWAYS first and always present: it is the denominator every other figure in the
501
- * cell is computed over, and a sum with no visible n is a number nobody can check
502
- * ([[no-unverifiable-aggregates]]). A configured metric whose field has gone stale is
503
- * dropped individually, the charts precedent β€” one bad ref must not cost the other three.
504
- *
505
- * `aggregateOrNull` (not the chart `reduce`) is deliberate: a day with no usable values
506
- * renders "β€”", never a 0 that reads as a real measurement.
507
- */
508
- const summaryMetrics = useMemo(() => {
509
- const out: { id: string; label: string; field?: Field; agg: ChartAgg }[] = [
510
- { id: "__count__", label: "Records", agg: "count" },
511
- ];
512
- for (const m of metrics ?? []) {
513
- const f = fieldByKey?.get(m.field);
514
- if (!f) continue;
515
- if (!(CHART_AGGS as readonly string[]).includes(m.agg)) continue;
516
- out.push({ id: m.id, label: f.label, field: f, agg: m.agg as ChartAgg });
517
- }
518
- return out;
519
- }, [metrics, fieldByKey]);
520
-
521
- if (!shown) {
522
- return (
523
- <div className="cg-mode-empty">
524
- No dates to place on a calendar yet.
525
- {noDate > 0 && ` ${noDate.toLocaleString()} record${noDate === 1 ? "" : "s"} carry no date.`}
526
- </div>
527
- );
528
- }
529
-
530
- const y = Number(shown.slice(0, 4));
531
- const m0 = Number(shown.slice(5, 7));
532
- const daysInMonth = new Date(Date.UTC(y, m0, 0)).getUTCDate();
533
- // Monday-start week β€” the date-window vocabulary's convention (week=Monday).
534
- const firstWeekday = (new Date(Date.UTC(y, m0 - 1, 1)).getUTCDay() + 6) % 7;
535
- const cells: (number | null)[] = [
536
- ...Array.from({ length: firstWeekday }, () => null),
537
- ...Array.from({ length: daysInMonth }, (_, i) => i + 1),
538
- ];
539
- while (cells.length % 7 !== 0) cells.push(null);
540
- const monthCount = [...byDay.values()].reduce((n, b) => n + b.length, 0);
541
-
542
- return (
543
- <div className="cg-calview">
544
- <div className="cg-cal-bar">
545
- <button
546
- type="button"
547
- className="cg-btn cg-cal-nav"
548
- aria-label="Previous month"
549
- onClick={() => setMonth(shiftMonth(shown, -1))}
550
- >
551
- β€Ή
552
- </button>
553
- <span className="cg-cal-title">{monthTitle(shown)}</span>
554
- <button
555
- type="button"
556
- className="cg-btn cg-cal-nav"
557
- aria-label="Next month"
558
- onClick={() => setMonth(shiftMonth(shown, 1))}
559
- >
560
- β€Ί
561
- </button>
562
- {/* Item 4 (C-DISP) β€” the DENOMINATOR, stated. In summary mode every figure in every
563
- cell is computed over the records this month PLACED, which is not the same set as
564
- the records the filter matched: a record with no {field.label} is on no day at
565
- all. Saying "N in this month" beside a wall of sums is what keeps those sums
566
- checkable, and the "without a date" chip beside it is the other half of the
567
- sentence. */}
568
- <span className="cg-cal-note">
569
- {mode === "summary"
570
- ? `Totals over ${monthCount.toLocaleString()} record${monthCount === 1 ? "" : "s"} placed this month Β· by ${field.label}`
571
- : `${monthCount.toLocaleString()} in this month Β· by ${field.label}`}
572
- </span>
573
- {noDate > 0 && (
574
- <span
575
- className="cg-cal-nodate"
576
- title={`${noDate.toLocaleString()} matching record${noDate === 1 ? "" : "s"} have no ${field.label} and are not on the calendar. They remain in the Grid and List views.`}
577
- >
578
- {noDate.toLocaleString()} without a date
579
- </span>
580
- )}
581
- </div>
582
- <div className="cg-cal-grid">
583
- {["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"].map((d) => (
584
- <div key={d} className="cg-cal-dow">
585
- {d}
586
- </div>
587
- ))}
588
- {cells.map((day, i) => {
589
- const iso = day ? `${shown}-${String(day).padStart(2, "0")}` : "";
590
- const bucket = day ? byDay.get(iso) ?? [] : [];
591
- return (
592
- <div
593
- key={i}
594
- className={"cg-cal-cell" + (day ? "" : " is-blank") + (iso === today ? " is-today" : "")}
595
- >
596
- {day && <div className="cg-cal-day">{day}</div>}
597
- {mode === "summary"
598
- ? day &&
599
- bucket.length > 0 &&
600
- summaryMetrics.map((m) => {
601
- const vals: number[] = [];
602
- if (m.field)
603
- for (const e of bucket) {
604
- const n = asChartNumber(e.row[m.field.key]);
605
- if (n != null) vals.push(n);
606
- }
607
- const v = aggregateOrNull(m.agg, vals, bucket.length);
608
- return (
609
- <div key={m.id} className="cg-cal-metric">
610
- <span className="cg-cal-metric-k">{m.label}</span>
611
- <span className="cg-cal-metric-v">
612
- {/* "β€”" when the day held no usable value. A 0 here would be a
613
- measurement nobody made. */}
614
- {v == null
615
- ? "β€”"
616
- : v.toLocaleString(undefined, { maximumFractionDigits: 2 })}
617
- </span>
618
- </div>
619
- );
620
- })
621
- : bucket.map((e) => (
622
- <button
623
- key={e.pid}
624
- type="button"
625
- className="cg-cal-chip"
626
- title={e.title}
627
- onClick={() => onOpen(e.pid)}
628
- >
629
- {e.title}
630
- </button>
631
- ))}
632
- </div>
633
- );
634
- })}
635
- </div>
636
- </div>
637
- );
638
- });
639
-
640
- // ----------------------------------------------------------------- kanban
641
-
642
- /**
643
- * Owner item 1 (2026-08-02) β€” "kanban: laggy record-open after load".
644
- *
645
- * MEASURED, not guessed. On the live board a card costs ~11 DOM nodes and one
646
- * `formatDisplay` call per card key (36 cards -> 108 cells -> 403 nodes), and the lane cap is
647
- * per LANE (`KANBAN_PAGE`), not per board β€” so a real book stacked into 8 lanes rebuilds ~400
648
- * cards / ~1,200 cells / ~4,500 elements. That cost is fine ONCE. The defect was that it was
649
- * paid on EVERY CustomerGrid render, because this component was a bare function: clicking a
650
- * card sets `detailPid`, the grid re-renders, and the whole board was reconciled again before
651
- * the modal could paint. The click paid for the board.
652
- *
653
- * `memo` is only half the fix and the other half is at the CALL SITE β€” a memo whose props are
654
- * rebuilt every render never bails. `cardKeys` (a `.filter().slice()`) and `onMove` (an inline
655
- * arrow) are now memoised in CustomerGrid.tsx; `rows`, `field`, `fieldByKey` and the setState
656
- * `onOpen` were already stable. So a `detailPid` change now re-renders the modal and nothing
657
- * else.
658
- *
659
- * Two suspects the split doc listed were DISPROVEN by reading the code, and are recorded so
660
- * nobody re-hunts them: the glide `DataEditor` already unmounts outside grid mode
661
- * (`CustomerGrid.tsx` renders it under `displayMode === "grid"`), and `stacks` below already
662
- * memoised correctly β€” `field` comes out of the `stackFieldChoices` useMemo, so its identity
663
- * is stable and the memo was hitting.
664
- */
665
- export const KanbanView = memo(function KanbanView({
666
- rows,
667
- field,
668
- fieldByKey,
669
- cardKeys,
670
- titleKey,
671
- canMove,
672
- readOnlyReason,
673
- clamped = true,
674
- onMove,
675
- onOpen,
676
- }: {
677
- /** DISTINCT data rows from the full pipeline, overlay edits layered. */
678
- rows: Row[];
679
- field: Field;
680
- fieldByKey: Map<string, Field>;
681
- /** The handful of visible fields each card lists under its title. */
682
- cardKeys: string[];
683
- titleKey: string;
684
- /** True only for an EDITABLE overlay select β€” the one case a drag may write. */
685
- canMove: boolean;
686
- /** Stated when cards cannot move (status = source-computed; permissions). */
687
- readOnlyReason: string | null;
688
- /** Item 3 (C-DISP) β€” trim every card to a standard height. Default ON. */
689
- clamped?: boolean;
690
- onMove: (pid: number, value: string) => void;
691
- onOpen: (pid: number) => void;
692
- }) {
693
- const [expanded, setExpanded] = useState<Set<string>>(new Set());
694
-
695
- const stacks = useMemo(() => {
696
- const order: string[] = field.type === "select" ? [...choiceOptions(field)] : [];
697
- const buckets = new Map<string, Row[]>(order.map((v) => [v, []]));
698
- let blank: Row[] = [];
699
- for (const r of rows) {
700
- const v = String(r[field.key] ?? "").trim();
701
- if (v === "") {
702
- blank.push(r);
703
- continue;
704
- }
705
- let bucket = buckets.get(v);
706
- if (!bucket) {
707
- bucket = [];
708
- buckets.set(v, bucket);
709
- order.push(v);
710
- }
711
- bucket.push(r);
712
- }
713
- const out = order.map((v) => ({ key: v, label: v, rows: buckets.get(v)! }));
714
- // The blank stack renders whenever it has rows β€” and, on an editable
715
- // board, always: it is the drop target that CLEARS a value. "(empty)" is
716
- // the grid grouping's own label for the same bucket.
717
- if (blank.length || canMove) out.push({ key: "", label: "(empty)", rows: blank });
718
- return out;
719
- }, [rows, field, canMove]);
720
-
721
- const onDrop = (stackKey: string) => (e: DragEvent<HTMLDivElement>) => {
722
- e.preventDefault();
723
- const pid = Number(e.dataTransfer.getData("text/plain"));
724
- if (Number.isFinite(pid) && pid > 0) onMove(pid, stackKey);
725
- };
726
-
727
- // Wave-7 item W14 β€” the WHOLE card opens the record, like a calendar chip does.
728
- // A completed DRAG must not read as a click: browsers can deliver a click after
729
- // dragend, so the drag flag suppresses exactly one post-drag click.
730
- const draggedRef = useRef(false);
731
-
732
- return (
733
- <div className={"cg-kbview" + (clamped ? " is-clamped" : "")}>
734
- {readOnlyReason && <div className="cg-kb-note">{readOnlyReason}</div>}
735
- <div className="cg-kb-lanes">
736
- {stacks.map((s) => {
737
- const isOpen = expanded.has(s.key);
738
- const shownRows = isOpen ? s.rows : s.rows.slice(0, KANBAN_PAGE);
739
- const tint = s.key ? optionTint(field, s.key) : undefined;
740
- return (
741
- <div
742
- key={s.key || "(empty)"}
743
- className="cg-kb-lane"
744
- onDragOver={canMove ? (e) => e.preventDefault() : undefined}
745
- onDrop={canMove ? onDrop(s.key) : undefined}
746
- >
747
- <div className="cg-kb-head">
748
- <span
749
- className="cg-kb-pill"
750
- style={tint ? { background: tint.bg, color: tint.fg } : undefined}
751
- >
752
- {s.label}
753
- </span>
754
- <span className="cg-kb-count">{s.rows.length.toLocaleString()}</span>
755
- </div>
756
- <div className="cg-kb-cards">
757
- {shownRows.map((r) => (
758
- <div
759
- key={r.pid}
760
- className={"cg-kb-card" + (canMove ? " is-draggable" : "")}
761
- draggable={canMove}
762
- // W14: the card is the click target β€” role/tabIndex make it a real
763
- // button to the keyboard (Enter/Space), and the drag flag keeps a
764
- // finished drag from also opening the record.
765
- role="button"
766
- tabIndex={0}
767
- aria-label={`Open ${String(r[titleKey] ?? "record")}`}
768
- onClick={() => {
769
- if (draggedRef.current) return;
770
- onOpen(r.pid);
771
- }}
772
- onKeyDown={(e) => {
773
- if (e.key !== "Enter" && e.key !== " ") return;
774
- e.preventDefault();
775
- onOpen(r.pid);
776
- }}
777
- onDragStart={
778
- canMove
779
- ? (e) => {
780
- draggedRef.current = true;
781
- e.dataTransfer.setData("text/plain", String(r.pid));
782
- }
783
- : undefined
784
- }
785
- onDragEnd={
786
- canMove
787
- ? () => {
788
- // Cleared a tick later: the post-drag click (when the
789
- // browser sends one) arrives before this timeout fires.
790
- window.setTimeout(() => {
791
- draggedRef.current = false;
792
- }, 0);
793
- }
794
- : undefined
795
- }
796
- >
797
- <span className="cg-kb-title">{String(r[titleKey] ?? "")}</span>
798
- {cardKeys.map((k) => {
799
- const f = fieldByKey.get(k);
800
- if (!f) return null;
801
- const text = formatDisplay(f, r[k]);
802
- if (!text) return null;
803
- return (
804
- <div key={k} className="cg-kb-cell">
805
- <span className="cg-lv-k">{f.label}</span>
806
- <span className="cg-lv-v">{text}</span>
807
- </div>
808
- );
809
- })}
810
- </div>
811
- ))}
812
- {s.rows.length > KANBAN_PAGE && !isOpen && (
813
- <button
814
- type="button"
815
- className="cg-link-btn cg-kb-more"
816
- onClick={() =>
817
- setExpanded((prev) => new Set(prev).add(s.key))
818
- }
819
- >
820
- Showing first {KANBAN_PAGE} β€” show all{" "}
821
- {s.rows.length.toLocaleString()}
822
- </button>
823
- )}
824
- </div>
825
- </div>
826
- );
827
- })}
828
- </div>
829
- </div>
830
- );
831
- });
 
1
+ // ---------------------------------------------------------------------------
2
+ // customer-grid / viewModes.tsx
3
+ // Wave-6 item 10 β€” the three DISPLAY MODES beside the grid: List Β· Calendar Β·
4
+ // Kanban, plus the switcher the toolbar hosts. All three render the SAME
5
+ // pipeline output the grid paints (filter β†’ search β†’ sort β†’ group), so the
6
+ // toolbar count, the filters and the sorts mean exactly what they mean on the
7
+ // grid; only the projection changes.
8
+ //
9
+ // Honesty rules carried over:
10
+ // - Calendar: records without a date are NEVER silently hidden β€” a
11
+ // "N without a date" pill discloses them (rule 8b). Other months are not
12
+ // "hidden" either; they are navigable.
13
+ // - Kanban: stack counts are the FULL bucket counts; the per-stack render
14
+ // cap is stated beside the control that lifts it. A `status` board is
15
+ // read-only and says so β€” cards move only on an editable overlay select,
16
+ // through the same overlay_patch every other edit door uses.
17
+ // - List: grouping renders as real section headers with the group's count;
18
+ // the display cap stays the grid's own "Showing first N" bar.
19
+ // ---------------------------------------------------------------------------
20
+
21
+ import { memo, useMemo, useRef, useState } from "react";
22
+ import type { DragEvent } from "react";
23
+ import { choiceOptions } from "./types";
24
+ import type { DisplayMode, Field, Row, VisibleRow } from "./types";
25
+ // Item 4 (C-DISP) β€” the calendar's summary aggregates come from the SAME functions the charts
26
+ // use, so a sum in a day cell and a sum in a bar mean the same thing.
27
+ import { CHART_AGGS, aggregateOrNull, asChartNumber } from "../viz/chartData";
28
+ import type { ChartAgg } from "../viz/chartData";
29
+ import { MAX_CALENDAR_METRICS } from "./types";
30
+
31
+ /** Item 4 β€” plain words for the aggregates. "avg" is jargon in a picker aimed at a day cell. */
32
+ const AGG_LABELS: Record<ChartAgg, string> = {
33
+ sum: "Total",
34
+ avg: "Average",
35
+ count: "Count",
36
+ min: "Lowest",
37
+ max: "Highest",
38
+ };
39
+ import { formatDisplay } from "./cells";
40
+ import { optionTint } from "./choiceColors";
41
+ import { CREATABLE_MODES, MODE_LABELS } from "./iconShapes";
42
+ import { LockMark, ModeIcon } from "./icons";
43
+ import { FieldSelectButton } from "./FieldSelect";
44
+ import { Popover } from "../filter-kit";
45
+
46
+ /** Stacks render this many cards before offering "Show all" β€” a stated cap,
47
+ * never a silent one (the stack header always carries the full count). */
48
+ const KANBAN_PAGE = 50;
49
+
50
+ // ------------------------------------------------------------- the switcher
51
+
52
+ export function ModeSwitch({
53
+ mode,
54
+ onMode,
55
+ locked = false,
56
+ dateField,
57
+ dateChoices,
58
+ stackField,
59
+ stackChoices,
60
+ colorField,
61
+ colorChoices,
62
+ sizeField,
63
+ sizeChoices,
64
+ onPickField,
65
+ clamped = true,
66
+ onClamp,
67
+ calendarMode = "records",
68
+ onCalendarMode,
69
+ calendarMetrics = [],
70
+ metricChoices = [],
71
+ onCalendarMetrics,
72
+ }: {
73
+ mode: DisplayMode;
74
+ onMode: (m: DisplayMode) => void;
75
+ /**
76
+ * Wave-9 contract C3 (I12) β€” this view's display mode is FROZEN. The trigger stops being a
77
+ * dropdown and becomes a label that says so. The field selects below it stay live: C3
78
+ * freezes the MODE, and a kanban's stack field is configuration ("filters/sorts/columns
79
+ * stay editable"), so removing those too would be a broader lock than the contract grants.
80
+ */
81
+ locked?: boolean;
82
+ /** The calendar's effective date field (resolved by the caller). */
83
+ dateField?: Field;
84
+ dateChoices: Field[];
85
+ /** The kanban's effective stack field (resolved by the caller). */
86
+ stackField?: Field;
87
+ stackChoices: Field[];
88
+ /** Wave-8 I3/I5 β€” the map's encodings, resolved by the caller from the VIEW
89
+ * DEF exactly like the two above (never from component state that dies on
90
+ * unmount). Both are optional encodings, so both offer a "no encoding" row β€”
91
+ * which is why their `<select>`s carry an explicit empty option instead of
92
+ * relying on a first option, the wave-7 trap. */
93
+ colorField?: Field;
94
+ colorChoices: Field[];
95
+ sizeField?: Field;
96
+ sizeChoices: Field[];
97
+ onPickField: (k: "dateField" | "stackField" | "colorField" | "sizeField", key: string) => void;
98
+ /** Item 3 (C-DISP) β€” cards are clamped unless the view stored the literal `false`. */
99
+ clamped?: boolean;
100
+ /** `false` = opt out of the clamp; `undefined` = back to the default (the key comes OFF). */
101
+ onClamp?: (next: false | undefined) => void;
102
+ /** Item 4 (C-DISP) β€” calendar days list records (default) or show aggregates. */
103
+ calendarMode?: "records" | "summary";
104
+ onCalendarMode?: (next: "records" | "summary") => void;
105
+ /** Item 4 β€” the chosen per-day totals, and the numeric-family fields on offer. */
106
+ calendarMetrics?: { id: string; field: string; agg: string }[];
107
+ metricChoices?: Field[];
108
+ onCalendarMetrics?: (next: { id: string; field: string; agg: string }[]) => void;
109
+ }) {
110
+ // Wave-7 item W12: the switcher is a DROPDOWN in the toolbar-button family β€” the
111
+ // same Popover component Fields/Filter/Sort use, radio rows inside (the Rows/Color
112
+ // panel pattern), with the current mode named on the trigger chip.
113
+ return (
114
+ <span className="cg-modes">
115
+ {/* Wave-8 I18 β€” the trigger wears the CURRENT mode's own mark (not a generic
116
+ layout glyph), and every row in the list carries its own, so the switcher
117
+ is readable at a glance instead of only by its text. */}
118
+ {locked ? (
119
+ // I12 β€” NOT a disabled button. A greyed dropdown invites a click and then does
120
+ // nothing, which reads as broken; this states the fact instead. The title explains
121
+ // what is frozen and what is not, because "locked" alone would imply the filters and
122
+ // sorts are frozen too, and they are not.
123
+ <span
124
+ className="cg-modes-locked"
125
+ title={`This view is locked as ${MODE_LABELS[mode]}. Filters, sorts and columns are still editable β€” its creator or an admin can unlock it from the view menu.`}
126
+ >
127
+ <ModeIcon mode={mode} />
128
+ <span>View Β· {MODE_LABELS[mode]}</span>
129
+ <LockMark />
130
+ </span>
131
+ ) : (
132
+ <Popover
133
+ label={`View Β· ${MODE_LABELS[mode]}`}
134
+ icon={<ModeIcon mode={mode} />}
135
+ active={mode !== "grid"}
136
+ >
137
+ {(close) => (
138
+ <div className="cg-pop-body">
139
+ <div className="cg-pop-title">View as</div>
140
+ {CREATABLE_MODES.map((m) => (
141
+ <label key={m} className="cg-radio-row">
142
+ <input
143
+ type="radio"
144
+ name="cg-viewmode"
145
+ checked={mode === m}
146
+ onChange={() => {
147
+ onMode(m);
148
+ close();
149
+ }}
150
+ />
151
+ <ModeIcon mode={m} />
152
+ <span>{MODE_LABELS[m]}</span>
153
+ </label>
154
+ ))}
155
+ </div>
156
+ )}
157
+ </Popover>
158
+ )}
159
+ {/* Item 20 (C-FLDSEL) β€” the mode bar's field pickers wear the type mark, same control
160
+ as the filter and sort rows. These two have no "none" state: a calendar without a
161
+ date field and a board without a stack field are not modes, so the picker is never
162
+ in its placeholder state here unless the view names a field the table has lost β€”
163
+ which it now SHOWS rather than silently replacing with the first choice. */}
164
+ {mode === "calendar" && dateChoices.length > 0 && (
165
+ <FieldSelectButton
166
+ className="cg-mode-field"
167
+ ariaLabel="Calendar date field"
168
+ value={dateField?.key}
169
+ onChange={(key) => onPickField("dateField", key)}
170
+ fields={dateChoices.map((f) => ({ key: f.key, label: f.label, type: f.type }))}
171
+ />
172
+ )}
173
+ {mode === "kanban" && stackChoices.length > 0 && (
174
+ <FieldSelectButton
175
+ className="cg-mode-field"
176
+ ariaLabel="Kanban stack field"
177
+ value={stackField?.key}
178
+ onChange={(key) => onPickField("stackField", key)}
179
+ fields={stackChoices.map((f) => ({ key: f.key, label: f.label, type: f.type }))}
180
+ />
181
+ )}
182
+ {/* Owner item 3 (C-DISP) β€” the card-length toggle, beside the stack-field select the
183
+ contract names. Cards are CLAMPED by default now (that is the "standardized" the
184
+ owner asked for: a lane of same-height cards is scannable, a lane of ragged ones is
185
+ not), so this button is the opt-out.
186
+
187
+ ⚠ The stored value is the literal `false` and ONLY `false` β€” absent means clamped.
188
+ `true` would be a second spelling of the default, and two spellings of one state is
189
+ how a save starts churning. That is why the handler sends `false` or `undefined`
190
+ rather than a boolean. */}
191
+ {mode === "kanban" && onClamp && (
192
+ <button
193
+ type="button"
194
+ className={"cg-tb-btn cg-mode-field" + (clamped ? " is-on" : "")}
195
+ aria-pressed={clamped}
196
+ onClick={() => onClamp(clamped ? false : undefined)}
197
+ title={
198
+ clamped
199
+ ? "Cards are trimmed to a standard height. Click to let them grow to their content."
200
+ : "Cards grow to their content. Click to trim them to a standard height."
201
+ }
202
+ >
203
+ {clamped ? "Short cards" : "Full cards"}
204
+ </button>
205
+ )}
206
+ {/* Owner item 4 (C-DISP) β€” records vs summaries. A toggle rather than a select: there
207
+ are exactly two states and the button can say which one you are in. */}
208
+ {mode === "calendar" && onCalendarMode && (
209
+ <button
210
+ type="button"
211
+ className={"cg-tb-btn cg-mode-field" + (calendarMode === "summary" ? " is-on" : "")}
212
+ aria-pressed={calendarMode === "summary"}
213
+ onClick={() => onCalendarMode(calendarMode === "summary" ? "records" : "summary")}
214
+ title={
215
+ calendarMode === "summary"
216
+ ? "Each day shows totals. Click to list the records instead."
217
+ : "Each day lists its records. Click to show totals instead."
218
+ }
219
+ >
220
+ {calendarMode === "summary" ? "Summaries" : "Records"}
221
+ </button>
222
+ )}
223
+ {/* Item 4 β€” the metric PICKER, and it is what makes the item's "count/sum/avg" true.
224
+ Without it `summaryMetrics` can only ever be the always-on Records count, so a
225
+ summary day could say "Records: 3" and nothing else β€” the renderer would be right and
226
+ the feature would be half-delivered.
227
+
228
+ Only shown in summary mode: a picker for a thing that is not on screen is noise. */}
229
+ {mode === "calendar" && calendarMode === "summary" && onCalendarMetrics && (
230
+ <Popover
231
+ label={`Totals Β· ${calendarMetrics.length + 1}`}
232
+ icon={<ModeIcon mode="chart" />}
233
+ active={calendarMetrics.length > 0}
234
+ >
235
+ {() => (
236
+ <div className="cg-pop-body">
237
+ <div className="cg-pop-title">Totals per day</div>
238
+ <div className="cg-pop-note">
239
+ Records is always counted β€” every other figure in the cell is computed over it.
240
+ Up to {MAX_CALENDAR_METRICS} more.
241
+ </div>
242
+ {metricChoices.length === 0 && (
243
+ <div className="cg-pop-note">
244
+ This table has no numeric fields to total.
245
+ </div>
246
+ )}
247
+ {metricChoices.map((f) => {
248
+ const chosen = calendarMetrics.find((m) => m.field === f.key);
249
+ const full = calendarMetrics.length >= MAX_CALENDAR_METRICS;
250
+ return (
251
+ <div key={f.key} className="cg-cal-pick">
252
+ <label className="cg-check-row">
253
+ <input
254
+ type="checkbox"
255
+ checked={!!chosen}
256
+ disabled={!chosen && full}
257
+ onChange={() => {
258
+ const next = chosen
259
+ ? calendarMetrics.filter((m) => m.field !== f.key)
260
+ : [
261
+ ...calendarMetrics,
262
+ { id: `cm_${f.key}`, field: f.key, agg: "sum" },
263
+ ];
264
+ onCalendarMetrics(next);
265
+ }}
266
+ />
267
+ <span className="cg-check-label">{f.label}</span>
268
+ </label>
269
+ {chosen && (
270
+ <select
271
+ className="cg-select"
272
+ value={chosen.agg}
273
+ aria-label={`How to total ${f.label}`}
274
+ onChange={(e) =>
275
+ onCalendarMetrics(
276
+ calendarMetrics.map((m) =>
277
+ m.field === f.key ? { ...m, agg: e.target.value } : m
278
+ )
279
+ )
280
+ }
281
+ >
282
+ {CHART_AGGS.filter((a) => a !== "count").map((a) => (
283
+ <option key={a} value={a}>
284
+ {AGG_LABELS[a]}
285
+ </option>
286
+ ))}
287
+ </select>
288
+ )}
289
+ </div>
290
+ );
291
+ })}
292
+ </div>
293
+ )}
294
+ </Popover>
295
+ )}
296
+ {/* The map's two encodings are OPTIONAL, so "none" is a real choice and not merely the
297
+ absence of one: it is a row in the list AND the placeholder the button falls back to,
298
+ which is the same state said twice on purpose β€” you can see what you would return to
299
+ before you pick it. The "Colour: " prefix lived on every option because a native
300
+ select had nowhere else to say which encoding it was; the aria-label and the row
301
+ carry that now, so the labels are just the field names. */}
302
+ {mode === "map" && colorChoices.length > 0 && (
303
+ <FieldSelectButton
304
+ className="cg-mode-field"
305
+ ariaLabel="Colour pins by"
306
+ placeholder="Colour: none"
307
+ // `?? ""` on purpose: "" is the key of the explicit "No colour" row, so the none
308
+ // state MARKS itself in the list instead of leaving every row unmarked.
309
+ value={colorField?.key ?? ""}
310
+ onChange={(key) => onPickField("colorField", key)}
311
+ fields={[
312
+ { key: "", label: "No colour", type: undefined },
313
+ ...colorChoices.map((f) => ({
314
+ key: f.key, label: `Colour: ${f.label}`, type: f.type,
315
+ })),
316
+ ]}
317
+ />
318
+ )}
319
+ {mode === "map" && sizeChoices.length > 0 && (
320
+ <FieldSelectButton
321
+ className="cg-mode-field"
322
+ ariaLabel="Size pins by"
323
+ placeholder="Size: none"
324
+ value={sizeField?.key ?? ""}
325
+ onChange={(key) => onPickField("sizeField", key)}
326
+ fields={[
327
+ { key: "", label: "No size", type: undefined },
328
+ ...sizeChoices.map((f) => ({
329
+ key: f.key, label: `Size: ${f.label}`, type: f.type,
330
+ })),
331
+ ]}
332
+ />
333
+ )}
334
+ </span>
335
+ );
336
+ }
337
+
338
+ // ------------------------------------------------------------------- list
339
+
340
+ /** Item 1 β€” memoised on the same argument; `onToggleGroup` was an inline arrow at the call
341
+ * site and is now a useCallback, without which this memo could never bail. */
342
+ export const ListView = memo(function ListView({
343
+ rows,
344
+ fieldByKey,
345
+ visibleKeys,
346
+ titleKey,
347
+ onOpen,
348
+ onToggleGroup,
349
+ }: {
350
+ /** The CAPPED display slice, exactly what the grid would paint β€” the
351
+ * "Showing first N" bar below stays the single statement of the cap. */
352
+ rows: VisibleRow[];
353
+ fieldByKey: Map<string, Field>;
354
+ visibleKeys: string[];
355
+ titleKey: string;
356
+ onOpen: (pid: number) => void;
357
+ onToggleGroup: (groupKey: string) => void;
358
+ }) {
359
+ const inlineKeys = visibleKeys.filter((k) => k !== titleKey);
360
+ return (
361
+ <div className="cg-listview">
362
+ {rows.map((vr, i) => {
363
+ if (vr.kind === "group-footer") return null;
364
+ if (vr.kind === "group-header") {
365
+ return (
366
+ <button
367
+ type="button"
368
+ key={`g:${vr.groupKey}:${i}`}
369
+ className="cg-lv-group"
370
+ onClick={() => onToggleGroup(vr.groupKey)}
371
+ aria-expanded={!vr.collapsed}
372
+ >
373
+ <span className="cg-lv-chev">{vr.collapsed ? "β–Ά" : "β–Ό"}</span>
374
+ <span className="cg-lv-group-label">{vr.label}</span>
375
+ <span className="cg-lv-count">{vr.count.toLocaleString()}</span>
376
+ </button>
377
+ );
378
+ }
379
+ const r = vr.record;
380
+ return (
381
+ <button
382
+ type="button"
383
+ key={`r:${r.pid}:${i}`}
384
+ className="cg-lv-row"
385
+ onClick={() => onOpen(r.pid)}
386
+ >
387
+ <span className="cg-lv-title">{String(r[titleKey] ?? "")}</span>
388
+ <span className="cg-lv-cells">
389
+ {inlineKeys.map((k) => {
390
+ const f = fieldByKey.get(k);
391
+ if (!f) return null;
392
+ const text = formatDisplay(f, r[k]);
393
+ if (!text) return null;
394
+ return (
395
+ <span key={k} className="cg-lv-cell">
396
+ <span className="cg-lv-k">{f.label}</span>
397
+ <span className="cg-lv-v">{text}</span>
398
+ </span>
399
+ );
400
+ })}
401
+ </span>
402
+ </button>
403
+ );
404
+ })}
405
+ {rows.length === 0 && (
406
+ <div className="cg-mode-empty">No records match this view.</div>
407
+ )}
408
+ </div>
409
+ );
410
+ });
411
+
412
+ // --------------------------------------------------------------- calendar
413
+
414
+ /** "YYYY-MM" arithmetic without a clock: month navigation is pure string/UTC
415
+ * math over the anchor the caller supplied (the tenant's today, never
416
+ * `new Date()` β€” the [[date-window-vocabulary]] rule). */
417
+ function shiftMonth(month: string, delta: number): string {
418
+ const y = Number(month.slice(0, 4));
419
+ const m = Number(month.slice(5, 7));
420
+ const d = new Date(Date.UTC(y, m - 1 + delta, 1));
421
+ return d.toISOString().slice(0, 7);
422
+ }
423
+
424
+ function monthTitle(month: string): string {
425
+ const y = Number(month.slice(0, 4));
426
+ const m = Number(month.slice(5, 7));
427
+ return new Date(Date.UTC(y, m - 1, 1)).toLocaleDateString(undefined, {
428
+ month: "long",
429
+ year: "numeric",
430
+ timeZone: "UTC",
431
+ });
432
+ }
433
+
434
+ /** Item 1 β€” memoised for the same reason as KanbanView below: a whole month of chips must not
435
+ * be reconciled again just because the record modal opened. All five props are already
436
+ * stable at the call site (`rows` is the `modeDataRows` useMemo, `field` comes out of
437
+ * `dateFieldChoices`, `onOpen` is a setState), so this one needed no call-site change. */
438
+ export const CalendarView = memo(function CalendarView({
439
+ rows,
440
+ field,
441
+ today,
442
+ titleKey,
443
+ mode = "records",
444
+ metrics,
445
+ fieldByKey,
446
+ onOpen,
447
+ }: {
448
+ /** DISTINCT data rows from the full pipeline (never the display slice β€” a
449
+ * month is its own bound). */
450
+ rows: Row[];
451
+ field: Field;
452
+ /** The tenant's today, from the payload. Absent = anchor on the data. */
453
+ today?: string;
454
+ titleKey: string;
455
+ /** Item 4 (C-DISP) β€” chips (default) or per-day aggregates. */
456
+ mode?: "records" | "summary";
457
+ /** The aggregates a summary day shows. Count of records is always shown first. */
458
+ metrics?: { id: string; field: string; agg: string }[];
459
+ fieldByKey?: Map<string, Field>;
460
+ onOpen: (pid: number) => void;
461
+ }) {
462
+ const entries = useMemo(
463
+ () =>
464
+ rows.map((r) => ({
465
+ pid: r.pid,
466
+ title: String(r[titleKey] ?? ""),
467
+ day: String(r[field.key] ?? "").slice(0, 10),
468
+ row: r,
469
+ })),
470
+ [rows, field.key, titleKey]
471
+ );
472
+ const dated = useMemo(
473
+ () => entries.filter((e) => /^\d{4}-\d{2}-\d{2}$/.test(e.day)),
474
+ [entries]
475
+ );
476
+ const noDate = entries.length - dated.length;
477
+ const anchorMonth = useMemo(() => {
478
+ if (today && /^\d{4}-\d{2}/.test(today)) return today.slice(0, 7);
479
+ const months = dated.map((e) => e.day.slice(0, 7)).sort();
480
+ return months.length ? months[months.length - 1] : null;
481
+ }, [today, dated]);
482
+ const [month, setMonth] = useState<string | null>(anchorMonth);
483
+ const shown = month ?? anchorMonth;
484
+
485
+ const byDay = useMemo(() => {
486
+ const m = new Map<string, { pid: number; title: string; row: Row }[]>();
487
+ if (!shown) return m;
488
+ for (const e of dated) {
489
+ if (!e.day.startsWith(shown)) continue;
490
+ const bucket = m.get(e.day) ?? [];
491
+ bucket.push({ pid: e.pid, title: e.title, row: e.row });
492
+ m.set(e.day, bucket);
493
+ }
494
+ return m;
495
+ }, [dated, shown]);
496
+
497
+ /**
498
+ * Item 4 (C-DISP) β€” the aggregates each summary day shows.
499
+ *
500
+ * Count is ALWAYS first and always present: it is the denominator every other figure in the
501
+ * cell is computed over, and a sum with no visible n is a number nobody can check
502
+ * ([[no-unverifiable-aggregates]]). A configured metric whose field has gone stale is
503
+ * dropped individually, the charts precedent β€” one bad ref must not cost the other three.
504
+ *
505
+ * `aggregateOrNull` (not the chart `reduce`) is deliberate: a day with no usable values
506
+ * renders "β€”", never a 0 that reads as a real measurement.
507
+ */
508
+ const summaryMetrics = useMemo(() => {
509
+ const out: { id: string; label: string; field?: Field; agg: ChartAgg }[] = [
510
+ { id: "__count__", label: "Records", agg: "count" },
511
+ ];
512
+ for (const m of metrics ?? []) {
513
+ const f = fieldByKey?.get(m.field);
514
+ if (!f) continue;
515
+ if (!(CHART_AGGS as readonly string[]).includes(m.agg)) continue;
516
+ out.push({ id: m.id, label: f.label, field: f, agg: m.agg as ChartAgg });
517
+ }
518
+ return out;
519
+ }, [metrics, fieldByKey]);
520
+
521
+ if (!shown) {
522
+ return (
523
+ <div className="cg-mode-empty">
524
+ No dates to place on a calendar yet.
525
+ {noDate > 0 && ` ${noDate.toLocaleString()} record${noDate === 1 ? "" : "s"} carry no date.`}
526
+ </div>
527
+ );
528
+ }
529
+
530
+ const y = Number(shown.slice(0, 4));
531
+ const m0 = Number(shown.slice(5, 7));
532
+ const daysInMonth = new Date(Date.UTC(y, m0, 0)).getUTCDate();
533
+ // Monday-start week β€” the date-window vocabulary's convention (week=Monday).
534
+ const firstWeekday = (new Date(Date.UTC(y, m0 - 1, 1)).getUTCDay() + 6) % 7;
535
+ const cells: (number | null)[] = [
536
+ ...Array.from({ length: firstWeekday }, () => null),
537
+ ...Array.from({ length: daysInMonth }, (_, i) => i + 1),
538
+ ];
539
+ while (cells.length % 7 !== 0) cells.push(null);
540
+ const monthCount = [...byDay.values()].reduce((n, b) => n + b.length, 0);
541
+
542
+ return (
543
+ <div className="cg-calview">
544
+ <div className="cg-cal-bar">
545
+ <button
546
+ type="button"
547
+ className="cg-btn cg-cal-nav"
548
+ aria-label="Previous month"
549
+ onClick={() => setMonth(shiftMonth(shown, -1))}
550
+ >
551
+ β€Ή
552
+ </button>
553
+ <span className="cg-cal-title">{monthTitle(shown)}</span>
554
+ <button
555
+ type="button"
556
+ className="cg-btn cg-cal-nav"
557
+ aria-label="Next month"
558
+ onClick={() => setMonth(shiftMonth(shown, 1))}
559
+ >
560
+ β€Ί
561
+ </button>
562
+ {/* Item 4 (C-DISP) β€” the DENOMINATOR, stated. In summary mode every figure in every
563
+ cell is computed over the records this month PLACED, which is not the same set as
564
+ the records the filter matched: a record with no {field.label} is on no day at
565
+ all. Saying "N in this month" beside a wall of sums is what keeps those sums
566
+ checkable, and the "without a date" chip beside it is the other half of the
567
+ sentence. */}
568
+ <span className="cg-cal-note">
569
+ {mode === "summary"
570
+ ? `Totals over ${monthCount.toLocaleString()} record${monthCount === 1 ? "" : "s"} placed this month Β· by ${field.label}`
571
+ : `${monthCount.toLocaleString()} in this month Β· by ${field.label}`}
572
+ </span>
573
+ {noDate > 0 && (
574
+ <span
575
+ className="cg-cal-nodate"
576
+ title={`${noDate.toLocaleString()} matching record${noDate === 1 ? "" : "s"} have no ${field.label} and are not on the calendar. They remain in the Grid and List views.`}
577
+ >
578
+ {noDate.toLocaleString()} without a date
579
+ </span>
580
+ )}
581
+ </div>
582
+ <div className="cg-cal-grid">
583
+ {["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"].map((d) => (
584
+ <div key={d} className="cg-cal-dow">
585
+ {d}
586
+ </div>
587
+ ))}
588
+ {cells.map((day, i) => {
589
+ const iso = day ? `${shown}-${String(day).padStart(2, "0")}` : "";
590
+ const bucket = day ? byDay.get(iso) ?? [] : [];
591
+ return (
592
+ <div
593
+ key={i}
594
+ className={"cg-cal-cell" + (day ? "" : " is-blank") + (iso === today ? " is-today" : "")}
595
+ >
596
+ {day && <div className="cg-cal-day">{day}</div>}
597
+ {mode === "summary"
598
+ ? day &&
599
+ bucket.length > 0 &&
600
+ summaryMetrics.map((m) => {
601
+ const vals: number[] = [];
602
+ if (m.field)
603
+ for (const e of bucket) {
604
+ const n = asChartNumber(e.row[m.field.key]);
605
+ if (n != null) vals.push(n);
606
+ }
607
+ const v = aggregateOrNull(m.agg, vals, bucket.length);
608
+ return (
609
+ <div key={m.id} className="cg-cal-metric">
610
+ <span className="cg-cal-metric-k">{m.label}</span>
611
+ <span className="cg-cal-metric-v">
612
+ {/* "β€”" when the day held no usable value. A 0 here would be a
613
+ measurement nobody made. */}
614
+ {v == null
615
+ ? "β€”"
616
+ : v.toLocaleString(undefined, { maximumFractionDigits: 2 })}
617
+ </span>
618
+ </div>
619
+ );
620
+ })
621
+ : bucket.map((e) => (
622
+ <button
623
+ key={e.pid}
624
+ type="button"
625
+ className="cg-cal-chip"
626
+ title={e.title}
627
+ onClick={() => onOpen(e.pid)}
628
+ >
629
+ {e.title}
630
+ </button>
631
+ ))}
632
+ </div>
633
+ );
634
+ })}
635
+ </div>
636
+ </div>
637
+ );
638
+ });
639
+
640
+ // ----------------------------------------------------------------- kanban
641
+
642
+ /**
643
+ * Owner item 1 (2026-08-02) β€” "kanban: laggy record-open after load".
644
+ *
645
+ * MEASURED, not guessed. On the live board a card costs ~11 DOM nodes and one
646
+ * `formatDisplay` call per card key (36 cards -> 108 cells -> 403 nodes), and the lane cap is
647
+ * per LANE (`KANBAN_PAGE`), not per board β€” so a real book stacked into 8 lanes rebuilds ~400
648
+ * cards / ~1,200 cells / ~4,500 elements. That cost is fine ONCE. The defect was that it was
649
+ * paid on EVERY CustomerGrid render, because this component was a bare function: clicking a
650
+ * card sets `detailPid`, the grid re-renders, and the whole board was reconciled again before
651
+ * the modal could paint. The click paid for the board.
652
+ *
653
+ * `memo` is only half the fix and the other half is at the CALL SITE β€” a memo whose props are
654
+ * rebuilt every render never bails. `cardKeys` (a `.filter().slice()`) and `onMove` (an inline
655
+ * arrow) are now memoised in CustomerGrid.tsx; `rows`, `field`, `fieldByKey` and the setState
656
+ * `onOpen` were already stable. So a `detailPid` change now re-renders the modal and nothing
657
+ * else.
658
+ *
659
+ * Two suspects the split doc listed were DISPROVEN by reading the code, and are recorded so
660
+ * nobody re-hunts them: the glide `DataEditor` already unmounts outside grid mode
661
+ * (`CustomerGrid.tsx` renders it under `displayMode === "grid"`), and `stacks` below already
662
+ * memoised correctly β€” `field` comes out of the `stackFieldChoices` useMemo, so its identity
663
+ * is stable and the memo was hitting.
664
+ */
665
+ export const KanbanView = memo(function KanbanView({
666
+ rows,
667
+ field,
668
+ fieldByKey,
669
+ cardKeys,
670
+ titleKey,
671
+ canMove,
672
+ readOnlyReason,
673
+ clamped = true,
674
+ onMove,
675
+ onOpen,
676
+ }: {
677
+ /** DISTINCT data rows from the full pipeline, overlay edits layered. */
678
+ rows: Row[];
679
+ field: Field;
680
+ fieldByKey: Map<string, Field>;
681
+ /** The handful of visible fields each card lists under its title. */
682
+ cardKeys: string[];
683
+ titleKey: string;
684
+ /** True only for an EDITABLE overlay select β€” the one case a drag may write. */
685
+ canMove: boolean;
686
+ /** Stated when cards cannot move (status = source-computed; permissions). */
687
+ readOnlyReason: string | null;
688
+ /** Item 3 (C-DISP) β€” trim every card to a standard height. Default ON. */
689
+ clamped?: boolean;
690
+ onMove: (pid: number, value: string) => void;
691
+ onOpen: (pid: number) => void;
692
+ }) {
693
+ const [expanded, setExpanded] = useState<Set<string>>(new Set());
694
+
695
+ const stacks = useMemo(() => {
696
+ const order: string[] = field.type === "select" ? [...choiceOptions(field)] : [];
697
+ const buckets = new Map<string, Row[]>(order.map((v) => [v, []]));
698
+ let blank: Row[] = [];
699
+ for (const r of rows) {
700
+ const v = String(r[field.key] ?? "").trim();
701
+ if (v === "") {
702
+ blank.push(r);
703
+ continue;
704
+ }
705
+ let bucket = buckets.get(v);
706
+ if (!bucket) {
707
+ bucket = [];
708
+ buckets.set(v, bucket);
709
+ order.push(v);
710
+ }
711
+ bucket.push(r);
712
+ }
713
+ const out = order.map((v) => ({ key: v, label: v, rows: buckets.get(v)! }));
714
+ // The blank stack renders whenever it has rows β€” and, on an editable
715
+ // board, always: it is the drop target that CLEARS a value. "(empty)" is
716
+ // the grid grouping's own label for the same bucket.
717
+ if (blank.length || canMove) out.push({ key: "", label: "(empty)", rows: blank });
718
+ return out;
719
+ }, [rows, field, canMove]);
720
+
721
+ const onDrop = (stackKey: string) => (e: DragEvent<HTMLDivElement>) => {
722
+ e.preventDefault();
723
+ const pid = Number(e.dataTransfer.getData("text/plain"));
724
+ if (Number.isFinite(pid) && pid > 0) onMove(pid, stackKey);
725
+ };
726
+
727
+ // Wave-7 item W14 β€” the WHOLE card opens the record, like a calendar chip does.
728
+ // A completed DRAG must not read as a click: browsers can deliver a click after
729
+ // dragend, so the drag flag suppresses exactly one post-drag click.
730
+ const draggedRef = useRef(false);
731
+
732
+ return (
733
+ <div className={"cg-kbview" + (clamped ? " is-clamped" : "")}>
734
+ {readOnlyReason && <div className="cg-kb-note">{readOnlyReason}</div>}
735
+ <div className="cg-kb-lanes">
736
+ {stacks.map((s) => {
737
+ const isOpen = expanded.has(s.key);
738
+ const shownRows = isOpen ? s.rows : s.rows.slice(0, KANBAN_PAGE);
739
+ const tint = s.key ? optionTint(field, s.key) : undefined;
740
+ return (
741
+ <div
742
+ key={s.key || "(empty)"}
743
+ className="cg-kb-lane"
744
+ onDragOver={canMove ? (e) => e.preventDefault() : undefined}
745
+ onDrop={canMove ? onDrop(s.key) : undefined}
746
+ >
747
+ <div className="cg-kb-head">
748
+ <span
749
+ className="cg-kb-pill"
750
+ style={tint ? { background: tint.bg, color: tint.fg } : undefined}
751
+ >
752
+ {s.label}
753
+ </span>
754
+ <span className="cg-kb-count">{s.rows.length.toLocaleString()}</span>
755
+ </div>
756
+ <div className="cg-kb-cards">
757
+ {shownRows.map((r) => (
758
+ <div
759
+ key={r.pid}
760
+ className={"cg-kb-card" + (canMove ? " is-draggable" : "")}
761
+ draggable={canMove}
762
+ // W14: the card is the click target β€” role/tabIndex make it a real
763
+ // button to the keyboard (Enter/Space), and the drag flag keeps a
764
+ // finished drag from also opening the record.
765
+ role="button"
766
+ tabIndex={0}
767
+ aria-label={`Open ${String(r[titleKey] ?? "record")}`}
768
+ onClick={() => {
769
+ if (draggedRef.current) return;
770
+ onOpen(r.pid);
771
+ }}
772
+ onKeyDown={(e) => {
773
+ if (e.key !== "Enter" && e.key !== " ") return;
774
+ e.preventDefault();
775
+ onOpen(r.pid);
776
+ }}
777
+ onDragStart={
778
+ canMove
779
+ ? (e) => {
780
+ draggedRef.current = true;
781
+ e.dataTransfer.setData("text/plain", String(r.pid));
782
+ }
783
+ : undefined
784
+ }
785
+ onDragEnd={
786
+ canMove
787
+ ? () => {
788
+ // Cleared a tick later: the post-drag click (when the
789
+ // browser sends one) arrives before this timeout fires.
790
+ window.setTimeout(() => {
791
+ draggedRef.current = false;
792
+ }, 0);
793
+ }
794
+ : undefined
795
+ }
796
+ >
797
+ <span className="cg-kb-title">{String(r[titleKey] ?? "")}</span>
798
+ {cardKeys.map((k) => {
799
+ const f = fieldByKey.get(k);
800
+ if (!f) return null;
801
+ const text = formatDisplay(f, r[k]);
802
+ if (!text) return null;
803
+ return (
804
+ <div key={k} className="cg-kb-cell">
805
+ <span className="cg-lv-k">{f.label}</span>
806
+ <span className="cg-lv-v">{text}</span>
807
+ </div>
808
+ );
809
+ })}
810
+ </div>
811
+ ))}
812
+ {s.rows.length > KANBAN_PAGE && !isOpen && (
813
+ <button
814
+ type="button"
815
+ className="cg-link-btn cg-kb-more"
816
+ onClick={() =>
817
+ setExpanded((prev) => new Set(prev).add(s.key))
818
+ }
819
+ >
820
+ Showing first {KANBAN_PAGE} β€” show all{" "}
821
+ {s.rows.length.toLocaleString()}
822
+ </button>
823
+ )}
824
+ </div>
825
+ </div>
826
+ );
827
+ })}
828
+ </div>
829
+ </div>
830
+ );
831
+ });
web/src/filter-kit/FieldsHidePanel.tsx ADDED
@@ -0,0 +1,318 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // ---------------------------------------------------------------------------
2
+ // filter-kit / FieldsHidePanel.tsx
3
+ // The "Hide fields" list β€” search, per-field toggle, drag-to-reorder, delete.
4
+ //
5
+ // Extracted from customer-grid/Toolbar.tsx (wave 15, contract C-KIT).
6
+ //
7
+ // ⚠ ONE MODEL CHANGE IN THE MOVE, and it is deliberate: the panel speaks HIDDEN,
8
+ // where the toolbar's version spoke VISIBLE. Its title has always been "Hide
9
+ // fields" and the thing it now also edits β€” a user's `perms[module].hiddenFields`
10
+ // β€” is a list of hidden keys, so a panel that took the complement would have made
11
+ // the admin editor invert on the way in and again on the way out. The grid adapts
12
+ // instead (one memo at the call site), because the grid is the surface that
13
+ // happens to store the other polarity.
14
+ // ---------------------------------------------------------------------------
15
+
16
+ import { useState } from "react";
17
+ import type { Field } from "../customer-grid/types";
18
+ import { FieldTypeIcon } from "../customer-grid/icons";
19
+ import { TYPE_LABELS } from "../customer-grid/iconShapes";
20
+
21
+ export interface FieldsHidePanelProps {
22
+ /** Owner item 23 β€” in the view's COLUMN ORDER, not definition order. Dragging a row here
23
+ * rewrites `config.order`, so a list showing a different sequence from the one it edits
24
+ * would move a field to a position the user never pointed at. */
25
+ fields: Field[];
26
+ /** The keys that are HIDDEN. Every field not named here renders as shown. */
27
+ hidden: ReadonlySet<string>;
28
+ onToggle: (key: string) => void;
29
+ onHideAll?: () => void;
30
+ onShowAll?: () => void;
31
+ /** The one field that can never be hidden (the identity column). Absent = nothing is
32
+ * locked, which is the right default for a module whose identity column is not this
33
+ * panel's business. */
34
+ lockedKey?: string;
35
+ /** Owner item 23 β€” the whole new order, keys only. The panel owns the arithmetic because it
36
+ * owns the list the user is pointing at; the caller just persists it. */
37
+ onFieldOrder?: (keys: string[]) => void;
38
+ /** Wave-7 item W9 β€” the keys the caller allows a PERMANENT delete on (the same
39
+ * created-strata wall as the column menu's Delete: `custom` and never the locked
40
+ * identity column). Base/preset fields are simply not in the set, so no delete
41
+ * affordance renders for them at all. */
42
+ deletableKeys?: ReadonlySet<string>;
43
+ onDeleteField?: (key: string) => void;
44
+ }
45
+
46
+ /**
47
+ * The Fields show/hide panel (owner item 7 remainder, wave 2 2026-07-27): a SEARCH box over the
48
+ * field list, and a small muted `Pre-set` chip on every Odoo-precomputed field. The chip's
49
+ * predicate is the shared contract's, exactly: `source === "odoo" && !custom` β€” user-created
50
+ * columns (`custom_`/`measure_`) and the overlay stratum are yours; everything else came with
51
+ * the table. Show all / Hide all keep acting on ALL fields, not the searched subset β€” their
52
+ * labels say "all", and a narrowed meaning under an active search would be a quiet lie.
53
+ */
54
+ export function FieldsHidePanel({
55
+ fields,
56
+ hidden,
57
+ onToggle,
58
+ onHideAll,
59
+ onShowAll,
60
+ lockedKey,
61
+ onFieldOrder,
62
+ deletableKeys,
63
+ onDeleteField,
64
+ }: FieldsHidePanelProps) {
65
+ const [query, setQuery] = useState("");
66
+ /** W9 β€” destructive, so the trash arms first (the grid's confirm pattern): first
67
+ * click reads "Delete permanently?", the second fires. Per-key, so arming one row
68
+ * and clicking another re-arms rather than firing. */
69
+ const [confirmKey, setConfirmKey] = useState<string | null>(null);
70
+ /** Item 23 β€” the row being dragged, and the row it is currently over. Both are KEYS, never
71
+ * indices: the list re-renders on every move and an index would point at whatever slid into
72
+ * that slot. */
73
+ const [dragKey, setDragKey] = useState<string | null>(null);
74
+ const [overKey, setOverKey] = useState<string | null>(null);
75
+ const q = query.trim().toLowerCase();
76
+ const shown = q ? fields.filter((f) => f.label.toLowerCase().includes(q)) : fields;
77
+ /**
78
+ * Item 23 β€” reorder is OFF while a search is narrowing the list. Dropping "City" above
79
+ * "State" in a list that is hiding the eight fields between them means nothing the user can
80
+ * predict: the visible neighbour is not the real neighbour. Airtable does the same. The grip
81
+ * still renders (so the row does not change shape mid-search) but says why it is inert.
82
+ */
83
+ const canReorder = !!onFieldOrder && q === "";
84
+ /** Move `key` to where `target` currently sits, in the FULL order. Returns null when the
85
+ * move is a no-op or forbidden, so the caller never persists a config identical to the one
86
+ * it has (which would still cost an autosave round trip). */
87
+ const reorderTo = (key: string, target: string): string[] | null => {
88
+ if (key === target) return null;
89
+ // The identity column is pinned first by `reconcileOrder` regardless, so a drag involving
90
+ // it would appear to work and then silently snap back. Refuse it at the door instead.
91
+ if (key === lockedKey || target === lockedKey) return null;
92
+ const keys = fields.map((f) => f.key);
93
+ const from = keys.indexOf(key);
94
+ const to = keys.indexOf(target);
95
+ if (from < 0 || to < 0) return null;
96
+ const next = keys.slice();
97
+ next.splice(from, 1);
98
+ next.splice(to, 0, key);
99
+ return next;
100
+ };
101
+ /** Keyboard equivalent of the drag: a pointer-only reorder is unusable without a mouse, and
102
+ * the grip is a real button precisely so it can carry this. */
103
+ const nudge = (key: string, delta: -1 | 1): void => {
104
+ if (!canReorder) return;
105
+ const keys = fields.map((f) => f.key);
106
+ const at = keys.indexOf(key);
107
+ const target = keys[at + delta];
108
+ if (target === undefined) return;
109
+ const next = reorderTo(key, target);
110
+ if (next) onFieldOrder!(next);
111
+ };
112
+ return (
113
+ <div className="cg-pop-body">
114
+ {/* Owner item 23 β€” "Hide fields", Airtable's wording and the honest one: this panel's job
115
+ is choosing what NOT to show. "Fields" named the noun and left the verb to be guessed. */}
116
+ <div className="cg-pop-title">Hide fields</div>
117
+ <input
118
+ type="text"
119
+ className="cg-input cg-fields-search"
120
+ placeholder="Find a field…"
121
+ aria-label="Find a field"
122
+ value={query}
123
+ onChange={(e) => setQuery(e.target.value)}
124
+ />
125
+ <div className="cg-pop-list">
126
+ {shown.map((f) => {
127
+ const locked = lockedKey !== undefined && f.key === lockedKey;
128
+ const on = !hidden.has(f.key);
129
+ const deletable = !!onDeleteField && !!deletableKeys?.has(f.key);
130
+ const armed = confirmKey === f.key;
131
+ return (
132
+ <label
133
+ key={f.key}
134
+ className={
135
+ "cg-check-row" +
136
+ // Item 12 β€” the ROW is the control (clicking anywhere on it toggles the
137
+ // checkbox, which the <label> wrapper has always done: measured, not assumed
138
+ // β€” `useOverlayLayer`'s pointerdown listener returns early inside its own
139
+ // panel, so nothing cancels label activation). What the row could NOT do was
140
+ // SAY which state it was in without reading a 15px checkbox, so a hidden
141
+ // field's row now reads as hidden. The checkbox stays: it is the a11y control
142
+ // and the keyboard one.
143
+ (on ? "" : " is-off") +
144
+ (locked ? " is-locked" : "") +
145
+ (dragKey === f.key ? " is-dragging" : "") +
146
+ (overKey === f.key && dragKey !== null && dragKey !== f.key
147
+ ? " is-drop-target"
148
+ : "")
149
+ }
150
+ title={locked ? "Always visible" : undefined}
151
+ // Item 23 β€” the whole ROW is the drop zone; only the GRIP starts a drag. Dropping
152
+ // is a big target on purpose (a 22px handle is a hard thing to hit precisely);
153
+ // starting is a small one, so the row still behaves as a label everywhere else.
154
+ onDragOver={
155
+ canReorder && dragKey && dragKey !== f.key
156
+ ? (e) => {
157
+ e.preventDefault(); // without this the drop NEVER fires
158
+ e.dataTransfer.dropEffect = "move";
159
+ if (overKey !== f.key) setOverKey(f.key);
160
+ }
161
+ : undefined
162
+ }
163
+ onDrop={
164
+ canReorder && dragKey
165
+ ? (e) => {
166
+ e.preventDefault();
167
+ // ...and this: a drop inside a <label> would otherwise ALSO activate the
168
+ // label and toggle the column's visibility as a side effect of moving it.
169
+ e.stopPropagation();
170
+ const next = reorderTo(dragKey, f.key);
171
+ setDragKey(null);
172
+ setOverKey(null);
173
+ if (next) onFieldOrder!(next);
174
+ }
175
+ : undefined
176
+ }
177
+ >
178
+ {/* Owner item 23 β€” the six-dot grip. Rendered for EVERY row including the locked
179
+ one (an absent handle would misalign that row against all the others), but
180
+ inert there: the identity column is pinned first by `reconcileOrder`, so a
181
+ drag would appear to work and snap back.
182
+ A real <button>, not a decorative <span>: it carries the keyboard reorder,
183
+ which is the only route for anyone not using a pointer. */}
184
+ <button
185
+ type="button"
186
+ className="cg-field-grip"
187
+ draggable={canReorder && !locked}
188
+ aria-label={
189
+ locked
190
+ ? `${f.label} is always first`
191
+ : canReorder
192
+ ? `Reorder ${f.label} β€” drag, or use the arrow keys`
193
+ : `Reorder ${f.label} (clear the search first)`
194
+ }
195
+ title={
196
+ canReorder && !locked
197
+ ? "Drag to reorder, or use the arrow keys"
198
+ : locked
199
+ ? "This column is always first"
200
+ : "Clear the search to reorder"
201
+ }
202
+ onDragStart={(e) => {
203
+ // Firefox refuses to start a drag with no payload set.
204
+ e.dataTransfer.setData("text/plain", f.key);
205
+ e.dataTransfer.effectAllowed = "move";
206
+ setDragKey(f.key);
207
+ }}
208
+ onDragEnd={() => {
209
+ setDragKey(null);
210
+ setOverKey(null);
211
+ }}
212
+ // Inside a <label>, exactly as the delete button below: an unguarded click
213
+ // activates the label and hides the column you were trying to move.
214
+ onClick={(e) => {
215
+ e.preventDefault();
216
+ e.stopPropagation();
217
+ }}
218
+ onKeyDown={(e) => {
219
+ if (e.key !== "ArrowUp" && e.key !== "ArrowDown") return;
220
+ e.preventDefault();
221
+ e.stopPropagation();
222
+ nudge(f.key, e.key === "ArrowUp" ? -1 : 1);
223
+ }}
224
+ >
225
+ <svg width="10" height="16" viewBox="0 0 10 16" aria-hidden focusable="false">
226
+ {[4, 8, 12].map((cy) =>
227
+ [2.5, 7.5].map((cx) => (
228
+ <circle key={`${cx}-${cy}`} cx={cx} cy={cy} r="1.15" fill="currentColor" />
229
+ ))
230
+ )}
231
+ </svg>
232
+ </button>
233
+ <input
234
+ type="checkbox"
235
+ checked={on}
236
+ disabled={locked}
237
+ onChange={() => onToggle(f.key)}
238
+ />
239
+ {/* Wave-8 I20 β€” the field-TYPE mark, same geometry the column header
240
+ draws (icons.tsx). Titled, because this list is where the icon
241
+ vocabulary is learned. */}
242
+ <FieldTypeIcon type={f.type} title={TYPE_LABELS[f.type]} />
243
+ <span className="cg-check-label">{f.label}</span>
244
+ {f.source === "odoo" && !f.custom && (
245
+ <span className="cg-preset-tag">Pre-set</span>
246
+ )}
247
+ {/* Wave-6 item 9c β€” a cohort-scoped field says so (contract: "label it"). */}
248
+ {f.scope === "cohort" && (
249
+ <span className="cg-preset-tag cg-scope-tag">Cohort-only</span>
250
+ )}
251
+ {locked && <span className="cg-lock-tag">Locked</span>}
252
+ {deletable && (
253
+ // Inside a <label>: preventDefault stops the click from ALSO toggling
254
+ // the row's checkbox (label activation), which would hide the column
255
+ // as a side effect of trying to delete it.
256
+ <button
257
+ type="button"
258
+ className={"cg-check-del" + (armed ? " is-armed" : "")}
259
+ aria-label={
260
+ armed ? `Permanently delete ${f.label}?` : `Delete ${f.label}`
261
+ }
262
+ title={armed ? undefined : "Removes this field and its values on every row."}
263
+ onClick={(e) => {
264
+ e.preventDefault();
265
+ e.stopPropagation();
266
+ if (!armed) {
267
+ setConfirmKey(f.key);
268
+ return;
269
+ }
270
+ setConfirmKey(null);
271
+ onDeleteField(f.key);
272
+ }}
273
+ >
274
+ {armed ? (
275
+ "Delete permanently?"
276
+ ) : (
277
+ <svg width="14" height="14" viewBox="0 0 16 16" fill="none" aria-hidden>
278
+ <path
279
+ d="M3.5 4.5h9M6.5 4.5V3h3v1.5M5 4.5l.6 8.5h4.8l.6-8.5"
280
+ stroke="currentColor"
281
+ strokeWidth={1.3}
282
+ strokeLinecap="round"
283
+ strokeLinejoin="round"
284
+ />
285
+ </svg>
286
+ )}
287
+ </button>
288
+ )}
289
+ </label>
290
+ );
291
+ })}
292
+ {shown.length === 0 && (
293
+ <div className="cg-builder-empty">No field matches your search.</div>
294
+ )}
295
+ </div>
296
+ {/* Item 12 (owner, 2026-08-02) β€” the two bulk actions sit in a quiet grey box rather
297
+ than floating under a hairline. They act on ALL fields at once, which is a different
298
+ kind of act from the per-row checkboxes above them; the box says so without a second
299
+ heading, and it is what Airtable does with the same pair.
300
+ Each renders only when the caller supplies its handler β€” the house posture: a missing
301
+ prop makes the action ABSENT, never present-and-inert. */}
302
+ {(onShowAll || onHideAll) && (
303
+ <div className="cg-pop-footer cg-fields-footer">
304
+ {onShowAll && (
305
+ <button type="button" className="cg-link-btn" onClick={onShowAll}>
306
+ Show all
307
+ </button>
308
+ )}
309
+ {onHideAll && (
310
+ <button type="button" className="cg-link-btn" onClick={onHideAll}>
311
+ Hide all
312
+ </button>
313
+ )}
314
+ </div>
315
+ )}
316
+ </div>
317
+ );
318
+ }
web/src/filter-kit/FilterBuilderPanel.tsx ADDED
@@ -0,0 +1,982 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // ---------------------------------------------------------------------------
2
+ // filter-kit / FilterBuilderPanel.tsx
3
+ // The Airtable-style RECURSIVE condition builder, as a MOUNTABLE PANEL.
4
+ //
5
+ // Extracted from customer-grid/Toolbar.tsx (wave 15, contract C-KIT) so the admin
6
+ // permission editor and the grid toolbar build filters with the SAME control
7
+ // rather than two that drift. Behaviour is identical to the toolbar's β€” this is a
8
+ // move, not a rewrite.
9
+ //
10
+ // THE KIT FETCHES NOTHING. Every vocabulary it needs (fields, cohorts, measures,
11
+ // the people a `user` field may name) arrives as a prop, which is what lets the
12
+ // same panel serve a module whose rows this browser has never loaded.
13
+ // ---------------------------------------------------------------------------
14
+
15
+ import { useCallback, useMemo, useState } from "react";
16
+ import type { ReactNode } from "react";
17
+ import type {
18
+ Conjunction,
19
+ Field,
20
+ FilterGroup,
21
+ FilterNode,
22
+ FilterOp,
23
+ FilterRhs,
24
+ FilterRule,
25
+ FilterTree,
26
+ Measure,
27
+ } from "../customer-grid/types";
28
+ import {
29
+ COHORT_FIELD, MAX_COHORT_IDS, MAX_FILTER_DEPTH, RANK_OPS, STAT_KINDS, STAT_LABELS,
30
+ VALUE_FREE_OPS, choiceOptions, cohortIds, filterTreeConj, filterTreeNodes,
31
+ filterableFields, isFilterGroup, isMeasureRule, isRankOp, normalizeCohortOp, rhsColId,
32
+ } from "../customer-grid/types";
33
+ import type { CohortOp, StatKind } from "../customer-grid/types";
34
+ import type { AnchorMode } from "../customer-grid/windows";
35
+ import { ANCHOR_LABELS, ANCHOR_MODES, MAX_N } from "../customer-grid/windows";
36
+ import { FieldSelectButton } from "../customer-grid/FieldSelect";
37
+ import type { FieldSelectItem } from "../customer-grid/FieldSelect";
38
+ import { WindowPicker } from "./WindowPicker";
39
+ import {
40
+ COHORT_OP_LIST, DEFAULT_DATE_WINDOW, DEFAULT_WINDOW, MEASURE_MARK, MEASURE_OP_LIST,
41
+ MEASURE_PAIR_OP_LIST, WITHIN_KINDS, cohortOpLabel, groupSummary, hasRankCondition,
42
+ isDateFamily, isNumericType, newCondition, newRuleId, opLabel, opsForType, rankDefault,
43
+ withCurrent, withCurrentField,
44
+ } from "./ops";
45
+ import "../customer-grid/filters.css";
46
+
47
+ /** The choice vocabulary of one field, resolved once and threaded down as a function so no
48
+ * level of the tree has to carry three separate maps to answer one question. */
49
+ type ChoicesFor = (colId: string) => string[];
50
+
51
+ /**
52
+ * Owner item 3 β€” the DATE value: an anchor mode, then whatever that mode needs.
53
+ *
54
+ * [is before] [one month ago] <- mode only
55
+ * [is before] [N days ago] [30] <- mode + a number
56
+ * [is before] [an exact date] [ πŸ“… ] <- mode + a date
57
+ *
58
+ * The four value-free modes render NO second control, which is exactly why `isRuleActive` has
59
+ * to know about them: an empty value would otherwise read as a half-typed condition and be
60
+ * ignored, quietly widening the result.
61
+ */
62
+ function AnchorValue({
63
+ rule,
64
+ onPatch,
65
+ }: {
66
+ rule: FilterRule;
67
+ onPatch: (p: Partial<FilterRule>) => void;
68
+ }) {
69
+ const mode = rule.dateMode ?? "exact";
70
+ return (
71
+ <span className="cg-cond-anchor">
72
+ <select
73
+ className="cg-select cg-cond-anchor-mode"
74
+ value={mode}
75
+ aria-label="Date"
76
+ onChange={(e) => {
77
+ // Clear the value with the mode. A "30" left behind on `an exact date`, or a date
78
+ // left behind on `N days ago`, is state the user can neither see nor clear.
79
+ const next = e.target.value as AnchorMode;
80
+ onPatch({ dateMode: next, value: "" });
81
+ }}
82
+ >
83
+ {ANCHOR_MODES.map((m) => (
84
+ <option key={m} value={m}>
85
+ {m === "n_days_ago" ? ANCHOR_LABELS[m].replace("{n}", "N") : ANCHOR_LABELS[m]}
86
+ </option>
87
+ ))}
88
+ </select>
89
+ {mode === "n_days_ago" && (
90
+ <input
91
+ className="cg-input cg-cond-win-n"
92
+ type="number"
93
+ min={0}
94
+ max={MAX_N}
95
+ aria-label="Number of days ago"
96
+ value={rule.value}
97
+ onChange={(e) => onPatch({ value: e.target.value })}
98
+ />
99
+ )}
100
+ {mode === "exact" && (
101
+ <input
102
+ className="cg-input cg-cond-val"
103
+ type="date"
104
+ aria-label="Date"
105
+ value={rule.value}
106
+ onChange={(e) => onPatch({ value: e.target.value })}
107
+ />
108
+ )}
109
+ </span>
110
+ );
111
+ }
112
+
113
+ /**
114
+ * CG-9 (owner item 4) β€” the comparand when it is ANOTHER ATTRIBUTE rather than a number.
115
+ *
116
+ * `Sales [this year] > Sales [year to date, last year]`. For a MEASURE the right side carries
117
+ * its own window, which is the whole point: the two sides differ by period, not by name.
118
+ */
119
+ function RhsPicker({
120
+ rule,
121
+ options,
122
+ isMeasure,
123
+ onPatch,
124
+ }: {
125
+ rule: FilterRule;
126
+ options: FieldSelectItem[];
127
+ isMeasure: boolean;
128
+ onPatch: (p: Partial<FilterRule>) => void;
129
+ }) {
130
+ const rhs = rule.rhs;
131
+ const colId = rhsColId(rhs) ?? "";
132
+ return (
133
+ <span className="cg-cond-rhs">
134
+ {/* Item 20 β€” the empty comparand was an `<option value="">` that a select renders as
135
+ its first row; here it is the picker's PLACEHOLDER state, so "not chosen yet" is a
136
+ state of the control rather than an entry in the vocabulary. */}
137
+ <FieldSelectButton
138
+ className="cg-cond-field"
139
+ ariaLabel="Compare with field"
140
+ placeholder="Select a field…"
141
+ value={colId || undefined}
142
+ fields={options}
143
+ onChange={(key) => {
144
+ onPatch({
145
+ rhs: isMeasure
146
+ ? { kind: "measure", colId: key,
147
+ window: (rhs?.kind === "measure" && rhs.window) || DEFAULT_WINDOW }
148
+ : { kind: "field", colId: key },
149
+ });
150
+ }}
151
+ />
152
+ {isMeasure && colId !== "" && (
153
+ <WindowPicker
154
+ window={(rhs?.kind === "measure" && rhs.window) || DEFAULT_WINDOW}
155
+ onWindow={(w) => onPatch({ rhs: { kind: "measure", colId, window: w } })}
156
+ />
157
+ )}
158
+ </span>
159
+ );
160
+ }
161
+
162
+ // --- the value control for one filter condition (type/op aware) ------------
163
+ function ConditionValue({
164
+ rule,
165
+ type,
166
+ statusOptions,
167
+ onValue,
168
+ onValue2,
169
+ }: {
170
+ rule: FilterRule;
171
+ type: Field["type"];
172
+ statusOptions: string[];
173
+ onValue: (v: string) => void;
174
+ onValue2: (v: string) => void;
175
+ }) {
176
+ if (rule.op === "between") {
177
+ const inputType = type === "date" || type === "created_time" ? "date" : "number";
178
+ return (
179
+ <span className="cg-cond-between">
180
+ <input
181
+ className="cg-input cg-cond-val"
182
+ type={inputType}
183
+ value={rule.value}
184
+ onChange={(e) => onValue(e.target.value)}
185
+ />
186
+ <span className="cg-cond-and">and</span>
187
+ <input
188
+ className="cg-input cg-cond-val"
189
+ type={inputType}
190
+ value={rule.value2 ?? ""}
191
+ onChange={(e) => onValue2(e.target.value)}
192
+ />
193
+ </span>
194
+ );
195
+ }
196
+ if (
197
+ type === "status" || type === "select" || type === "user" || type === "multiselect"
198
+ ) {
199
+ return (
200
+ <select
201
+ className="cg-select cg-cond-val"
202
+ value={rule.value}
203
+ onChange={(e) => onValue(e.target.value)}
204
+ >
205
+ <option value="">Select…</option>
206
+ {statusOptions.map((v) => (
207
+ <option key={v} value={v}>
208
+ {v}
209
+ </option>
210
+ ))}
211
+ </select>
212
+ );
213
+ }
214
+ const inputType =
215
+ type === "date" || type === "created_time"
216
+ ? "date"
217
+ : isNumericType(type)
218
+ ? "number"
219
+ : "text";
220
+ return (
221
+ <input
222
+ className="cg-input cg-cond-val"
223
+ type={inputType}
224
+ placeholder="Value"
225
+ value={rule.value}
226
+ onChange={(e) => onValue(e.target.value)}
227
+ />
228
+ );
229
+ }
230
+
231
+ /**
232
+ * C-OPS β€” the value control for a rank condition.
233
+ *
234
+ * Two shapes, because the two questions are different: a COUNT (or a percentage) is typed and
235
+ * unbounded-ish, while a quantile is a choice from four or ten. Rendering the quantile as a
236
+ * number box would let somebody type `inQuartile 7`, which the engine refuses outright β€” the
237
+ * control that cannot express the invalid state is the better one.
238
+ *
239
+ * Bounds are on the input as `min`/`max` AND enforced in the engine, which is not redundancy:
240
+ * a number input's bounds are advisory (typing past them is allowed and only surfaces on form
241
+ * validation), so the box is a hint and `rankOps.bound` is the wall. A value outside the range
242
+ * makes the condition UNANSWERABLE β€” it matches nothing and says so beside the count.
243
+ */
244
+ function RankValue({
245
+ rule,
246
+ onValue,
247
+ }: {
248
+ rule: FilterRule;
249
+ onValue: (v: string) => void;
250
+ }) {
251
+ const buckets = rule.op === "inQuartile" ? 4 : rule.op === "inDecile" ? 10 : 0;
252
+ if (buckets) {
253
+ return (
254
+ <select
255
+ className="cg-select cg-cond-val"
256
+ value={rule.value}
257
+ aria-label={rule.op === "inQuartile" ? "Quartile" : "Decile"}
258
+ onChange={(e) => onValue(e.target.value)}
259
+ >
260
+ {Array.from({ length: buckets }, (_, i) => String(i + 1)).map((n) => (
261
+ <option key={n} value={n}>
262
+ {/* The ends are the ones people mean, so they say so rather than making the
263
+ reader remember which end 1 is. */}
264
+ {n === "1"
265
+ ? `${n} (lowest)`
266
+ : n === String(buckets)
267
+ ? `${n} (highest)`
268
+ : n}
269
+ </option>
270
+ ))}
271
+ </select>
272
+ );
273
+ }
274
+ const pct = rule.op === "inTopPct" || rule.op === "inBottomPct";
275
+ return (
276
+ <input
277
+ className="cg-input cg-cond-val"
278
+ type="number"
279
+ min={1}
280
+ max={pct ? 100 : 10000}
281
+ step={1}
282
+ placeholder={pct ? "10" : "10"}
283
+ aria-label={pct ? "Percent" : "How many"}
284
+ value={rule.value}
285
+ onChange={(e) => onValue(e.target.value)}
286
+ />
287
+ );
288
+ }
289
+
290
+ /**
291
+ * The cohorts a `Where [Cohort] [is any of] […]` condition names (owner, 2026-07-27).
292
+ *
293
+ * Chips plus an add-select, not a `<select multiple>`: a native multi-select needs ctrl-click to
294
+ * build a set and shows what is chosen only by highlight, so the condition would stop reading as
295
+ * a sentence β€” and the one thing this row has to do is say what it filters. The add-select also
296
+ * keeps exactly one `.cg-cond-val` in the row, which is the control the shipped round-trip gate
297
+ * drives; choosing a cohort there APPENDS rather than replaces.
298
+ *
299
+ * The select is rendered even when there is nothing left to add, disabled. A control that
300
+ * vanishes at the cap would reflow the sentence mid-edit, and a gate that located it by class
301
+ * would report a missing control rather than a full set.
302
+ *
303
+ * A cohort the view names but the user no longer has still renders, as `(deleted list)` β€” the
304
+ * `withCurrent` rule applied to a set. The engine refuses such a condition outright (evalNode
305
+ * returns false for the whole leaf, not for that member), so showing the stale chip is exactly
306
+ * what lets somebody remove it.
307
+ */
308
+ function CohortPicker({
309
+ rule,
310
+ lists,
311
+ onPatch,
312
+ }: {
313
+ rule: FilterRule;
314
+ lists: { id: string; name: string }[];
315
+ onPatch: (p: Partial<FilterRule>) => void;
316
+ }) {
317
+ const chosen = cohortIds(rule.value);
318
+ const nameById = new Map(lists.map((l) => [l.id, l.name]));
319
+ const remaining = lists.filter((l) => !chosen.includes(l.id));
320
+ const canAdd = remaining.length > 0 && chosen.length < MAX_COHORT_IDS;
321
+ const setIds = (ids: string[]) => onPatch({ value: ids.join(",") });
322
+ return (
323
+ <span className="cg-cond-cohorts">
324
+ {chosen.map((id) => (
325
+ <span key={id} className={"cg-chip" + (nameById.has(id) ? "" : " cg-chip--gone")}>
326
+ <span className="cg-chip-text">{nameById.get(id) ?? "(deleted list)"}</span>
327
+ <button
328
+ type="button"
329
+ className="cg-chip-x"
330
+ aria-label={`Remove ${nameById.get(id) ?? id}`}
331
+ onClick={() => setIds(chosen.filter((c) => c !== id))}
332
+ >
333
+ Γ—
334
+ </button>
335
+ </span>
336
+ ))}
337
+ <select
338
+ className="cg-select cg-cond-val cg-cond-cohort-add"
339
+ value=""
340
+ aria-label="Cohort"
341
+ disabled={!canAdd}
342
+ onChange={(e) => e.target.value && setIds([...chosen, e.target.value])}
343
+ >
344
+ {/* "nothing left to add" rendered as "nothing left to ad…" at 136px β€” the fourth time a
345
+ closed vocabulary has outgrown its control here. Shortened, not widened: the control
346
+ is sized so a COHORT NAME stays readable, and that is the string that matters. */}
347
+ <option value="">
348
+ {!canAdd ? "all added" : chosen.length ? "Add a cohort…" : "Select a cohort…"}
349
+ </option>
350
+ {remaining.map((l) => (
351
+ <option key={l.id} value={l.id}>
352
+ {l.name}
353
+ </option>
354
+ ))}
355
+ </select>
356
+ </span>
357
+ );
358
+ }
359
+
360
+ // --- Filter: an Airtable-style RECURSIVE condition builder -----------------
361
+ // Anatomy per Airtable (captured from the live product 2026-07-25):
362
+ // row 0 : static "Where"
363
+ // row 1 : the and/or DROPDOWN β€” one conjunction per LEVEL, not per condition
364
+ // row 2..n : static text mirroring that level's conjunction
365
+ // a group : inset panel + summary line ("All/Any of the following are true…")
366
+ // carrying its OWN conjunction and its own Where/and-or rows
367
+ // Nesting is capped at MAX_FILTER_DEPTH (3) β€” Airtable grays the group button out.
368
+
369
+ /** The leading cell of a condition row: "Where", the conjunction picker, or the mirror. */
370
+ function RowPrefix({
371
+ index,
372
+ conj,
373
+ onConj,
374
+ }: {
375
+ index: number;
376
+ conj: Conjunction;
377
+ onConj: (c: Conjunction) => void;
378
+ }) {
379
+ if (index === 0) return <span className="cg-cond-prefix">Where</span>;
380
+ if (index === 1)
381
+ return (
382
+ <select
383
+ className="cg-select cg-cond-conj"
384
+ value={conj}
385
+ aria-label="Combine conditions with"
386
+ onChange={(e) => onConj(e.target.value as Conjunction)}
387
+ >
388
+ <option value="and">and</option>
389
+ <option value="or">or</option>
390
+ </select>
391
+ );
392
+ return <span className="cg-cond-prefix cg-cond-conj-echo">{conj}</span>;
393
+ }
394
+
395
+ /** Everything a level of the tree needs that does not change as it recurses. One object rather
396
+ * than eight repeated props: the list grew past the point where each level restating it made
397
+ * the recursion easier to read. */
398
+ interface LevelContext {
399
+ fields: Field[];
400
+ fieldByKey: Map<string, Field>;
401
+ measures: Measure[];
402
+ measureByKey: Map<string, Measure>;
403
+ /** Cohorts this user has β€” the vocabulary of `Where [Cohort] [is part of] […]`. */
404
+ lists: { id: string; name: string }[];
405
+ choicesFor: ChoicesFor;
406
+ }
407
+
408
+ /**
409
+ * One nesting level: renders its nodes (leaves and nested groups) plus the
410
+ * add-buttons. Recurses through GroupNode for children that are groups.
411
+ */
412
+ function ConditionLevel({
413
+ nodes,
414
+ conj,
415
+ depth,
416
+ ctx,
417
+ onNodes,
418
+ onConj,
419
+ }: {
420
+ nodes: FilterNode[];
421
+ conj: Conjunction;
422
+ /** 1 = the root level. A new group's depth would be depth + 1. */
423
+ depth: number;
424
+ ctx: LevelContext;
425
+ onNodes: (nodes: FilterNode[]) => void;
426
+ onConj: (c: Conjunction) => void;
427
+ }) {
428
+ /** Item 13 / R9 β€” which add-link was last used at THIS level. Per level, because the state
429
+ * belongs to the row of buttons the user clicked, not to the builder as a whole. */
430
+ const [lastAdd, setLastAdd] = useState<"condition" | "group" | null>(null);
431
+ const setNode = (i: number, next: FilterNode) =>
432
+ onNodes(nodes.map((n, j) => (j === i ? next : n)));
433
+ const removeNode = (i: number) => onNodes(nodes.filter((_, j) => j !== i));
434
+
435
+ const addCondition = () => {
436
+ const c = newCondition(ctx.fields);
437
+ if (c) onNodes([...nodes, c]);
438
+ };
439
+ // New groups default to "or" β€” matching Airtable, and the useful case (the
440
+ // root ANDs a set of alternatives together).
441
+ const addGroup = () => {
442
+ const c = newCondition(ctx.fields);
443
+ if (c) onNodes([...nodes, { conj: "or", children: [c] }]);
444
+ };
445
+ const canNest = depth < MAX_FILTER_DEPTH;
446
+
447
+ return (
448
+ <>
449
+ {nodes.map((node, i) => (
450
+ <div className="cg-cond-line" key={i}>
451
+ <RowPrefix index={i} conj={conj} onConj={onConj} />
452
+ {isFilterGroup(node) ? (
453
+ <GroupNode
454
+ group={node}
455
+ depth={depth + 1}
456
+ ctx={ctx}
457
+ onGroup={(g) => setNode(i, g)}
458
+ onRemove={() => removeNode(i)}
459
+ />
460
+ ) : (
461
+ <LeafRow
462
+ rule={node}
463
+ ctx={ctx}
464
+ onRule={(r) => setNode(i, r)}
465
+ onRemove={() => removeNode(i)}
466
+ />
467
+ )}
468
+ </div>
469
+ ))}
470
+ {/* Item 13 (owner, 2026-08-02) β€” the two add-links are BOLD, and the one you just used
471
+ holds a dark-blue state.
472
+ ⚠ R9 says that state lasts while the popover is open and a fresh open starts
473
+ neutral β€” which is exactly what a `useState` HERE gives for free, because `Popover`
474
+ renders its children only while open (`{open && <AnchoredOverlay…>}`) and unmounts
475
+ them on close. Nothing persists it, nothing has to clear it, and there is no way for
476
+ it to survive a reopen. A `:active` pseudo-class would have been the wrong tool
477
+ twice over: it lasts for the duration of the mouse-down, and it says "you are
478
+ pressing this" rather than "this is the one you have been using". */}
479
+ <div className="cg-builder-add">
480
+ <button
481
+ type="button"
482
+ className={"cg-link-btn" + (lastAdd === "condition" ? " is-on" : "")}
483
+ onClick={() => {
484
+ setLastAdd("condition");
485
+ addCondition();
486
+ }}
487
+ >
488
+ + Add condition
489
+ </button>
490
+ <button
491
+ type="button"
492
+ className={"cg-link-btn" + (lastAdd === "group" ? " is-on" : "")}
493
+ onClick={() => {
494
+ setLastAdd("group");
495
+ addGroup();
496
+ }}
497
+ disabled={!canNest}
498
+ title={
499
+ canNest
500
+ ? "Group conditions so they evaluate together"
501
+ : `Condition groups can nest ${MAX_FILTER_DEPTH} levels deep`
502
+ }
503
+ >
504
+ + Add condition group
505
+ </button>
506
+ </div>
507
+ </>
508
+ );
509
+ }
510
+
511
+ /**
512
+ * One leaf condition: field β–Ύ | (window β–Ύ) | operator β–Ύ | value | remove.
513
+ *
514
+ * The window bracket appears only for a MEASURE (CG-8) β€” a column already has its window baked
515
+ * in ("YTD $" IS year-to-date), and offering one there would imply it could be changed.
516
+ */
517
+ function LeafRow({
518
+ rule,
519
+ ctx,
520
+ onRule,
521
+ onRemove,
522
+ }: {
523
+ rule: FilterRule;
524
+ ctx: LevelContext;
525
+ onRule: (r: FilterRule) => void;
526
+ onRemove: () => void;
527
+ }) {
528
+ const { fields, fieldByKey, measures, measureByKey, lists, choicesFor } = ctx;
529
+ const isMeasure = isMeasureRule(rule);
530
+ const isCohort = rule.colId === COHORT_FIELD;
531
+ const hasCohorts = lists.length > 0;
532
+ const t = isMeasure
533
+ ? measureByKey.get(rule.colId)?.type ?? "currency"
534
+ : fieldByKey.get(rule.colId)?.type ?? "text";
535
+ const patch = (p: Partial<FilterRule>) => onRule({ ...rule, ...p });
536
+ // Switching field resets op to that type's default + clears the value(s), so a
537
+ // numeric op can never linger on a text column. Crossing the column/measure line also
538
+ // adds or removes the WINDOW and the rule ID, since those are what MAKE it a measure β€”
539
+ // leaving a window behind on a column condition would keep the server answering it. The
540
+ // rhs goes too: a comparand chosen for the old field is meaningless against the new one.
541
+ const onField = (key: string) => {
542
+ if (key === COHORT_FIELD) {
543
+ onRule({ colId: COHORT_FIELD, op: COHORT_OP_LIST[0], value: "" });
544
+ return;
545
+ }
546
+ const m = measureByKey.get(key);
547
+ if (m) {
548
+ onRule({
549
+ id: rule.id ?? newRuleId(),
550
+ colId: key,
551
+ op: MEASURE_OP_LIST[0],
552
+ value: "",
553
+ value2: undefined,
554
+ window: rule.window ?? DEFAULT_WINDOW,
555
+ });
556
+ return;
557
+ }
558
+ const nt = fieldByKey.get(key)?.type ?? "text";
559
+ onRule({ colId: key, op: opsForType(nt)[0], value: "", value2: undefined });
560
+ };
561
+ // Switching to/from a value-free op clears the stale value it can't show. `within` swaps the
562
+ // value for a RANGE and drops any field comparand, since a range has no other side.
563
+ const onOp = (op: FilterOp | CohortOp) => {
564
+ // A cohort keeps its SET when the set operator changes β€” "any of these three" and "none of
565
+ // these three" are the same three cohorts asked about differently, and clearing them would
566
+ // make the obvious edit destructive.
567
+ if (isCohort) return patch({ op });
568
+ // C-OPS: a rank op arrives with its N already chosen (see rankDefault) and drops every
569
+ // comparand β€” "the top 10 compared with another field" is not a question.
570
+ if (isRankOp(op as string))
571
+ return onRule({ ...rule, op: op as FilterOp, value: rankDefault(op as FilterOp),
572
+ value2: undefined, rhs: undefined, dateWindow: undefined });
573
+ if (VALUE_FREE_OPS.has(op as FilterOp))
574
+ return onRule({ ...rule, op, value: "", value2: undefined, rhs: undefined });
575
+ if (op === "within")
576
+ return onRule({ ...rule, op, value: "", value2: undefined, rhs: undefined,
577
+ dateWindow: rule.dateWindow ?? DEFAULT_DATE_WINDOW });
578
+ if (rule.op === "within")
579
+ return onRule({ ...rule, op, dateWindow: undefined, value: "" });
580
+ patch({ op });
581
+ };
582
+ // Owner item 4: the value box is REPLACEABLE by another attribute. Offered where a
583
+ // comparison between two of the same kind of thing means something β€” numbers against
584
+ // numbers, dates against dates, a measure against a measure over its own period.
585
+ const rhsOptions: FieldSelectItem[] = isMeasure
586
+ ? measures.map((m) => ({ key: m.key, label: m.label, type: MEASURE_MARK }))
587
+ : fields
588
+ .filter((f) => f.key !== rule.colId
589
+ && (isNumericType(t) ? isNumericType(f.type) : f.type === t))
590
+ .map((f) => ({ key: f.key, label: f.label, type: f.type }));
591
+ const canCompareField = !isCohort && rule.op !== "within"
592
+ && !VALUE_FREE_OPS.has(rule.op as FilterOp) && !isRankOp(rule.op)
593
+ && rhsOptions.length > 0 && (isMeasure || isNumericType(t) || isDateFamily(t));
594
+ const usingStat = rule.rhs?.kind === "stat";
595
+ const usingField = rule.rhs != null && !usingStat;
596
+ // Explicitly widened: the cohort branch contributes a DISJOINT vocabulary, and without the
597
+ // annotation `withCurrent`'s `T extends string` infers from the first branch alone.
598
+ const opList: (FilterOp | CohortOp)[] = isMeasure
599
+ ? (usingField || usingStat ? MEASURE_PAIR_OP_LIST : MEASURE_OP_LIST)
600
+ : isCohort ? COHORT_OP_LIST : opsForType(t);
601
+ const opValue: FilterOp | CohortOp = isCohort ? normalizeCohortOp(rule.op) : rule.op;
602
+ // C-OPS β€” the RANK family, offered under its own divider for the numeric family only.
603
+ //
604
+ // A COLUMN only: a measure leaf is answered by a server-side pid set over a window, so
605
+ // ranking one client-side would be a second answer to the same question (and the host's
606
+ // MEASURE_OPS deliberately does not carry these). A cohort leaf is set membership.
607
+ //
608
+ // Offered separately rather than appended to `opsForType` because these operators are a
609
+ // different KIND of question β€” every other one is about this row's value, these are about
610
+ // where the row sits among the others β€” and a divider is the cheapest way to say so.
611
+ const canRank = !isMeasure && !isCohort && isNumericType(t);
612
+ // `withCurrent` runs over the COMBINED offer so a rule already holding a rank op is not
613
+ // appended a second time; the split below then puts each op under the right heading. A
614
+ // rank op on a field that can no longer be ranked still renders β€” as itself, in the group,
615
+ // which is what lets somebody see it and change it.
616
+ const offeredOps = withCurrent(canRank ? [...opList, ...RANK_OPS] : opList, opValue);
617
+ const plainOps = offeredOps.filter((op) => !isRankOp(op));
618
+ const rankedOps = offeredOps.filter((op) => isRankOp(op));
619
+
620
+ return (
621
+ <span className={"cg-cond-row" + (isMeasure ? " is-measure" : "")
622
+ + (isCohort ? " is-cohort" : "")
623
+ + (rule.rhs != null ? " has-rhs" : "")}>
624
+ {/* ONE flat list (owner item 1). A measure used to sit under a "Measures (pick a
625
+ period)" optgroup; the owner's instruction was that it is all the same list β€”
626
+ you pick a thing to filter on, and a measure simply also asks for a period. Item 20
627
+ adds the type MARK to each row and takes NO grouping with it: the marks are what the
628
+ optgroup was reaching for, and they say it per row instead of splitting the list. */}
629
+ <FieldSelectButton
630
+ className="cg-cond-field"
631
+ ariaLabel="Field"
632
+ value={rule.colId}
633
+ onChange={onField}
634
+ fields={[
635
+ ...withCurrentField(fields, rule.colId, fieldByKey, measureByKey, hasCohorts),
636
+ ...measures.map((m) => ({ key: m.key, label: m.label, type: MEASURE_MARK })),
637
+ // A cohort leaf asks about membership of a SET, which is the multiselect mark's
638
+ // own meaning β€” the vocabulary already had the right glyph for it.
639
+ ...(hasCohorts
640
+ ? [{ key: COHORT_FIELD, label: "Cohort", type: "multiselect" as const }]
641
+ : []),
642
+ ]}
643
+ />
644
+ {isMeasure && (
645
+ <WindowPicker
646
+ window={rule.window ?? DEFAULT_WINDOW}
647
+ onWindow={(w) => patch({ window: w })}
648
+ />
649
+ )}
650
+ <select
651
+ className="cg-select cg-cond-op"
652
+ // A view saved before 2026-07-27 holds `eq`/`neq`. Normalising HERE, rather than letting
653
+ // `withCurrent` append it, is the difference between a legacy rule reading "is any of"
654
+ // once and the list carrying two options with the same label and different values. The
655
+ // display stays truthful either way β€” `eq` IS `anyOf` β€” and the first edit writes the
656
+ // new op, matching what the validator already does on the server.
657
+ value={opValue}
658
+ aria-label="Condition"
659
+ onChange={(e) => onOp(e.target.value as FilterOp | CohortOp)}
660
+ >
661
+ {plainOps.map((op) => (
662
+ <option key={op} value={op}>
663
+ {/* `op as FilterOp` is safe by construction, not by hope: `opList` is the cohort
664
+ vocabulary EXACTLY when `isCohort`, so the other branch only ever sees the
665
+ column/measure one. The two lists are disjoint, so a wrong cast would show as a
666
+ raw key ("anyOf") on screen rather than as a plausible label. */}
667
+ {isCohort ? cohortOpLabel(op) : opLabel(op as FilterOp, t)}
668
+ </option>
669
+ ))}
670
+ {rankedOps.length > 0 && (
671
+ <optgroup label="Ranked">
672
+ {rankedOps.map((op) => (
673
+ <option key={op} value={op}>
674
+ {opLabel(op as FilterOp, t)}
675
+ </option>
676
+ ))}
677
+ </optgroup>
678
+ )}
679
+ </select>
680
+ {canCompareField && (
681
+ // The switch between "a value I type" and "another attribute". Two options rather than
682
+ // a checkbox, because the row already reads as a sentence and this is the noun slot.
683
+ <select
684
+ className="cg-select cg-cond-mode"
685
+ value={usingStat ? "stat" : usingField ? "field" : "value"}
686
+ aria-label="Compare against"
687
+ onChange={(e) => {
688
+ const mode = e.target.value;
689
+ if (mode === "stat")
690
+ return patch({ rhs: { kind: "stat", stat: "median" },
691
+ value: "", value2: undefined,
692
+ // a statistic is a computed cut-off: the same four ops a
693
+ // measure-vs-measure allows, for the same float reason
694
+ // reachable only via `canCompareField`, which excludes a cohort
695
+ op: MEASURE_PAIR_OP_LIST.includes(rule.op as FilterOp)
696
+ ? rule.op : MEASURE_PAIR_OP_LIST[1] });
697
+ if (mode === "field") {
698
+ // An EMPTY comparand: incomplete, so the rule stays inactive until a field is
699
+ // picked. RhsPicker adds the window when the measure side gets one.
700
+ const empty: FilterRhs = isMeasure
701
+ ? { kind: "measure", colId: "", window: DEFAULT_WINDOW }
702
+ : { kind: "field", colId: "" };
703
+ return patch({ rhs: empty, value: "", value2: undefined });
704
+ }
705
+ patch({ rhs: undefined, value: "" });
706
+ }}
707
+ >
708
+ <option value="value">a value</option>
709
+ <option value="field">another field</option>
710
+ {/* Statistics are computed SERVER-SIDE over the caller's pool, so they are offered
711
+ for a MEASURE only. A column statistic would need a second percentile
712
+ implementation on the client and the lock-step gate that goes with it. */}
713
+ {isMeasure && <option value="stat">a statistic</option>}
714
+ </select>
715
+ )}
716
+ {/* value-free ops render NO value control (Airtable does the same) */}
717
+ {VALUE_FREE_OPS.has(rule.op as FilterOp) ? (
718
+ <span className="cg-cond-val cg-cond-noval" aria-hidden />
719
+ ) : usingStat ? (
720
+ <select
721
+ className="cg-select cg-cond-val cg-cond-stat"
722
+ value={rule.rhs?.kind === "stat" ? rule.rhs.stat : "median"}
723
+ aria-label="Statistic"
724
+ onChange={(e) => patch({ rhs: { kind: "stat", stat: e.target.value as StatKind } })}
725
+ >
726
+ {STAT_KINDS.map((k) => (
727
+ <option key={k} value={k}>
728
+ {STAT_LABELS[k]}
729
+ </option>
730
+ ))}
731
+ </select>
732
+ ) : usingField ? (
733
+ <RhsPicker rule={rule} options={rhsOptions} isMeasure={isMeasure} onPatch={patch} />
734
+ ) : isCohort ? (
735
+ <CohortPicker rule={rule} lists={lists} onPatch={patch} />
736
+ ) : isRankOp(rule.op) ? (
737
+ <RankValue rule={rule} onValue={(v) => patch({ value: v })} />
738
+ ) : rule.op === "within" ? (
739
+ <WindowPicker
740
+ window={rule.dateWindow ?? DEFAULT_DATE_WINDOW}
741
+ onWindow={(w) => patch({ dateWindow: w })}
742
+ kinds={WITHIN_KINDS}
743
+ />
744
+ ) : isDateFamily(t) ? (
745
+ <AnchorValue rule={rule} onPatch={patch} />
746
+ ) : (
747
+ <ConditionValue
748
+ rule={rule}
749
+ type={t}
750
+ statusOptions={choicesFor(rule.colId)}
751
+ onValue={(v) => patch({ value: v })}
752
+ onValue2={(v) => patch({ value2: v })}
753
+ />
754
+ )}
755
+ <button
756
+ type="button"
757
+ className="cg-cond-x"
758
+ aria-label="Remove condition"
759
+ onClick={onRemove}
760
+ >
761
+ Γ—
762
+ </button>
763
+ </span>
764
+ );
765
+ }
766
+
767
+ /** A nested condition group: summary line + its own recursive level. */
768
+ function GroupNode({
769
+ group,
770
+ depth,
771
+ ctx,
772
+ onGroup,
773
+ onRemove,
774
+ }: {
775
+ group: FilterGroup;
776
+ depth: number;
777
+ ctx: LevelContext;
778
+ onGroup: (g: FilterGroup) => void;
779
+ onRemove: () => void;
780
+ }) {
781
+ return (
782
+ <span className="cg-cond-group" data-depth={depth}>
783
+ <span className="cg-cond-group-head">
784
+ <span className="cg-cond-group-sum">
785
+ {group.children.length
786
+ ? groupSummary(group.conj)
787
+ : "Add a condition to this group…"}
788
+ </span>
789
+ <button
790
+ type="button"
791
+ className="cg-cond-x"
792
+ aria-label="Remove condition group"
793
+ onClick={onRemove}
794
+ >
795
+ Γ—
796
+ </button>
797
+ </span>
798
+ <span className="cg-cond-group-body">
799
+ <ConditionLevel
800
+ nodes={group.children}
801
+ conj={group.conj}
802
+ depth={depth}
803
+ ctx={ctx}
804
+ onNodes={(children) => onGroup({ ...group, children })}
805
+ onConj={(conj) => onGroup({ ...group, conj })}
806
+ />
807
+ </span>
808
+ </span>
809
+ );
810
+ }
811
+
812
+ export interface FilterBuilderPanelProps {
813
+ /**
814
+ * The module's COMPLETE field list. The panel offers the FILTERABLE ones
815
+ * (`filterableFields`) and resolves labels from all of them β€” a condition saved against a
816
+ * column that has since stopped being filterable must still render its own name rather than
817
+ * turning into "?", so narrowing the picker may never orphan history.
818
+ */
819
+ fields: Field[];
820
+ /** The whole filter as ONE value β€” nodes plus the root conjunction. See types.FilterTree. */
821
+ filters: FilterTree;
822
+ onChange: (next: FilterTree) => void;
823
+ /** Cohorts the subject of this filter has, for `Where [Cohort] [is any of] […]`. */
824
+ cohorts?: { id: string; name: string }[];
825
+ /** CG-8 β€” measures the builder may offer alongside the columns. Absent = columns only. */
826
+ measures?: Measure[];
827
+ /** The people a `user` field may name. Never invented here β€” the host's real user list. */
828
+ userOptions?: string[];
829
+ /**
830
+ * The tenant's today, ISO. RESERVED: it is the anchor a relative window resolves against,
831
+ * and it is accepted so a caller that holds it (the grid, the admin editor) has one obvious
832
+ * place to put it. It renders NOTHING today β€” a "this resolves to <range>" hint under the
833
+ * date controls was considered for wave 15 and rejected as a visual delta C-KIT forbids.
834
+ * Kept in the signature rather than added later so no call site has to change to gain it.
835
+ */
836
+ today?: string;
837
+ /**
838
+ * The per-field CHOICE VOCABULARY, by field key. The one prop that is not cosmetic when it
839
+ * is absent: `status` columns take their values from the DATA (the grid discovers them from
840
+ * its rows), which a panel over a module whose rows it has never loaded cannot do. Absent,
841
+ * choices fall back to the field's own declared `options` and, for `user`, to `userOptions`
842
+ * β€” so an admin editor gets working select/multiselect/user dropdowns and only Odoo `status`
843
+ * columns come up empty for it.
844
+ */
845
+ statusValues?: Record<string, string[]>;
846
+ /**
847
+ * Item 12 (C-LOCK) β€” this view is LOCKED to a cohort. Present = say so, because the lock
848
+ * narrows the list and is not one of the conditions shown here: without the banner the count
849
+ * and the conditions disagree with no visible reason.
850
+ *
851
+ * `name`/`count` ABSENT means the reader cannot see the set β€” a shared view locked to
852
+ * somebody else's cohort. The engine matches nothing in that case (fail-closed, the
853
+ * cohort-leaf law), so the banner has to say which kind of nothing this is.
854
+ */
855
+ cohortLock?: { name?: string; count?: number };
856
+ /**
857
+ * Extra footer content, rendered beside "Clear all" β€” the grid puts its "Copy from another
858
+ * view" door here. A SLOT rather than props, exactly like the toolbar's `cohortAction`: the
859
+ * door needs the other views and the view-patch plumbing, none of which a panel that also
860
+ * serves an admin editor should know about.
861
+ */
862
+ footerExtra?: ReactNode;
863
+ }
864
+
865
+ export function FilterBuilderPanel({
866
+ fields,
867
+ filters,
868
+ onChange,
869
+ cohorts = [],
870
+ measures = [],
871
+ userOptions,
872
+ statusValues,
873
+ cohortLock,
874
+ footerExtra,
875
+ }: FilterBuilderPanelProps) {
876
+ const nodes = filterTreeNodes(filters);
877
+ const conj = filterTreeConj(filters);
878
+ // The COMPLETE map on purpose (see `fields` above): the picker is narrowed, the label
879
+ // resolution is not.
880
+ const fieldByKey = useMemo(() => {
881
+ const m = new Map<string, Field>();
882
+ for (const f of fields) m.set(f.key, f);
883
+ return m;
884
+ }, [fields]);
885
+ const condFields = useMemo(() => filterableFields(fields), [fields]);
886
+ const measureByKey = useMemo(() => {
887
+ const m = new Map<string, Measure>();
888
+ for (const item of measures) m.set(item.key, item);
889
+ return m;
890
+ }, [measures]);
891
+ const choicesFor = useCallback<ChoicesFor>(
892
+ (colId) => {
893
+ // A supplied map WINS, including when it holds an empty list: "this status column has no
894
+ // values in the data" is an answer, not a missing one.
895
+ const declared = statusValues?.[colId];
896
+ if (declared) return declared;
897
+ const f = fieldByKey.get(colId);
898
+ if (!f) return [];
899
+ return f.type === "user" ? userOptions ?? [] : choiceOptions(f);
900
+ },
901
+ [statusValues, fieldByKey, userOptions]
902
+ );
903
+ const ctx = useMemo<LevelContext>(
904
+ () => ({ fields: condFields, fieldByKey, measures, measureByKey, lists: cohorts,
905
+ choicesFor }),
906
+ [condFields, fieldByKey, measures, measureByKey, cohorts, choicesFor]
907
+ );
908
+
909
+ return (
910
+ <div className="cg-pop-body cg-builder">
911
+ <div className="cg-pop-title">Filter</div>
912
+ {/* C-LOCK (item 12) β€” the lock is NOT a condition row: it cannot be written here and
913
+ cannot be removed here (the view menu owns it). So it has to be SAID here, above
914
+ the conditions it bounds β€” otherwise the count and the conditions disagree and the
915
+ builder shows nothing that explains the gap. A reader who cannot see the set gets a
916
+ different sentence, because the engine shows them nobody and "no records" alone does
917
+ not distinguish a permission wall from a filter that genuinely matches nobody. */}
918
+ {cohortLock && (
919
+ <div className="cg-flt-lockchip">
920
+ {cohortLock.name
921
+ ? `Customer list locked to ${cohortLock.name}` +
922
+ (typeof cohortLock.count === "number"
923
+ ? ` Β· ${cohortLock.count.toLocaleString()} ${
924
+ cohortLock.count === 1 ? "customer" : "customers"
925
+ }`
926
+ : "")
927
+ : "Customer list locked to a set you cannot see"}
928
+ </div>
929
+ )}
930
+ {nodes.length === 0 ? (
931
+ <div className="cg-builder-empty">
932
+ No conditions. Add one to narrow the list.
933
+ </div>
934
+ ) : (
935
+ <div className="cg-builder-caption">In this view, show records</div>
936
+ )}
937
+ <ConditionLevel
938
+ nodes={nodes}
939
+ conj={conj}
940
+ depth={1}
941
+ ctx={ctx}
942
+ onNodes={(next) => onChange({ conj, nodes: next })}
943
+ onConj={(next) => onChange({ conj: next, nodes })}
944
+ />
945
+ {/* C-OPS β€” a ranked condition answers a question about the OTHER records, and there is
946
+ no way to see from the row which others. Three sentences, shown only while one is in
947
+ the tree: the population, what is left out of it, and the one thing about quantiles
948
+ that is genuinely not guessable (equal-size by RANK, so two identical values can
949
+ land on opposite sides of a boundary). */}
950
+ {hasRankCondition(nodes) && (
951
+ <div className="cg-pop-note">
952
+ Ranked among the records your other conditions keep β€” so β€œtop 10” inside a filtered
953
+ view means the top 10 of that view. Records with no value are not ranked at all.
954
+ Quartiles and deciles are equal-size slices BY RANK, not by value.
955
+ </div>
956
+ )}
957
+ {/* The footer carries "Clear all" (only when there is something to clear) and whatever
958
+ door the host mounts in `footerExtra`.
959
+ ⚠ The door is in the FOOTER rather than beside the add-links, where the reference
960
+ screenshot has it, for one structural reason: `.cg-builder-add` is emitted once per
961
+ NESTING LEVEL, so a link there would repeat inside every condition group and offer
962
+ to overwrite the whole view from inside one of its brackets. The footer is the one
963
+ place in this popover that means "the view", which is what the copy acts on. It is
964
+ also offered when there are NO conditions yet, which is when somebody most wants to
965
+ start from another view. */}
966
+ {(nodes.length > 0 || footerExtra) && (
967
+ <div className="cg-pop-footer cg-builder-footer">
968
+ {nodes.length > 0 && (
969
+ <button
970
+ type="button"
971
+ className="cg-link-btn"
972
+ onClick={() => onChange({ conj, nodes: [] })}
973
+ >
974
+ Clear all
975
+ </button>
976
+ )}
977
+ {footerExtra}
978
+ </div>
979
+ )}
980
+ </div>
981
+ );
982
+ }
web/src/filter-kit/Popover.tsx ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // ---------------------------------------------------------------------------
2
+ // filter-kit / Popover.tsx
3
+ // The quiet text+icon toolbar button that opens an anchored panel.
4
+ //
5
+ // Extracted from customer-grid/Toolbar.tsx (wave 15, C-KIT). It lives here rather
6
+ // than beside the toolbar because it is what makes the Filter / Hide-fields
7
+ // panels LOOK the same wherever they are mounted, and "the same" is achieved by
8
+ // being the same component, not by a lookalike.
9
+ // ---------------------------------------------------------------------------
10
+
11
+ import { useEffect, useId, useRef, useState } from "react";
12
+ import type { ReactNode } from "react";
13
+ import { AnchoredOverlay } from "../customer-grid/OverlaySurface";
14
+
15
+ const stroke = {
16
+ stroke: "currentColor",
17
+ strokeWidth: 1.5,
18
+ strokeLinecap: "round" as const,
19
+ strokeLinejoin: "round" as const,
20
+ };
21
+
22
+ export function Chevron() {
23
+ return (
24
+ <svg width="10" height="10" viewBox="0 0 16 16" fill="none" aria-hidden>
25
+ <path d="M4 6l4 4 4-4" {...stroke} />
26
+ </svg>
27
+ );
28
+ }
29
+
30
+ // --- click-outside popover -------------------------------------------------
31
+ // Exported for the view-mode switcher (wave-7 item W12): the switcher must be a
32
+ // dropdown VISUALLY IDENTICAL to Fields/Filter/Sort, and sameness is achieved by
33
+ // being the same component, not a lookalike.
34
+ export function Popover({
35
+ label,
36
+ icon,
37
+ active,
38
+ tone,
39
+ wide,
40
+ measureWide,
41
+ pairWide,
42
+ forceOpenSignal,
43
+ children,
44
+ }: {
45
+ label: string;
46
+ icon: ReactNode;
47
+ active?: boolean;
48
+ /**
49
+ * Owner item 22 β€” the SEMANTIC hue this control wears once it is active:
50
+ * filter = green, sort = yellow, group = purple. Absent keeps the neutral blue active state,
51
+ * which is right for Fields / Color / Rows: those change how the table LOOKS, while these
52
+ * three change what it SAYS (which rows, in what order, in what buckets) β€” and only the
53
+ * second group earns a colour of its own.
54
+ *
55
+ * A class, never an inline style: the hexes live in index.css as `--lp-*` and in theme.ts for
56
+ * the canvas, and those two are held together by verify_icons' I7c parity. An inline style
57
+ * here would be a third copy, outside the gate.
58
+ */
59
+ tone?: "filter" | "sort" | "group";
60
+ /** widen the panel for the condition/sort builders (multi-control rows) */
61
+ wide?: boolean;
62
+ /** CG-8: wider still, for the extra WINDOW control a measure condition carries. */
63
+ measureWide?: boolean;
64
+ /** CG-9: wider again while a rule compares against another ATTRIBUTE β€” three more controls.
65
+ * Conditional rather than permanent, so an ordinary condition keeps its derived width. */
66
+ pairWide?: boolean;
67
+ /** Wave-5 item 1 β€” a monotonic signal that OPENS this popover (the column menu's
68
+ * "Filter by this field" lands the user in the builder, not in front of a closed button). */
69
+ forceOpenSignal?: number;
70
+ children: (close: () => void) => ReactNode;
71
+ }) {
72
+ const [open, setOpen] = useState(false);
73
+ const triggerRef = useRef<HTMLButtonElement>(null);
74
+ const panelId = useId();
75
+ useEffect(() => {
76
+ if (forceOpenSignal && forceOpenSignal > 0) setOpen(true);
77
+ }, [forceOpenSignal]);
78
+
79
+ return (
80
+ <div className="cg-pop-wrap">
81
+ <button
82
+ ref={triggerRef}
83
+ type="button"
84
+ className={
85
+ "cg-tb-btn" +
86
+ (tone ? ` cg-tb-btn--${tone}` : "") +
87
+ (active || open ? " is-active" : "")
88
+ }
89
+ onClick={() => setOpen((o) => !o)}
90
+ aria-expanded={open}
91
+ aria-haspopup="dialog"
92
+ aria-controls={open ? panelId : undefined}
93
+ // Wave-15 item 11 β€” the toolbar collapses these to ICON ONLY under width pressure
94
+ // rather than growing a horizontal scrollbar, so the name has to survive somewhere
95
+ // else. `title` is the hover affordance; `aria-label` is NOT optional beside it β€”
96
+ // `display: none` removes the label span from the accessibility tree entirely, so
97
+ // without this the collapsed button would be an unnamed button to a screen reader.
98
+ // Set at ALL widths, not only narrow ones: markup cannot see a media query, and a name
99
+ // that exists only below 1080px is a name nobody maintains.
100
+ title={label}
101
+ aria-label={label}
102
+ >
103
+ {icon}
104
+ {/* Classed rather than a bare <span>: the collapse rule must hit exactly the labels
105
+ that have an icon to fall back to. Two toolbar buttons are TEXT ONLY
106
+ (`.cg-tb-addcust`, `.cg-mode-field`) and hiding their words would leave an empty
107
+ box β€” a control that is painted, clickable and says nothing. */}
108
+ <span className="cg-tb-label">{label}</span>
109
+ <Chevron />
110
+ </button>
111
+ {open && triggerRef.current && (
112
+ <AnchoredOverlay
113
+ anchor={triggerRef.current}
114
+ className={
115
+ "cg-pop" + (wide ? " cg-pop--wide" : "") +
116
+ (measureWide ? " cg-pop--measures" : "") +
117
+ (pairWide ? " cg-pop--pair" : "")
118
+ }
119
+ onDismiss={() => setOpen(false)}
120
+ role="dialog"
121
+ ariaLabel={`${label} options`}
122
+ id={panelId}
123
+ dataKind={`toolbar-${label.split(" ")[0].toLowerCase()}`}
124
+ >
125
+ {children(() => setOpen(false))}
126
+ </AnchoredOverlay>
127
+ )}
128
+ </div>
129
+ );
130
+ }
web/src/filter-kit/WindowPicker.tsx ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // ---------------------------------------------------------------------------
2
+ // filter-kit / WindowPicker.tsx
3
+ // The DATE-WINDOW bracket, shared by the condition builder and the column menu.
4
+ //
5
+ // Extracted from customer-grid/Toolbar.tsx (wave 15, C-KIT).
6
+ // ---------------------------------------------------------------------------
7
+
8
+ import type { WindowKind, WindowSpec } from "../customer-grid/windows";
9
+ import { N_KINDS, WINDOW_KINDS, WINDOW_LABELS } from "../customer-grid/windows";
10
+
11
+ /**
12
+ * CG-8 β€” the WINDOW bracket of `Where [Sales] [in the last 90 days] [>] [5,000]`.
13
+ *
14
+ * Sits between the field and the operator, because that is the order the sentence reads. The
15
+ * kinds and their wording come from `windows.ts`, which is one half of a lock-step contract with
16
+ * `harness/windows.py` β€” so the phrase on screen and the days the server sums cannot drift.
17
+ *
18
+ * Two kinds need a second control: `last_n_days`/`next_n_days` take an N, and `custom` takes two
19
+ * dates. A custom range with only one bound is legal and means open-ended on the other side.
20
+ */
21
+ export function WindowPicker({
22
+ window: spec,
23
+ onWindow,
24
+ kinds = WINDOW_KINDS as readonly WindowKind[],
25
+ }: {
26
+ window: WindowSpec;
27
+ onWindow: (w: WindowSpec) => void;
28
+ /** A narrowed offer. `is within` shows the seven ranges the owner listed plus `custom`;
29
+ * a measure's window shows all sixteen. Same vocabulary either way β€” the LIST is what
30
+ * differs, never the meaning. */
31
+ kinds?: readonly WindowKind[];
32
+ }) {
33
+ const kind = spec.kind;
34
+ const offered = kinds.includes(kind) ? kinds : [...kinds, kind];
35
+ return (
36
+ <span className="cg-cond-window">
37
+ <select
38
+ className="cg-select cg-cond-win-kind"
39
+ value={kind}
40
+ aria-label="Date window"
41
+ onChange={(e) => {
42
+ const next = e.target.value as WindowSpec["kind"];
43
+ // Carry nothing across: an `n` left behind on a `custom` window, or a stale `from`
44
+ // on a relative one, is state the user cannot see and cannot clear.
45
+ if (N_KINDS.has(next)) onWindow({ kind: next, n: spec.n ?? 30 });
46
+ else if (next === "custom")
47
+ onWindow({ kind: next, from: spec.from ?? "", to: spec.to ?? "" });
48
+ else onWindow({ kind: next });
49
+ }}
50
+ >
51
+ {offered.map((k) => (
52
+ <option key={k} value={k}>
53
+ {N_KINDS.has(k)
54
+ ? WINDOW_LABELS[k].replace("{n}", "N")
55
+ : WINDOW_LABELS[k]}
56
+ </option>
57
+ ))}
58
+ </select>
59
+ {N_KINDS.has(kind) && (
60
+ <input
61
+ className="cg-input cg-cond-win-n"
62
+ type="number"
63
+ min={1}
64
+ max={3650}
65
+ aria-label="Number of days"
66
+ value={spec.n ?? ""}
67
+ onChange={(e) =>
68
+ onWindow({ ...spec, n: e.target.value === "" ? undefined : Number(e.target.value) })
69
+ }
70
+ />
71
+ )}
72
+ {kind === "custom" && (
73
+ <>
74
+ <input
75
+ className="cg-input cg-cond-win-date"
76
+ type="date"
77
+ aria-label="Window start"
78
+ value={spec.from ?? ""}
79
+ onChange={(e) => onWindow({ ...spec, from: e.target.value })}
80
+ />
81
+ <span className="cg-cond-and">and</span>
82
+ <input
83
+ className="cg-input cg-cond-win-date"
84
+ type="date"
85
+ aria-label="Window end"
86
+ value={spec.to ?? ""}
87
+ onChange={(e) => onWindow({ ...spec, to: e.target.value })}
88
+ />
89
+ </>
90
+ )}
91
+ </span>
92
+ );
93
+ }
web/src/filter-kit/index.ts ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // ---------------------------------------------------------------------------
2
+ // filter-kit β€” the mountable filter + hide-fields panels (wave 15, contract C-KIT).
3
+ //
4
+ // ONE condition builder for every surface that has to describe "which records".
5
+ // The grid toolbar mounts it over a view; the admin permission editor mounts it
6
+ // over a user's permanent filter for a module. Two vocabularies of the same idea
7
+ // would drift within a wave β€” this is why the extraction happened first.
8
+ //
9
+ // THE KIT FETCHES NOTHING. Fields, cohorts, measures, the people a `user` field
10
+ // may name, and the per-field choice lists all arrive as props, which is what
11
+ // lets the same panel serve a module whose rows this browser never loaded.
12
+ // ---------------------------------------------------------------------------
13
+
14
+ export { FilterBuilderPanel } from "./FilterBuilderPanel";
15
+ export type { FilterBuilderPanelProps } from "./FilterBuilderPanel";
16
+ export { FieldsHidePanel } from "./FieldsHidePanel";
17
+ export type { FieldsHidePanelProps } from "./FieldsHidePanel";
18
+ export { Popover, Chevron } from "./Popover";
19
+ export { WindowPicker } from "./WindowPicker";
20
+ export {
21
+ MEASURE_OP_LIST, countConditions, newRuleId, opsForType,
22
+ } from "./ops";
web/src/filter-kit/ops.ts ADDED
@@ -0,0 +1,380 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // ---------------------------------------------------------------------------
2
+ // filter-kit / ops.ts
3
+ // The filter/sort operator VOCABULARY β€” which operators each field type offers,
4
+ // and how each one reads to a human.
5
+ //
6
+ // Extracted verbatim from customer-grid/Toolbar.tsx (wave 15, contract C-KIT) so
7
+ // the permission editor and the grid toolbar offer ONE vocabulary rather than two
8
+ // that drift. The matching engine (matchFilter/makeComparator in useVisibleRows)
9
+ // and its Python mirrors (filter_sql.py, filter_eval.py) are the other halves of
10
+ // the same contract; these are only the labels the popovers render.
11
+ // ---------------------------------------------------------------------------
12
+
13
+ import type {
14
+ Conjunction,
15
+ Field,
16
+ FieldType,
17
+ FilterNode,
18
+ FilterOp,
19
+ FilterRule,
20
+ Measure,
21
+ } from "../customer-grid/types";
22
+ import {
23
+ COHORT_FIELD, COHORT_OPS, MEASURE_OPS, MEASURE_PAIR_OPS, isFilterGroup,
24
+ isDateFamilyType, isMeasureRule, isNumericFieldType, isRankOp, normalizeCohortOp,
25
+ } from "../customer-grid/types";
26
+ import type { CohortOp } from "../customer-grid/types";
27
+ import type { FieldSelectItem, FieldSelectType } from "../customer-grid/FieldSelect";
28
+ import type { WindowKind, WindowSpec } from "../customer-grid/windows";
29
+
30
+ // The type families live in types.ts (ONE definition for every UI surface); the engine keeps
31
+ // its own deliberately self-contained copies β€” see isNumericFieldType's doc.
32
+ export const isNumericType = isNumericFieldType;
33
+ export const isDateFamily = isDateFamilyType;
34
+
35
+ /**
36
+ * Operators offered for a field type (first = the default for new conditions).
37
+ * Mirrors Airtable's own per-type sets, verified against the live product
38
+ * (2026-07-25): a text field offers exactly contains / does not contain / is /
39
+ * is not / is empty / is not empty. Every type ends with the two value-free ops.
40
+ *
41
+ * NOTE on isEmpty over the Customer List contract: several Odoo-derived money
42
+ * columns (revenue_ytd, revenue_ly, at_risk, ltm_rev, orders_24m, est_missed) are
43
+ * built with 0.0/0 defaults in customer_list.pool(), so "is empty" correctly
44
+ * matches NOTHING there β€” 0 is a real value, not a blank. The columns where it
45
+ * genuinely bites are last_order (''), days_since, typical_gap_days, yoy_pct, and
46
+ * every overlay field (notes / custom) β€” "customers with no notes yet" is the
47
+ * common case. Offered on all types anyway, exactly as Airtable does.
48
+ *
49
+ * ⚠ AND the SENTINEL columns, which are a third case and the one that surprises:
50
+ * agent Β· city Β· state Β· country Β· zip Β· payment_terms Β· pricelist Β· tags all
51
+ * collapse a blank to the STRING '(none)' in `_partner_attrs`, so grouping has no
52
+ * null bucket. `isEmpty` tests `value === ""`, so on these it matches nothing even
53
+ * though 76 customers have no country and 79 no zip β€” the blanks are found with
54
+ * `is` `(none)`, which is also what the cell visibly says. Each of those fields
55
+ * carries that sentence as its column `note`, because a source comment is not
56
+ * where the person filtering is looking. DATE attributes keep '' instead
57
+ * (customer_since, last_order): '(none)' in a date column would sort and compare
58
+ * as text against ISO dates.
59
+ */
60
+ export function opsForType(t: FieldType): FilterOp[] {
61
+ // Wave-5: a checkbox stores '1' or blank, so "is checked" IS `isNotEmpty` and "is
62
+ // unchecked" IS `isEmpty` β€” the honest mapping onto the existing vocabulary (no new
63
+ // FilterOp, the filter_sql lock-step untouched). Both are value-free, so no value control
64
+ // renders. First = the default: "is checked".
65
+ if (t === "checkbox") return ["isNotEmpty", "isEmpty"];
66
+ if (isNumericType(t))
67
+ return ["gte", "gt", "lte", "lt", "eq", "neq", "between", "isEmpty", "isNotEmpty"];
68
+ if (isDateFamily(t))
69
+ // Owner item 3, in the order they asked for it. `between` is GONE from the offer β€” "is
70
+ // within" plus a custom range says the same thing and reads better β€” but it stays in the
71
+ // ENGINE, because saved views hold it. `legacyOps` below is what keeps such a view
72
+ // rendering its own operator instead of silently showing the first one in this list.
73
+ return ["eq", "within", "lt", "gt", "lte", "gte", "neq", "isEmpty", "isNotEmpty"];
74
+ // `select` and `user` are picked from a fixed list, so they behave like `status`: is / is
75
+ // not / empty. `contains` on a chosen value is a substring test against a closed vocabulary β€”
76
+ // it would find "Done" inside "Not done" and read as a bug.
77
+ if (t === "status" || t === "select" || t === "user")
78
+ return ["eq", "neq", "isEmpty", "isNotEmpty"];
79
+ // A `multiselect` cell is a comma-joined SET, so the useful question is membership β€” "has" β€”
80
+ // which is the EXISTING `contains` op over the joined string (no new engine vocabulary; the
81
+ // ops are mirrored in filter_sql.py and inventing one here would break the lock-step). The
82
+ // value is still picked from the declared options, so the substring caveat above is bounded
83
+ // by the user's own choice list. `eq` reads "is exactly": the whole set is that one choice.
84
+ if (t === "multiselect")
85
+ return ["contains", "doesNotContain", "eq", "neq", "isEmpty", "isNotEmpty"];
86
+ return ["contains", "doesNotContain", "eq", "neq", "isEmpty", "isNotEmpty"]; // text
87
+ }
88
+
89
+ /**
90
+ * C-OPS β€” the RANK operators, worded so the row still reads as a sentence.
91
+ *
92
+ * The unit lives in the OPERATOR, not beside the box: "top" followed by a bare 10 is ambiguous
93
+ * between ten records and ten percent, so `top N` and `top N%` are two operators and the box
94
+ * supplies N. The alternative β€” a "%" suffix element after the input β€” would put a second
95
+ * thing in the value slot that every gate locating `.cg-cond-val` would have to know about.
96
+ *
97
+ * ⚠ AND THEY ARE SHORT ON PURPOSE. A 136px `.cg-select` has ~97.9px of readable width (see
98
+ * `cohortOpLabel` below, and `withCurrentField` below) β€” about 15 characters of 12.5px Inter.
99
+ * "is in the bottom N%" is 19 and would have shipped CLIPPED, which no assertion here can see
100
+ * and no screenshot in this session could catch. Dropping the "is " costs nothing: the numeric
101
+ * operators beside these are bare glyphs (`β‰₯ > ≀ <`), so the row already reads without one,
102
+ * and the `Ranked` divider carries the "these are a different kind of question" signal. Fifth
103
+ * time this control has outgrown a label; the label gives way, never the control.
104
+ */
105
+ export const RANK_OP_LABELS: Record<string, string> = {
106
+ topN: "top N",
107
+ bottomN: "bottom N",
108
+ inTopPct: "top N%",
109
+ inBottomPct: "bottom N%",
110
+ aboveAvg: "above average",
111
+ belowAvg: "below average",
112
+ inQuartile: "in quartile",
113
+ inDecile: "in decile",
114
+ };
115
+
116
+ /**
117
+ * The value a rank op starts at when it is chosen.
118
+ *
119
+ * Seeded rather than left blank, and this is a deliberate break from how the other operators
120
+ * behave: a blank value makes a rule INACTIVE, so `is in the top N` with nothing typed would
121
+ * sit in the builder narrowing nothing, and "the filter I just added does nothing" reads as a
122
+ * broken control rather than as an unfinished sentence. Every rank op has an obvious default β€”
123
+ * ten, or the top slice β€” so there is a right answer to seed. The two averages take none.
124
+ */
125
+ export function rankDefault(op: FilterOp): string {
126
+ switch (op) {
127
+ case "topN":
128
+ case "bottomN":
129
+ case "inTopPct":
130
+ case "inBottomPct":
131
+ case "inDecile":
132
+ return "10";
133
+ case "inQuartile":
134
+ return "4";
135
+ default:
136
+ return ""; // aboveAvg / belowAvg β€” value-free
137
+ }
138
+ }
139
+
140
+ /** Does this tree hold an ACTIVE-looking rank condition? Drives the builder's helper line β€”
141
+ * the semantics of a quantile are not guessable, so they are stated where they are chosen. */
142
+ export function hasRankCondition(nodes: FilterNode[]): boolean {
143
+ for (const node of nodes ?? []) {
144
+ if (isFilterGroup(node)) {
145
+ if (hasRankCondition(node.children)) return true;
146
+ continue;
147
+ }
148
+ if (isRankOp(node.op) && !isMeasureRule(node)) return true;
149
+ }
150
+ return false;
151
+ }
152
+
153
+ /** Human label for an operator, read naturally per field type. */
154
+ export function opLabel(op: FilterOp, t: FieldType): string {
155
+ // Rank first and type-independently: a rank op means the same thing on every numeric
156
+ // family, and a view whose column has since changed type must still SAY what it holds
157
+ // rather than falling through to a raw key.
158
+ if (isRankOp(op)) return RANK_OP_LABELS[op] ?? op;
159
+ // Checkbox first: its two value-free ops READ as states, not as blankness β€” the storage
160
+ // contract ('1' or blank) is an implementation detail the sentence must not leak.
161
+ if (t === "checkbox") {
162
+ if (op === "isNotEmpty") return "is checked";
163
+ if (op === "isEmpty") return "is unchecked";
164
+ }
165
+ // Type-independent: Airtable words these identically for every field type.
166
+ if (op === "isEmpty") return "is empty";
167
+ if (op === "isNotEmpty") return "is not empty";
168
+ if (isDateFamily(t)) {
169
+ switch (op) {
170
+ case "eq":
171
+ return "is";
172
+ case "neq":
173
+ return "is not";
174
+ case "within":
175
+ return "is within";
176
+ case "lt":
177
+ return "is before";
178
+ case "lte":
179
+ return "is on or before";
180
+ case "gt":
181
+ return "is after";
182
+ case "gte":
183
+ return "is on or after";
184
+ case "between":
185
+ return "is between"; // no longer offered; still rendered for a saved view
186
+ }
187
+ }
188
+ if (isNumericType(t)) {
189
+ switch (op) {
190
+ case "gte":
191
+ return "β‰₯"; // β‰₯
192
+ case "gt":
193
+ return ">";
194
+ case "lte":
195
+ return "≀"; // ≀
196
+ case "lt":
197
+ return "<";
198
+ case "eq":
199
+ return "=";
200
+ case "neq":
201
+ return "β‰ "; // β‰ 
202
+ case "between":
203
+ return "is between";
204
+ default:
205
+ return op;
206
+ }
207
+ }
208
+ if (t === "multiselect") {
209
+ // Membership wording over the joined-set cell. "has" IS `contains` (see opsForType) β€” only
210
+ // the label changes, so the engine and its Python mirror stay untouched.
211
+ switch (op) {
212
+ case "contains":
213
+ return "has";
214
+ case "doesNotContain":
215
+ return "does not have";
216
+ case "eq":
217
+ return "is exactly";
218
+ case "neq":
219
+ return "is not exactly";
220
+ default:
221
+ return op;
222
+ }
223
+ }
224
+ // text / status. (Airtable suffixes value-taking ops with "…" in the OPEN
225
+ // dropdown only; a native <select> shows one string in both states, so we use
226
+ // the closed-state wording β€” which is what's on screen almost all the time.)
227
+ switch (op) {
228
+ case "contains":
229
+ return "contains";
230
+ case "doesNotContain":
231
+ return "does not contain";
232
+ case "eq":
233
+ return "is";
234
+ case "neq":
235
+ return "is not";
236
+ default:
237
+ return op;
238
+ }
239
+ }
240
+
241
+ /**
242
+ * The offered list, PLUS whatever the rule is actually set to.
243
+ *
244
+ * A `<select>` whose `value` is not among its `<option>`s renders the FIRST option instead β€”
245
+ * so a saved view holding a dropped operator (a date `between`) or a column that has since left
246
+ * the filter list (`at_risk`, once its measure replacement shipped) would display something the
247
+ * rule does not say, and the first edit would silently rewrite it to that. Painted, plausible,
248
+ * and wrong: the class of failure a screenshot catches and an assertion does not.
249
+ */
250
+ export function withCurrent<T extends string>(offered: readonly T[], current: T | undefined): T[] {
251
+ return current && !offered.includes(current) ? [...offered, current] : [...offered];
252
+ }
253
+
254
+ /** A group's summary line, mirroring Airtable's wording. */
255
+ export function groupSummary(conj: Conjunction): string {
256
+ return conj === "or"
257
+ ? "Any of the following are true…"
258
+ : "All of the following are true…";
259
+ }
260
+
261
+ /**
262
+ * CG-8 β€” the operators a MEASURE condition may use, and why they are not `opsForType`.
263
+ *
264
+ * A measure is answered by a SQL `HAVING`, and `harness/measure_filter.OPS` has exactly six
265
+ * comparisons. `between` would need two, and `isEmpty`/`isNotEmpty` have no meaning for a sum
266
+ * that is defined to be 0 when there is nothing to add up β€” the resolver refuses all three by
267
+ * name. Offering them here would produce a condition the server can only reject.
268
+ *
269
+ * The owner's "dates between X and Y" is the WINDOW's between, not the value's, and that is the
270
+ * `custom` window kind β€” so nothing is lost.
271
+ */
272
+ export const MEASURE_OP_LIST: FilterOp[] = [...MEASURE_OPS];
273
+
274
+ /** CG-9 β€” narrower still when the other side is a measure. `=` and `β‰ ` between two sums of
275
+ * floats match nobody and everybody respectively; see types.ts MEASURE_PAIR_OPS. */
276
+ export const MEASURE_PAIR_OP_LIST: FilterOp[] = [...MEASURE_PAIR_OPS];
277
+
278
+ /**
279
+ * A cohort condition names a SET of cohorts (owner, 2026-07-27), so its operators are set
280
+ * operators. `eq`/`neq` are not offered β€” the validator rewrites them to `anyOf`/`noneOf`, and
281
+ * `withCurrent` would otherwise show a legacy view an operator it can never choose again.
282
+ */
283
+ export const COHORT_OP_LIST: CohortOp[] = [...COHORT_OPS];
284
+
285
+ /**
286
+ * ⚠ "is part of any of" measures ~96px at 12.5px Inter against the 97.9px of readable width a
287
+ * 136px select actually has (136 - 20.1 arrow - 16 padding - 2 border) β€” inside the box only
288
+ * until a fallback font renders it. Airtable's own wording for a multi-select is shorter and
289
+ * says the same thing, so the LABEL gives way, not the control. Third time this rule has been
290
+ * applied; see the "(not filterable)" and "the 75th percentile" clippings before it.
291
+ */
292
+ export function cohortOpLabel(op: FilterOp | CohortOp): string {
293
+ switch (normalizeCohortOp(op)) {
294
+ case "allOf":
295
+ return "is all of";
296
+ case "noneOf":
297
+ return "is none of";
298
+ default:
299
+ return "is any of";
300
+ }
301
+ }
302
+
303
+ /** Item 20 β€” the mark a MEASURE row wears in every picker on this surface. Named once so the
304
+ * three lists that offer measures cannot drift into two different glyphs for one concept. */
305
+ export const MEASURE_MARK: FieldSelectType = "measure";
306
+
307
+ /** A measure condition is identified by its window, so a new one needs a default window. */
308
+ export const DEFAULT_WINDOW: WindowSpec = { kind: "ltm" };
309
+
310
+ /** The default RANGE for `is within` β€” the owner's first example ("the past month"). */
311
+ export const DEFAULT_DATE_WINDOW: WindowSpec = { kind: "past_month" };
312
+
313
+ /**
314
+ * The ranges `is within` offers, in the owner's own order (item 3, 2026-07-26):
315
+ * the past number of days Β· the past week Β· the past month Β· the past year Β· this calendar
316
+ * week Β· this calendar month Β· this calendar year.
317
+ *
318
+ * Plus `custom`, which is not a nicety: dropping `between` from the date operators would
319
+ * otherwise remove the ability to ask for two exact dates at all. The remaining kinds
320
+ * (yesterday, last_quarter, ytd_last_year, the forward-looking ones…) stay available to a
321
+ * MEASURE's window, where they make sense; "last order is within year to date, last year" is a
322
+ * question nobody asks.
323
+ */
324
+ export const WITHIN_KINDS: WindowKind[] = [
325
+ "last_n_days", "past_week", "past_month", "past_year",
326
+ "this_week", "this_month", "this_year", "custom",
327
+ ];
328
+
329
+ /**
330
+ * The field dropdown's COLUMN half, plus the column the rule is actually set to if the picker
331
+ * no longer offers it. See `withCurrent` β€” a select whose value is missing from its options
332
+ * silently displays a different field than the rule holds. This is not hypothetical: the
333
+ * shipped "Win-back" list filters `at_risk`, which left the filter list the day its measure
334
+ * replacement arrived.
335
+ */
336
+ export function withCurrentField(
337
+ fields: Field[],
338
+ current: string,
339
+ fieldByKey: Map<string, Field>,
340
+ measureByKey: Map<string, Measure>,
341
+ hasCohorts: boolean
342
+ ): FieldSelectItem[] {
343
+ // Item 20: the rows carry their TYPE now, because the picker paints the type mark. Same
344
+ // list, same order, same `withCurrent` rule β€” only the shape of a row grew a field.
345
+ const out: FieldSelectItem[] = fields.map((f) => ({
346
+ key: f.key, label: f.label, type: f.type,
347
+ }));
348
+ const known = new Set(out.map((o) => o.key));
349
+ if (!current || known.has(current) || measureByKey.has(current)) return out;
350
+ if (current === COHORT_FIELD && hasCohorts) return out;
351
+ // The field's OWN label, with no "(not filterable)" annotation: the select is ~170px and the
352
+ // suffix CLIPPED to "At risk $ (not filter" β€” a truncated parenthetical reads as a rendering
353
+ // bug, and the property that matters is that the condition says what it says. Found by
354
+ // reading the screenshot; every assertion in the run was green.
355
+ const f = fieldByKey.get(current);
356
+ out.push({ key: current, label: f ? f.label : current, type: f?.type });
357
+ return out;
358
+ }
359
+
360
+ /** Ids only have to be unique within one view's tree; they never leave this browser's view. */
361
+ let ruleSeq = 0;
362
+ export function newRuleId(): string {
363
+ ruleSeq += 1;
364
+ return `r${Date.now().toString(36)}${ruleSeq.toString(36)}`;
365
+ }
366
+
367
+ /** A fresh leaf condition on the first available field. */
368
+ export function newCondition(fields: Field[]): FilterRule | null {
369
+ const f0 = fields[0];
370
+ if (!f0) return null;
371
+ return { colId: f0.key, op: opsForType(f0.type)[0], value: "" };
372
+ }
373
+
374
+ /** Total LEAF conditions in a filter tree (groups contribute their contents). */
375
+ export function countConditions(nodes: FilterNode[]): number {
376
+ let n = 0;
377
+ for (const node of nodes)
378
+ n += isFilterGroup(node) ? countConditions(node.children) : 1;
379
+ return n;
380
+ }
web/src/index.css CHANGED
@@ -160,6 +160,31 @@
160
  --lp-purple: #c3b3ee; /* FILL only (1.91:1) */
161
  --lp-purple-tint: #f1eefb; /* the GROUP chip wash + its column header */
162
  --lp-purple-deep: #6b57a8; /* 5.17:1 on its tint β€” group chip text */
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
163
  }
164
 
165
  /* ⚠ wave-10 follow-up β€” THE ROOT MUST MATCH THE HOST'S, or the shared type scale is a lie.
@@ -704,13 +729,24 @@ body {
704
  .cg-btn:hover:not(:disabled) {
705
  background: var(--cg-soft);
706
  }
 
 
 
 
 
 
 
 
707
  .cg-btn--primary {
708
- border-color: var(--lp-blue-deep);
709
- background: var(--lp-blue-solid);
710
  color: var(--cg-white);
711
  }
712
  .cg-btn--primary:hover:not(:disabled) {
713
- background: var(--cg-primary-hover);
 
 
 
714
  }
715
  .cg-btn:focus-visible,
716
  .cg-view-main:focus-visible,
@@ -718,6 +754,16 @@ body {
718
  outline: 2px solid var(--lp-blue-deep);
719
  outline-offset: 1px;
720
  }
 
 
 
 
 
 
 
 
 
 
721
  .cg-btn:disabled,
722
  .cg-column-actions button:disabled {
723
  opacity: 0.45;
@@ -993,9 +1039,16 @@ body {
993
  color: var(--lp-ink);
994
  user-select: none;
995
  min-width: 0;
996
- overflow-x: auto;
 
 
 
 
 
 
 
 
997
  overflow-y: hidden;
998
- scrollbar-width: thin;
999
  }
1000
 
1001
  .cg-tb-spacer {
@@ -1008,6 +1061,54 @@ body {
1008
  background: rgba(20, 24, 40, 0.1);
1009
  }
1010
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1011
  /* quiet text + icon button */
1012
  .cg-tb-btn {
1013
  display: inline-flex;
@@ -2587,9 +2688,10 @@ body {
2587
  .login-eye:disabled { cursor: not-allowed; opacity: 0.55; }
2588
  .login-eye svg { width: 17px; height: 17px; fill: none; stroke: currentColor; stroke-width: 1.4; stroke-linecap: round; stroke-linejoin: round; }
2589
 
2590
- /* The measured white for text ON `--lp-blue-solid` (6.40:1). A named token
2591
- rather than an inline #fff, so the contrast PAIR is documented where it is
2592
- used and cannot be edited by halves. */
 
2593
  .login-submit {
2594
  --shell-on-solid: #ffffff;
2595
  display: block;
@@ -2600,16 +2702,31 @@ body {
2600
  font-size: var(--lp-fs-sm);
2601
  font-weight: 600;
2602
  color: var(--shell-on-solid);
2603
- background: var(--lp-blue-solid);
2604
- border: 1px solid var(--lp-blue-solid);
2605
  border-radius: var(--lp-r-md);
2606
  cursor: pointer;
2607
  }
2608
- /* brightness rather than a second hex: a hover shade is a derivation of the
2609
- token, not a colour of its own. */
2610
- .login-submit:hover:not(:disabled) { filter: brightness(0.94); }
2611
- .login-submit:active:not(:disabled) { filter: brightness(0.88); }
2612
- .login-submit:focus-visible { outline: 2px solid var(--lp-blue-deep); outline-offset: 2px; }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2613
  .login-submit:disabled { opacity: 0.6; cursor: not-allowed; filter: none; }
2614
 
2615
  /* Reserved in the layout ALWAYS, so an arriving error never shoves the card.
@@ -3440,13 +3557,59 @@ body {
3440
  legs, measured overflow 203/183px). At narrow widths the toolbar WRAPS β€” the count
3441
  stays visible inside it on a second row; the fixed 44px height becomes a minimum so
3442
  the flex column below simply yields the extra row's height. */
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3443
  @media (max-width: 1080px) {
3444
- .cg-toolbar {
3445
- flex-wrap: wrap;
3446
- height: auto;
3447
- min-height: 44px;
3448
- padding-top: 4px;
3449
- padding-bottom: 4px;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3450
  }
3451
  }
3452
 
@@ -4914,7 +5077,12 @@ a.cg-map-ctl-b { text-decoration: none; }
4914
  align-items: center;
4915
  justify-content: center;
4916
  padding: 32px;
4917
- background: rgb(32 36 51 / 28%);
 
 
 
 
 
4918
  backdrop-filter: blur(3px);
4919
  }
4920
  .set-modal {
@@ -5044,18 +5212,122 @@ a.cg-map-ctl-b { text-decoration: none; }
5044
  font-weight: 600;
5045
  cursor: pointer;
5046
  }
5047
- .set-primary { border: 1px solid var(--lp-blue-solid); background: var(--lp-blue-solid); color: var(--lp-surface); }
5048
- .set-primary:hover:enabled { background: var(--lp-ink); border-color: var(--lp-ink); }
 
 
 
 
5049
  .set-secondary { border: 1px solid var(--lp-line); background: var(--lp-surface); color: var(--lp-ink); }
5050
  .set-secondary:hover:enabled { border-color: var(--lp-blue-deep); }
5051
  .set-primary:disabled, .set-secondary:disabled { opacity: 0.5; cursor: default; }
5052
- .set-primary:focus-visible, .set-secondary:focus-visible { outline: 2px solid var(--lp-blue-deep); outline-offset: 1px; }
 
 
 
 
5053
  .set-add { margin-top: 16px; }
5054
  /* The password block. The red hairline is the only signal that it revokes every
5055
  session the account has open β€” the sentence above the button says it in
5056
  words, and this says it before the words are read. */
5057
  .set-danger { margin-top: 18px; padding-top: 14px; border-top: 1px solid var(--lp-red-deep); }
5058
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5059
  /* ═══ TSREC REGION (wave 14) β€” PANEL keep out ═══ */
5060
  /* ------------------------------------------------------------------------- */
5061
  /* Owner item 7 (2026-08-02, contract C-TS): the TIME SERIES view β€” metric */
 
160
  --lp-purple: #c3b3ee; /* FILL only (1.91:1) */
161
  --lp-purple-tint: #f1eefb; /* the GROUP chip wash + its column header */
162
  --lp-purple-deep: #6b57a8; /* 5.17:1 on its tint β€” group chip text */
163
+
164
+ /* --- Wave-15 C-BOLD (owner ruling R7) β€” THE PRIMARY ACTION -----------------
165
+ "Key buttons bold (dark purple)". A THIRD role in the palette, and it is
166
+ worth naming why it is not one of the five hues above: `--lp-purple` is the
167
+ SEMANTIC hue of the group control (its chip, its involved columns), and a
168
+ Save button painted from it would say "this button is about grouping". The
169
+ primary is a ROLE, not a hue β€” so it gets its own name and its own family.
170
+
171
+ ⚠ NOT `--lp-blue-solid`, which these CTAs used until this wave. That token
172
+ is still the product blue and still correct everywhere else it is read; it
173
+ simply stops being what "the primary button" means.
174
+
175
+ MEASURED, never eyeballed (WCAG 2.x relative luminance, white foreground):
176
+ --lp-primary 7.71:1 --lp-primary-hover 9.47:1
177
+ --lp-primary-tint 1.18:1 on white β€” a WASH, in the measured band of
178
+ the other `-tint` values (1.14–1.20), so the same
179
+ rule holds: it fills, it never carries text.
180
+ R7's floor is 4.5:1 and the owner's named hex (#5b3fd4) already measures
181
+ 6.76:1; this is that hue darkened ~8%, which is the "dark" half of the
182
+ ruling. The hover is a further ~15% darkening β€” DARKER than the base, the
183
+ same law `--cg-primary-hover` states above, because a hover that lightens
184
+ reads as a disabled state. */
185
+ --lp-primary: #5433cc;
186
+ --lp-primary-hover: #472bad;
187
+ --lp-primary-tint: #eeeafc;
188
  }
189
 
190
  /* ⚠ wave-10 follow-up β€” THE ROOT MUST MATCH THE HOST'S, or the shared type scale is a lie.
 
729
  .cg-btn:hover:not(:disabled) {
730
  background: var(--cg-soft);
731
  }
732
+ /* Wave-15 R7 (C-BOLD) β€” THE grid's primary CTA, in the bold dark purple S3 published.
733
+ This one rule is the whole grid-side sweep: `.cg-btn--primary` is what every popover and
734
+ dialog in this tree paints its committing action with ("Save", "Create and change", "Copy
735
+ configuration", "Delete permanently?"). The other ~20 `--lp-blue-solid` uses under `.cg-*`
736
+ are LINKS, accent dots and focus washes, not buttons β€” R7 names key CTAs, and repainting a
737
+ link purple because it was blue would be a palette change nobody asked for.
738
+ ⚠ Variables, never the hexes: verify_icons' I7c parity diffs the declared `--lp-*` against
739
+ theme.ts, and a literal here would sit outside it. */
740
  .cg-btn--primary {
741
+ border-color: var(--lp-primary);
742
+ background: var(--lp-primary);
743
  color: var(--cg-white);
744
  }
745
  .cg-btn--primary:hover:not(:disabled) {
746
+ /* `--lp-primary-hover`, not `--cg-primary-hover`: that token derives from
747
+ `--lp-blue-solid`, so it would hover a purple button towards a dark BLUE. It has no other
748
+ consumer now β€” S3 owns the `:root` block and can retire it. */
749
+ background: var(--lp-primary-hover);
750
  }
751
  .cg-btn:focus-visible,
752
  .cg-view-main:focus-visible,
 
754
  outline: 2px solid var(--lp-blue-deep);
755
  outline-offset: 1px;
756
  }
757
+ /* ⚠ AFTER the rule above, and that is load-bearing rather than tidy: `.cg-btn--primary:
758
+ focus-visible` and `.cg-btn:focus-visible` have IDENTICAL specificity (0,2,0), so source
759
+ order is the only thing that decides. Written before it, the primary CTA would silently keep
760
+ the blue ring β€” the wave-9 nav scar, in miniature. S3's law: primary CTAs ring in their own
761
+ hue, everything else keeps `--lp-blue-deep`; a blue ring on a purple button reads as
762
+ leftover paint. */
763
+ .cg-btn--primary:focus-visible {
764
+ outline: 2px solid var(--lp-primary);
765
+ outline-offset: 1px;
766
+ }
767
  .cg-btn:disabled,
768
  .cg-column-actions button:disabled {
769
  opacity: 0.45;
 
1039
  color: var(--lp-ink);
1040
  user-select: none;
1041
  min-width: 0;
1042
+ /* ⭐ Wave-15 item 11 (owner) β€” THE TOOLBAR NEVER SCROLLS SIDEWAYS. This was `overflow-x:
1043
+ auto`, which is how a control strip ends up with a scrollbar under it: the controls are
1044
+ all still "there", and the ones that matter are off-screen behind a gesture nobody makes
1045
+ in a toolbar. It collapses to icons instead (see the two media steps below), so everything
1046
+ stays reachable at every width the grid runs at.
1047
+ `hidden` rather than `visible` is the belt: if some future control still overflows, it is
1048
+ clipped at the edge instead of painting over the grid beneath β€” and a clipped control is
1049
+ something a screenshot shows, where a scrolled one looks like a complete toolbar. */
1050
+ overflow-x: hidden;
1051
  overflow-y: hidden;
 
1052
  }
1053
 
1054
  .cg-tb-spacer {
 
1061
  background: rgba(20, 24, 40, 0.1);
1062
  }
1063
 
1064
+ /* Wave-15 item 5c (C-LOCK / R10) β€” the cohort-lock chip, beside Filter / Sort / Group.
1065
+ Deliberately NOT a `.cg-tb-btn`: it states a fact and does not act, and the lock is changed
1066
+ from the view rail's menu. Same height and radius as the buttons so the strip stays one row
1067
+ of objects, but no hover, no pointer, no chevron.
1068
+ It carries `.cg-tb-label`, so it COLLAPSES TO ITS PADLOCK with everything else under width
1069
+ pressure (item 11) and keeps its sentence in the `title`. */
1070
+ .cg-tb-lock {
1071
+ display: inline-flex;
1072
+ align-items: center;
1073
+ gap: 6px;
1074
+ flex: 0 0 auto;
1075
+ height: 30px;
1076
+ padding: 0 9px;
1077
+ border-radius: var(--lp-r-md);
1078
+ /* ⚠ NEUTRAL, and this is a correction made from reading the render rather than the diff.
1079
+ The chip was first written in `--lp-purple-*` and it landed immediately beside the GROUP
1080
+ chip, which R6 assigns purple β€” two purple chips side by side, one meaning "bucketed by
1081
+ Agent" and one meaning "locked to a list". The three semantic hues belong to Filter, Sort
1082
+ and Group; the lock is not a fourth control, it is a STATE of the table, so it stays out of
1083
+ that vocabulary entirely. Grey with a padlock reads as a fact, which is what it is. */
1084
+ background: var(--cg-soft);
1085
+ color: var(--lp-ink);
1086
+ white-space: nowrap;
1087
+ cursor: default;
1088
+ }
1089
+ .cg-tb-lock svg {
1090
+ color: var(--lp-muted);
1091
+ flex: 0 0 auto;
1092
+ }
1093
+
1094
+ /* Wave-15 item 5 (C-LOCK / R10) β€” the rail's "Cohorts" section. The cohort module's page is
1095
+ going away and its lists live here now, each a locked view row. A hairline and a quiet
1096
+ heading separate them from the views above, because they answer a different question:
1097
+ the views say which ARRANGEMENT, these say which LIST. */
1098
+ .cg-rail-section {
1099
+ margin-top: 10px;
1100
+ padding-top: 8px;
1101
+ border-top: 1px solid var(--lp-line);
1102
+ }
1103
+ .cg-rail-head {
1104
+ padding: 2px 10px 6px;
1105
+ font-size: var(--lp-fs-2xs);
1106
+ font-weight: 600;
1107
+ letter-spacing: 0.04em;
1108
+ text-transform: uppercase;
1109
+ color: var(--lp-muted);
1110
+ }
1111
+
1112
  /* quiet text + icon button */
1113
  .cg-tb-btn {
1114
  display: inline-flex;
 
2688
  .login-eye:disabled { cursor: not-allowed; opacity: 0.55; }
2689
  .login-eye svg { width: 17px; height: 17px; fill: none; stroke: currentColor; stroke-width: 1.4; stroke-linecap: round; stroke-linejoin: round; }
2690
 
2691
+ /* The measured white for text ON `--lp-primary` (7.71:1 β€” wave-15 C-BOLD moved
2692
+ this button off `--lp-blue-solid`, whose pairing measured 6.40:1). A named
2693
+ token rather than an inline #fff, so the contrast PAIR is documented where it
2694
+ is used and cannot be edited by halves. */
2695
  .login-submit {
2696
  --shell-on-solid: #ffffff;
2697
  display: block;
 
2702
  font-size: var(--lp-fs-sm);
2703
  font-weight: 600;
2704
  color: var(--shell-on-solid);
2705
+ background: var(--lp-primary);
2706
+ border: 1px solid var(--lp-primary);
2707
  border-radius: var(--lp-r-md);
2708
  cursor: pointer;
2709
  }
2710
+ /* ⚠ WAS `filter: brightness(0.94)`, on the reasoning that "a hover shade is a
2711
+ derivation of the token, not a colour of its own". That was right while there
2712
+ was only one hover in the shell; C-BOLD publishes `--lp-primary-hover`, and
2713
+ two CTA families deriving their own shades from one base is how the Sign-in
2714
+ button and the Save button end up hovering to different purples. The PRESSED
2715
+ state stays a derivation β€” it is a momentary step below whatever it sits on,
2716
+ not a colour anybody names. */
2717
+ .login-submit:hover:not(:disabled) {
2718
+ background: var(--lp-primary-hover);
2719
+ border-color: var(--lp-primary-hover);
2720
+ }
2721
+ .login-submit:active:not(:disabled) { filter: brightness(0.92); }
2722
+ /* The ring takes the CONTROL's own accent, not the file-wide `--lp-blue-deep`.
2723
+ A blue ring drawn around a purple button reads as leftover paint rather than
2724
+ as focus; every non-primary control keeps the blue ring, so the rule is
2725
+ "primary CTAs ring in the primary", stated once here and once at
2726
+ `.set-primary:focus-visible`. `outline-offset` puts it on the white page,
2727
+ where it measures 7.71:1 β€” visible against the surround, not against the
2728
+ button it would otherwise disappear into. */
2729
+ .login-submit:focus-visible { outline: 2px solid var(--lp-primary); outline-offset: 2px; }
2730
  .login-submit:disabled { opacity: 0.6; cursor: not-allowed; filter: none; }
2731
 
2732
  /* Reserved in the layout ALWAYS, so an arriving error never shoves the card.
 
3557
  legs, measured overflow 203/183px). At narrow widths the toolbar WRAPS β€” the count
3558
  stays visible inside it on a second row; the fixed 44px height becomes a minimum so
3559
  the flex column below simply yields the extra row's height. */
3560
+ /* ⭐ Wave-15 item 11 β€” the toolbar COLLAPSES TO ICONS instead of wrapping or scrolling.
3561
+ This block used to say `flex-wrap: wrap; height: auto` β€” a second toolbar row, which pushed
3562
+ the grid down and made the strip's height depend on the window. The owner asked for neither
3563
+ that nor a scrollbar: the controls give up their WORDS first, because a filter funnel and a
3564
+ sort glyph are recognisable and "Filter Β· 2" is not worth 60px of a 44px strip.
3565
+
3566
+ ⚠ Media queries, not container queries, and that is measured rather than lazy: the grid
3567
+ renders in its OWN iframe, so the iframe width IS the container width β€” the same reason
3568
+ `.cg-count-compact` above works. `container-type: inline-size` on an ancestor would also
3569
+ change how that ancestor sizes its children, for no gain here.
3570
+
3571
+ The name survives in `title` + `aria-label` on every collapsed button (see Popover.tsx) β€”
3572
+ `display: none` removes a label from the accessibility tree, so the aria half is what keeps
3573
+ these from becoming unnamed buttons rather than a nicety.
3574
+
3575
+ Arithmetic, so the steps are not taste: a labelled control is ~95-125px (18 padding + 14
3576
+ icon + 6 gap + label + 6 gap + 10 chevron); seven of them plus a 214px search plus the count
3577
+ is ~1070-1170px, which is why 1080 is where the first step lands. Icon-only takes each to
3578
+ 48px, so the same seven fit in ~336px and the strip is comfortable to ~600px. */
3579
  @media (max-width: 1080px) {
3580
+ .cg-tb-label {
3581
+ display: none;
3582
+ }
3583
+ /* Tighter without the words, or the icons sit in a lot of empty box. */
3584
+ .cg-tb-btn {
3585
+ padding: 0 7px;
3586
+ gap: 4px;
3587
+ }
3588
+ /* ⚠ Text-only toolbar buttons keep their words at every width β€” they have NO icon to fall
3589
+ back to, so collapsing them would leave an empty, clickable box. They are what
3590
+ `.cg-tb-label` exists to distinguish; this makes the exemption explicit rather than
3591
+ relying on the label span's absence. */
3592
+ .cg-tb-addcust,
3593
+ .cg-mode-field {
3594
+ padding: 0 9px;
3595
+ }
3596
+ }
3597
+
3598
+ /* The second step, for the genuinely cramped case (a narrow embed, or 50%/67% browser zoom,
3599
+ which scales the LAYOUT viewport and therefore trips these queries exactly as a small window
3600
+ does). The chevron is the least informative glyph in the button β€” it says "this opens", which
3601
+ the icon plus a click already teaches β€” so it goes before anything that names a control. */
3602
+ @media (max-width: 760px) {
3603
+ .cg-tb-btn > svg:last-child {
3604
+ display: none;
3605
+ }
3606
+ .cg-tb-btn {
3607
+ padding: 0 6px;
3608
+ gap: 0;
3609
+ }
3610
+ /* The search keeps a usable floor instead of shrinking to its own icon. */
3611
+ .cg-search-input {
3612
+ width: 120px;
3613
  }
3614
  }
3615
 
 
5077
  align-items: center;
5078
  justify-content: center;
5079
  padding: 32px;
5080
+ /* ⚠ WAS `rgb(32 36 51 / 28%)` β€” the SAME ink the palette publishes, written in
5081
+ decimal so no hex sweep could ever find it. That is the notation the :root
5082
+ block's own warning is about ("a colour audit that greps only hex is
5083
+ incomplete"), sitting in the file that carries the warning. Derived from the
5084
+ token now: the scrim tracks the ink instead of remembering it. */
5085
+ background: color-mix(in srgb, var(--lp-ink) 28%, transparent);
5086
  backdrop-filter: blur(3px);
5087
  }
5088
  .set-modal {
 
5212
  font-weight: 600;
5213
  cursor: pointer;
5214
  }
5215
+ /* Wave-15 C-BOLD (R7): the primary action reads `--lp-primary`, and its hover
5216
+ reads the published hover shade. ⚠ The hover was `--lp-ink` β€” near-black β€”
5217
+ which was defensible under a blue base and is not under a purple one: it
5218
+ stopped being a shade of the button and became a different button. */
5219
+ .set-primary { border: 1px solid var(--lp-primary); background: var(--lp-primary); color: var(--lp-surface); }
5220
+ .set-primary:hover:enabled { background: var(--lp-primary-hover); border-color: var(--lp-primary-hover); }
5221
  .set-secondary { border: 1px solid var(--lp-line); background: var(--lp-surface); color: var(--lp-ink); }
5222
  .set-secondary:hover:enabled { border-color: var(--lp-blue-deep); }
5223
  .set-primary:disabled, .set-secondary:disabled { opacity: 0.5; cursor: default; }
5224
+ /* Split from `.set-secondary`'s ring on purpose β€” see `.login-submit:focus-visible`
5225
+ for the one statement of the rule. A secondary button is not a primary and keeps
5226
+ the file-wide blue. */
5227
+ .set-primary:focus-visible { outline: 2px solid var(--lp-primary); outline-offset: 1px; }
5228
+ .set-secondary:focus-visible { outline: 2px solid var(--lp-blue-deep); outline-offset: 1px; }
5229
  .set-add { margin-top: 16px; }
5230
  /* The password block. The red hairline is the only signal that it revokes every
5231
  session the account has open β€” the sentence above the button says it in
5232
  words, and this says it before the words are read. */
5233
  .set-danger { margin-top: 18px; padding-top: 14px; border-top: 1px solid var(--lp-red-deep); }
5234
 
5235
+ /* --- R9: the permission editor (settings/PermsEditor) -----------------------
5236
+ A FULL-PANE TAKEOVER of the modal body, so the layout job here is small and
5237
+ specific: give the page a head that keeps the way out visible, stack one card
5238
+ per module, and let the grid's OWN panels sit inside those cards at their own
5239
+ size. The panels bring their entire appearance with them (`.cg-pop` and the
5240
+ `.cg-*` rules under it) β€” that is contract C-KIT working, and it is why there
5241
+ is no condition-builder styling in this block. Nothing here restyles a `.cg-*`
5242
+ rule; the two classes below only bound the box those panels sit in. */
5243
+ .set-perms { position: relative; }
5244
+ .set-perm-head {
5245
+ display: flex;
5246
+ align-items: flex-start;
5247
+ gap: 14px;
5248
+ margin-bottom: 16px;
5249
+ }
5250
+ .set-perm-who { min-width: 0; }
5251
+ /* The `.set-h` default carries 14px of bottom margin meant for a pane title
5252
+ that starts a block; here the username sits directly under it. */
5253
+ .set-perm-title { margin: 0; }
5254
+ .set-perm-banner { margin-bottom: 14px; }
5255
+ .set-perm-intro { margin: 0 0 16px; max-width: 68ch; line-height: var(--lp-lh); }
5256
+
5257
+ .set-perm-mod { margin-top: 14px; }
5258
+ .set-perm-modhead {
5259
+ display: flex;
5260
+ align-items: baseline;
5261
+ justify-content: space-between;
5262
+ gap: 12px;
5263
+ }
5264
+ .set-perm-toggle { padding: 0; }
5265
+ .set-perm-modname { font-size: var(--lp-fs-sm); font-weight: 620; }
5266
+ /* The rule in one phrase, beside the switch that sets it. Muted because it is a
5267
+ restatement of the controls below, never a control itself. */
5268
+ .set-perm-sum {
5269
+ flex: none;
5270
+ font-size: var(--lp-fs-2xs);
5271
+ color: var(--lp-muted);
5272
+ font-variant-numeric: tabular-nums;
5273
+ }
5274
+ .set-perm-panels {
5275
+ display: flex;
5276
+ flex-wrap: wrap;
5277
+ align-items: flex-start;
5278
+ gap: 14px;
5279
+ margin-top: 14px;
5280
+ }
5281
+ /* The kit's panels are popover-sized by design. Given a real width here they
5282
+ read as two cards of one section rather than two menus that failed to close;
5283
+ `flex: 1 1 320px` lets them sit side by side on a wide modal and stack on a
5284
+ narrow one without a media query. */
5285
+ .set-perm-pop { flex: 1 1 320px; max-width: 100%; }
5286
+ .set-perm-actions { align-items: center; margin-top: 20px; }
5287
+ .set-perm-dirty { margin: 0; }
5288
+
5289
+ /* The account name IS the door to this page (R9), so it has to look like a link
5290
+ and behave like a button: `pg-cell-link` gives the appearance, this removes
5291
+ the block-button box a <button> would otherwise impose on a table cell. */
5292
+ .set-user-door { display: block; padding: 0; text-align: left; }
5293
+ .set-user-door .set-user { display: block; }
5294
+
5295
+ /* Save asks first. Scoped INSIDE `.set-perms` rather than to the viewport: the
5296
+ question is about this page, and a second full-screen scrim over a dialog
5297
+ that already has one reads as the application having lost its place. */
5298
+ .set-confirm-wrap {
5299
+ position: absolute;
5300
+ inset: 0;
5301
+ /* β›” THIS NUMBER IS LOAD-BEARING, AND `z-index: 1` WAS A BUG. `.set-perm-pop`
5302
+ carries `.cg-pop`, which declares `z-index: var(--cg-z-menu)` (50) β€” and per
5303
+ the flexbox spec a z-index other than `auto` on a FLEX ITEM creates a
5304
+ stacking context even with `position: static`, which both mounted panels
5305
+ are. Nothing between them and this wrap opens a stacking context of its own
5306
+ (`.set-perms` and `.set-body` are positioned but `z-index: auto`), so all
5307
+ three resolve inside `.set-backdrop`'s context: panels at 50, confirm at 1.
5308
+ The filter and hide-fields panels punched straight through the scrim and
5309
+ covered the question β€” painted, dimmed and unanswerable
5310
+ ([[ui-invisible-to-assertions]]). It must outrank `--cg-z-menu`; the drawer
5311
+ step is the next one published, and `.set-backdrop` already reads a
5312
+ `--cg-z-*` token, so this is the established way for a `.set-` rule to say
5313
+ "above the grid's menus". */
5314
+ z-index: var(--cg-z-drawer);
5315
+ display: flex;
5316
+ align-items: center;
5317
+ justify-content: center;
5318
+ padding: 24px;
5319
+ /* Token-derived, never a literal rgba() β€” see the note on `.set-backdrop`. */
5320
+ background: color-mix(in srgb, var(--lp-surface) 74%, transparent);
5321
+ }
5322
+ .set-confirm {
5323
+ width: min(420px, 100%);
5324
+ padding: 18px 20px;
5325
+ border: 1px solid var(--lp-line);
5326
+ border-radius: var(--lp-r-lg);
5327
+ background: var(--lp-surface);
5328
+ box-shadow: var(--shell-shadow-overlay);
5329
+ }
5330
+
5331
  /* ═══ TSREC REGION (wave 14) β€” PANEL keep out ═══ */
5332
  /* ------------------------------------------------------------------------- */
5333
  /* Owner item 7 (2026-08-02, contract C-TS): the TIME SERIES view β€” metric */
web/src/settings/PermsEditor.tsx ADDED
@@ -0,0 +1,388 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // ---------------------------------------------------------------------------
2
+ // settings / PermsEditor.tsx β€” wave 15, ruling R9: the permission editor.
3
+ //
4
+ // "Manage users β†’ click a user β†’ the modal body BECOMES that user's
5
+ // permissioning page." A full-pane takeover, not a drawer beside the list and
6
+ // not a third dialog: the thing being edited is a whole account's access, and
7
+ // giving it a room of its own is what makes room for a filter builder and a
8
+ // field list per module without either being a 200px scroll-box.
9
+ //
10
+ // β›” EVERY CONTROL HERE IS A COURTESY. `/admin/*` is refused to a member at the
11
+ // server, fail-closed, and the wall that acts on what this page writes is
12
+ // `core/perm_scope.permits()` β€” which re-validates the whole record. Nothing on
13
+ // this page is a permission check; this page is where an admin SAYS what the
14
+ // wall should be.
15
+ //
16
+ // THE PANELS ARE THE GRID'S OWN (contract C-KIT). Not lookalikes β€” the same
17
+ // `FilterBuilderPanel` and `FieldsHidePanel` the toolbar mounts, from
18
+ // `filter-kit/`, which is the entire reason that extraction happened before this
19
+ // file existed. An admin writing "customers where dba is Fisch" uses the control
20
+ // they already know, and there is one condition grammar in the product rather
21
+ // than two that drift within a wave.
22
+ //
23
+ // ⚠ WHAT THIS EDITOR CANNOT OFFER, AND WHY IT IS RIGHT THAT IT DOES NOT:
24
+ // Β· **Cohort conditions** β€” cohorts are a user's own workspace objects and an
25
+ // admin editing someone else's account holds no list of them. The prop is
26
+ // absent, so the affordance is absent (never present-and-inert).
27
+ // Β· **`status` choice lists** β€” the grid discovers those from ROWS it has
28
+ // loaded; this page has loaded none. Select/multiselect/user fields still
29
+ // offer their declared options, so only Odoo lifecycle columns come up bare.
30
+ // Both are C-KIT's documented absences, restated here because a reader of this
31
+ // file will meet them as "why is that dropdown empty".
32
+ // ---------------------------------------------------------------------------
33
+
34
+ import { useCallback, useEffect, useRef, useState } from "react";
35
+ import { FilterBuilderPanel, FieldsHidePanel } from "../filter-kit";
36
+ import { getUserPerms, putUserPerms } from "./settingsApi";
37
+ import type { PermsPayload, PermsRecord } from "./permsModel";
38
+ import {
39
+ accessSummary,
40
+ filterOf,
41
+ hiddenSet,
42
+ hideableKeys,
43
+ identityKey,
44
+ isDirty,
45
+ moduleSummary,
46
+ parsePermsPayload,
47
+ setAccess,
48
+ setFilter,
49
+ setHidden,
50
+ toPutBody,
51
+ toggleHidden,
52
+ } from "./permsModel";
53
+
54
+ type Load =
55
+ | { phase: "loading" }
56
+ | { phase: "error"; message: string }
57
+ | { phase: "ready"; payload: PermsPayload };
58
+
59
+ /** What the confirm step is asking about. `null` = nothing is being confirmed. */
60
+ type Ask = null | { kind: "save" } | { kind: "discard" };
61
+
62
+ export function PermsEditor({
63
+ username,
64
+ displayName,
65
+ userOptions,
66
+ onBack,
67
+ onSaved,
68
+ }: {
69
+ username: string;
70
+ /** Shown in the heading. The account is identified by `username` everywhere
71
+ * that matters β€” a display name is not unique and is not the key. */
72
+ displayName: string;
73
+ /** The people a `user`-typed field may name, for the condition builder. Real
74
+ * accounts, never invented: an admin filtering on an owner who does not exist
75
+ * writes a rule that matches nothing and looks like it should match. */
76
+ userOptions?: string[];
77
+ onBack: () => void;
78
+ onSaved: (message: string) => void;
79
+ }) {
80
+ const [load, setLoad] = useState<Load>({ phase: "loading" });
81
+ /** The record as the SERVER holds it β€” the baseline `isDirty` compares to. */
82
+ const [saved, setSaved] = useState<PermsRecord>({});
83
+ const [draft, setDraft] = useState<PermsRecord>({});
84
+ const [ask, setAsk] = useState<Ask>(null);
85
+ const [busy, setBusy] = useState(false);
86
+ const [error, setError] = useState("");
87
+
88
+ useEffect(() => {
89
+ let dead = false;
90
+ setLoad({ phase: "loading" });
91
+ void getUserPerms(username).then((r) => {
92
+ if (dead) return;
93
+ if (!r.ok) {
94
+ setLoad({ phase: "error", message: r.message });
95
+ return;
96
+ }
97
+ const payload = parsePermsPayload(r.data);
98
+ if (!payload) {
99
+ // An unreadable payload is NOT an empty one. Rendering "no modules"
100
+ // here would invite an admin to save a record that grants nothing,
101
+ // over a record they never saw.
102
+ setLoad({
103
+ phase: "error",
104
+ message: "The permission record could not be read. Close and try again.",
105
+ });
106
+ return;
107
+ }
108
+ setSaved(payload.entries);
109
+ setDraft(payload.entries);
110
+ setLoad({ phase: "ready", payload });
111
+ });
112
+ return () => {
113
+ dead = true;
114
+ };
115
+ }, [username]);
116
+
117
+ const payload = load.phase === "ready" ? load.payload : null;
118
+ const dirty = payload ? isDirty(payload, saved, draft) : false;
119
+
120
+ const goBack = useCallback(() => {
121
+ if (dirty) setAsk({ kind: "discard" });
122
+ else onBack();
123
+ }, [dirty, onBack]);
124
+
125
+ // ⚠ CAPTURE PHASE, ON PURPOSE. The settings modal binds its own window
126
+ // `keydown` and closes the WHOLE dialog on Escape β€” which, on this page,
127
+ // would throw away an admin's unsaved permission edits with no prompt and no
128
+ // undo. A capture-phase listener on the same target runs before that
129
+ // bubble-phase one, so `stopPropagation()` here actually stops it.
130
+ const dirtyRef = useRef(dirty);
131
+ dirtyRef.current = dirty;
132
+ const askRef = useRef(ask);
133
+ askRef.current = ask;
134
+ useEffect(() => {
135
+ const onKey = (e: KeyboardEvent) => {
136
+ if (e.key !== "Escape") return;
137
+ if (askRef.current) {
138
+ e.stopPropagation();
139
+ setAsk(null);
140
+ return;
141
+ }
142
+ if (dirtyRef.current) {
143
+ e.stopPropagation();
144
+ setAsk({ kind: "discard" });
145
+ }
146
+ };
147
+ window.addEventListener("keydown", onKey, true);
148
+ return () => window.removeEventListener("keydown", onKey, true);
149
+ }, []);
150
+
151
+ // ⚠ THE CONFIRM MUST BE BROUGHT INTO VIEW, and this is not polish. Its scrim
152
+ // is scoped to THIS PANE rather than the viewport (a second full-screen scrim
153
+ // over a dialog that already has one reads as the application losing its
154
+ // place) β€” but the pane grows with the module list while `.set-body` is what
155
+ // scrolls, so a card centred in the PANE can sit hundreds of pixels above the
156
+ // visible area. The admin clicks Save at the bottom of a long page and
157
+ // nothing appears to happen. One module fits today; the second one does not.
158
+ const confirmRef = useRef<HTMLDivElement | null>(null);
159
+ useEffect(() => {
160
+ if (!ask) return;
161
+ confirmRef.current?.scrollIntoView({ block: "center" });
162
+ // Focus follows the question, so Enter answers it and a screen reader is
163
+ // taken to the alert rather than left where the pointer was.
164
+ confirmRef.current?.querySelector<HTMLButtonElement>("button")?.focus();
165
+ }, [ask]);
166
+
167
+ const save = useCallback(() => {
168
+ if (!payload) return;
169
+ setBusy(true);
170
+ setError("");
171
+ const body = toPutBody(payload, draft);
172
+ void putUserPerms(username, body).then((r) => {
173
+ setBusy(false);
174
+ setAsk(null);
175
+ if (r.ok) {
176
+ setSaved(body.perms);
177
+ onSaved(`Saved access for ${username}.`);
178
+ } else {
179
+ setError(r.message);
180
+ }
181
+ });
182
+ }, [payload, draft, username, onSaved]);
183
+
184
+ return (
185
+ <div className="set-pane set-perms">
186
+ <div className="set-perm-head">
187
+ <button type="button" className="set-secondary" onClick={goBack}>
188
+ Back to accounts
189
+ </button>
190
+ <div className="set-perm-who">
191
+ <h3 className="set-h set-perm-title">Access for {displayName}</h3>
192
+ <span className="set-username">{username}</span>
193
+ </div>
194
+ </div>
195
+
196
+ {error ? <p className="set-error">{error}</p> : null}
197
+
198
+ {load.phase === "loading" ? <p className="pg-empty">Loading access…</p> : null}
199
+ {load.phase === "error" ? <p className="set-error">{load.message}</p> : null}
200
+
201
+ {payload ? (
202
+ <>
203
+ {/* β›” AN ADMIN BYPASSES `perms` ENTIRELY (C-PERM amendment 4) β€” the
204
+ clause that also keeps break-glass alive during a store outage. So
205
+ every rule below is INERT for this account, and the page has to say
206
+ so: an editor that renders a filter and a hidden-field list without
207
+ a word is inviting somebody to "restrict" an administrator and walk
208
+ away believing they did. The controls stay usable on purpose β€” the
209
+ rules are real the moment the account stops being an admin. */}
210
+ {payload.isAdmin ? (
211
+ <p className="set-notice set-perm-banner">
212
+ This is an administrator account. Administrators see everything, so
213
+ nothing set here applies to them β€” these rules take effect only if
214
+ the account is changed to Member.
215
+ </p>
216
+ ) : null}
217
+
218
+ {/* C-PERM amendment 4 β€” an un-migrated record still runs under the
219
+ PREVIOUS wall, so its empty perms mean "not written yet", not "no
220
+ access". Saying so is the difference between an admin reading this
221
+ page correctly and one who thinks the account is locked out. */}
222
+ {!payload.migrated && !payload.isAdmin ? (
223
+ <p className="set-notice set-perm-banner">
224
+ This account still uses the previous access model, so the rules below
225
+ are not in force yet. Saving moves it to the per-module model β€” set
226
+ every module deliberately before you do.
227
+ </p>
228
+ ) : null}
229
+
230
+ {/* A whole-record replace drops what it does not name. An admin should
231
+ learn that here, not from a support ticket about a filter that
232
+ vanished. */}
233
+ {payload.orphanModules.length ? (
234
+ <p className="set-error set-perm-banner">
235
+ This account has rules for {payload.orphanModules.join(", ")}, which
236
+ this deployment no longer offers. Saving removes them.
237
+ </p>
238
+ ) : null}
239
+
240
+ <p className="set-help set-perm-intro">
241
+ {accessSummary(payload, draft)}. Each module can be turned off entirely,
242
+ narrowed to the records a condition describes, or shown with fields
243
+ hidden. Restrictions apply everywhere the account looks β€” the tables,
244
+ the exports and every number computed from them.
245
+ </p>
246
+
247
+ {payload.modules.length === 0 ? (
248
+ <p className="pg-empty">
249
+ This deployment declares no modules that can be restricted.
250
+ </p>
251
+ ) : null}
252
+
253
+ {payload.modules.map((m) => {
254
+ const entry = draft[m.key];
255
+ const on = entry?.access === true;
256
+ const schemaless = m.fields.length === 0;
257
+ return (
258
+ <section className="set-card set-perm-mod" key={m.key}>
259
+ <div className="set-perm-modhead">
260
+ <label className="set-check set-perm-toggle">
261
+ <input
262
+ type="checkbox"
263
+ checked={on}
264
+ onChange={(e) => setDraft((d) => setAccess(d, m.key, e.target.checked))}
265
+ />
266
+ <span className="set-perm-modname">{m.label}</span>
267
+ </label>
268
+ <span className="set-perm-sum">{moduleSummary(entry, schemaless)}</span>
269
+ </div>
270
+
271
+ {/* R9's fail-closed rendering: no readable schema means the
272
+ access toggle and nothing else. The record it saves says the
273
+ same thing β€” no filter, no hidden fields β€” so the editor and
274
+ the payload cannot disagree (permsModel.toPutBody). */}
275
+ {on && schemaless ? (
276
+ <p className="set-help">
277
+ No field list is available for this module, so access is all this
278
+ editor can set for it. Conditions and hidden fields need a schema.
279
+ </p>
280
+ ) : null}
281
+
282
+ {on && !schemaless ? (
283
+ <div className="set-perm-panels">
284
+ <div className="cg-pop set-perm-pop">
285
+ <FilterBuilderPanel
286
+ fields={m.fields}
287
+ filters={filterOf(draft, m.key)}
288
+ onChange={(next) => setDraft((d) => setFilter(d, m.key, next))}
289
+ userOptions={userOptions}
290
+ />
291
+ </div>
292
+ <div className="cg-pop set-perm-pop">
293
+ <FieldsHidePanel
294
+ fields={m.fields}
295
+ hidden={hiddenSet(draft, m.key)}
296
+ onToggle={(key) => setDraft((d) => toggleHidden(d, m.key, key))}
297
+ // ⚠ `lockedKey` IS NOT OPTIONAL HERE, whatever the prop
298
+ // says. Absent, the panel locks nothing and one click on
299
+ // "Hide all" hides the row's own name too β€” a record
300
+ // whose faithful enforcement is a table of blank rows,
301
+ // which C-PERM's PUT validation would accept because the
302
+ // identity column is a perfectly KNOWN field key.
303
+ lockedKey={identityKey(m.fields)}
304
+ onHideAll={() =>
305
+ setDraft((d) => setHidden(d, m.key, hideableKeys(m.fields)))
306
+ }
307
+ onShowAll={() => setDraft((d) => setHidden(d, m.key, []))}
308
+ />
309
+ </div>
310
+ </div>
311
+ ) : null}
312
+ </section>
313
+ );
314
+ })}
315
+
316
+ <div className="set-actions set-perm-actions">
317
+ <button
318
+ type="button"
319
+ className="set-primary"
320
+ disabled={busy || !dirty}
321
+ onClick={() => setAsk({ kind: "save" })}
322
+ >
323
+ Save access
324
+ </button>
325
+ <button type="button" className="set-secondary" disabled={busy} onClick={goBack}>
326
+ Cancel
327
+ </button>
328
+ {dirty ? <span className="set-help set-perm-dirty">Unsaved changes</span> : null}
329
+ </div>
330
+ </>
331
+ ) : null}
332
+
333
+ {ask ? (
334
+ <div className="set-confirm-wrap">
335
+ <div
336
+ ref={confirmRef}
337
+ className="set-confirm"
338
+ role="alertdialog"
339
+ aria-modal="true"
340
+ aria-label={ask.kind === "save" ? "Confirm access change" : "Discard changes"}
341
+ >
342
+ {ask.kind === "save" ? (
343
+ <>
344
+ <h4 className="set-h4">Change what {displayName} can see?</h4>
345
+ <p className="set-help">
346
+ This takes effect the next time they load a page. {accessSummaryLine(payload, draft)}
347
+ </p>
348
+ </>
349
+ ) : (
350
+ <>
351
+ <h4 className="set-h4">Discard these changes?</h4>
352
+ <p className="set-help">
353
+ The access rules for {displayName} stay as they were.
354
+ </p>
355
+ </>
356
+ )}
357
+ <div className="set-actions">
358
+ <button
359
+ type="button"
360
+ className="set-primary"
361
+ disabled={busy}
362
+ onClick={() => (ask.kind === "save" ? save() : (setAsk(null), onBack()))}
363
+ >
364
+ {ask.kind === "save" ? "Save access" : "Discard"}
365
+ </button>
366
+ <button
367
+ type="button"
368
+ className="set-secondary"
369
+ disabled={busy}
370
+ onClick={() => setAsk(null)}
371
+ >
372
+ Keep editing
373
+ </button>
374
+ </div>
375
+ </div>
376
+ </div>
377
+ ) : null}
378
+ </div>
379
+ );
380
+ }
381
+
382
+ /** The confirm's one-line restatement. Deliberately the SAME sentence the pane
383
+ * header shows: a confirm that summarises differently from the page behind it
384
+ * is asking the reader to reconcile two descriptions under time pressure. */
385
+ function accessSummaryLine(payload: PermsPayload | null, draft: PermsRecord): string {
386
+ const s = accessSummary(payload, draft);
387
+ return s ? `${s} after this change.` : "";
388
+ }
web/src/settings/SettingsModal.tsx CHANGED
@@ -7,6 +7,13 @@
7
  // that exact thing for when we click Settings and Manage User, where the
8
  // background is clearly blurred too."*
9
  //
 
 
 
 
 
 
 
10
  // A MODAL, NOT A PAGE, and the shipped version's reasoning holds here too:
11
  // settings are a detour, not a destination β€” you change a toggle and go back to
12
  // what you were doing. The Streamlit app kept a settings PAGE alongside the
@@ -32,19 +39,20 @@ import {
32
  setAvatar,
33
  setPassword,
34
  } from "./settingsApi";
 
 
35
 
36
- export type SettingsSection = "account" | "scope" | "users";
37
-
38
- const BU_LABELS: Record<number, string> = { 5: "Fisch", 6: "Royal" };
39
- const BU_IDS = [5, 6];
40
 
41
- function scopeWords(bus: number[] | string[] | "all"): string {
42
- if (bus === "all") return "All business units";
43
- if (!Array.isArray(bus) || bus.length === 0) return "All business units";
44
- return bus
45
- .map((b) => (typeof b === "number" ? (BU_LABELS[b] ?? String(b)) : String(b)))
46
- .join(", ");
47
- }
48
 
49
  function moduleWords(mods: string[] | "all"): string {
50
  // ⚠ `[]` READS as unrestricted β€” the existing semantic Y4 says not to "fix"
@@ -61,6 +69,10 @@ function UsersPane() {
61
  const [error, setError] = useState("");
62
  const [notice, setNotice] = useState("");
63
  const [editing, setEditing] = useState<string | null>(null);
 
 
 
 
64
  const [busy, setBusy] = useState(false);
65
 
66
  const reload = useCallback(() => {
@@ -95,6 +107,31 @@ function UsersPane() {
95
 
96
  if (users === null) return <p className="pg-empty">Loading accounts…</p>;
97
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
98
  return (
99
  <div className="set-pane">
100
  <h3 className="set-h">Accounts</h3>
@@ -109,8 +146,14 @@ function UsersPane() {
109
  <tr>
110
  <th scope="col">User</th>
111
  <th scope="col">Role</th>
112
- <th scope="col">Business units</th>
113
- <th scope="col">Modules</th>
 
 
 
 
 
 
114
  <th scope="col">Status</th>
115
  <th scope="col" />
116
  </tr>
@@ -119,12 +162,27 @@ function UsersPane() {
119
  {users.map((u) => (
120
  <tr key={u.username} className={u.active ? "" : "is-inactive"}>
121
  <td>
122
- <span className="set-user">{u.name || u.username}</span>
 
 
 
 
 
 
 
123
  <span className="set-username">{u.username}</span>
124
  </td>
125
  <td>{u.role === "admin" ? "Admin" : "Member"}</td>
126
- <td>{scopeWords(u.bus)}</td>
127
- <td>{moduleWords(u.modules)}</td>
 
 
 
 
 
 
 
 
128
  <td>{u.active ? "Active" : "Deactivated"}</td>
129
  <td className="is-right">
130
  <button
@@ -162,52 +220,22 @@ function UsersPane() {
162
  );
163
  }
164
 
165
- function BuPicker({
166
- value,
167
- onChange,
168
- id,
169
- }: {
170
- value: number[] | "all";
171
- onChange: (v: number[] | "all") => void;
172
- id: string;
173
- }) {
174
- const all = value === "all";
175
- const set = new Set(all ? [] : (value as number[]));
176
- return (
177
- <div className="set-field">
178
- <span className="set-label">Business units</span>
179
- <label className="set-check">
180
- <input
181
- type="checkbox"
182
- checked={all}
183
- onChange={(e) => onChange(e.target.checked ? "all" : BU_IDS.slice())}
184
- />
185
- All business units
186
- </label>
187
- {!all
188
- ? BU_IDS.map((b) => (
189
- <label className="set-check" key={b}>
190
- <input
191
- type="checkbox"
192
- checked={set.has(b)}
193
- onChange={(e) => {
194
- const next = new Set(set);
195
- if (e.target.checked) next.add(b);
196
- else next.delete(b);
197
- onChange([...next]);
198
- }}
199
- />
200
- {BU_LABELS[b]}
201
- </label>
202
- ))
203
- : null}
204
- <p className="set-help" id={`${id}-help`}>
205
- A member scoped to one unit sees no other unit's data anywhere β€” the
206
- strict-isolation rule the permission model is built on.
207
- </p>
208
- </div>
209
- );
210
- }
211
 
212
  function EditUser({
213
  user,
@@ -222,7 +250,6 @@ function EditUser({
222
  }) {
223
  const [name, setName] = useState(user.name ?? "");
224
  const [role, setRole] = useState(user.role ?? "user");
225
- const [bus, setBus] = useState<number[] | "all">(user.bus);
226
  const [pw, setPw] = useState("");
227
  const [pwSaid, setPwSaid] = useState("");
228
 
@@ -241,13 +268,18 @@ function EditUser({
241
  <option value="admin">Admin</option>
242
  </select>
243
  </div>
244
- <BuPicker id="set-bus" value={bus} onChange={setBus} />
 
 
 
 
 
245
  <div className="set-actions">
246
  <button
247
  type="button"
248
  className="set-primary"
249
  disabled={busy}
250
- onClick={() => onApply(user.username, { name, role, bus }, `Saved ${user.username}.`)}
251
  >
252
  Save changes
253
  </button>
@@ -316,7 +348,6 @@ function AddUser({
316
  const [username, setUsername] = useState("");
317
  const [name, setName] = useState("");
318
  const [role, setRole] = useState("user");
319
- const [bus, setBus] = useState<number[] | "all">("all");
320
  const [password, setPassword_] = useState("");
321
  const [busy, setBusy] = useState(false);
322
 
@@ -357,7 +388,6 @@ function AddUser({
357
  <option value="admin">Admin</option>
358
  </select>
359
  </div>
360
- <BuPicker id="set-new-bus" value={bus} onChange={setBus} />
361
  <div className="set-field">
362
  <label className="set-label" htmlFor="set-new-pw">Password</label>
363
  <input
@@ -368,6 +398,15 @@ function AddUser({
368
  autoComplete="new-password"
369
  onChange={(e) => setPassword_(e.target.value)}
370
  />
 
 
 
 
 
 
 
 
 
371
  </div>
372
  <div className="set-actions">
373
  <button
@@ -380,7 +419,10 @@ function AddUser({
380
  username: username.trim().toLowerCase(),
381
  name: name || username.trim(),
382
  role,
383
- bus,
 
 
 
384
  // ⚠ `"all"`, never `[]`. An empty list READS as unrestricted, so
385
  // sending one to mean "nothing" would grant everything.
386
  modules: "all",
@@ -575,6 +617,7 @@ export function SettingsModal({
575
  onSection,
576
  onClose,
577
  onUser,
 
578
  }: {
579
  user: SessionUser;
580
  section: SettingsSection;
@@ -583,6 +626,12 @@ export function SettingsModal({
583
  /** Wave 14 C-AVATAR β€” the shell's session setter, so a photo change updates the account
584
  * chip live instead of on the next full reload. Optional: absent, the photo still saves. */
585
  onUser?: (u: SessionUser) => void;
 
 
 
 
 
 
586
  }) {
587
  const [settings, setSettings] = useState<SettingsPayload | null>(null);
588
  const admin = isAdmin(user);
@@ -610,8 +659,9 @@ export function SettingsModal({
610
  ];
611
  // A non-admin deep-linked to the users pane lands on Account rather than on
612
  // an empty frame. The server would refuse the data anyway; this just avoids
613
- // showing a room with nothing in it.
614
- const active = section === "users" && !admin ? "account" : section;
 
615
 
616
  return (
617
  <div
@@ -620,9 +670,14 @@ export function SettingsModal({
620
  if (e.target === e.currentTarget) onClose();
621
  }}
622
  >
623
- <div className="set-modal" role="dialog" aria-modal="true" aria-label="Settings">
 
 
 
 
 
624
  <nav className="set-rail">
625
- <span className="set-rail-cap">Settings</span>
626
  {rail.map(([key, label]) => (
627
  <button
628
  key={key}
@@ -636,7 +691,7 @@ export function SettingsModal({
636
  </nav>
637
 
638
  <div className="set-body">
639
- <button type="button" className="set-close" onClick={onClose} aria-label="Close settings">
640
  Γ—
641
  </button>
642
 
@@ -662,22 +717,44 @@ export function SettingsModal({
662
  {active === "scope" ? (
663
  <div className="set-pane">
664
  <h3 className="set-h">Your access</h3>
 
 
 
 
 
 
 
665
  <p className="set-help">
666
- What this account may see. Only an administrator can change it β€”
667
- shown here so the numbers on every page can be read in context.
668
  </p>
669
- <div className="pg-drill-row">
670
- <span className="pg-drill-key">Business units</span>
671
- <span className="pg-drill-val">
672
- {scopeWords(settings?.scope.bus ?? user.bus)}
673
- </span>
674
- </div>
675
  <div className="pg-drill-row">
676
  <span className="pg-drill-key">Modules</span>
677
  <span className="pg-drill-val">
678
  {moduleWords(settings?.scope.modules ?? user.modules)}
679
  </span>
680
  </div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
681
  </div>
682
  ) : null}
683
 
 
7
  // that exact thing for when we click Settings and Manage User, where the
8
  // background is clearly blurred too."*
9
  //
10
+ // ⚠ WAVE 15 R12 β€” THE SURFACE IS CALLED "PROFILE" NOW, in this shell only. The
11
+ // file, the export and the `SettingsSection` type keep their names deliberately:
12
+ // the ruling renames a LABEL, and renaming the module would ripple through the
13
+ // shell, the gate's source list and every import for no user-visible gain. The
14
+ // Streamlit host keeps "Settings" β€” the two runtimes are allowed to disagree
15
+ // about a word while one of them is being deleted.
16
+ //
17
  // A MODAL, NOT A PAGE, and the shipped version's reasoning holds here too:
18
  // settings are a detour, not a destination β€” you change a toggle and go back to
19
  // what you were doing. The Streamlit app kept a settings PAGE alongside the
 
39
  setAvatar,
40
  setPassword,
41
  } from "./settingsApi";
42
+ import { PermsEditor } from "./PermsEditor";
43
+ import { moduleSummary, parseEntry, reachableSection } from "./permsModel";
44
 
45
+ // The vocabulary lives beside the rule that gates it (permsModel), and is
46
+ // re-exported here so `Shell.tsx`'s import does not have to know that.
47
+ export type { SettingsSection } from "./permsModel";
48
+ import type { SettingsSection } from "./permsModel";
49
 
50
+ // β›” `BU_LABELS`, `BU_IDS` and `scopeWords` ALL WENT WITH THE PICKER (R1).
51
+ // Nothing offers, writes or RENDERS a business unit in this shell any more β€”
52
+ // the last reader was the accounts list, and its column is now "Access". The
53
+ // concept survives only as a legacy value on the record, which S1's migration
54
+ // converts to a permanent filter once. `noUnusedLocals` is what walked the
55
+ // removal down to the last orphan, which is the tsconfig earning its keep.
 
56
 
57
  function moduleWords(mods: string[] | "all"): string {
58
  // ⚠ `[]` READS as unrestricted β€” the existing semantic Y4 says not to "fix"
 
69
  const [error, setError] = useState("");
70
  const [notice, setNotice] = useState("");
71
  const [editing, setEditing] = useState<string | null>(null);
72
+ /** R9 β€” the username whose ACCESS page has taken over the body. Separate from
73
+ * `editing` (the account-details card) because they are two different jobs:
74
+ * one changes who the account IS, the other changes what it may SEE. */
75
+ const [permsFor, setPermsFor] = useState<string | null>(null);
76
  const [busy, setBusy] = useState(false);
77
 
78
  const reload = useCallback(() => {
 
107
 
108
  if (users === null) return <p className="pg-empty">Loading accounts…</p>;
109
 
110
+ // R9's FULL-PANE TAKEOVER, literally: the users pane IS the modal body, so
111
+ // returning the editor here replaces the whole body and nothing else has to
112
+ // know. The rail stays β€” it is chrome, not body, and an admin who wants out
113
+ // of this page entirely should not have to find a Back button first.
114
+ if (permsFor) {
115
+ const who = users.find((u) => u.username === permsFor);
116
+ return (
117
+ <PermsEditor
118
+ username={permsFor}
119
+ displayName={who?.name || permsFor}
120
+ // Real accounts, for `user`-typed conditions. Display name is what those
121
+ // cells hold, with the username as the fallback for an account that has
122
+ // never set one.
123
+ userOptions={users.map((u) => u.name || u.username)}
124
+ onBack={() => setPermsFor(null)}
125
+ onSaved={(msg) => {
126
+ setPermsFor(null);
127
+ setNotice(msg);
128
+ setError("");
129
+ reload();
130
+ }}
131
+ />
132
+ );
133
+ }
134
+
135
  return (
136
  <div className="set-pane">
137
  <h3 className="set-h">Accounts</h3>
 
146
  <tr>
147
  <th scope="col">User</th>
148
  <th scope="col">Role</th>
149
+ {/* β›” "Business units" IS GONE (R1). The record still carries `bus`
150
+ through the strangler period, but a column headed with a dead
151
+ concept teaches the reader the wrong model of the product β€”
152
+ and after S1's migration the value behind it stops being what
153
+ scopes anybody. "Access" is what replaced it, and it is a page
154
+ now rather than a cell, because a permanent filter does not fit
155
+ in one. */}
156
+ <th scope="col">Access</th>
157
  <th scope="col">Status</th>
158
  <th scope="col" />
159
  </tr>
 
162
  {users.map((u) => (
163
  <tr key={u.username} className={u.active ? "" : "is-inactive"}>
164
  <td>
165
+ {/* R9's door: the USER is the link to their access page. */}
166
+ <button
167
+ type="button"
168
+ className="pg-cell-link set-user-door"
169
+ onClick={() => setPermsFor(u.username)}
170
+ >
171
+ <span className="set-user">{u.name || u.username}</span>
172
+ </button>
173
  <span className="set-username">{u.username}</span>
174
  </td>
175
  <td>{u.role === "admin" ? "Admin" : "Member"}</td>
176
+ {/* ⚠ An admin BYPASSES perms entirely (C-PERM amendment 4) β€” the
177
+ clause that also keeps break-glass alive during a store
178
+ outage. Saying "Everything (admin)" here rather than
179
+ rendering a rule prevents the one dangerous misreading: that
180
+ the restrictions on an admin's access page are in force. */}
181
+ <td>
182
+ {u.role === "admin"
183
+ ? "Everything (admin)"
184
+ : (u.accessSummary ?? moduleWords(u.modules))}
185
+ </td>
186
  <td>{u.active ? "Active" : "Deactivated"}</td>
187
  <td className="is-right">
188
  <button
 
220
  );
221
  }
222
 
223
+ // β›” `BuPicker` WAS HERE, AND IT IS NOT COMING BACK (wave 15, R1). Business unit
224
+ // died as a USER-FACING CONCEPT: BU access is now one permanent filter among
225
+ // others under the per-module permissioning engine β€” "dba is any of [Fisch,
226
+ // Both]" says exactly what the two checkboxes used to say, in the same grammar
227
+ // as every other restriction, and an admin who wants a different cut is no
228
+ // longer limited to the two cuts somebody hard-coded.
229
+ //
230
+ // The picker's old help text is worth keeping in one form, because the property
231
+ // it named still holds and is still the point: a member scoped to one unit sees
232
+ // no other unit's data anywhere. What changed is WHERE that is enforced β€” the
233
+ // permanent filter and its server-side wall (C-PERM), not a `bus` list.
234
+ //
235
+ // ⚠ `bus` still exists on the RECORD and in `AdminUser` during the strangler
236
+ // period (legacy Streamlit pages read it; S1's migration converts it once). What
237
+ // no longer exists is a UI that WRITES it β€” see EditUser/AddUser below, which
238
+ // deliberately stopped sending the field they can no longer edit.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
239
 
240
  function EditUser({
241
  user,
 
250
  }) {
251
  const [name, setName] = useState(user.name ?? "");
252
  const [role, setRole] = useState(user.role ?? "user");
 
253
  const [pw, setPw] = useState("");
254
  const [pwSaid, setPwSaid] = useState("");
255
 
 
268
  <option value="admin">Admin</option>
269
  </select>
270
  </div>
271
+ {/* ⚠ THE PATCH NO LONGER CARRIES `bus`, and that is load-bearing rather
272
+ than tidy. With the picker gone this form cannot edit the field, so a
273
+ PATCH that still sent it would be a client echoing back a value it
274
+ only read β€” and once S1's migration converts `bus` into a permanent
275
+ filter and clears the field, that echo would RESURRECT it. A form
276
+ writes what it edits and nothing else. */}
277
  <div className="set-actions">
278
  <button
279
  type="button"
280
  className="set-primary"
281
  disabled={busy}
282
+ onClick={() => onApply(user.username, { name, role }, `Saved ${user.username}.`)}
283
  >
284
  Save changes
285
  </button>
 
348
  const [username, setUsername] = useState("");
349
  const [name, setName] = useState("");
350
  const [role, setRole] = useState("user");
 
351
  const [password, setPassword_] = useState("");
352
  const [busy, setBusy] = useState(false);
353
 
 
388
  <option value="admin">Admin</option>
389
  </select>
390
  </div>
 
391
  <div className="set-field">
392
  <label className="set-label" htmlFor="set-new-pw">Password</label>
393
  <input
 
398
  autoComplete="new-password"
399
  onChange={(e) => setPassword_(e.target.value)}
400
  />
401
+ {/* Said before the click, because a new account is created OPEN and is
402
+ narrowed afterwards. That order is the server's (an absent `bus`
403
+ defaults to every unit) and this wave does not change it β€” what the
404
+ wave changes is that "afterwards" now leads somewhere: open the
405
+ account and set its per-module access, filters and hidden fields. */}
406
+ <p className="set-help">
407
+ A new account starts with access to everything this deployment shows.
408
+ Open it from the list afterwards to set what they may see.
409
+ </p>
410
  </div>
411
  <div className="set-actions">
412
  <button
 
419
  username: username.trim().toLowerCase(),
420
  name: name || username.trim(),
421
  role,
422
+ // ⚠ `bus` IS DELIBERATELY ABSENT (R1) β€” see the note where the
423
+ // picker used to be. The route defaults an absent `bus` to "all",
424
+ // so this is the same account it always created, minus a client
425
+ // asserting a value it cannot edit.
426
  // ⚠ `"all"`, never `[]`. An empty list READS as unrestricted, so
427
  // sending one to mean "nothing" would grant everything.
428
  modules: "all",
 
617
  onSection,
618
  onClose,
619
  onUser,
620
+ moduleLabels,
621
  }: {
622
  user: SessionUser;
623
  section: SettingsSection;
 
626
  /** Wave 14 C-AVATAR β€” the shell's session setter, so a photo change updates the account
627
  * chip live instead of on the next full reload. Optional: absent, the photo still saves. */
628
  onUser?: (u: SessionUser) => void;
629
+ /** Registry key β†’ the label the nav already shows for it. Passed down rather
630
+ * than fetched or hardcoded: the shell holds a server-filtered nav with every
631
+ * label in it, and a second copy of that mapping in this file would be a
632
+ * place for "Customer" to become "Customers" in one door only. Absent β‡’ rows
633
+ * fall back to the key, which is honest if ugly. */
634
+ moduleLabels?: Record<string, string>;
635
  }) {
636
  const [settings, setSettings] = useState<SettingsPayload | null>(null);
637
  const admin = isAdmin(user);
 
659
  ];
660
  // A non-admin deep-linked to the users pane lands on Account rather than on
661
  // an empty frame. The server would refuse the data anyway; this just avoids
662
+ // showing a room with nothing in it. The rule is a NAMED function so the gate
663
+ // can negative-control it β€” see `permsModel.reachableSection`.
664
+ const active = reachableSection(section, admin);
665
 
666
  return (
667
  <div
 
670
  if (e.target === e.currentTarget) onClose();
671
  }}
672
  >
673
+ {/* ⚠ WAVE 15 R12 β€” the modal is "Profile" in the staging shell. The
674
+ accessible name tracks the visible one on purpose: a dialog a screen
675
+ reader announces as "Settings" while the rail reads "Profile" is the
676
+ same drift as a stale comment, only harder to notice. Manage users is
677
+ still a SECTION inside it (R12 is a rename, not a re-architecture). */}
678
+ <div className="set-modal" role="dialog" aria-modal="true" aria-label="Profile">
679
  <nav className="set-rail">
680
+ <span className="set-rail-cap">Profile</span>
681
  {rail.map(([key, label]) => (
682
  <button
683
  key={key}
 
691
  </nav>
692
 
693
  <div className="set-body">
694
+ <button type="button" className="set-close" onClick={onClose} aria-label="Close profile">
695
  Γ—
696
  </button>
697
 
 
717
  {active === "scope" ? (
718
  <div className="set-pane">
719
  <h3 className="set-h">Your access</h3>
720
+ {/* β›” THE "Business units" ROW IS GONE (R1) β€” the concept it
721
+ reported no longer exists on this side of the product. It is
722
+ NOT replaced by nothing: what shapes a restricted account's
723
+ rows is now a permanent filter per module, and the rows below
724
+ say so. A pane reporting "All modules" while a filter quietly
725
+ halves somebody's book is worse than the row it replaced β€”
726
+ that is the user who files a bug about the numbers. */}
727
  <p className="set-help">
728
+ What this account may open, and anything that narrows it. Only an
729
+ administrator can change this.
730
  </p>
 
 
 
 
 
 
731
  <div className="pg-drill-row">
732
  <span className="pg-drill-key">Modules</span>
733
  <span className="pg-drill-val">
734
  {moduleWords(settings?.scope.modules ?? user.modules)}
735
  </span>
736
  </div>
737
+ {/* One row per module the account is restricted in. `moduleSummary`
738
+ is the SAME sentence the admin editor shows, from the same
739
+ function β€” two dialects of "2 conditions, 3 fields hidden"
740
+ would eventually disagree about what a rule says. Admins are
741
+ skipped: they bypass perms entirely, so any stored rule is
742
+ inert and printing it here would be a lie about their access. */}
743
+ {!admin
744
+ ? Object.entries(settings?.scope.perms ?? {}).map(([key, raw]) => {
745
+ const entry = parseEntry(raw);
746
+ const words = moduleSummary(entry);
747
+ // "Full access" adds nothing beside the Modules row above;
748
+ // only a REAL narrowing earns a line.
749
+ if (words === "Full access") return null;
750
+ return (
751
+ <div className="pg-drill-row" key={key}>
752
+ <span className="pg-drill-key">{moduleLabels?.[key] ?? key}</span>
753
+ <span className="pg-drill-val">{words}</span>
754
+ </div>
755
+ );
756
+ })
757
+ : null}
758
  </div>
759
  ) : null}
760
 
web/src/settings/permsModel.ts ADDED
@@ -0,0 +1,434 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // ---------------------------------------------------------------------------
2
+ // settings / permsModel.ts β€” wave 15, contract C-PERM (ruling R9).
3
+ //
4
+ // The permission editor's PURE HALF: the wire shapes, the parse, the draft the
5
+ // admin is editing, and the body the PUT sends. No React, no fetch, so the
6
+ // rules that decide who can see what are testable under node without a browser
7
+ // or a server (verify_login's `_test` harness runs them).
8
+ //
9
+ // β›” NOTHING HERE ENFORCES ANYTHING. Every rule below is about producing a
10
+ // WELL-FORMED and HONEST payload; the wall is `core/perm_scope.permits()` on the
11
+ // server, and it re-validates all of this. An editor that produced a malformed
12
+ // record would be refused β€” the point of the care here is that it never gets
13
+ // that far, and that the admin is never shown a state the server does not hold.
14
+ //
15
+ // THREE RULES THAT LOOK LIKE STYLE AND ARE NOT:
16
+ //
17
+ // 1. **A module with no readable schema renders as an ACCESS TOGGLE ONLY, and
18
+ // saves `{access, filter: null, hiddenFields: []}`** (R9). The failure mode
19
+ // it prevents: half a filter tree, PUT against a field list nobody could
20
+ // read. Fail-closed is not "deny everything" here β€” it is "never write a
21
+ // restriction you could not show the admin".
22
+ // 2. **An unknown field TYPE lands on `text`**, it does not disappear and it
23
+ // is not passed through. Passing it through would hand the condition
24
+ // builder an operator set for a type it does not have; dropping the field
25
+ // would take away an admin's ability to HIDE a column just because they
26
+ // cannot filter on it. `text` is the house fallback the viz layer already
27
+ // uses for exactly this (verify_ui's `field-vocabulary-not-whitelisted`).
28
+ // 3. **A module the server no longer declares is DROPPED by the whole-record
29
+ // replace β€” and the editor says so out loud** (`orphanModules`). A silent
30
+ // drop of somebody's permanent filter is a permission change nobody made.
31
+ // ---------------------------------------------------------------------------
32
+
33
+ import type { Field, FieldType, FilterTree } from "../customer-grid/types";
34
+
35
+ // --- who may reach the editor at all ----------------------------------------
36
+
37
+ /** The modal's rail entries. Declared HERE, beside the rule that gates them, so
38
+ * the component and the gate read one definition of the vocabulary rather than
39
+ * two that can drift by one member. `SettingsModal` re-exports it. */
40
+ export type SettingsSection = "account" | "scope" | "users";
41
+
42
+ /**
43
+ * A non-admin never LANDS on the users pane β€” and therefore never reaches the
44
+ * permission editor, which lives inside it.
45
+ *
46
+ * β›” THIS IS A COURTESY, NOT THE CHECK. The server refuses every `/admin/*`
47
+ * route to a member regardless, and `/perms` is one of them. What this prevents
48
+ * is a member deep-linked (or restored) into a room whose every control would
49
+ * 403 β€” an empty frame that reads as a broken product rather than as a closed
50
+ * door. It is a named function instead of an inline ternary for one reason: an
51
+ * inline ternary cannot have a negative control, and "the pane a non-admin gets
52
+ * bounced out of" is exactly the kind of rule that gets refactored away by
53
+ * someone who does not know it is load-bearing.
54
+ */
55
+ export function reachableSection(section: SettingsSection, admin: boolean): SettingsSection {
56
+ return section === "users" && !admin ? "account" : section;
57
+ }
58
+
59
+ // --- the wire (C-PERM) ------------------------------------------------------
60
+
61
+ /** One module's rule for one user. The shape `PUT /admin/users/{u}/perms` takes. */
62
+ export interface PermsEntry {
63
+ /** May this account open the module at all. `false` β‡’ `may_open` denies. */
64
+ access: boolean;
65
+ /** The PERMANENT filter, AND-ed under everything the user does. `null` = none.
66
+ * ⚠ The whole tree β€” `{conj?, nodes}` β€” never a bare node list: `[A, B]` under
67
+ * `or` means something entirely different from `[A, B]` under `and`, and the
68
+ * loss is invisible in every payload (C-PERM amendment 2). */
69
+ filter: FilterTree | null;
70
+ /** Field keys this account never receives. Server-stripped from every wire. */
71
+ hiddenFields: string[];
72
+ }
73
+
74
+ export type PermsRecord = Record<string, PermsEntry>;
75
+
76
+ /** A module the editor can draw a full rule for: it came with a field list. */
77
+ export interface PermsModule {
78
+ key: string;
79
+ label: string;
80
+ /** Empty β‡’ no readable schema β‡’ access toggle only (rule 1 above). */
81
+ fields: Field[];
82
+ }
83
+
84
+ export interface PermsPayload {
85
+ /** In server order β€” the order the sections render in. */
86
+ modules: PermsModule[];
87
+ entries: PermsRecord;
88
+ /** Keys in `perms` that the server no longer declares. A whole-record replace
89
+ * drops them; the editor states that before the admin saves. */
90
+ orphanModules: string[];
91
+ /** C-PERM amendment 4's migration marker. ABSENT means this record still runs
92
+ * under the LEGACY wall (`bus`/`agent` query scope + the `modules` grant), so
93
+ * the editor must not present empty perms as "no access" β€” that would be a
94
+ * confident lie about an account that can currently see everything. */
95
+ migrated: boolean;
96
+ /** This account is an ADMIN, and admins bypass `perms` entirely. Every rule
97
+ * the editor can draw for them is inert β€” which it has to say out loud. */
98
+ isAdmin: boolean;
99
+ }
100
+
101
+ // --- parsing ----------------------------------------------------------------
102
+
103
+ /** Every `FieldType`, as a runtime set.
104
+ *
105
+ * ⚠ The `Record<FieldType, true>` is the point, not the Set: it is a
106
+ * COMPILE-TIME exhaustiveness check. Add a type to the union in
107
+ * `customer-grid/types.ts` and this file stops compiling until it is listed
108
+ * here β€” which is how a whitelist stays honest across a tree boundary S3 does
109
+ * not own. A hand-maintained array would silently narrow instead. */
110
+ const FIELD_TYPE_TABLE: Record<FieldType, true> = {
111
+ text: true, status: true, currency: true, int: true, date: true, pct: true,
112
+ select: true, user: true, multiselect: true, checkbox: true, phone: true,
113
+ email: true, url: true, rating: true, created_time: true, formula: true,
114
+ };
115
+
116
+ export const KNOWN_FIELD_TYPES: ReadonlySet<string> = new Set(Object.keys(FIELD_TYPE_TABLE));
117
+
118
+ /** Rule 2: whitelist, never pass through, never drop. */
119
+ export function fieldType(raw: unknown): FieldType {
120
+ return typeof raw === "string" && KNOWN_FIELD_TYPES.has(raw) ? (raw as FieldType) : "text";
121
+ }
122
+
123
+ function asStringArray(raw: unknown): string[] {
124
+ return Array.isArray(raw) ? raw.filter((v) => typeof v === "string") : [];
125
+ }
126
+
127
+ /** One field of a module's schema, from the nav/schema payload shape.
128
+ * `key` and `label` are the minimum that makes a row renderable β€” a field
129
+ * without them cannot be shown OR named in a rule, so it is skipped rather
130
+ * than rendered as a blank the admin might tick. */
131
+ export function parseField(raw: unknown): Field | null {
132
+ if (!raw || typeof raw !== "object") return null;
133
+ const r = raw as Record<string, unknown>;
134
+ if (typeof r.key !== "string" || r.key === "") return null;
135
+ const label = typeof r.label === "string" && r.label !== "" ? r.label : r.key;
136
+ const options = asStringArray(r.options);
137
+ return {
138
+ key: r.key,
139
+ label,
140
+ type: fieldType(r.type),
141
+ // Anything not explicitly the overlay stratum is treated as source data.
142
+ // Consequence in this editor: nothing here offers to EDIT a field, so the
143
+ // only thing `source` drives is the "Pre-set" chip in the hide list.
144
+ source: r.source === "overlay" ? "overlay" : "odoo",
145
+ // Carried because `identityKey` reads it β€” see the rule there.
146
+ ...(r.pinned === true ? { pinned: true } : {}),
147
+ ...(options.length ? { options } : {}),
148
+ ...(typeof r.note === "string" ? { note: r.note } : {}),
149
+ ...(typeof r.description === "string" && r.description !== ""
150
+ ? { note: r.description }
151
+ : {}),
152
+ };
153
+ }
154
+
155
+ /** `fields_by_module[key]` is a BARE ARRAY of fields β€” S1's canonical answer
156
+ * (routes_admin `get_perms`), not the nav/schema envelope the contract line
157
+ * implied. The earlier tolerant branch that also read `{fields: […]}` is gone:
158
+ * one shape, asserted here, beats two readings of a sentence.
159
+ *
160
+ * The LABEL does not come from here β€” it rides the payload's `modules` list,
161
+ * which is also what fixes the ORDER. Anything unreadable yields an EMPTY field
162
+ * list, which R9 already has a defined rendering for (access toggle only). */
163
+ export function parseModule(key: string, label: string, raw: unknown): PermsModule {
164
+ const fields: Field[] = [];
165
+ for (const f of Array.isArray(raw) ? raw : []) {
166
+ const parsed = parseField(f);
167
+ if (parsed) fields.push(parsed);
168
+ }
169
+ return { key, label: label || key, fields };
170
+ }
171
+
172
+ /** A filter is taken WHOLE or not at all. A tree whose `nodes` is not a list is
173
+ * not a narrower filter, it is an unreadable one β€” and this editor's job is to
174
+ * never show a rule it could not also save back. */
175
+ export function parseFilter(raw: unknown): FilterTree | null {
176
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null;
177
+ const r = raw as Record<string, unknown>;
178
+ if (!Array.isArray(r.nodes)) return null;
179
+ const conj = r.conj === "or" ? "or" : r.conj === "and" ? "and" : undefined;
180
+ return {
181
+ ...(conj ? { conj } : {}),
182
+ nodes: r.nodes as FilterTree["nodes"],
183
+ };
184
+ }
185
+
186
+ /** ⚠ ABSENT ENTRY β‡’ `access: false`, matching what the server will ENFORCE for a
187
+ * migrated record (C-PERM amendment 4: `perms_v == 1` + no entry β‡’ DENY). The
188
+ * editor showing "access on" for a module the wall denies would send an admin
189
+ * to debug a permission that was never granted.
190
+ *
191
+ * For an UN-migrated record the same absence means the opposite β€” the legacy
192
+ * wall still applies and may grant everything β€” which is why `PermsPayload`
193
+ * carries `migrated` and the editor states it rather than letting this default
194
+ * speak for a case it does not describe. */
195
+ export function parseEntry(raw: unknown): PermsEntry {
196
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
197
+ return { access: false, filter: null, hiddenFields: [] };
198
+ }
199
+ const r = raw as Record<string, unknown>;
200
+ return {
201
+ access: r.access === true,
202
+ filter: parseFilter(r.filter),
203
+ hiddenFields: normalizeHidden(asStringArray(r.hiddenFields)),
204
+ };
205
+ }
206
+
207
+ /** Sorted + de-duplicated, always. Dirty-detection compares payloads, so a list
208
+ * whose ORDER can drift would make an untouched module read as edited. */
209
+ export function normalizeHidden(keys: readonly string[]): string[] {
210
+ return [...new Set(keys)].sort();
211
+ }
212
+
213
+ /**
214
+ * The IDENTITY column β€” the one field a module may never hide.
215
+ *
216
+ * β›” WHY THIS EXISTS AT ALL. `FieldsHidePanel` takes an optional `lockedKey` and
217
+ * documents that "absent = nothing is locked". Absent, a single click on
218
+ * "Hide all" hides EVERY field including the row's own name β€” and with
219
+ * amendment 5's server-side transitive closure behind it, that writes a record
220
+ * whose faithful enforcement is a table of blank rows. The user could open the
221
+ * module and see nothing in it, the wall doing exactly what the record said.
222
+ * Nothing in C-PERM's PUT validation refuses that: it refuses UNKNOWN field
223
+ * keys, and the identity column is perfectly known.
224
+ *
225
+ * ⚠ MIRRORED, NOT INVENTED: this is `useGridColumns.ts:201-204`'s rule verbatim
226
+ * β€” the pinned field, else the first. The grid computes the same key to decide
227
+ * which column its own Hide-fields panel locks, so an editor using a different
228
+ * rule would lock a different column from the one the table protects.
229
+ */
230
+ export function identityKey(fields: readonly Field[]): string {
231
+ return fields.find((f) => f.pinned)?.key ?? fields[0]?.key ?? "";
232
+ }
233
+
234
+ /** Every field a module MAY hide β€” the whole list minus its identity column. */
235
+ export function hideableKeys(fields: readonly Field[]): string[] {
236
+ const locked = identityKey(fields);
237
+ return fields.filter((f) => f.key !== locked).map((f) => f.key);
238
+ }
239
+
240
+ /** `{perms, fields_by_module}` β†’ everything the editor renders. Returns `null`
241
+ * only for a body that is not an object at all; a body missing either half
242
+ * parses to an editor with nothing to offer, which is the honest rendering of
243
+ * "the server told us nothing". */
244
+ export function parsePermsPayload(body: unknown): PermsPayload | null {
245
+ if (!body || typeof body !== "object") return null;
246
+ const b = body as Record<string, unknown>;
247
+ const byModule =
248
+ b.fields_by_module && typeof b.fields_by_module === "object"
249
+ ? (b.fields_by_module as Record<string, unknown>)
250
+ : {};
251
+ const rawPerms =
252
+ b.perms && typeof b.perms === "object" && !Array.isArray(b.perms)
253
+ ? (b.perms as Record<string, unknown>)
254
+ : {};
255
+
256
+ // ⚠ `modules` CARRIES THE LABELS AND THE ORDER, and `fields_by_module` carries
257
+ // neither. Deriving sections from the field map alone renders every heading as
258
+ // a registry KEY β€” "customer_data" where the product says "Customer" β€” and in
259
+ // whatever order the JSON happens to enumerate. The field map is still the
260
+ // outer bound: a module named in `modules` with no field list is the
261
+ // schema-less case, not an error.
262
+ const declared: Array<{ key: string; label: string }> = Array.isArray(b.modules)
263
+ ? (b.modules as unknown[]).flatMap((m) => {
264
+ if (!m || typeof m !== "object") return [];
265
+ const r = m as Record<string, unknown>;
266
+ return typeof r.key === "string" && r.key
267
+ ? [{ key: r.key, label: typeof r.label === "string" ? r.label : r.key }]
268
+ : [];
269
+ })
270
+ : Object.keys(byModule).map((k) => ({ key: k, label: k }));
271
+
272
+ const modules = declared.map((d) => parseModule(d.key, d.label, byModule[d.key]));
273
+ const entries: PermsRecord = {};
274
+ for (const m of modules) entries[m.key] = parseEntry(rawPerms[m.key]);
275
+
276
+ return {
277
+ modules,
278
+ entries,
279
+ orphanModules: Object.keys(rawPerms).filter((k) => !(k in entries)).sort(),
280
+ migrated: typeof b.perms_v === "number" && b.perms_v >= 1,
281
+ // `role == 'admin'` bypasses `perms` entirely (C-PERM amendment 4). Sent by
282
+ // the route so the editor can SAY so instead of rendering stored rules that
283
+ // do not apply β€” the one misreading of that clause that could hurt.
284
+ isAdmin: b.is_admin === true,
285
+ };
286
+ }
287
+
288
+ // --- the draft the admin is editing -----------------------------------------
289
+
290
+ /** Immutable edits: every setter returns a NEW record, so React sees the change
291
+ * and `isDirty` compares against a snapshot that no setter has mutated under
292
+ * it. In-place edits are how a Save button ends up permanently greyed. */
293
+ function withEntry(rec: PermsRecord, key: string, patch: Partial<PermsEntry>): PermsRecord {
294
+ const cur = rec[key] ?? { access: false, filter: null, hiddenFields: [] };
295
+ return { ...rec, [key]: { ...cur, ...patch } };
296
+ }
297
+
298
+ export function setAccess(rec: PermsRecord, key: string, access: boolean): PermsRecord {
299
+ return withEntry(rec, key, { access });
300
+ }
301
+
302
+ export function setFilter(rec: PermsRecord, key: string, filter: FilterTree | null): PermsRecord {
303
+ // An empty tree is NO filter, not an empty one. `{nodes: []}` matches every
304
+ // row, so persisting it would mean "restricted, to everything" β€” a rule that
305
+ // reads as a restriction in the record and is not one on screen.
306
+ const empty = !filter || filter.nodes.length === 0;
307
+ return withEntry(rec, key, { filter: empty ? null : filter });
308
+ }
309
+
310
+ export function setHidden(rec: PermsRecord, key: string, hidden: readonly string[]): PermsRecord {
311
+ return withEntry(rec, key, { hiddenFields: normalizeHidden(hidden) });
312
+ }
313
+
314
+ export function toggleHidden(rec: PermsRecord, key: string, fieldKey: string): PermsRecord {
315
+ const cur = rec[key]?.hiddenFields ?? [];
316
+ const next = cur.includes(fieldKey)
317
+ ? cur.filter((k) => k !== fieldKey)
318
+ : [...cur, fieldKey];
319
+ return setHidden(rec, key, next);
320
+ }
321
+
322
+ export function hiddenSet(rec: PermsRecord, key: string): ReadonlySet<string> {
323
+ return new Set(rec[key]?.hiddenFields ?? []);
324
+ }
325
+
326
+ export function filterOf(rec: PermsRecord, key: string): FilterTree {
327
+ // The panel takes a tree, never null β€” an absent filter is an EMPTY tree to
328
+ // edit, which is what "add your first condition" has to render against.
329
+ return rec[key]?.filter ?? { nodes: [] };
330
+ }
331
+
332
+ // --- what gets sent ---------------------------------------------------------
333
+
334
+ /**
335
+ * The PUT body. Whole-record replace, so this emits an entry for EVERY module
336
+ * the server declared β€” including the ones the admin never touched, because a
337
+ * missing key in a replace is a deletion, not a no-op.
338
+ *
339
+ * ⚠ A module with no readable schema is emitted `{access, filter: null,
340
+ * hiddenFields: []}` (R9). Its access toggle is real and is honoured; what is
341
+ * refused is inventing a restriction against a field list nobody could read.
342
+ */
343
+ export function toPutBody(payload: PermsPayload, rec: PermsRecord): { perms: PermsRecord } {
344
+ const perms: PermsRecord = {};
345
+ for (const m of payload.modules) {
346
+ const e = rec[m.key] ?? { access: false, filter: null, hiddenFields: [] };
347
+ // ⚠ The identity column is stripped at the BOUNDARY as well as withheld
348
+ // from the UI. The panel never offers it, but a record written before this
349
+ // rule β€” or by anything else β€” could still name it, and this editor is the
350
+ // last place that record passes through before the wall enforces it
351
+ // faithfully. Two layers for the same reason C-PERM validates at PUT time
352
+ // AND `permits()` re-checks: records go stale in ways forms cannot.
353
+ const locked = identityKey(m.fields);
354
+ perms[m.key] = m.fields.length
355
+ ? {
356
+ access: e.access,
357
+ filter: e.filter,
358
+ hiddenFields: normalizeHidden(e.hiddenFields.filter((k) => k !== locked)),
359
+ }
360
+ : { access: e.access, filter: null, hiddenFields: [] };
361
+ }
362
+ return { perms };
363
+ }
364
+
365
+ /** Compares the SENT SHAPE, not the draft, so a change the payload cannot carry
366
+ * (a hidden-field list on a schema-less module) never lights up Save. */
367
+ export function isDirty(payload: PermsPayload, saved: PermsRecord, draft: PermsRecord): boolean {
368
+ return (
369
+ JSON.stringify(toPutBody(payload, saved)) !== JSON.stringify(toPutBody(payload, draft))
370
+ );
371
+ }
372
+
373
+ // --- how a rule reads -------------------------------------------------------
374
+
375
+ /** Counts a tree's leaves, groups included. The editor states the size of a
376
+ * restriction rather than showing "Filtered" for one condition and for twenty. */
377
+ export function countLeaves(tree: FilterTree | null): number {
378
+ if (!tree) return 0;
379
+ let n = 0;
380
+ const walk = (nodes: readonly unknown[]) => {
381
+ for (const node of nodes) {
382
+ if (node && typeof node === "object" && Array.isArray((node as { children?: unknown[] }).children)) {
383
+ walk((node as { children: unknown[] }).children);
384
+ } else {
385
+ n += 1;
386
+ }
387
+ }
388
+ };
389
+ walk(tree.nodes);
390
+ return n;
391
+ }
392
+
393
+ /**
394
+ * One sentence per module for the accounts list and the section head.
395
+ *
396
+ * ⚠ NO EMOJI, no icon vocabulary β€” this string is read aloud by a screen reader
397
+ * and printed in the gate's output. It also never says "restricted" without
398
+ * saying to WHAT: "Filtered" alone is the kind of summary that makes an admin
399
+ * open every section to find the one that is set.
400
+ */
401
+ export function moduleSummary(entry: PermsEntry | undefined, schemaless = false): string {
402
+ if (!entry || !entry.access) return "No access";
403
+ if (schemaless) return "Full access";
404
+ const conds = countLeaves(entry.filter);
405
+ const hidden = entry.hiddenFields.length;
406
+ if (!conds && !hidden) return "Full access";
407
+ const parts: string[] = [];
408
+ if (conds) parts.push(`${conds} condition${conds === 1 ? "" : "s"}`);
409
+ if (hidden) parts.push(`${hidden} field${hidden === 1 ? "" : "s"} hidden`);
410
+ return parts.join(", ");
411
+ }
412
+
413
+ /** The account-list cell: what this user may open, across all modules. */
414
+ export function accessSummary(payload: PermsPayload | null, rec: PermsRecord): string {
415
+ if (!payload || payload.modules.length === 0) return "";
416
+ const open = payload.modules.filter((m) => rec[m.key]?.access);
417
+ if (open.length === 0) return "No access";
418
+ // ⚠ A SCHEMA-LESS MODULE CANNOT BE RESTRICTED, so it is never counted as one
419
+ // β€” the same guard `moduleSummary` takes. Without it a draft filter on a
420
+ // module whose rule `toPutBody` strips would be summarised as "1 restricted",
421
+ // describing a restriction that is not going to be saved. The header and the
422
+ // Save confirmation both read this sentence, so it must describe the PAYLOAD.
423
+ const restricted = open.filter(
424
+ (m) =>
425
+ m.fields.length > 0 &&
426
+ ((rec[m.key]?.filter?.nodes.length ?? 0) > 0 ||
427
+ (rec[m.key]?.hiddenFields.length ?? 0) > 0)
428
+ ).length;
429
+ const all = open.length === payload.modules.length;
430
+ const head = all
431
+ ? `All ${open.length} module${open.length === 1 ? "" : "s"}`
432
+ : `${open.length} of ${payload.modules.length} modules`;
433
+ return restricted ? `${head}, ${restricted} restricted` : head;
434
+ }
web/src/settings/settingsApi.ts CHANGED
@@ -33,11 +33,33 @@ export interface AdminUser {
33
  modules: string[] | "all";
34
  active: boolean;
35
  epoch?: number;
 
 
 
 
 
 
 
 
 
 
 
 
36
  }
37
 
38
  export interface SettingsPayload {
39
  user: { username: string; name: string; role: string };
40
- scope: { bus: string[] | "all"; modules: string[] | "all" };
 
 
 
 
 
 
 
 
 
 
41
  tenant?: Record<string, unknown>;
42
  }
43
 
@@ -91,11 +113,14 @@ export function listUsers(): Promise<ApiResult<{ users: AdminUser[] }>> {
91
  return call<{ users: AdminUser[] }>("/admin/users");
92
  }
93
 
 
 
 
 
94
  export interface NewUser {
95
  username: string;
96
  name: string;
97
  role: string;
98
- bus: number[] | "all";
99
  modules: string[] | "all";
100
  password: string;
101
  }
@@ -104,7 +129,10 @@ export function createUser(u: NewUser): Promise<ApiResult<AdminUser>> {
104
  return call<AdminUser>("/admin/users", { method: "POST", body: JSON.stringify(u) });
105
  }
106
 
107
- export type UserPatch = Partial<Pick<AdminUser, "name" | "role" | "bus" | "modules" | "active">>;
 
 
 
108
 
109
  export function patchUser(username: string, patch: UserPatch): Promise<ApiResult<AdminUser>> {
110
  return call<AdminUser>(`/admin/users/${encodeURIComponent(username)}`, {
@@ -123,6 +151,35 @@ export function setPassword(username: string, password: string): Promise<ApiResu
123
  });
124
  }
125
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
126
  /** Wave 14 C-AVATAR β€” own-profile photo. The server returns the refreshed `{user}` envelope;
127
  * the caller parses it with `session.parseUserEnvelope` so the shell chip updates live. */
128
  export function setAvatar(dataUrl: string): Promise<ApiResult<{ user: unknown }>> {
 
33
  modules: string[] | "all";
34
  active: boolean;
35
  epoch?: number;
36
+ /**
37
+ * β­’ REQUESTED OF S1, ADDITIVE, NOT YET SERVED (wave 15). One sentence per
38
+ * account for the list's Access column β€” "All 2 modules, 1 restricted" β€”
39
+ * computed from `perms` server-side, because the alternative is one
40
+ * `/perms` round trip per row to fill one cell.
41
+ *
42
+ * Absent is handled, not assumed: the column falls back to the legacy
43
+ * `modules` grant, which is what governs an un-migrated record anyway. The
44
+ * shape is `permsModel.accessSummary`'s output, so both ends say the same
45
+ * sentence rather than two dialects of it.
46
+ */
47
+ accessSummary?: string;
48
  }
49
 
50
  export interface SettingsPayload {
51
  user: { username: string; name: string; role: string };
52
+ scope: {
53
+ bus: string[] | "all";
54
+ modules: string[] | "all";
55
+ /** C-PERM β€” the caller's OWN effective wall, read-only. Present since wave
56
+ * 15. Read here so "Your access" can state what NARROWS this account, not
57
+ * merely what it may open: a pane saying "All modules" while a permanent
58
+ * filter halves somebody's book is how a user comes to believe the numbers
59
+ * are wrong. Never enforcement β€” hidden fields are stripped from every wire
60
+ * regardless, so a client ignoring this is narrowed anyway, never widened. */
61
+ perms?: Record<string, unknown>;
62
+ };
63
  tenant?: Record<string, unknown>;
64
  }
65
 
 
113
  return call<{ users: AdminUser[] }>("/admin/users");
114
  }
115
 
116
+ /** ⚠ NO `bus` (wave 15, R1). The field still exists on the RECORD β€” `AdminUser`
117
+ * keeps reading it through the strangler period β€” but nothing in this client
118
+ * writes it any more, so the create payload does not name it. The route
119
+ * defaults an absent `bus` to `"all"`, which is what this form always sent. */
120
  export interface NewUser {
121
  username: string;
122
  name: string;
123
  role: string;
 
124
  modules: string[] | "all";
125
  password: string;
126
  }
 
129
  return call<AdminUser>("/admin/users", { method: "POST", body: JSON.stringify(u) });
130
  }
131
 
132
+ /** ⚠ `bus` is NOT patchable from this client any more (R1) β€” a form writes what
133
+ * it edits, and once the migration converts `bus` into a permanent filter and
134
+ * clears the field, an echoed value would put it back. */
135
+ export type UserPatch = Partial<Pick<AdminUser, "name" | "role" | "modules" | "active">>;
136
 
137
  export function patchUser(username: string, patch: UserPatch): Promise<ApiResult<AdminUser>> {
138
  return call<AdminUser>(`/admin/users/${encodeURIComponent(username)}`, {
 
151
  });
152
  }
153
 
154
+ // --- wave 15, C-PERM: the per-module permission record ----------------------
155
+ //
156
+ // β›” ADMIN-ONLY AND FAIL-CLOSED AT THE SERVER. These two calls are exactly as
157
+ // forbidden to a member as the rest of `/admin/*`; the editor that consumes them
158
+ // is hidden from non-admins as a courtesy and refused as a rule.
159
+ //
160
+ // The body is passed through UNPARSED on purpose β€” `permsModel.parsePermsPayload`
161
+ // owns the shape, so the parse is one testable function rather than a validation
162
+ // that half-lives in a fetch wrapper.
163
+
164
+ export function getUserPerms(username: string): Promise<ApiResult<unknown>> {
165
+ return call<unknown>(`/admin/users/${encodeURIComponent(username)}/perms`);
166
+ }
167
+
168
+ /**
169
+ * WHOLE-RECORD REPLACE. Every module the server declared is present in `perms`,
170
+ * including untouched ones: a key omitted from a replace is a DELETION.
171
+ * `permsModel.toPutBody` is the only sanctioned way to build this body.
172
+ */
173
+ export function putUserPerms(
174
+ username: string,
175
+ body: { perms: Record<string, unknown> }
176
+ ): Promise<ApiResult<unknown>> {
177
+ return call<unknown>(`/admin/users/${encodeURIComponent(username)}/perms`, {
178
+ method: "PUT",
179
+ body: JSON.stringify(body),
180
+ });
181
+ }
182
+
183
  /** Wave 14 C-AVATAR β€” own-profile photo. The server returns the refreshed `{user}` envelope;
184
  * the caller parses it with `session.parseUserEnvelope` so the shell chip updates live. */
185
  export function setAvatar(dataUrl: string): Promise<ApiResult<{ user: unknown }>> {
web/src/shell/Shell.tsx CHANGED
@@ -213,7 +213,13 @@ function AccountMenu({
213
  <div className="shell-menu" role="menu">
214
  {/* Two entry points, ONE modal β€” "Manage users" just lands on a
215
  different rail entry. Admin-only is a courtesy here; the server
216
- refuses `/admin/*` to a member regardless. */}
 
 
 
 
 
 
217
  <button
218
  type="button"
219
  className="shell-menu-item"
@@ -223,7 +229,7 @@ function AccountMenu({
223
  onSettings("account");
224
  }}
225
  >
226
- Settings
227
  </button>
228
  {isAdmin(user) ? (
229
  <button
@@ -250,8 +256,13 @@ function AccountMenu({
250
  onClick={() => setOpen(false)}
251
  >
252
  {/* The host's Settings page is scope + preferences for the app's
253
- own pages; "App settings" says which of the two Settings this
254
- one is. Other utility rows keep their registry label. */}
 
 
 
 
 
255
  {p.key === "settings" ? "App settings" : p.label}
256
  <ExtIcon />
257
  </a>
@@ -832,15 +843,17 @@ export default function Shell() {
832
  // branch, which is the whole return on the envelope contract.
833
  <PageSurface key={active.key} pageKey={active.key} label={active.label} />
834
  ) : active?.kind === "native" ? (
835
- // Customer and Cohort are ONE component over two surfaces. The `key` forces a remount
836
- // on a route change: the grid holds view/cohort selection in state, and carrying a
837
- // Customer view into the Cohort surface would show the wrong left panel against the
838
- // right rows β€” the kind of cross-surface bleed that looks like a data bug.
 
 
839
  <div className="shell-grid-host">
840
  <OverlayProvider>
841
  <CustomerGrid
842
  key={active.key}
843
- scope={active.key === "cohort" ? "cohort" : "customer"}
844
  />
845
  </OverlayProvider>
846
  </div>
@@ -868,6 +881,12 @@ export default function Shell() {
868
  onSection={setSettings}
869
  onClose={() => setSettings(null)}
870
  onUser={(u) => setSession({ phase: "authed", user: u })}
 
 
 
 
 
 
871
  />
872
  ) : null}
873
 
 
213
  <div className="shell-menu" role="menu">
214
  {/* Two entry points, ONE modal β€” "Manage users" just lands on a
215
  different rail entry. Admin-only is a courtesy here; the server
216
+ refuses `/admin/*` to a member regardless.
217
+
218
+ ⚠ WAVE 15 R12 β€” "Settings" is "Profile" HERE AND NOWHERE ELSE. The
219
+ Streamlit host keeps its own "Settings", deliberately: the rename
220
+ is about what THIS door calls the page you reach from your own
221
+ account row, and a strangler period is not the moment to make two
222
+ runtimes disagree about a registry key. */}
223
  <button
224
  type="button"
225
  className="shell-menu-item"
 
229
  onSettings("account");
230
  }}
231
  >
232
+ Profile
233
  </button>
234
  {isAdmin(user) ? (
235
  <button
 
256
  onClick={() => setOpen(false)}
257
  >
258
  {/* The host's Settings page is scope + preferences for the app's
259
+ own pages. "App settings" named it that way to distinguish it
260
+ from THIS shell's Settings entry β€” which R12 has now renamed to
261
+ Profile, so the ambiguity it was solving is gone. The label
262
+ stays anyway, for the reason it would be chosen today: this row
263
+ hands off to the OTHER application, and "App settings" says so
264
+ a beat before the arrow does. Other utility rows keep their
265
+ registry label. */}
266
  {p.key === "settings" ? "App settings" : p.label}
267
  <ExtIcon />
268
  </a>
 
843
  // branch, which is the whole return on the envelope contract.
844
  <PageSurface key={active.key} pageKey={active.key} label={active.label} />
845
  ) : active?.kind === "native" ? (
846
+ // The native grid surfaces β€” ONE component, topic decided by the route. Wave 16:
847
+ // the `#/cohort` route left with the cohort registry row (cohorts are LOCKED VIEWS
848
+ // in the Customer rail, C-LOCK; `scope=cohort` stays a working server surface for
849
+ // stored artifacts), and `#/product_data` arrived (C-TOPIC) β€” the same tree over
850
+ // the SKU catalogue. The `key` forces a remount on a route change so one topic's
851
+ // view state never bleeds into the other's.
852
  <div className="shell-grid-host">
853
  <OverlayProvider>
854
  <CustomerGrid
855
  key={active.key}
856
+ scope={active.key === "product_data" ? "product" : "customer"}
857
  />
858
  </OverlayProvider>
859
  </div>
 
881
  onSection={setSettings}
882
  onClose={() => setSettings(null)}
883
  onUser={(u) => setSession({ phase: "authed", user: u })}
884
+ // Wave 15 β€” the nav already holds a server-filtered {key: label} for
885
+ // every surface this account may open, so "Your access" names its
886
+ // restrictions in the words the rail uses rather than in registry
887
+ // keys. Derived here rather than mapped in the modal so there is only
888
+ // one place either door learns what a module is called.
889
+ moduleLabels={Object.fromEntries(entries.map((e) => [e.key, e.label]))}
890
  />
891
  ) : null}
892
 
web/src/shell/nav.ts CHANGED
@@ -323,33 +323,38 @@ export interface NavEntry {
323
  }
324
 
325
  /**
326
- * The surfaces THIS TREE can actually render. Two keys:
327
- * Β· `customer_data` β€” the Customer table, the same `customer-grid` component
328
- * the Streamlit embed ships;
329
- * Β· `sales` β€” EXIT wave 2 (W2-7): rendered from the Y1 page envelope through
330
- * the shared `ui/` primitives, so it is a DATA-driven page rather than a
331
- * hand-built one.
332
  *
333
  * ⚠ This is a CLIENT capability list, not a permission list, and the two must
334
  * not be confused. The server decides what a user MAY open; this decides what
335
  * the shell KNOWS HOW to draw. A key here that the server did not send is
336
  * simply never rendered β€” the payload is the outer bound, always.
337
  *
338
- * β­’ WAVE 3 ADDS `ar` AND `procurement` BY ADDING THEM HERE. That is the whole
339
- * bet of the Y1 envelope: a ported page is a registry entry plus a server-side
340
- * builder, never a new component tree.
 
 
 
 
 
341
  */
342
  export const NATIVE_KEYS: ReadonlySet<string> = new Set<string>(
343
- // `cohort` joined 2026-07-30: it is the SAME grid over hand-curated sets, and the server
344
- // now says so via `/workspace?scope=cohort` -> `workspace.cohortMode`. Before that route
345
- // could express a scope, this shell had no way to draw Cohort and handed it back to
346
- // Streamlit β€” the write path had accepted `scopeKey` the whole time.
347
- ["customer_data", "cohort", "sales"]);
 
 
348
 
349
  /** The native keys the Y1 page envelope drives (as opposed to `customer_data`,
350
  * which is its own component tree). Kept beside NATIVE_KEYS so the two cannot
351
- * drift: everything here MUST also be native, asserted in the gate. */
352
- export const ENVELOPE_KEYS: ReadonlySet<string> = new Set<string>(["sales"]);
 
353
 
354
  /** The app's own deep link (`?page=<registry key>`) β€” the strangler hand-off
355
  * lands on the exact page rather than a landing screen. */
@@ -434,7 +439,8 @@ export function shapeNav(pages: NavPage[], appBase: string): NavEntry[] {
434
  * came up. A landing page is a product decision and belongs in a list somebody
435
  * can read, not in whatever the registry happens to order first.
436
  */
437
- export const LANDING_PREFERENCE: readonly string[] = ["customer_data", "cohort"];
 
438
 
439
  export function defaultRoute(entries: NavEntry[]): string {
440
  for (const key of LANDING_PREFERENCE) {
 
323
  }
324
 
325
  /**
326
+ * The surfaces THIS TREE can actually render:
327
+ * Β· `customer_data` / `cohort` β€” the Customer table, the same `customer-grid`
328
+ * component the Streamlit embed ships.
 
 
 
329
  *
330
  * ⚠ This is a CLIENT capability list, not a permission list, and the two must
331
  * not be confused. The server decides what a user MAY open; this decides what
332
  * the shell KNOWS HOW to draw. A key here that the server did not send is
333
  * simply never rendered β€” the payload is the outer bound, always.
334
  *
335
+ * β­’ THE NEXT PORTED SURFACE (Collections / Procurement) JOINS BY ADDING ITS KEY
336
+ * HERE + a server-side builder. That is the whole bet of the Y1 envelope: a
337
+ * ported page is a registry entry plus a builder, never a new component tree.
338
+ * `sales` was the proof (EXIT wave 2) and LEFT wave 16 (owner item 7, R3/R11):
339
+ * the registry row is archived, the builder unregistered, and the owner
340
+ * rebuilds sales views from the grid's chart/dashboard modes β€” so the envelope
341
+ * machinery (PageView, ui/, viz/) is currently a capability with no shipped
342
+ * page, kept warm by the render-smoke fixture.
343
  */
344
  export const NATIVE_KEYS: ReadonlySet<string> = new Set<string>(
345
+ // `cohort` joined 2026-07-30 and LEFT wave 16 (owner item 5, R10): every cohort now
346
+ // projects as a LOCKED VIEW in the Customer rail's "Cohorts" section (wave-15 C-LOCK),
347
+ // so the separate route is gone. The cohort MACHINERY stays β€” `scope=cohort`,
348
+ // `workspace.cohortMode`, the events β€” reachable from the Customer surface.
349
+ // `product_data` joined wave 16 (C-TOPIC, owner items 9+10): the SAME grid tree over the
350
+ // SKU catalogue β€” Shell maps it to `scope="product"` and everything else is the topic's.
351
+ ["customer_data", "product_data"]);
352
 
353
  /** The native keys the Y1 page envelope drives (as opposed to `customer_data`,
354
  * which is its own component tree). Kept beside NATIVE_KEYS so the two cannot
355
+ * drift: everything here MUST also be native, asserted in the gate. EMPTY
356
+ * since wave 16 (sales retired) β€” the next builder's key lands here. */
357
+ export const ENVELOPE_KEYS: ReadonlySet<string> = new Set<string>([]);
358
 
359
  /** The app's own deep link (`?page=<registry key>`) β€” the strangler hand-off
360
  * lands on the exact page rather than a landing screen. */
 
439
  * came up. A landing page is a product decision and belongs in a list somebody
440
  * can read, not in whatever the registry happens to order first.
441
  */
442
+ // (`cohort` left the list with its NATIVE_KEYS exit, wave 16 β€” a landing must be drawable.)
443
+ export const LANDING_PREFERENCE: readonly string[] = ["customer_data"];
444
 
445
  export function defaultRoute(entries: NavEntry[]): string {
446
  for (const key of LANDING_PREFERENCE) {
web/src/viz/DashboardView.css CHANGED
@@ -40,6 +40,73 @@
40
  font-size: var(--lp-fs-3xs);
41
  }
42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
  /* ==========================================================================
44
  Wave 14 items 18 + R7 β€” the chart editor's label column.
45
  ==========================================================================
 
40
  font-size: var(--lp-fs-3xs);
41
  }
42
 
43
+ /* ==========================================================================
44
+ Wave-16 C-CHARTCAP (b) β€” the delta line under a KPI number.
45
+ ==========================================================================
46
+ Colour states direction, not judgment: green up / red down is the finance
47
+ read `pages_sales` used, and `flat`/`off` stay muted. The refusal notes
48
+ ("no orders yet") wear the muted tone too β€” they are honesty, not alarm. */
49
+ .cg-ch-kpidelta {
50
+ display: flex;
51
+ align-items: center;
52
+ justify-content: center;
53
+ gap: 4px;
54
+ padding: 2px 8px 6px;
55
+ font-size: var(--lp-fs-2xs);
56
+ font-weight: 600;
57
+ color: var(--lp-muted);
58
+ }
59
+
60
+ .cg-ch-kpidelta.is-up {
61
+ color: var(--lp-green-deep);
62
+ }
63
+
64
+ .cg-ch-kpidelta.is-down {
65
+ color: var(--lp-red-deep);
66
+ }
67
+
68
+ /* ==========================================================================
69
+ Wave-16 C-CHARTCAP (c) β€” the table kind.
70
+ ==========================================================================
71
+ A summary card, styled like the sheet: hairline rows, numbers right-aligned
72
+ in tabular figures, the group column free to truncate. The card scrolls its
73
+ own overflow so a tall table never stretches the board row. */
74
+ .cg-ch-table {
75
+ height: 100%;
76
+ overflow: auto;
77
+ }
78
+
79
+ .cg-ch-table table {
80
+ width: 100%;
81
+ border-collapse: collapse;
82
+ font-size: var(--lp-fs-2xs);
83
+ }
84
+
85
+ .cg-ch-table th,
86
+ .cg-ch-table td {
87
+ padding: 3px 8px;
88
+ text-align: left;
89
+ border-bottom: 1px solid var(--lp-line);
90
+ white-space: nowrap;
91
+ overflow: hidden;
92
+ text-overflow: ellipsis;
93
+ max-width: 180px;
94
+ }
95
+
96
+ .cg-ch-table th {
97
+ position: sticky;
98
+ top: 0;
99
+ background: var(--lp-surface);
100
+ color: var(--lp-muted);
101
+ font-weight: 600;
102
+ font-size: var(--lp-fs-3xs);
103
+ }
104
+
105
+ .cg-ch-table .cg-ch-td-num {
106
+ text-align: right;
107
+ font-variant-numeric: tabular-nums;
108
+ }
109
+
110
  /* ==========================================================================
111
  Wave 14 items 18 + R7 β€” the chart editor's label column.
112
  ==========================================================================