fsanyoto commited on
Commit
56e1f2f
·
verified ·
1 Parent(s): 5351cc8

Deploy AIOS web (React glide grid + FastAPI slice)

Browse files
Files changed (36) hide show
  1. api/main.py +5 -3
  2. api/routes_grid.py +197 -7
  3. api/routes_nav.py +121 -3
  4. royalimports_os/aios_grid.py +142 -53
  5. royalimports_os/aios_grid_fields.json +228 -215
  6. royalimports_os/core/grid_events.py +34 -0
  7. royalimports_os/core/measure_resolve.py +44 -0
  8. royalimports_os/core/table_store.py +218 -188
  9. royalimports_os/harness/filter_sql.py +20 -1
  10. royalimports_os/harness/measure_filter.py +59 -0
  11. royalimports_os/harness/runtime.py +3 -0
  12. royalimports_os/modules/customer_data.py +38 -1
  13. web/public/sample_customers.json +477 -456
  14. web/src/customer-grid/ColumnMenu.tsx +363 -353
  15. web/src/customer-grid/CustomerGrid.tsx +446 -230
  16. web/src/customer-grid/RecordDetail.css +247 -4
  17. web/src/customer-grid/RecordDetail.tsx +489 -183
  18. web/src/customer-grid/TimeSeriesPanel.tsx +405 -0
  19. web/src/customer-grid/Toolbar.tsx +210 -5
  20. web/src/customer-grid/ViewSidebar.tsx +97 -3
  21. web/src/customer-grid/apiBridge.ts +42 -0
  22. web/src/customer-grid/filters.css +30 -0
  23. web/src/customer-grid/iconShapes.ts +20 -0
  24. web/src/customer-grid/rankOps.ts +316 -0
  25. web/src/customer-grid/recordLayout.ts +107 -0
  26. web/src/customer-grid/timeSeriesData.ts +351 -0
  27. web/src/customer-grid/types.ts +302 -61
  28. web/src/customer-grid/useVisibleRows.ts +136 -8
  29. web/src/customer-grid/viewEcho.ts +21 -0
  30. web/src/customer-grid/viewModes.tsx +270 -27
  31. web/src/index.css +466 -202
  32. web/src/shell/NavExtras.tsx +445 -0
  33. web/src/shell/Shell.tsx +186 -48
  34. web/src/shell/nav.ts +196 -0
  35. web/src/shell/navExtras.css +352 -0
  36. web/src/viz/chartData.ts +252 -225
api/main.py CHANGED
@@ -97,10 +97,12 @@ if not _FIELDS_PATH.is_file():
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/date pass through untouched; every OTHER odoo field is numeric -> rounded. Derived
101
- # from field TYPE (not a hand-kept key list) so a new text/date field can never be wrongly rounded.
 
102
  _PASSTHROUGH_KEYS = {f["key"] for f in FIELDS
103
- if f["source"] == "odoo" and f["type"] in ("text", "status", "date")}
 
104
 
105
  app = FastAPI(title="AIOS web API")
106
 
 
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
 
api/routes_grid.py CHANGED
@@ -21,6 +21,7 @@ STORE DOWN = 503. `fallback_ws` is None on this adapter, so `core.grid_events` r
21
  `StoreUnavailable` rather than writing to an in-memory workspace no API request could ever read
22
  back. A 200 over a write that evaporated is the failure this rule exists to prevent.
23
  """
 
24
  import time
25
 
26
  from fastapi import APIRouter, Body, Depends
@@ -137,6 +138,195 @@ def workspace(scope: str = "customer",
137
  return {"workspace": workspace}
138
 
139
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
140
  @router.post("/grid/events")
141
  def grid_events_route(body: dict = Body(default=None),
142
  session: Session = Depends(module_gate(MODULE))):
@@ -158,9 +348,9 @@ def grid_events_route(body: dict = Body(default=None),
158
  # typo degraded silently to customer-scope behaviour on a WRITE. Read and write must agree on
159
  # what a scope is, or the surface you read is not the surface you wrote.
160
  scope = _scope_or_400((body or {}).get("scopeKey"))
161
- # This assembly validates the write; it is not a payload the browser will render. Leave
162
- # one-shot field-name correction acks queued for the subsequent /workspace refresh.
163
- g = grid_assembly(session, scope=scope, consume_corrections=False)
164
  # ⚠ THE MEASURE CONTEXT IS NOT OPTIONAL (2026-07-31). Without `measure_offer`,
165
  # `clean_measure_field` had an empty admission list and every measure-column create over
166
  # HTTP was silently refused; without `measure_keys`, `clean_filter_tree` stripped every
@@ -169,10 +359,10 @@ def grid_events_route(body: dict = Body(default=None),
169
  # never write.
170
  ctx = _ctx(session, g["fields"], g["pids"], scope_key=scope,
171
  measure_keys=frozenset(m["key"] for m in g["measures"]),
172
- resolved_ids=frozenset(g["measure_sets"]),
173
- cohort_ids=frozenset(c["id"] for c in g["lists"]),
174
- measure_offer=tuple(g["measures"]),
175
- visible_views=tuple(g["views"]))
176
 
177
  # Per-event results so the client can tell which of a batch landed — the component's own
178
  # bridge has no response channel at all, so this is strictly more than the embed gets.
 
21
  `StoreUnavailable` rather than writing to an in-memory workspace no API request could ever read
22
  back. A 200 over a write that evaporated is the failure this rule exists to prevent.
23
  """
24
+ import datetime as dt
25
  import time
26
 
27
  from fastapi import APIRouter, Body, Depends
 
138
  return {"workspace": workspace}
139
 
140
 
141
+ # ─────────────────────────────────────────────── the TIME-SERIES channel (C-TS, 2026-08-02)
142
+ _TS_BUCKETS = ("week", "month", "quarter", "year")
143
+ _TS_MAX_BUCKETS = 120 # one grouped query per field makes bucket count nearly free
144
+ _TS_MAX_FIELDS = 12
145
+ _TS_MAX_PIDS = 5000
146
+ _TS_MAX_LAST_N = 120
147
+
148
+
149
+ def _ts_start_of(bucket, d):
150
+ """The calendar START of the bucket holding `d` (week = Monday, the vocabulary rule)."""
151
+ if bucket == "week":
152
+ return d - dt.timedelta(days=d.weekday())
153
+ if bucket == "month":
154
+ return d.replace(day=1)
155
+ if bucket == "quarter":
156
+ return d.replace(month=((d.month - 1) // 3) * 3 + 1, day=1)
157
+ return d.replace(month=1, day=1)
158
+
159
+
160
+ def _ts_next(bucket, d):
161
+ if bucket == "week":
162
+ return d + dt.timedelta(days=7)
163
+ if bucket == "year":
164
+ return d.replace(year=d.year + 1)
165
+ step = 1 if bucket == "month" else 3
166
+ m = d.month + step
167
+ return dt.date(d.year + (m - 1) // 12, (m - 1) % 12 + 1, 1)
168
+
169
+
170
+ def _ts_prev(bucket, d):
171
+ if bucket == "week":
172
+ return d - dt.timedelta(days=7)
173
+ if bucket == "year":
174
+ return d.replace(year=d.year - 1)
175
+ step = 1 if bucket == "month" else 3
176
+ y, m = d.year, d.month - step
177
+ while m < 1:
178
+ m += 12
179
+ y -= 1
180
+ return dt.date(y, m, 1)
181
+
182
+
183
+ def _ts_label(bucket, start):
184
+ if bucket == "week":
185
+ return f"Wk of {start.strftime('%b %d')}"
186
+ if bucket == "month":
187
+ return start.strftime("%b %Y")
188
+ if bucket == "quarter":
189
+ return f"Q{(start.month - 1) // 3 + 1} {start.year}"
190
+ return str(start.year)
191
+
192
+
193
+ @router.post("/grid/timeseries")
194
+ def grid_timeseries(body: dict = Body(default=None),
195
+ session: Session = Depends(module_gate(MODULE))):
196
+ """Pooled measure values per calendar bucket — the time-series view's data channel.
197
+
198
+ The client sends the pids its view currently matches (the filter IS the scope); the server
199
+ intersects them with the session's book, so the request can only ever NARROW. Values are
200
+ POOLED aggregates computed by the semantic layer's own expression per bucket (the
201
+ additivity law: an average is computed at pool grain, never averaged over per-customer
202
+ answers). A bucket with no rows is 0 for a sum/count and null for anything else — null is
203
+ "unanswerable", 0 is a real zero, and the client renders them differently on purpose.
204
+ """
205
+ from core import measure_resolve
206
+ from routes_customers import _pool_stamp, _team_agent, allowed_pids
207
+
208
+ body = body or {}
209
+ bucket = body.get("bucket")
210
+ if bucket not in _TS_BUCKETS:
211
+ raise err(400, "bad_timeseries", "bucket must be one of week, month, quarter, year")
212
+ raw_fields = body.get("fields")
213
+ if not isinstance(raw_fields, list) or not raw_fields:
214
+ raise err(400, "bad_timeseries", "fields must be a non-empty list of field keys")
215
+ if len(raw_fields) > _TS_MAX_FIELDS:
216
+ raise err(400, "bad_timeseries", f"at most {_TS_MAX_FIELDS} fields per request")
217
+ raw_pids = body.get("pids")
218
+ if not isinstance(raw_pids, list) or not raw_pids:
219
+ raise err(400, "bad_timeseries", "pids must be a non-empty list")
220
+ if len(raw_pids) > _TS_MAX_PIDS:
221
+ raise err(400, "bad_timeseries", f"at most {_TS_MAX_PIDS} pids per request")
222
+ try:
223
+ wanted = {int(p) for p in raw_pids}
224
+ except (TypeError, ValueError):
225
+ raise err(400, "bad_timeseries", "pids must be integers")
226
+ pool = wanted & {int(p) for p in allowed_pids(session)}
227
+ if not pool:
228
+ # 403, not an empty 200: the caller asked about customers outside their book, and an
229
+ # all-zero series over nobody would read as "no activity", not "not yours".
230
+ raise err(403, "out_of_scope", "none of those customers are in your book")
231
+
232
+ span = body.get("span")
233
+ if not isinstance(span, dict):
234
+ raise err(400, "bad_timeseries", "span must be {'lastN': n} or {'from': .., 'to': ..}")
235
+ today = time.strftime("%Y-%m-%d")
236
+ t = dt.date.fromisoformat(today)
237
+ n = span.get("lastN")
238
+ starts = []
239
+ if n is not None:
240
+ if not isinstance(n, int) or isinstance(n, bool) or not (1 <= n <= _TS_MAX_LAST_N):
241
+ raise err(400, "bad_timeseries", f"lastN must be 1..{_TS_MAX_LAST_N}")
242
+ cur = _ts_start_of(bucket, t)
243
+ starts = [cur]
244
+ for _ in range(n - 1):
245
+ cur = _ts_prev(bucket, cur)
246
+ starts.append(cur)
247
+ starts.reverse()
248
+ else:
249
+ try:
250
+ d_from = dt.date.fromisoformat(str(span.get("from")))
251
+ d_to = dt.date.fromisoformat(str(span.get("to")))
252
+ except (TypeError, ValueError):
253
+ raise err(400, "bad_timeseries", "span.from/to must be ISO dates (YYYY-MM-DD)")
254
+ if d_from > d_to:
255
+ d_from, d_to = d_to, d_from
256
+ cur = _ts_start_of(bucket, d_from)
257
+ while cur <= d_to:
258
+ starts.append(cur)
259
+ if len(starts) > _TS_MAX_BUCKETS:
260
+ raise err(400, "bad_timeseries",
261
+ f"that span is more than {_TS_MAX_BUCKETS} {bucket} buckets - "
262
+ f"narrow it")
263
+ cur = _ts_next(bucket, cur)
264
+ if not starts:
265
+ raise err(400, "bad_timeseries", "the span holds no buckets")
266
+ ends = [_ts_next(bucket, s) - dt.timedelta(days=1) for s in starts]
267
+
268
+ rt = session.runtime
269
+ if not rt.available():
270
+ raise err(503, "store_unavailable", "the tenant store is unavailable")
271
+ import modules.customer_data as cl_mod
272
+ # Read-only route: it must not consume a one-shot label-correction ack the browser has
273
+ # not seen yet (the same rule event validation follows).
274
+ ws = cl_mod.table_workspace(session.uname, consume_corrections=False)
275
+ fdefs = ws.get("fields") or {}
276
+ keys, dropped, seen = [], [], set()
277
+ for k in raw_fields:
278
+ k = str(k or "")
279
+ if not k or k in seen:
280
+ continue
281
+ seen.add(k)
282
+ fd = fdefs.get(k)
283
+ if not isinstance(fd, dict) or not isinstance(fd.get("measure"), dict):
284
+ # Named, never silent: v1 eligibility is measure-backed fields only (C-TS).
285
+ dropped.append({"field": k, "reason": "not_a_measure_field"})
286
+ continue
287
+ keys.append(k)
288
+ if not keys:
289
+ raise err(400, "bad_timeseries",
290
+ "none of the requested fields are measure fields (v1 serves measure-backed "
291
+ "fields only)")
292
+ mfields = [{"key": k, "measure": dict(fdefs[k]["measure"])} for k in keys]
293
+
294
+ team_id, agent = _team_agent(session)
295
+ stamp = _pool_stamp(rt, team_id, agent)
296
+ problems = []
297
+ answers = measure_resolve.series_values(
298
+ mfields, bucket, starts[0].isoformat(), ends[-1].isoformat(),
299
+ team_id, frozenset(pool), today, stamp, rt.series_memo,
300
+ on_error=lambda tag, e: problems.append(str(e)[:200]))
301
+
302
+ columns = []
303
+ for s, e in zip(starts, ends):
304
+ col = {"key": s.isoformat(), "label": _ts_label(bucket, s),
305
+ "from": s.isoformat(), "to": e.isoformat()}
306
+ if e > t:
307
+ col["partial"] = True
308
+ columns.append(col)
309
+ rows = []
310
+ for k in keys:
311
+ ans = answers.get(k)
312
+ if ans is None:
313
+ dropped.append({"field": k, "reason": "unresolvable"})
314
+ continue
315
+ vals_by = ans.get("values") or {}
316
+ agg_kind = str(ans.get("agg") or "sum")
317
+ zero_fill = agg_kind in ("sum", "count")
318
+ vals = [vals_by.get(s.isoformat(), 0 if zero_fill else None) for s in starts]
319
+ total = round(sum(v for v in vals if v is not None), 2) if zero_fill else None
320
+ rows.append({"field": k, "label": str(fdefs[k].get("label") or k)[:120],
321
+ "agg": agg_kind, "values": vals, "total": total})
322
+ meta = {"pool": len(pool), "today": today, "bucket": bucket}
323
+ if dropped:
324
+ meta["dropped"] = dropped
325
+ if problems:
326
+ meta["problems"] = problems[:5]
327
+ return {"columns": columns, "rows": rows, "meta": meta}
328
+
329
+
330
  @router.post("/grid/events")
331
  def grid_events_route(body: dict = Body(default=None),
332
  session: Session = Depends(module_gate(MODULE))):
 
348
  # typo degraded silently to customer-scope behaviour on a WRITE. Read and write must agree on
349
  # what a scope is, or the surface you read is not the surface you wrote.
350
  scope = _scope_or_400((body or {}).get("scopeKey"))
351
+ # This assembly validates the write; it is not a payload the browser will render. Leave
352
+ # one-shot field-name correction acks queued for the subsequent /workspace refresh.
353
+ g = grid_assembly(session, scope=scope, consume_corrections=False)
354
  # ⚠ THE MEASURE CONTEXT IS NOT OPTIONAL (2026-07-31). Without `measure_offer`,
355
  # `clean_measure_field` had an empty admission list and every measure-column create over
356
  # HTTP was silently refused; without `measure_keys`, `clean_filter_tree` stripped every
 
359
  # never write.
360
  ctx = _ctx(session, g["fields"], g["pids"], scope_key=scope,
361
  measure_keys=frozenset(m["key"] for m in g["measures"]),
362
+ resolved_ids=frozenset(g["measure_sets"]),
363
+ cohort_ids=frozenset(c["id"] for c in g["lists"]),
364
+ measure_offer=tuple(g["measures"]),
365
+ visible_views=tuple(g["views"]))
366
 
367
  # Per-event results so the client can tell which of a batch landed — the component's own
368
  # bridge has no response channel at all, so this is strictly more than the embed gets.
api/routes_nav.py CHANGED
@@ -10,12 +10,53 @@ The full rule set — archived is invisible to everyone, `group_only` rows are e
10
  `prefs.json` Library preference is deliberately NOT applied — is documented on
11
  `core.perms.nav_pages`, which is where it belongs: one place, both callers.
12
  """
13
- from fastapi import APIRouter, Depends
14
 
15
- from deps import Session, perms, require_session
16
 
17
  router = APIRouter(prefix="/api/v1")
18
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
 
20
  @router.get("/nav")
21
  def nav(session: Session = Depends(require_session)):
@@ -28,7 +69,84 @@ def nav(session: Session = Depends(require_session)):
28
  """
29
  pages = perms.nav_pages(session.user)
30
  if not pages:
31
- from deps import err
32
  raise err(403, "no_surfaces",
33
  "your account has no dashboards assigned — ask an administrator")
34
  return {"pages": pages, "landing": perms.landing_page(session.user)}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10
  `prefs.json` Library preference is deliberately NOT applied — is documented on
11
  `core.perms.nav_pages`, which is where it belongs: one place, both callers.
12
  """
13
+ from fastapi import APIRouter, Body, Depends
14
 
15
+ from deps import Session, err, perms, require_session
16
 
17
  router = APIRouter(prefix="/api/v1")
18
 
19
+ #: Wave 2026-08-02 (C-SCHEMA): per-user folders over the database list, the view-folder
20
+ #: pattern applied to the nav. Cosmetic per-user state — placement never grants or hides a
21
+ #: surface (the server-filtered nav still decides what exists).
22
+ _NAV_PREFS_KEY = "nav_prefs"
23
+ _MAX_NAV_FOLDERS = 16
24
+
25
+
26
+ def _clean_nav_prefs(raw, page_keys):
27
+ """Validated wholesale replacement, the `clean_folders` posture: prune, never invent.
28
+
29
+ `page_keys` is the set of TOP-LEVEL keys this session may see; a placement of an unknown
30
+ or invisible key is dropped (it can return when the grant does — placement is cosmetic,
31
+ so pruning is loss-free). Unknown folder refs drop the placement, not the folder.
32
+ """
33
+ raw = raw if isinstance(raw, dict) else {}
34
+ folders, seen = [], set()
35
+ for f in (raw.get("folders") or [])[:_MAX_NAV_FOLDERS]:
36
+ if not isinstance(f, dict):
37
+ continue
38
+ fid = str(f.get("id") or "").strip()[:40]
39
+ name = " ".join(str(f.get("name") or "").split())[:40]
40
+ if not fid or fid in seen or not name:
41
+ continue
42
+ seen.add(fid)
43
+ folders.append({"id": fid, "name": name})
44
+ ids = {f["id"] for f in folders}
45
+ placement = {}
46
+ src = raw.get("placement")
47
+ if isinstance(src, dict):
48
+ for k, v in src.items():
49
+ k, v = str(k)[:60], str(v)[:40]
50
+ if v in ids and (page_keys is None or k in page_keys):
51
+ placement[k] = v
52
+ return {"folders": folders, "placement": placement}
53
+
54
+
55
+ def _visible_top_keys(user):
56
+ """The keys a placement may name: top-level rows (group heads + parentless pages)."""
57
+ pages = perms.nav_pages(user) or []
58
+ return {p["key"] for p in pages if not p.get("parent")}
59
+
60
 
61
  @router.get("/nav")
62
  def nav(session: Session = Depends(require_session)):
 
69
  """
70
  pages = perms.nav_pages(session.user)
71
  if not pages:
 
72
  raise err(403, "no_surfaces",
73
  "your account has no dashboards assigned — ask an administrator")
74
  return {"pages": pages, "landing": perms.landing_page(session.user)}
75
+
76
+
77
+ @router.get("/nav/prefs")
78
+ def nav_prefs(session: Session = Depends(require_session)):
79
+ """This user's database-list folders, re-validated at serve time against what they may
80
+ currently see (a revoked page's placement vanishes with the page, and returns with it)."""
81
+ try:
82
+ stored = (session.runtime.get(_NAV_PREFS_KEY) or {}).get(session.uname) or {}
83
+ except Exception:
84
+ stored = {}
85
+ return {"prefs": _clean_nav_prefs(stored, _visible_top_keys(session.user))}
86
+
87
+
88
+ @router.post("/nav/prefs")
89
+ def save_nav_prefs(body: dict = Body(default=None),
90
+ session: Session = Depends(require_session)):
91
+ """Wholesale replace, like the table folder stratum — the client sent its complete
92
+ picture, validated here; a partial merge would resurrect deleted folders forever."""
93
+ clean = _clean_nav_prefs(body or {}, _visible_top_keys(session.user))
94
+ if not session.runtime.available():
95
+ raise err(503, "store_unavailable",
96
+ "the tenant store is unavailable — nothing was saved")
97
+
98
+ def _up(data):
99
+ data = data if isinstance(data, dict) else {}
100
+ if clean["folders"] or clean["placement"]:
101
+ data[session.uname] = clean
102
+ else:
103
+ data.pop(session.uname, None)
104
+ return data
105
+
106
+ try:
107
+ session.runtime.update(_NAV_PREFS_KEY, _up)
108
+ except Exception:
109
+ raise err(503, "store_unavailable",
110
+ "the folder change was not saved — the store refused the write")
111
+ return {"prefs": clean}
112
+
113
+
114
+ @router.get("/nav/schema/{key}")
115
+ def nav_schema(key: str, session: Session = Depends(require_session)):
116
+ """The database's schema drawer payload: its field contract + the semantic measures this
117
+ session may build with. Fail-closed on the SAME predicate as the nav — a key the session
118
+ may not open answers 403, never a redacted schema."""
119
+ session.require(key)
120
+ pages = perms.nav_pages(session.user) or []
121
+ page = next((p for p in pages if p.get("key") == key), None)
122
+ if page is None:
123
+ raise err(404, "unknown_page", f"{key!r} is not a database this session can see")
124
+ fields = []
125
+ if key in ("customer_data", "cohort", "customers"):
126
+ try:
127
+ import aios_grid
128
+ for f in aios_grid.FIELDS:
129
+ entry = {"key": f["key"], "label": f["label"], "type": f["type"],
130
+ "source": f["source"],
131
+ "description": str(f.get("description") or "")}
132
+ if f.get("options"):
133
+ entry["options"] = list(f["options"])
134
+ fields.append(entry)
135
+ except Exception:
136
+ fields = []
137
+ measures = []
138
+ try:
139
+ from core import measure_resolve
140
+ team_id = perms.scope_team_id(session.user)
141
+ for m in measure_resolve.offer(team_id) or []:
142
+ measures.append({"key": str(m.get("key") or ""),
143
+ "label": str(m.get("label") or m.get("key") or ""),
144
+ "type": str(m.get("type") or "")})
145
+ except Exception:
146
+ measures = []
147
+ out = {"key": key, "label": page.get("label") or key,
148
+ "source": page.get("source") or "", "fields": fields, "measures": measures}
149
+ if not fields:
150
+ # Honest, never a mock: a database whose contract is not yet published says so.
151
+ out["note"] = "This database has not published a field contract yet."
152
+ return out
royalimports_os/aios_grid.py CHANGED
@@ -112,7 +112,7 @@ MEASURE_FIELD_PREFIX = "measure_"
112
  MEASURE_FIELD_TYPES = {"currency", "int", "pct"}
113
 
114
 
115
- def _clean_options(raw):
116
  """Choices for a `select`: strings, trimmed, de-duplicated case-insensitively, capped.
117
  Mirrors types.ts parseOptions — a choice list that means one thing in the picker and
118
  another in the filter dropdown is a column with two vocabularies."""
@@ -125,42 +125,42 @@ def _clean_options(raw):
125
  continue
126
  seen.add(s.lower())
127
  out.append(s)
128
- return out[:MAX_FIELD_OPTIONS]
129
-
130
-
131
- def _clean_option_colors(raw, options):
132
- """Choice-label -> #RRGGBB, limited to the field's canonical option vocabulary."""
133
- if not isinstance(raw, dict):
134
- return {}
135
- supplied = {}
136
- for label, color in raw.items():
137
- if not isinstance(label, str) or not isinstance(color, str):
138
- continue
139
- clean = color.strip().upper()
140
- if re.fullmatch(r"#[0-9A-F]{6}", clean):
141
- supplied[label.strip().lower()] = clean
142
- out = {}
143
- for option in options or []:
144
- color = supplied.get(str(option).strip().lower())
145
- if color:
146
- out[str(option)] = color
147
- return out
148
-
149
-
150
- def _choice_appearance(raw, options):
151
- """Validated select-family appearance. Absent colour toggle means legacy-on."""
152
- if not isinstance(raw, dict):
153
- return {}
154
- out = {}
155
- if isinstance(raw.get("colorCodeOptions"), bool):
156
- out["colorCodeOptions"] = raw["colorCodeOptions"]
157
- colors = _clean_option_colors(raw.get("optionColors"), options)
158
- if colors:
159
- out["optionColors"] = colors
160
- return out
161
-
162
-
163
- def _clean_rating_max(raw):
164
  """A rating's star count, bounded. Anything unusable is the default, not a refusal — the
165
  field still holds its 1..max integers either way."""
166
  try:
@@ -269,15 +269,15 @@ def _field_extras(saved, ftype):
269
  fmt = _clean_format(saved.get("format"), ftype)
270
  if fmt:
271
  out["format"] = fmt
272
- if saved.get("scope") == "cohort":
273
- out["scope"] = "cohort"
274
- corrected_from = saved.get("labelCorrectedFrom")
275
- correction_id = saved.get("labelCorrectionId")
276
- if (isinstance(corrected_from, str) and corrected_from.strip()
277
- and isinstance(correction_id, str) and correction_id.strip()):
278
- out["labelCorrectedFrom"] = corrected_from.strip()[:120]
279
- out["labelCorrectionId"] = correction_id.strip()[:180]
280
- return out
281
 
282
 
283
  #: The DERIVED column listing the cohorts a customer is in (owner, 2026-07-27).
@@ -508,11 +508,11 @@ def fields_from_workspace(workspace=None, cohorts=False, scope_key=None):
508
  "default": bool(field.get("default", True)),
509
  "custom": True,
510
  "agg": field.get("agg") if field.get("agg") in {"sum"} else None,
511
- "note": str(field.get("note") or "")[:2000],
512
- **({"options": options} if ftype in ("select", "multiselect") else {}),
513
- **(_choice_appearance(field, options)
514
- if ftype in ("select", "multiselect") else {}),
515
- # comma-joined SET semantics (the Cohorts column's contract): the row belongs to
516
  # every member, groups count it under each, the toolbar count stays distinct.
517
  **({"multi": True} if ftype == "multiselect" else {}),
518
  **({"max": _clean_rating_max(field.get("max"))} if ftype == "rating" else {}),
@@ -570,7 +570,17 @@ def rows_from_pool(pool_rows, fields=None, overlays=None, derived=None):
570
  # Ops the Airtable-parity condition builder can emit. isEmpty/isNotEmpty are
571
  # VALUE-FREE (they legitimately carry no value and must never be dropped for it).
572
  FILTER_OPS = {'contains', 'doesNotContain', 'eq', 'neq', 'isEmpty', 'isNotEmpty',
573
- 'gt', 'gte', 'lt', 'lte', 'between', 'within'}
 
 
 
 
 
 
 
 
 
 
574
  #: The RESERVED pseudo-column of a cohort-membership leaf (owner item 5, 2026-07-26). It is not
575
  #: a Field and never will be — a cohort is a hand-curated SET, so making it a column would mean
576
  #: a cell per row per cohort. Mirrors customer-grid/types.ts COHORT_FIELD.
@@ -685,7 +695,18 @@ def _clean_rhs(raw, valid_keys):
685
  #: views are sitting in mode:'dashboard' right now (wave 8's own close-out records one). The
686
  #: rename is therefore a stored-value MIGRATION, not a constant rename: accept 'dashboard' on
687
  #: READ forever, only ever WRITE 'chart'.
688
- DISPLAY_MODES = {'grid', 'list', 'calendar', 'kanban', 'map', 'dashboard', 'chart'}
 
 
 
 
 
 
 
 
 
 
 
689
 
690
  #: Old wire value -> the value we store today. Applied AFTER the membership test so an unknown
691
  #: mode is still rejected rather than accidentally aliased.
@@ -823,6 +844,59 @@ def _clean_display(raw, valid_keys):
823
  for ref in ('dateField', 'stackField', 'titleField', 'colorField', 'sizeField'):
824
  if raw.get(ref) in valid_keys:
825
  out[ref] = raw[ref]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
826
  charts = raw.get('charts')
827
  if isinstance(charts, list):
828
  clean = [c for c in (_clean_chart(x, valid_keys) for x in charts[:MAX_CHARTS]) if c]
@@ -1204,6 +1278,21 @@ def workspace_wire(ws, uname, pool_pids, defs=None, scope_key='customer', storag
1204
  if _c['id'] in _cplaced:
1205
  _c['folderId'] = _cplaced[_c['id']]
1206
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1207
  return workspace, fields, views, cohort_lists
1208
 
1209
 
 
112
  MEASURE_FIELD_TYPES = {"currency", "int", "pct"}
113
 
114
 
115
+ def _clean_options(raw):
116
  """Choices for a `select`: strings, trimmed, de-duplicated case-insensitively, capped.
117
  Mirrors types.ts parseOptions — a choice list that means one thing in the picker and
118
  another in the filter dropdown is a column with two vocabularies."""
 
125
  continue
126
  seen.add(s.lower())
127
  out.append(s)
128
+ return out[:MAX_FIELD_OPTIONS]
129
+
130
+
131
+ def _clean_option_colors(raw, options):
132
+ """Choice-label -> #RRGGBB, limited to the field's canonical option vocabulary."""
133
+ if not isinstance(raw, dict):
134
+ return {}
135
+ supplied = {}
136
+ for label, color in raw.items():
137
+ if not isinstance(label, str) or not isinstance(color, str):
138
+ continue
139
+ clean = color.strip().upper()
140
+ if re.fullmatch(r"#[0-9A-F]{6}", clean):
141
+ supplied[label.strip().lower()] = clean
142
+ out = {}
143
+ for option in options or []:
144
+ color = supplied.get(str(option).strip().lower())
145
+ if color:
146
+ out[str(option)] = color
147
+ return out
148
+
149
+
150
+ def _choice_appearance(raw, options):
151
+ """Validated select-family appearance. Absent colour toggle means legacy-on."""
152
+ if not isinstance(raw, dict):
153
+ return {}
154
+ out = {}
155
+ if isinstance(raw.get("colorCodeOptions"), bool):
156
+ out["colorCodeOptions"] = raw["colorCodeOptions"]
157
+ colors = _clean_option_colors(raw.get("optionColors"), options)
158
+ if colors:
159
+ out["optionColors"] = colors
160
+ return out
161
+
162
+
163
+ def _clean_rating_max(raw):
164
  """A rating's star count, bounded. Anything unusable is the default, not a refusal — the
165
  field still holds its 1..max integers either way."""
166
  try:
 
269
  fmt = _clean_format(saved.get("format"), ftype)
270
  if fmt:
271
  out["format"] = fmt
272
+ if saved.get("scope") == "cohort":
273
+ out["scope"] = "cohort"
274
+ corrected_from = saved.get("labelCorrectedFrom")
275
+ correction_id = saved.get("labelCorrectionId")
276
+ if (isinstance(corrected_from, str) and corrected_from.strip()
277
+ and isinstance(correction_id, str) and correction_id.strip()):
278
+ out["labelCorrectedFrom"] = corrected_from.strip()[:120]
279
+ out["labelCorrectionId"] = correction_id.strip()[:180]
280
+ return out
281
 
282
 
283
  #: The DERIVED column listing the cohorts a customer is in (owner, 2026-07-27).
 
508
  "default": bool(field.get("default", True)),
509
  "custom": True,
510
  "agg": field.get("agg") if field.get("agg") in {"sum"} else None,
511
+ "note": str(field.get("note") or "")[:2000],
512
+ **({"options": options} if ftype in ("select", "multiselect") else {}),
513
+ **(_choice_appearance(field, options)
514
+ if ftype in ("select", "multiselect") else {}),
515
+ # comma-joined SET semantics (the Cohorts column's contract): the row belongs to
516
  # every member, groups count it under each, the toolbar count stays distinct.
517
  **({"multi": True} if ftype == "multiselect" else {}),
518
  **({"max": _clean_rating_max(field.get("max"))} if ftype == "rating" else {}),
 
570
  # Ops the Airtable-parity condition builder can emit. isEmpty/isNotEmpty are
571
  # VALUE-FREE (they legitimately carry no value and must never be dropped for it).
572
  FILTER_OPS = {'contains', 'doesNotContain', 'eq', 'neq', 'isEmpty', 'isNotEmpty',
573
+ 'gt', 'gte', 'lt', 'lte', 'between', 'within',
574
+ # Wave 2026-08-02 (C-OPS): RANK operators — evaluated as a SET pass over the
575
+ # sibling-filtered domain by the client engine (useVisibleRows). The validator
576
+ # accepts them like any op (structural, not semantic); filter_sql REFUSES to
577
+ # compile them to row SQL (a per-row WHERE cannot express Top-N). aboveAvg /
578
+ # belowAvg are VALUE-FREE; the rest encode their argument in `value` as a
579
+ # string int (topN/bottomN 1..10000, inTopPct/inBottomPct 1..100,
580
+ # inQuartile 1..4, inDecile 1..10). Deliberately NOT in MEASURE_OPS: on a
581
+ # measure-carrying column they rank the field's own derived values.
582
+ 'topN', 'bottomN', 'inTopPct', 'inBottomPct',
583
+ 'aboveAvg', 'belowAvg', 'inQuartile', 'inDecile'}
584
  #: The RESERVED pseudo-column of a cohort-membership leaf (owner item 5, 2026-07-26). It is not
585
  #: a Field and never will be — a cohort is a hand-curated SET, so making it a column would mean
586
  #: a cell per row per cohort. Mirrors customer-grid/types.ts COHORT_FIELD.
 
695
  #: views are sitting in mode:'dashboard' right now (wave 8's own close-out records one). The
696
  #: rename is therefore a stored-value MIGRATION, not a constant rename: accept 'dashboard' on
697
  #: READ forever, only ever WRITE 'chart'.
698
+ DISPLAY_MODES = {'grid', 'list', 'calendar', 'kanban', 'map', 'dashboard', 'chart',
699
+ 'timeseries'}
700
+
701
+ #: C-DISP (wave 2026-08-02): the time-series view's bucket vocabulary and caps, plus the
702
+ #: calendar-summary metric cap. types.ts mirrors these as TS_BUCKETS / TS_MAX_LAST_N /
703
+ #: TS_MAX_FIELDS / MAX_CALENDAR_METRICS, and cleanDisplay applies the same per-entry drops,
704
+ #: so an accepted save reads back byte-identically on both engines.
705
+ TS_BUCKETS = {'week', 'month', 'quarter', 'year'}
706
+ TS_MAX_LAST_N = 120
707
+ TS_MAX_FIELDS = 12
708
+ MAX_CALENDAR_METRICS = 4
709
+ _ISO_DAY = re.compile(r'^\d{4}-\d{2}-\d{2}$')
710
 
711
  #: Old wire value -> the value we store today. Applied AFTER the membership test so an unknown
712
  #: mode is still rejected rather than accidentally aliased.
 
844
  for ref in ('dateField', 'stackField', 'titleField', 'colorField', 'sizeField'):
845
  if raw.get(ref) in valid_keys:
846
  out[ref] = raw[ref]
847
+ # ── C-DISP (wave 2026-08-02) ─────────────────────────────────────────────────────────
848
+ # kanbanClamp: stored ONLY as the literal opt-OUT. Absent means clamped — the new
849
+ # standardized default — so storing True would be a second way to say nothing (the same
850
+ # rule that keeps mode:'grid' out of the store).
851
+ if raw.get('kanbanClamp') is False:
852
+ out['kanbanClamp'] = False
853
+ if raw.get('calendarMode') in ('records', 'summary'):
854
+ out['calendarMode'] = raw['calendarMode']
855
+ metrics = raw.get('calendarMetrics')
856
+ if isinstance(metrics, list):
857
+ clean_m, seen_m = [], set()
858
+ for m in metrics[:MAX_CALENDAR_METRICS]:
859
+ # Dropped INDIVIDUALLY (the charts precedent): one dead metric must not cost the
860
+ # user the summary card they configured around it.
861
+ if not isinstance(m, dict):
862
+ continue
863
+ mid = str(m.get('id') or '')[:40]
864
+ if (not mid or mid in seen_m or m.get('field') not in valid_keys
865
+ or m.get('agg') not in CHART_AGGS):
866
+ continue
867
+ seen_m.add(mid)
868
+ clean_m.append({'id': mid, 'field': m['field'], 'agg': m['agg']})
869
+ if clean_m:
870
+ out['calendarMetrics'] = clean_m
871
+ if raw.get('tsBucket') in TS_BUCKETS:
872
+ out['tsBucket'] = raw['tsBucket']
873
+ span = raw.get('tsSpan')
874
+ if isinstance(span, dict):
875
+ clean_span = {}
876
+ n = span.get('lastN')
877
+ if isinstance(n, int) and not isinstance(n, bool) and 1 <= n <= TS_MAX_LAST_N:
878
+ clean_span['lastN'] = n
879
+ else:
880
+ f, t = span.get('from'), span.get('to')
881
+ f = f if isinstance(f, str) and _ISO_DAY.match(f) else None
882
+ t = t if isinstance(t, str) and _ISO_DAY.match(t) else None
883
+ if f and t and f > t:
884
+ f, t = t, f
885
+ if f:
886
+ clean_span['from'] = f
887
+ if t:
888
+ clean_span['to'] = t
889
+ if clean_span:
890
+ out['tsSpan'] = clean_span
891
+ ts_fields = raw.get('tsFields')
892
+ if isinstance(ts_fields, list):
893
+ clean_f, seen_f = [], set()
894
+ for k in ts_fields[:TS_MAX_FIELDS]:
895
+ if k in valid_keys and k not in seen_f:
896
+ seen_f.add(k)
897
+ clean_f.append(k)
898
+ if clean_f:
899
+ out['tsFields'] = clean_f
900
  charts = raw.get('charts')
901
  if isinstance(charts, list):
902
  clean = [c for c in (_clean_chart(x, valid_keys) for x in charts[:MAX_CHARTS]) if c]
 
1278
  if _c['id'] in _cplaced:
1279
  _c['folderId'] = _cplaced[_c['id']]
1280
 
1281
+ # RECORD LAYOUT (wave 2026-08-02, C-LAYOUT): the per-user record-detail field order,
1282
+ # re-validated at SERVE time exactly like folders — a field can be deleted by a path
1283
+ # that knows nothing about this stratum, and a stale key must not outlive its field.
1284
+ _rl = ws.get('recordLayout')
1285
+ if isinstance(_rl, dict) and isinstance(_rl.get('order'), list):
1286
+ _fkeys = {f['key'] for f in fields if isinstance(f, dict) and f.get('key')}
1287
+ _order, _seen = [], set()
1288
+ for _k in _rl['order'][:200]:
1289
+ _k = str(_k or '')
1290
+ if _k and _k in _fkeys and _k not in _seen:
1291
+ _seen.add(_k)
1292
+ _order.append(_k)
1293
+ if _order:
1294
+ workspace['recordLayout'] = {'order': _order}
1295
+
1296
  return workspace, fields, views, cohort_lists
1297
 
1298
 
royalimports_os/aios_grid_fields.json CHANGED
@@ -1,217 +1,230 @@
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,currency,int,date,pct}. `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": "salesperson",
31
- "label": "Salesperson",
32
- "type": "text",
33
- "source": "odoo",
34
- "default": false,
35
- "description": "Who keyed in most of this customer's orders — not the Agent, who owns the account."
36
- },
37
- {
38
- "key": "city",
39
- "label": "City",
40
- "type": "text",
41
- "source": "odoo",
42
- "default": true,
43
- "description": "City on the customer's Odoo address."
44
- },
45
- {
46
- "key": "state",
47
- "label": "State",
48
- "type": "text",
49
- "source": "odoo",
50
- "default": true,
51
- "description": "State or province on the customer's Odoo address."
52
- },
53
- {
54
- "key": "country",
55
- "label": "Country",
56
- "type": "text",
57
- "source": "odoo",
58
- "default": false,
59
- "description": "Country on the customer's Odoo address."
60
- },
61
- {
62
- "key": "zip",
63
- "label": "ZIP",
64
- "type": "text",
65
- "source": "odoo",
66
- "default": false,
67
- "description": "Postal code on the customer's Odoo address."
68
- },
69
- {
70
- "key": "customer_since",
71
- "label": "Customer since",
72
- "type": "date",
73
- "source": "odoo",
74
- "default": false,
75
- "description": "When this customer was first set up in Odoo."
76
- },
77
- {
78
- "key": "tags",
79
- "label": "Tags",
80
- "type": "text",
81
- "source": "odoo",
82
- "default": false,
83
- "description": "Odoo labels on this customer, comma-separated."
84
- },
85
- {
86
- "key": "pricelist",
87
- "label": "Price list",
88
- "type": "text",
89
- "source": "odoo",
90
- "default": false,
91
- "description": "The price list this customer buys on."
92
- },
93
- {
94
- "key": "payment_terms",
95
- "label": "Payment terms",
96
- "type": "text",
97
- "source": "odoo",
98
- "default": false,
99
- "description": "Payment terms on this customer's account — Net 30, for example."
100
- },
101
- {
102
- "key": "last_order",
103
- "label": "Last order",
104
- "type": "date",
105
- "source": "odoo",
106
- "default": true,
107
- "description": "Date of the most recent confirmed order."
108
- },
109
- {
110
- "key": "overdue_days",
111
- "label": "Overdue days",
112
- "type": "int",
113
- "source": "odoo",
114
- "default": true,
115
- "description": "How many days late this customer is running against their own usual ordering rhythm."
116
- },
117
- {
118
- "_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.",
119
- "key": "est_missed",
120
- "label": "Est. missed $",
121
- "type": "currency",
122
- "source": "odoo",
123
- "default": true,
124
- "agg": "sum",
125
- "filterable": false,
126
- "description": "Estimated sales missed while quiet: missed orders (capped at 3) times average order value. An estimate, not money owed."
127
- },
128
- {
129
- "key": "ar_open",
130
- "label": "AR open $",
131
- "type": "currency",
132
- "source": "odoo",
133
- "default": false,
134
- "description": "Invoiced money owed, not yet overdue."
135
- },
136
- {
137
- "key": "ar_overdue",
138
- "label": "AR overdue $",
139
- "type": "currency",
140
- "source": "odoo",
141
- "default": false,
142
- "description": "Invoiced money past due — same basis as the Collections page."
143
- },
144
- {
145
- "key": "ar_exposure",
146
- "label": "Credit exposure $",
147
- "type": "currency",
148
- "source": "odoo",
149
- "default": false,
150
- "description": "The most you could be out if they stopped paying today: open, overdue, draft and not-yet-invoiced."
151
- },
152
- {
153
- "key": "days_to_pay",
154
- "label": "Days to pay",
155
- "type": "int",
156
- "source": "odoo",
157
- "default": false,
158
- "description": "Average days to pay an invoice in full. Blank means no fully paid invoice yet."
159
- },
160
- {
161
- "key": "top_category",
162
- "label": "Top category",
163
- "type": "text",
164
- "source": "odoo",
165
- "default": false,
166
- "description": "The category this customer spent the most on in the last 12 months."
167
- },
168
- {
169
- "key": "top_category_pct",
170
- "label": "Top category %",
171
- "type": "pct",
172
- "source": "odoo",
173
- "default": false,
174
- "description": "Share of last-12-months spend that went to the top category."
175
- },
176
- {
177
- "key": "sku_count",
178
- "label": "SKUs bought",
179
- "type": "int",
180
- "source": "odoo",
181
- "default": false,
182
- "description": "Distinct products bought in the last 12 months."
183
- },
184
- {
185
- "key": "top_sku",
186
- "label": "Top SKU",
187
- "type": "text",
188
- "source": "odoo",
189
- "default": false,
190
- "description": "The product this customer spent the most on in the last 12 months."
191
- },
192
- {
193
- "key": "days_since",
194
- "label": "Days since order",
195
- "type": "int",
196
- "source": "odoo",
197
- "default": false,
198
- "description": "Days since the last confirmed order."
199
- },
200
- {
201
- "key": "typical_gap_days",
202
- "label": "Typical gap days",
203
- "type": "int",
204
- "source": "odoo",
205
- "default": false,
206
- "description": "Days this customer usually goes between orders, from their own history."
207
- },
208
- {
209
- "key": "notes",
210
- "label": "Notes",
211
- "type": "text",
212
- "source": "overlay",
213
- "default": false,
214
- "description": "Your notes on this customer. Saved in this app only, visible only to you."
215
- }
216
- ]
217
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ }
royalimports_os/core/grid_events.py CHANGED
@@ -415,6 +415,32 @@ def handle_one(event, ctx):
415
  _tel.error('grid:view-select', _ae)
416
  return False
417
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
418
  if kind == 'view_upsert':
419
  raw = event.get('view')
420
  if not isinstance(raw, dict) or not isinstance(raw.get('config'), dict):
@@ -458,11 +484,19 @@ def handle_one(event, ctx):
458
  widths[key] = max(60, min(600, round(float(value))))
459
  except (TypeError, ValueError):
460
  pass
 
 
 
 
 
 
461
  config = {
462
  'filters': filters,
463
  # conjunction joining the ROOT-level conditions; anything but an
464
  # explicit 'or' means 'and' (legacy views had an implicit AND).
465
  'filterConj': 'or' if cfg.get('filterConj') == 'or' else 'and',
 
 
466
  'sorts': sorts,
467
  'groupBy': cfg.get('groupBy') if cfg.get('groupBy') in valid_keys else None,
468
  'colorBy': cfg.get('colorBy') if cfg.get('colorBy') in valid_keys else None,
 
415
  _tel.error('grid:view-select', _ae)
416
  return False
417
 
418
+ if kind == 'record_layout':
419
+ # Wave 2026-08-02 (C-LAYOUT): the per-user record-detail field order. Presentation
420
+ # state for one surface; grid column order is untouched. Unknown keys are pruned
421
+ # against the LIVE field set, dupes collapse, and the wire re-validates at serve
422
+ # time — so a client racing a field delete degrades to default order, never an error.
423
+ raw_order = event.get('order')
424
+ if not isinstance(raw_order, list):
425
+ return False
426
+ order, seen = [], set()
427
+ for k in raw_order[:200]:
428
+ k = str(k or '').strip()[:80]
429
+ if k and k in valid_keys and k not in seen:
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:
437
+ ws['recordLayout'] = {'order': order}
438
+ else:
439
+ ws.pop('recordLayout', None)
440
+ # Autosave hot path, like view_select: the client already renders the order it asked
441
+ # for, and the wire echoes it back on the next workspace read.
442
+ return False
443
+
444
  if kind == 'view_upsert':
445
  raw = event.get('view')
446
  if not isinstance(raw, dict) or not isinstance(raw.get('config'), dict):
 
484
  widths[key] = max(60, min(600, round(float(value))))
485
  except (TypeError, ValueError):
486
  pass
487
+ # C-LOCK (wave 2026-08-02, item 12's mechanism): a view may be LOCKED to one cohort.
488
+ # `cohort_ids` is the same permission list the cohort filter leaf uses — a lock naming
489
+ # a cohort this session cannot see is DROPPED at write, exactly like a cohort rule.
490
+ # (Readers of a SHARED locked view resolve the id against their OWN visible sets; an
491
+ # unresolvable lock matches NOTHING client-side — the cohort-leaf law, never a widen.)
492
+ cohort_lock = str(cfg.get('cohortLock') or '').strip()[:120]
493
  config = {
494
  'filters': filters,
495
  # conjunction joining the ROOT-level conditions; anything but an
496
  # explicit 'or' means 'and' (legacy views had an implicit AND).
497
  'filterConj': 'or' if cfg.get('filterConj') == 'or' else 'and',
498
+ **({'cohortLock': cohort_lock}
499
+ if cohort_lock and cohort_lock in set(cohort_ids) else {}),
500
  'sorts': sorts,
501
  'groupBy': cfg.get('groupBy') if cfg.get('groupBy') in valid_keys else None,
502
  'colorBy': cfg.get('colorBy') if cfg.get('colorBy') in valid_keys else None,
royalimports_os/core/measure_resolve.py CHANGED
@@ -83,6 +83,50 @@ def condition_sets(view_configs, pending_cfg, team_id, allowed_pids, today, stam
83
  return out
84
 
85
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86
  def column_values(fields, team_id, allowed_pids, today, stamp, memo, on_error=None):
87
  """Values for every FORMULA-MEASURE column among `fields` -> `{pid: {field key: value}}`,
88
  handed to `rows_from_pool(derived=…)` beside the cohort cells.
 
83
  return out
84
 
85
 
86
+ def series_values(fields, bucket, date_from, date_to, team_id, allowed_pids, today, stamp,
87
+ memo, on_error=None):
88
+ """`{field key: {'values': {bucket_start: v}, 'agg': kind}}` for every measure column
89
+ among `fields`, bucketed over [date_from, date_to] — the C-TS channel (2026-08-02).
90
+
91
+ Same memo discipline as `column_values`: keys carry (stamp, scope, POOL IDENTITY, the
92
+ question); a permanent failure memoises as None (the caller reports that field as
93
+ dropped), a TRANSIENT one (datastore still warming) never memoises, so the next call
94
+ retries instead of freezing a blank panel for the session's lifetime.
95
+ """
96
+ out = {}
97
+ mfields = [f for f in fields or [] if isinstance(f.get('measure'), dict)]
98
+ if not mfields:
99
+ return out
100
+ from harness import measure_filter as _mf
101
+ pk = _pool_key(allowed_pids)
102
+ for f in mfields:
103
+ mkey = (f.get('measure') or {}).get('key')
104
+ key = (stamp, team_id, pk, mkey, bucket, str(date_from), str(date_to))
105
+ if key not in memo:
106
+ try:
107
+ memo[key] = _mf.resolve_series(mkey, bucket, date_from, date_to,
108
+ today, team_id, allowed_pids)
109
+ except Exception as e:
110
+ if on_error:
111
+ on_error('measure-series', e)
112
+ transient = False
113
+ try:
114
+ from harness import datastore as _ds
115
+ transient = not _ds.ready()
116
+ except Exception:
117
+ transient = False
118
+ if transient:
119
+ continue # no memo entry -> the next call tries again
120
+ memo[key] = None
121
+ ans = memo[key]
122
+ if ans is None:
123
+ continue
124
+ out[f['key']] = ans
125
+ if len(memo) > 200:
126
+ memo.clear()
127
+ return out
128
+
129
+
130
  def column_values(fields, team_id, allowed_pids, today, stamp, memo, on_error=None):
131
  """Values for every FORMULA-MEASURE column among `fields` -> `{pid: {field key: value}}`,
132
  handed to `rows_from_pool(derived=…)` beside the cohort cells.
royalimports_os/core/table_store.py CHANGED
@@ -67,92 +67,92 @@ def _may_administer(view, viewer, is_admin=False):
67
  return bool(is_admin) or view.get('createdBy') == viewer
68
 
69
 
70
- def is_shared(view):
71
- """A view belongs in the shared bucket when its permissions reach beyond its creator."""
72
- return ((view or {}).get('permissions') or {}).get('edit') in ('collaborative', 'users')
73
-
74
-
75
- def _unique_name(wanted, existing, *, fallback='Untitled', max_len=120):
76
- """Allocate one human-facing name inside a store.update transaction.
77
-
78
- Keys/ids remain structural identity. Names compare case-insensitively after collapsing
79
- whitespace, because those variants are indistinguishable in the UI. This helper belongs
80
- in the store layer: allocating from a pre-write snapshot lets two concurrent requests both
81
- choose the same free name before either write lands.
82
- """
83
- limit = max(1, int(max_len))
84
-
85
- def _clean(value):
86
- return ' '.join(str(value or '').split())
87
-
88
- base = (_clean(wanted) or _clean(fallback) or 'Untitled')[:limit].rstrip()
89
- taken = {_clean(value).casefold() for value in existing if _clean(value)}
90
- if base.casefold() not in taken:
91
- return base
92
- index = 2
93
- while True:
94
- suffix = f' {index}'
95
- stem = base[:max(0, limit - len(suffix))].rstrip()
96
- candidate = f'{stem}{suffix}' if stem else str(index)[-limit:]
97
- if candidate.casefold() not in taken:
98
- return candidate
99
- index += 1
100
-
101
-
102
- class TableStore:
103
  """The six store operations for one table object's workspace, closed over its store key."""
104
 
105
  def __init__(self, table_key):
106
  self.table_key = table_key
107
 
108
  # ---------------------------------------------------------------- read
109
- def workspace(self, username, consume_corrections=True):
110
- """One user's durable workspace: always the full three-strata shape."""
111
- try:
112
- data = store.get(self.table_key) or {}
113
- ws = data.get(username, {}) or {}
114
- # A collision acknowledgement is protocol state, not part of a field definition.
115
- # Consume it with the first fresh workspace payload after the correcting write,
116
- # then splice a bounded copy into that payload only. Keeping it out of `fields`
117
- # prevents an old request id surviving forever and overriding a later rename.
118
- corrections = {}
119
- if consume_corrections and ws.get('fieldCorrections'):
120
- def _take(current):
121
- current_ws = current.get(username) or {}
122
- pending = current_ws.get('fieldCorrections') or {}
123
- corrections.update({
124
- str(key)[:80]: dict(value)
125
- for key, value in pending.items()
126
- if isinstance(value, dict)
127
- })
128
- current_ws.pop('fieldCorrections', None)
129
- return current
130
-
131
- data = store.update(self.table_key, _take, flush='async')
132
- ws = (data or {}).get(username, {}) or {}
133
- except Exception:
134
- ws = {}
135
- corrections = {}
136
- fields = {
137
- key: dict(value) if isinstance(value, dict) else value
138
- for key, value in (ws.get('fields') or {}).items()
139
- }
140
- for key, ack in corrections.items():
141
- field = fields.get(key)
142
- accepted_label = str(ack.get('label') or '')[:120]
143
- requested_label = str(ack.get('labelCorrectedFrom') or '')[:120]
144
- correction_id = str(ack.get('labelCorrectionId') or '')[:180]
145
- # A newer field write clears/replaces the pending ack in the SAME transaction.
146
- # The label check is an extra belt against ever attaching a stale ack to a newer
147
- # definition if a future store implementation weakens that ordering.
148
- if (isinstance(field, dict) and accepted_label
149
- and str(field.get('label') or '') == accepted_label
150
- and requested_label and correction_id):
151
- field['labelCorrectedFrom'] = requested_label
152
- field['labelCorrectionId'] = correction_id
153
- out = {
154
- 'views': dict(ws.get('views') or {}),
155
- 'fields': fields,
156
  'overlays': dict(ws.get('overlays') or {}),
157
  # wave-8 I11 (C4): folders over the saved views / cohorts sidebars. A FOURTH
158
  # stratum rather than a key on each item — see aios_grid.clean_folders for why
@@ -167,6 +167,10 @@ class TableStore:
167
  # fresh profile, which used to fall all the way to the system default view.
168
  if ws.get('activeViewId'):
169
  out['activeViewId'] = str(ws['activeViewId'])
 
 
 
 
170
  return out
171
 
172
  # ---------------------------------------------------------------- write
@@ -185,7 +189,7 @@ class TableStore:
185
  # the historical synchronous hub commit cost seconds per edit. The mutation applies to
186
  # the in-process cache (read-your-writes for every subsequent render); the hub write
187
  # coalesces in the background. Registry/auth writes elsewhere stay flush='sync'.
188
- return store.update(self.table_key, _up, flush='async')
189
 
190
  def save_active_view(self, username, view_id):
191
  """Remember which view this user last opened (owner item 3, 2026-07-31).
@@ -202,6 +206,32 @@ class TableStore:
202
  ws['activeViewId'] = vid
203
  self._update(username, _set)
204
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
205
  def save_folders(self, username, folders, item_folders):
206
  """Replace the folder stratum wholesale (wave-8 I11).
207
 
@@ -240,7 +270,7 @@ class TableStore:
240
  except Exception:
241
  return None
242
 
243
- def save_view(self, username, view, shared=None, reserved_names=(), is_admin=False):
244
  """Upsert a SavedView into its ONE home — personal workspace or the shared bucket.
245
 
246
  `shared` defaults to reading the view's own permissions (`is_shared`). Whichever home
@@ -255,29 +285,29 @@ class TableStore:
255
  raise ValueError('view id is required')
256
  if username == SHARED_KEY:
257
  raise ValueError('reserved username')
258
- to_shared = is_shared(view) if shared is None else bool(shared)
259
- requested = dict(view)
260
- accepted = {}
261
-
262
- def _up(data):
263
- # View names are tenant-global: every personal workspace plus the shared bucket.
264
- # This deliberately includes views the actor cannot see. The only disclosed fact
265
- # is that a display name is already taken, while the categorical "no duplicate
266
- # view names" contract remains true when a personal view is later shared.
267
- names = list(reserved_names or ())
268
- for workspace in data.values():
269
- if not isinstance(workspace, dict):
270
- continue
271
- names.extend(
272
- value.get('name')
273
- for candidate_id, value in (workspace.get('views') or {}).items()
274
- if candidate_id != view_id and isinstance(value, dict)
275
- )
276
- payload = dict(requested)
277
- payload['name'] = _unique_name(payload.get('name'), names)
278
- accepted.clear()
279
- accepted.update(payload)
280
- if to_shared:
281
  bucket = data.setdefault(SHARED_KEY, {})
282
  bucket.setdefault('views', {})[view_id] = payload
283
  # it may have lived in the creator's workspace before being shared
@@ -289,8 +319,8 @@ class TableStore:
289
  (data.get(SHARED_KEY, {}).get('views') or {}).pop(view_id, None)
290
  return data
291
 
292
- store.update(self.table_key, _up, flush='async')
293
- return dict(accepted)
294
 
295
  def delete_view(self, username, view_id):
296
  """Delete a custom/list view override. The system all-rows view is guarded by caller.
@@ -307,56 +337,56 @@ class TableStore:
307
 
308
  store.update(self.table_key, _up, flush='async')
309
 
310
- def save_field(self, username, field, reserved_names=(), correction_id=None):
311
- """Persist a column note or a user-created (custom_/measure_) field definition."""
312
- key = str((field or {}).get('key') or '').strip()
313
- if not key:
314
- raise ValueError('field key is required')
315
- requested = dict(field)
316
- accepted = {}
317
-
318
- def _save(ws):
319
- names = list(reserved_names or ())
320
- names.extend(
321
- value.get('label')
322
- for candidate_key, value in (ws.get('fields') or {}).items()
323
- if candidate_key != key and isinstance(value, dict)
324
- )
325
- payload = dict(requested)
326
- payload.pop('labelCorrectedFrom', None)
327
- payload.pop('labelCorrectionId', None)
328
- requested_label = ' '.join(
329
- str(payload.get('label') or 'Untitled').split())[:120].rstrip()
330
- payload['label'] = _unique_name(requested_label, names)
331
- corrections = ws.setdefault('fieldCorrections', {})
332
- corrections.pop(key, None)
333
- if payload['label'] != requested_label and correction_id:
334
- corrections[key] = {
335
- 'label': payload['label'],
336
- 'labelCorrectedFrom': requested_label,
337
- 'labelCorrectionId': str(correction_id)[:180],
338
- }
339
- if not corrections:
340
- ws.pop('fieldCorrections', None)
341
- accepted.clear()
342
- accepted.update(payload)
343
- # A cleared note on an immutable source field returns to the canonical schema
344
  # instead of leaving a meaningless override row. Custom fields remain even with
345
  # an empty note — and so does a PRESET field carrying a measure-window override
346
  # (wave-2 item 8) or a DISPLAY-format override (wave-5 item 10): the note may be
347
  # empty but the period/format is real user state.
348
- if (not payload.get('custom') and not str(payload.get('note') or '').strip()
349
- and not isinstance(payload.get('measure'), dict)
350
- and not isinstance(payload.get('format'), dict)):
351
- ws['fields'].pop(key, None)
352
- else:
353
- ws['fields'][key] = payload
354
-
355
- self._update(username, _save)
356
- return dict(accepted)
357
-
358
- def duplicate_field(self, username, source_key, new_key, field,
359
- reserved_names=(), correction_id=None):
360
  """Clone a user-created field in ONE store transaction (wave-5 item 1): the new
361
  definition plus — for `custom_` overlay sources only — every stored cell value under
362
  the source key. One transaction, because a def without its values (or values without a
@@ -365,44 +395,44 @@ class TableStore:
365
  createdBy; this layer only moves data."""
366
  source_key = str(source_key or '').strip()
367
  new_key = str(new_key or '').strip()
368
- if not source_key or not new_key or source_key == new_key:
369
- raise ValueError('duplicate_field needs two distinct keys')
370
- requested = dict(field)
371
- accepted = {}
372
-
373
- def _dup(ws):
374
- names = list(reserved_names or ())
375
- names.extend(
376
- value.get('label')
377
- for candidate_key, value in (ws.get('fields') or {}).items()
378
- if candidate_key != new_key and isinstance(value, dict)
379
- )
380
- payload = dict(requested)
381
- payload.pop('labelCorrectedFrom', None)
382
- payload.pop('labelCorrectionId', None)
383
- requested_label = ' '.join(
384
- str(payload.get('label') or 'Untitled').split())[:120].rstrip()
385
- payload['label'] = _unique_name(requested_label, names)
386
- corrections = ws.setdefault('fieldCorrections', {})
387
- corrections.pop(new_key, None)
388
- if payload['label'] != requested_label and correction_id:
389
- corrections[new_key] = {
390
- 'label': payload['label'],
391
- 'labelCorrectedFrom': requested_label,
392
- 'labelCorrectionId': str(correction_id)[:180],
393
- }
394
- if not corrections:
395
- ws.pop('fieldCorrections', None)
396
- accepted.clear()
397
- accepted.update(payload)
398
- ws['fields'][new_key] = payload
399
- if source_key.startswith('custom_'):
400
  for row in ws['overlays'].values():
401
  if isinstance(row, dict) and source_key in row:
402
  row[new_key] = row[source_key]
403
-
404
- self._update(username, _dup)
405
- return dict(accepted)
406
 
407
  def delete_field(self, username, key):
408
  """Delete a USER-CREATED field definition outright (owner gap closed 2026-07-27).
 
67
  return bool(is_admin) or view.get('createdBy') == viewer
68
 
69
 
70
+ def is_shared(view):
71
+ """A view belongs in the shared bucket when its permissions reach beyond its creator."""
72
+ return ((view or {}).get('permissions') or {}).get('edit') in ('collaborative', 'users')
73
+
74
+
75
+ def _unique_name(wanted, existing, *, fallback='Untitled', max_len=120):
76
+ """Allocate one human-facing name inside a store.update transaction.
77
+
78
+ Keys/ids remain structural identity. Names compare case-insensitively after collapsing
79
+ whitespace, because those variants are indistinguishable in the UI. This helper belongs
80
+ in the store layer: allocating from a pre-write snapshot lets two concurrent requests both
81
+ choose the same free name before either write lands.
82
+ """
83
+ limit = max(1, int(max_len))
84
+
85
+ def _clean(value):
86
+ return ' '.join(str(value or '').split())
87
+
88
+ base = (_clean(wanted) or _clean(fallback) or 'Untitled')[:limit].rstrip()
89
+ taken = {_clean(value).casefold() for value in existing if _clean(value)}
90
+ if base.casefold() not in taken:
91
+ return base
92
+ index = 2
93
+ while True:
94
+ suffix = f' {index}'
95
+ stem = base[:max(0, limit - len(suffix))].rstrip()
96
+ candidate = f'{stem}{suffix}' if stem else str(index)[-limit:]
97
+ if candidate.casefold() not in taken:
98
+ return candidate
99
+ index += 1
100
+
101
+
102
+ class TableStore:
103
  """The six store operations for one table object's workspace, closed over its store key."""
104
 
105
  def __init__(self, table_key):
106
  self.table_key = table_key
107
 
108
  # ---------------------------------------------------------------- read
109
+ def workspace(self, username, consume_corrections=True):
110
+ """One user's durable workspace: always the full three-strata shape."""
111
+ try:
112
+ data = store.get(self.table_key) or {}
113
+ ws = data.get(username, {}) or {}
114
+ # A collision acknowledgement is protocol state, not part of a field definition.
115
+ # Consume it with the first fresh workspace payload after the correcting write,
116
+ # then splice a bounded copy into that payload only. Keeping it out of `fields`
117
+ # prevents an old request id surviving forever and overriding a later rename.
118
+ corrections = {}
119
+ if consume_corrections and ws.get('fieldCorrections'):
120
+ def _take(current):
121
+ current_ws = current.get(username) or {}
122
+ pending = current_ws.get('fieldCorrections') or {}
123
+ corrections.update({
124
+ str(key)[:80]: dict(value)
125
+ for key, value in pending.items()
126
+ if isinstance(value, dict)
127
+ })
128
+ current_ws.pop('fieldCorrections', None)
129
+ return current
130
+
131
+ data = store.update(self.table_key, _take, flush='async')
132
+ ws = (data or {}).get(username, {}) or {}
133
+ except Exception:
134
+ ws = {}
135
+ corrections = {}
136
+ fields = {
137
+ key: dict(value) if isinstance(value, dict) else value
138
+ for key, value in (ws.get('fields') or {}).items()
139
+ }
140
+ for key, ack in corrections.items():
141
+ field = fields.get(key)
142
+ accepted_label = str(ack.get('label') or '')[:120]
143
+ requested_label = str(ack.get('labelCorrectedFrom') or '')[:120]
144
+ correction_id = str(ack.get('labelCorrectionId') or '')[:180]
145
+ # A newer field write clears/replaces the pending ack in the SAME transaction.
146
+ # The label check is an extra belt against ever attaching a stale ack to a newer
147
+ # definition if a future store implementation weakens that ordering.
148
+ if (isinstance(field, dict) and accepted_label
149
+ and str(field.get('label') or '') == accepted_label
150
+ and requested_label and correction_id):
151
+ field['labelCorrectedFrom'] = requested_label
152
+ field['labelCorrectionId'] = correction_id
153
+ out = {
154
+ 'views': dict(ws.get('views') or {}),
155
+ 'fields': fields,
156
  'overlays': dict(ws.get('overlays') or {}),
157
  # wave-8 I11 (C4): folders over the saved views / cohorts sidebars. A FOURTH
158
  # stratum rather than a key on each item — see aios_grid.clean_folders for why
 
167
  # fresh profile, which used to fall all the way to the system default view.
168
  if ws.get('activeViewId'):
169
  out['activeViewId'] = str(ws['activeViewId'])
170
+ # Wave 2026-08-02 (C-LAYOUT): the per-user record-detail field order. A fifth
171
+ # stratum, absent until the user first reorders — exactly "default order".
172
+ if isinstance(ws.get('recordLayout'), dict):
173
+ out['recordLayout'] = dict(ws['recordLayout'])
174
  return out
175
 
176
  # ---------------------------------------------------------------- write
 
189
  # the historical synchronous hub commit cost seconds per edit. The mutation applies to
190
  # the in-process cache (read-your-writes for every subsequent render); the hub write
191
  # coalesces in the background. Registry/auth writes elsewhere stay flush='sync'.
192
+ return store.update(self.table_key, _up, flush='async')
193
 
194
  def save_active_view(self, username, view_id):
195
  """Remember which view this user last opened (owner item 3, 2026-07-31).
 
206
  ws['activeViewId'] = vid
207
  self._update(username, _set)
208
 
209
+ def save_record_layout(self, username, order):
210
+ """The per-user RECORD-DETAIL field order (wave 2026-08-02, C-LAYOUT).
211
+
212
+ Presentation state for ONE surface — the record modal. Deliberately not view config:
213
+ the owner's ask is per-user, not per-view, and it must never reorder grid columns.
214
+ The event handler validated keys against the live field set; the wire re-validates at
215
+ serve time (aios_grid.workspace_wire), so a deleted field cannot outlive itself here.
216
+ An empty order clears the stratum back to "default order".
217
+ """
218
+ if username == SHARED_KEY:
219
+ return
220
+ clean, seen = [], set()
221
+ for key in (order or [])[:200]:
222
+ key = str(key or '').strip()[:80]
223
+ if key and key not in seen:
224
+ seen.add(key)
225
+ clean.append(key)
226
+
227
+ def _set(ws):
228
+ if clean:
229
+ ws['recordLayout'] = {'order': clean}
230
+ else:
231
+ ws.pop('recordLayout', None)
232
+
233
+ self._update(username, _set)
234
+
235
  def save_folders(self, username, folders, item_folders):
236
  """Replace the folder stratum wholesale (wave-8 I11).
237
 
 
270
  except Exception:
271
  return None
272
 
273
+ def save_view(self, username, view, shared=None, reserved_names=(), is_admin=False):
274
  """Upsert a SavedView into its ONE home — personal workspace or the shared bucket.
275
 
276
  `shared` defaults to reading the view's own permissions (`is_shared`). Whichever home
 
285
  raise ValueError('view id is required')
286
  if username == SHARED_KEY:
287
  raise ValueError('reserved username')
288
+ to_shared = is_shared(view) if shared is None else bool(shared)
289
+ requested = dict(view)
290
+ accepted = {}
291
+
292
+ def _up(data):
293
+ # View names are tenant-global: every personal workspace plus the shared bucket.
294
+ # This deliberately includes views the actor cannot see. The only disclosed fact
295
+ # is that a display name is already taken, while the categorical "no duplicate
296
+ # view names" contract remains true when a personal view is later shared.
297
+ names = list(reserved_names or ())
298
+ for workspace in data.values():
299
+ if not isinstance(workspace, dict):
300
+ continue
301
+ names.extend(
302
+ value.get('name')
303
+ for candidate_id, value in (workspace.get('views') or {}).items()
304
+ if candidate_id != view_id and isinstance(value, dict)
305
+ )
306
+ payload = dict(requested)
307
+ payload['name'] = _unique_name(payload.get('name'), names)
308
+ accepted.clear()
309
+ accepted.update(payload)
310
+ if to_shared:
311
  bucket = data.setdefault(SHARED_KEY, {})
312
  bucket.setdefault('views', {})[view_id] = payload
313
  # it may have lived in the creator's workspace before being shared
 
319
  (data.get(SHARED_KEY, {}).get('views') or {}).pop(view_id, None)
320
  return data
321
 
322
+ store.update(self.table_key, _up, flush='async')
323
+ return dict(accepted)
324
 
325
  def delete_view(self, username, view_id):
326
  """Delete a custom/list view override. The system all-rows view is guarded by caller.
 
337
 
338
  store.update(self.table_key, _up, flush='async')
339
 
340
+ def save_field(self, username, field, reserved_names=(), correction_id=None):
341
+ """Persist a column note or a user-created (custom_/measure_) field definition."""
342
+ key = str((field or {}).get('key') or '').strip()
343
+ if not key:
344
+ raise ValueError('field key is required')
345
+ requested = dict(field)
346
+ accepted = {}
347
+
348
+ def _save(ws):
349
+ names = list(reserved_names or ())
350
+ names.extend(
351
+ value.get('label')
352
+ for candidate_key, value in (ws.get('fields') or {}).items()
353
+ if candidate_key != key and isinstance(value, dict)
354
+ )
355
+ payload = dict(requested)
356
+ payload.pop('labelCorrectedFrom', None)
357
+ payload.pop('labelCorrectionId', None)
358
+ requested_label = ' '.join(
359
+ str(payload.get('label') or 'Untitled').split())[:120].rstrip()
360
+ payload['label'] = _unique_name(requested_label, names)
361
+ corrections = ws.setdefault('fieldCorrections', {})
362
+ corrections.pop(key, None)
363
+ if payload['label'] != requested_label and correction_id:
364
+ corrections[key] = {
365
+ 'label': payload['label'],
366
+ 'labelCorrectedFrom': requested_label,
367
+ 'labelCorrectionId': str(correction_id)[:180],
368
+ }
369
+ if not corrections:
370
+ ws.pop('fieldCorrections', None)
371
+ accepted.clear()
372
+ accepted.update(payload)
373
+ # A cleared note on an immutable source field returns to the canonical schema
374
  # instead of leaving a meaningless override row. Custom fields remain even with
375
  # an empty note — and so does a PRESET field carrying a measure-window override
376
  # (wave-2 item 8) or a DISPLAY-format override (wave-5 item 10): the note may be
377
  # empty but the period/format is real user state.
378
+ if (not payload.get('custom') and not str(payload.get('note') or '').strip()
379
+ and not isinstance(payload.get('measure'), dict)
380
+ and not isinstance(payload.get('format'), dict)):
381
+ ws['fields'].pop(key, None)
382
+ else:
383
+ ws['fields'][key] = payload
384
+
385
+ self._update(username, _save)
386
+ return dict(accepted)
387
+
388
+ def duplicate_field(self, username, source_key, new_key, field,
389
+ reserved_names=(), correction_id=None):
390
  """Clone a user-created field in ONE store transaction (wave-5 item 1): the new
391
  definition plus — for `custom_` overlay sources only — every stored cell value under
392
  the source key. One transaction, because a def without its values (or values without a
 
395
  createdBy; this layer only moves data."""
396
  source_key = str(source_key or '').strip()
397
  new_key = str(new_key or '').strip()
398
+ if not source_key or not new_key or source_key == new_key:
399
+ raise ValueError('duplicate_field needs two distinct keys')
400
+ requested = dict(field)
401
+ accepted = {}
402
+
403
+ def _dup(ws):
404
+ names = list(reserved_names or ())
405
+ names.extend(
406
+ value.get('label')
407
+ for candidate_key, value in (ws.get('fields') or {}).items()
408
+ if candidate_key != new_key and isinstance(value, dict)
409
+ )
410
+ payload = dict(requested)
411
+ payload.pop('labelCorrectedFrom', None)
412
+ payload.pop('labelCorrectionId', None)
413
+ requested_label = ' '.join(
414
+ str(payload.get('label') or 'Untitled').split())[:120].rstrip()
415
+ payload['label'] = _unique_name(requested_label, names)
416
+ corrections = ws.setdefault('fieldCorrections', {})
417
+ corrections.pop(new_key, None)
418
+ if payload['label'] != requested_label and correction_id:
419
+ corrections[new_key] = {
420
+ 'label': payload['label'],
421
+ 'labelCorrectedFrom': requested_label,
422
+ 'labelCorrectionId': str(correction_id)[:180],
423
+ }
424
+ if not corrections:
425
+ ws.pop('fieldCorrections', None)
426
+ accepted.clear()
427
+ accepted.update(payload)
428
+ ws['fields'][new_key] = payload
429
+ if source_key.startswith('custom_'):
430
  for row in ws['overlays'].values():
431
  if isinstance(row, dict) and source_key in row:
432
  row[new_key] = row[source_key]
433
+
434
+ self._update(username, _dup)
435
+ return dict(accepted)
436
 
437
  def delete_field(self, username, key):
438
  """Delete a USER-CREATED field definition outright (owner gap closed 2026-07-27).
royalimports_os/harness/filter_sql.py CHANGED
@@ -75,7 +75,17 @@ from collections import namedtuple
75
  FILTER_OPS = frozenset({
76
  'contains', 'doesNotContain', 'eq', 'neq', 'isEmpty', 'isNotEmpty',
77
  'gt', 'gte', 'lt', 'lte', 'between', 'within',
 
 
78
  })
 
 
 
 
 
 
 
 
79
  #: The RESERVED pseudo-column of a cohort-membership leaf. Mirrors types.ts COHORT_FIELD.
80
  COHORT_FIELD = '__cohort__'
81
  #: Set operators over a SET of cohorts. Mirrors types.ts COHORT_OPS; DISJOINT from FILTER_OPS.
@@ -99,7 +109,7 @@ def parse_cohort_ids(value):
99
  return out
100
  # types.ts VALUE_FREE_OPS: no value control is rendered, and they must never be judged
101
  # "inactive because the value is blank" — that would turn them into no-ops.
102
- VALUE_FREE_OPS = frozenset({'isEmpty', 'isNotEmpty'})
103
  # types.ts isNumericType()
104
  NUMERIC_TYPES = frozenset({'currency', 'int', 'pct'})
105
  TEXTUAL_TYPES = frozenset({'text', 'status'})
@@ -340,6 +350,15 @@ def _compile_leaf(rule, columns, state):
340
  if col_id == COHORT_FIELD:
341
  return _compile_cohort(rule, state)
342
 
 
 
 
 
 
 
 
 
 
343
  spec = columns[col_id]
344
 
345
  def used(sql, params=()):
 
75
  FILTER_OPS = frozenset({
76
  'contains', 'doesNotContain', 'eq', 'neq', 'isEmpty', 'isNotEmpty',
77
  'gt', 'gte', 'lt', 'lte', 'between', 'within',
78
+ 'topN', 'bottomN', 'inTopPct', 'inBottomPct',
79
+ 'aboveAvg', 'belowAvg', 'inQuartile', 'inDecile',
80
  })
81
+ #: Wave 2026-08-02 (C-OPS): the RANK subset — set-ranked over the sibling-filtered domain.
82
+ #: Vocabulary here, execution NOWHERE in this module: a per-row WHERE cannot express Top-N,
83
+ #: and compiling to 1=0 would answer "nothing" to a question that has an answer, under a
84
+ #: row_count that still looks authoritative. `_compile_leaf` therefore REFUSES (ValueError),
85
+ #: the same server-side posture as a relative anchor with no `today`. The TS engine
86
+ #: evaluates these as a set pass in useVisibleRows (gated by web/verify_rank_filters.py).
87
+ RANK_OPS = frozenset({'topN', 'bottomN', 'inTopPct', 'inBottomPct',
88
+ 'aboveAvg', 'belowAvg', 'inQuartile', 'inDecile'})
89
  #: The RESERVED pseudo-column of a cohort-membership leaf. Mirrors types.ts COHORT_FIELD.
90
  COHORT_FIELD = '__cohort__'
91
  #: Set operators over a SET of cohorts. Mirrors types.ts COHORT_OPS; DISJOINT from FILTER_OPS.
 
109
  return out
110
  # types.ts VALUE_FREE_OPS: no value control is rendered, and they must never be judged
111
  # "inactive because the value is blank" — that would turn them into no-ops.
112
+ VALUE_FREE_OPS = frozenset({'isEmpty', 'isNotEmpty', 'aboveAvg', 'belowAvg'})
113
  # types.ts isNumericType()
114
  NUMERIC_TYPES = frozenset({'currency', 'int', 'pct'})
115
  TEXTUAL_TYPES = frozenset({'text', 'status'})
 
350
  if col_id == COHORT_FIELD:
351
  return _compile_cohort(rule, state)
352
 
353
+ # --- C-OPS (wave 2026-08-02): a RANK leaf is structurally unanswerable at row grain ------
354
+ # Top-N / quantile membership is a property of the SET, not the row; the client engine
355
+ # answers it with a set pass over the sibling-filtered domain. Refuse loudly rather than
356
+ # compile something that means a different question (see RANK_OPS).
357
+ if op in RANK_OPS:
358
+ raise ValueError(
359
+ f'rank operator {op!r} cannot compile to row SQL - evaluate it as a set pass '
360
+ f'(the client engine) or pre-resolve the matching ids before compiling')
361
+
362
  spec = columns[col_id]
363
 
364
  def used(sql, params=()):
royalimports_os/harness/measure_filter.py CHANGED
@@ -611,6 +611,65 @@ def resolve_values(key, window, today, team_id=None, allowed_pids=None):
611
  return {int(p): round(float(totals.get(p, 0.0)) * scale, nd) for p in universe}
612
 
613
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
614
  def resolve_tree(rules, today, team_id=None, allowed_pids=None):
615
  """{rule_id: sorted pids} for every measure condition in a tree.
616
 
 
611
  return {int(p): round(float(totals.get(p, 0.0)) * scale, nd) for p in universe}
612
 
613
 
614
+ #: The series channel's calendar buckets. `date_trunc` names in DuckDB; 'week' truncates to
615
+ #: Monday, matching the date-window vocabulary's week convention.
616
+ SERIES_BUCKETS = frozenset({'week', 'month', 'quarter', 'year'})
617
+
618
+
619
+ def resolve_series(key, bucket, date_from, date_to, today, team_id=None, allowed_pids=None):
620
+ """POOLED value of one measure per calendar bucket — the time-series channel (C-TS,
621
+ wave 2026-08-02). Returns `{'values': {bucket_start_iso: value}, 'agg': kind}`.
622
+
623
+ ONE grouped query per measure: the aggregate expression is `semantic._measure_sql`'s own
624
+ (no second definition of a number), evaluated over the CALLER'S POOL per `date_trunc`
625
+ bucket. That is the pooled aggregate — a non-additive measure (an average) is computed at
626
+ pool grain, never averaged over per-customer answers (the additivity law).
627
+
628
+ Composites (ratio/derived) are REFUSED: they have no single aggregate expression, and
629
+ combining their bases per bucket is a correctness project, not a default — the caller
630
+ degrades that field honestly rather than showing a number nobody computed.
631
+
632
+ Scale and rounding mirror `resolve_values` exactly, so a bucket cell and the grid's own
633
+ measure column can never disagree on units. Buckets with no rows are ABSENT from the
634
+ answer — zero-filling is the CALLER'S decision because it depends on the agg kind: an
635
+ empty month of a SUM is a real 0, an empty month of an AVERAGE is unanswerable.
636
+ """
637
+ if bucket not in SERIES_BUCKETS:
638
+ raise _sem.ModelError(
639
+ f"unknown series bucket {bucket!r} - offered: week, month, quarter, year")
640
+ topic_for(key) # raises for anything not admitted
641
+ if is_composite(key):
642
+ raise _sem.ModelError(
643
+ f"{key!r} is a ratio/derived measure - the series channel computes "
644
+ f"single-aggregate measures only")
645
+ window = {'kind': 'custom', 'from': str(date_from), 'to': str(date_to)}
646
+ frm, id_col, agg, where, params = _query_parts(key, window, today, team_id)
647
+ _, _, s = _entity_sql(_base_topic(key))
648
+ meta = _sem.metrics().get(key, {})
649
+ agg_kind = str(meta.get('agg') or 'sum')
650
+ pool = _pool_of(allowed_pids)
651
+ sql_params = list(params)
652
+ pool_sql = ''
653
+ if pool is not None:
654
+ if not pool:
655
+ return {'values': {}, 'agg': agg_kind}
656
+ marks = ','.join('?' for _ in pool)
657
+ pool_sql = f" AND {id_col} IN ({marks})"
658
+ sql_params.extend(int(p) for p in sorted(pool))
659
+ sql = (f"SELECT CAST(date_trunc('{bucket}', CAST({s['date_col']} AS TIMESTAMP)) AS DATE)"
660
+ f" AS b, {agg} AS v FROM {frm} WHERE {where}{pool_sql} GROUP BY b")
661
+ con = _sem._store_con()
662
+ try:
663
+ rows = con.execute(sql, sql_params).fetchall()
664
+ finally:
665
+ con.close()
666
+ scale = ADMITTED.get(key, {}).get('input_scale') or 1.0
667
+ mtype = _sem._FORMAT_TYPE.get(meta.get('format'), 'currency')
668
+ nd = 1 if mtype == 'pct' else None
669
+ values = {str(b)[:10]: round(float(v) * scale, nd) for b, v in rows if b is not None}
670
+ return {'values': values, 'agg': agg_kind}
671
+
672
+
673
  def resolve_tree(rules, today, team_id=None, allowed_pids=None):
674
  """{rule_id: sorted pids} for every measure condition in a tree.
675
 
royalimports_os/harness/runtime.py CHANGED
@@ -80,6 +80,9 @@ class TenantRuntime:
80
  #: (stamp, scope, pool identity, question) so nothing user-shaped lives in them.
81
  measure_memo: dict = field(default_factory=dict)
82
  mset_memo: dict = field(default_factory=dict)
 
 
 
83
  _lock: threading.RLock = field(default_factory=threading.RLock, repr=False)
84
 
85
  @property
 
80
  #: (stamp, scope, pool identity, question) so nothing user-shaped lives in them.
81
  measure_memo: dict = field(default_factory=dict)
82
  mset_memo: dict = field(default_factory=dict)
83
+ #: Wave 2026-08-02 (C-TS): the time-series channel's own memo — separate from
84
+ #: measure_memo so column churn and series churn cannot evict each other's answers.
85
+ series_memo: dict = field(default_factory=dict)
86
  _lock: threading.RLock = field(default_factory=threading.RLock, repr=False)
87
 
88
  @property
royalimports_os/modules/customer_data.py CHANGED
@@ -229,6 +229,38 @@ def pool_first(agent_name=None, team_id=None, limit=100):
229
  return _pool_build(agent_name, team_id, limit=limit, fast=True)
230
 
231
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
232
  def _pool_build(agent_name, team_id, limit, fast=False):
233
  t = P.today()
234
  yf, yt = P.ytd(t)
@@ -252,7 +284,7 @@ def _pool_build(agent_name, team_id, limit, fast=False):
252
  if fast:
253
  # C1 fast phase: the slow families stay empty — their columns render blank behind the
254
  # toolbar's partial indicator until the full build swaps in.
255
- ar_a, mix_a, sp_a, geo_a = {}, {}, {}, {}
256
  else:
257
  # The three families the owner asked for (2026-07-27). Each degrades to {} rather than
258
  # raising: a customer table that cannot render because AR is momentarily unreachable is
@@ -264,6 +296,8 @@ def _pool_build(agent_name, team_id, limit, fast=False):
264
  # read-only reuse (coords_for never geocodes); missing → null lat/lon, and the
265
  # client's map view discloses the count.
266
  geo_a = map_mod.coords_for(list(all_pids))
 
 
267
  # customers whose only activity sits in the older half of the 24-month cadence window
268
  # appear in no revenue map — fetch their names directly (else the lapsed cohort, exactly
269
  # the win-back targets this union exists for, would render as '?')
@@ -294,6 +328,8 @@ def _pool_build(agent_name, team_id, limit, fast=False):
294
  or (ltm.get(pid) or {}).get('name') or extra_names.get(pid) or '?',
295
  'status': status,
296
  'agent': a.get('agent', '(none)'), 'city': a.get('city', '(none)'),
 
 
297
  'state': a.get('state', '(none)'),
298
  # Owner 2026-07-27, the partner-attribute family. `.get(..., default)` is not
299
  # defensive habit here: search_read returned 1,548 of 1,550 pool pids — two partners
@@ -519,6 +555,7 @@ duplicate_table_field = _TSTORE.duplicate_field
519
  patch_table_overlay = _TSTORE.patch_overlay
520
  save_table_folders = _TSTORE.save_folders
521
  save_table_active_view = _TSTORE.save_active_view # owner item 3: last-opened view, per user
 
522
 
523
 
524
  # ------------------------------------------------------------------ digest compatibility
 
229
  return _pool_build(agent_name, team_id, limit=limit, fast=True)
230
 
231
 
232
+ def _dba_attrs(pids, t):
233
+ """{pid: 'Fisch' | 'Royal' | 'Both'} — which brand(s) a customer's confirmed orders carry
234
+ over the pool's own 24-month universe (C-DBA, wave 2026-08-02).
235
+
236
+ GIFTWARE DEALS (the Amazon channel) is deliberately NOT a DBA — a customer buying only
237
+ through it stays blank here, exactly as ARCHITECTURE.md §4's wholesale scope treats that
238
+ team. Blank also covers the ledger-retained customers whose activity predates the window:
239
+ blank means "no brand attributable in 24 months", never a guess. One read_group, grouped
240
+ (partner, team); degrades to {} like the other attr families — a blank column beats a
241
+ page that cannot render.
242
+ """
243
+ try:
244
+ import datetime as _dt
245
+ d_from = (_dt.date.fromisoformat(str(t)) - _dt.timedelta(days=731)).isoformat()
246
+ pairs = O.read_group(
247
+ 'sale.order',
248
+ [('state', 'in', ('sale', 'done')), ('date_order', '>=', d_from),
249
+ ('partner_id', 'in', list(pids)), ('team_id', 'in', (5, 6))],
250
+ ['partner_id'], ['partner_id', 'team_id'], lazy=False)
251
+ teams = {}
252
+ for r in pairs:
253
+ pid = O.m2o_id(r.get('partner_id'))
254
+ tid = O.m2o_id(r.get('team_id'))
255
+ if pid and tid in (5, 6):
256
+ teams.setdefault(pid, set()).add(tid)
257
+ label = {5: 'Fisch', 6: 'Royal'}
258
+ return {pid: ('Both' if len(ts) == 2 else label[next(iter(ts))])
259
+ for pid, ts in teams.items()}
260
+ except Exception:
261
+ return {}
262
+
263
+
264
  def _pool_build(agent_name, team_id, limit, fast=False):
265
  t = P.today()
266
  yf, yt = P.ytd(t)
 
284
  if fast:
285
  # C1 fast phase: the slow families stay empty — their columns render blank behind the
286
  # toolbar's partial indicator until the full build swaps in.
287
+ ar_a, mix_a, sp_a, geo_a, dba_a = {}, {}, {}, {}, {}
288
  else:
289
  # The three families the owner asked for (2026-07-27). Each degrades to {} rather than
290
  # raising: a customer table that cannot render because AR is momentarily unreachable is
 
296
  # read-only reuse (coords_for never geocodes); missing → null lat/lon, and the
297
  # client's map view discloses the count.
298
  geo_a = map_mod.coords_for(list(all_pids))
299
+ # C-DBA (2026-08-02): the brand attribute rides the full build only, like the rest.
300
+ dba_a = _dba_attrs(all_pids, t)
301
  # customers whose only activity sits in the older half of the 24-month cadence window
302
  # appear in no revenue map — fetch their names directly (else the lapsed cohort, exactly
303
  # the win-back targets this union exists for, would render as '?')
 
328
  or (ltm.get(pid) or {}).get('name') or extra_names.get(pid) or '?',
329
  'status': status,
330
  'agent': a.get('agent', '(none)'), 'city': a.get('city', '(none)'),
331
+ # C-DBA: blank (not '(none)') — a select's blank is its own honest empty state.
332
+ 'dba': dba_a.get(pid, ''),
333
  'state': a.get('state', '(none)'),
334
  # Owner 2026-07-27, the partner-attribute family. `.get(..., default)` is not
335
  # defensive habit here: search_read returned 1,548 of 1,550 pool pids — two partners
 
555
  patch_table_overlay = _TSTORE.patch_overlay
556
  save_table_folders = _TSTORE.save_folders
557
  save_table_active_view = _TSTORE.save_active_view # owner item 3: last-opened view, per user
558
+ save_table_record_layout = _TSTORE.save_record_layout # 2026-08-02 C-LAYOUT: record-detail order
559
 
560
 
561
  # ------------------------------------------------------------------ digest compatibility
web/public/sample_customers.json CHANGED
@@ -1,458 +1,479 @@
1
- {
2
- "fields": [
3
- {
4
- "key": "customer",
5
- "label": "Customer",
6
- "type": "text",
7
- "source": "odoo",
8
- "pinned": true,
9
- "default": true,
10
- "description": "The customer's name in Odoo. One row per customer who ordered in the last 24 months."
11
- },
12
  {
13
  "key": "odoo_status",
14
- "label": "Odoo record",
15
- "type": "status",
16
- "source": "odoo",
17
- "default": false,
18
- "description": "Whether this customer still exists in Odoo. Archived means deleted there."
19
- },
20
- {
21
- "key": "agent",
22
- "label": "Agent",
23
- "type": "text",
24
- "source": "odoo",
25
- "default": true,
26
- "description": "The sales agent who owns this account."
27
- },
28
- {
29
- "key": "salesperson",
30
- "label": "Salesperson",
31
- "type": "text",
32
- "source": "odoo",
33
- "default": false,
34
- "description": "Who keyed in most of this customer's orders — not the Agent, who owns the account."
35
- },
36
- {
37
- "key": "city",
38
- "label": "City",
39
- "type": "text",
40
- "source": "odoo",
41
- "default": true,
42
- "description": "City on the customer's Odoo address."
43
- },
44
- {
45
- "key": "state",
46
- "label": "State",
47
- "type": "text",
48
- "source": "odoo",
49
- "default": true,
50
- "description": "State or province on the customer's Odoo address."
51
- },
52
- {
53
- "key": "country",
54
- "label": "Country",
55
- "type": "text",
56
- "source": "odoo",
57
- "default": false,
58
- "description": "Country on the customer's Odoo address."
59
- },
60
- {
61
- "key": "zip",
62
- "label": "ZIP",
63
- "type": "text",
64
- "source": "odoo",
65
- "default": false,
66
- "description": "Postal code on the customer's Odoo address."
67
- },
68
- {
69
- "key": "customer_since",
70
- "label": "Customer since",
71
- "type": "date",
72
- "source": "odoo",
73
- "default": false,
74
- "description": "When this customer was first set up in Odoo."
75
- },
76
- {
77
- "key": "tags",
78
- "label": "Tags",
79
- "type": "text",
80
- "source": "odoo",
81
- "default": false,
82
- "description": "Odoo labels on this customer, comma-separated."
83
- },
84
- {
85
- "key": "pricelist",
86
- "label": "Price list",
87
- "type": "text",
88
- "source": "odoo",
89
- "default": false,
90
- "description": "The price list this customer buys on."
91
- },
92
- {
93
- "key": "payment_terms",
94
- "label": "Payment terms",
95
- "type": "text",
96
- "source": "odoo",
97
- "default": false,
98
- "description": "Payment terms on this customer's account — Net 30, for example."
99
- },
100
- {
101
- "key": "last_order",
102
- "label": "Last order",
103
- "type": "date",
104
- "source": "odoo",
105
- "default": true,
106
- "description": "Date of the most recent confirmed order."
107
- },
108
- {
109
- "key": "overdue_days",
110
- "label": "Overdue days",
111
- "type": "int",
112
- "source": "odoo",
113
- "default": true,
114
- "description": "How many days late this customer is running against their own usual ordering rhythm."
115
- },
116
- {
117
- "_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.",
118
- "key": "est_missed",
119
- "label": "Est. missed $",
120
- "type": "currency",
121
- "source": "odoo",
122
- "default": true,
123
- "agg": "sum",
124
- "filterable": false,
125
- "description": "Estimated sales missed while quiet: missed orders (capped at 3) times average order value. An estimate, not money owed."
126
- },
127
- {
128
- "key": "ar_open",
129
- "label": "AR open $",
130
- "type": "currency",
131
- "source": "odoo",
132
- "default": false,
133
- "description": "Invoiced money owed, not yet overdue."
134
- },
135
- {
136
- "key": "ar_overdue",
137
- "label": "AR overdue $",
138
- "type": "currency",
139
- "source": "odoo",
140
- "default": false,
141
- "description": "Invoiced money past due — same basis as the Collections page."
142
- },
143
- {
144
- "key": "ar_exposure",
145
- "label": "Credit exposure $",
146
- "type": "currency",
147
- "source": "odoo",
148
- "default": false,
149
- "description": "The most you could be out if they stopped paying today: open, overdue, draft and not-yet-invoiced."
150
- },
151
- {
152
- "key": "days_to_pay",
153
- "label": "Days to pay",
154
- "type": "int",
155
- "source": "odoo",
156
- "default": false,
157
- "description": "Average days to pay an invoice in full. Blank means no fully paid invoice yet."
158
- },
159
- {
160
- "key": "top_category",
161
- "label": "Top category",
162
- "type": "text",
163
- "source": "odoo",
164
- "default": false,
165
- "description": "The category this customer spent the most on in the last 12 months."
166
- },
167
- {
168
- "key": "top_category_pct",
169
- "label": "Top category %",
170
- "type": "pct",
171
- "source": "odoo",
172
- "default": false,
173
- "description": "Share of last-12-months spend that went to the top category."
174
- },
175
- {
176
- "key": "sku_count",
177
- "label": "SKUs bought",
178
- "type": "int",
179
- "source": "odoo",
180
- "default": false,
181
- "description": "Distinct products bought in the last 12 months."
182
- },
183
- {
184
- "key": "top_sku",
185
- "label": "Top SKU",
186
- "type": "text",
187
- "source": "odoo",
188
- "default": false,
189
- "description": "The product this customer spent the most on in the last 12 months."
190
- },
191
- {
192
- "key": "days_since",
193
- "label": "Days since order",
194
- "type": "int",
195
- "source": "odoo",
196
- "default": false,
197
- "description": "Days since the last confirmed order."
198
- },
199
- {
200
- "key": "typical_gap_days",
201
- "label": "Typical gap days",
202
- "type": "int",
203
- "source": "odoo",
204
- "default": false,
205
- "description": "Days this customer usually goes between orders, from their own history."
206
- },
207
- {
208
- "key": "notes",
209
- "label": "Notes",
210
- "type": "text",
211
- "source": "overlay",
212
- "default": false,
213
- "description": "Your notes on this customer. Saved in this app only, visible only to you."
214
- }
215
- ],
216
- "rows": [
217
- {
218
- "pid": 101,
219
- "customer": "Poppy Flowers",
220
- "status": "New",
221
- "agent": "Naomi Linnell Rivera",
222
- "city": "Charlottesville",
223
- "state": "Virginia (US)",
224
- "last_order": "2026-07-21",
225
- "est_missed": 0,
226
- "notes": "",
227
- "country": "United States",
228
- "zip": "02720",
229
- "payment_terms": "30 Days",
230
- "pricelist": "Fisch 1 (USD)",
231
- "tags": "Royal",
232
- "customer_since": "2023-01-10",
233
- "salesperson": "Jessica",
234
- "ar_open": 0,
235
- "ar_overdue": 0,
236
- "ar_exposure": 0,
237
- "top_category": "Styrofoam",
238
- "top_category_pct": 0.47,
239
- "sku_count": 93,
240
- "top_sku": "AQUAFOAM FLORAL FOAM BRICK | 48-Piece per Pack",
241
- "days_to_pay": 34,
242
- "_created": "2023-01-15 09:10:00",
243
- "lat": 25.7617,
244
- "lon": -80.1918,
245
- "odoo_status": "Archived"
246
- },
247
- {
248
- "pid": 102,
249
- "customer": "Meadow & Vine Wholesale",
250
- "status": "Growing",
251
- "agent": "Carla Jimenez",
252
- "city": "Portland",
253
- "state": "Oregon (US)",
254
- "last_order": "2026-07-19",
255
- "est_missed": 0,
256
- "notes": "Expanding to a second storefront.",
257
- "country": "United States",
258
- "zip": "77041",
259
- "payment_terms": "Immediate Payment",
260
- "pricelist": "Royal 1 (USD)",
261
- "tags": "Royal, Key account",
262
- "customer_since": "2024-02-11",
263
- "salesperson": "Naomi",
264
- "ar_open": 1240.5,
265
- "ar_overdue": 0,
266
- "ar_exposure": 1740.5,
267
- "top_category": "Ribbon",
268
- "top_category_pct": 0.95,
269
- "sku_count": 4,
270
- "top_sku": "2\" X 24\" X 36\" GREEN STYROFOAM BOARD",
271
- "days_to_pay": null,
272
- "_created": "2023-02-15 09:11:00",
273
- "lat": 27.9506,
274
- "lon": -82.4572,
275
- "odoo_status": "Active"
276
- },
277
- {
278
- "pid": 103,
279
- "customer": "Bluestem Floral Supply",
280
- "status": "Growing",
281
- "agent": "Naomi Linnell Rivera",
282
- "city": "Kansas City",
283
- "state": "Missouri (US)",
284
- "last_order": "2026-07-17",
285
- "est_missed": 0,
286
- "notes": "",
287
- "country": "United States",
288
- "zip": "11219",
289
- "payment_terms": "60 Days",
290
- "pricelist": "Royal 1 (USD)",
291
- "tags": "Fisch",
292
- "customer_since": "2025-03-12",
293
- "salesperson": "Karen",
294
- "ar_open": 0,
295
- "ar_overdue": 5120.25,
296
- "ar_exposure": 5120.25,
297
- "top_category": "Foams & Finishes",
298
- "top_category_pct": 0.31,
299
- "sku_count": 27,
300
- "top_sku": "SATIN RIBBON 2IN",
301
- "days_to_pay": 61,
302
- "_created": "2023-03-15 09:12:00",
303
- "lat": 28.5384,
304
- "lon": -81.3789,
305
- "odoo_status": "Active"
306
- },
307
- {
308
- "pid": 104,
309
- "customer": "Camellia Row Florist",
310
- "status": "Declining",
311
- "agent": "Devon Marsh",
312
- "city": "Savannah",
313
- "state": "Georgia (US)",
314
- "last_order": "2026-05-30",
315
- "est_missed": 41200,
316
- "notes": "Switched some volume to a local grower.",
317
- "country": "United States",
318
- "zip": "07649",
319
- "payment_terms": "30 Days",
320
- "pricelist": "Fisch 1 (USD)",
321
- "tags": "(none)",
322
- "customer_since": "2026-04-13",
323
- "salesperson": "(none)",
324
- "ar_open": 8300,
325
- "ar_overdue": 940,
326
- "ar_exposure": 11440,
327
- "top_category": "All",
328
- "top_category_pct": 1.0,
329
- "sku_count": 1,
330
- "top_sku": "(none)",
331
- "days_to_pay": 12,
332
- "_created": "2023-04-15 09:13:00",
333
- "lat": 30.3322,
334
- "lon": -81.6557,
335
- "odoo_status": "Active"
336
- },
337
- {
338
- "pid": 105,
339
- "customer": "Harborlight Wholesale Blooms",
340
- "status": "Growing",
341
- "agent": "Carla Jimenez",
342
- "city": "Seattle",
343
- "state": "Washington (US)",
344
- "last_order": "2026-07-22",
345
- "est_missed": 0,
346
- "notes": "Top-10 account.",
347
- "country": "United States",
348
- "zip": "33125",
349
- "payment_terms": "Immediate Payment",
350
- "pricelist": "Royal 1 (USD)",
351
- "tags": "Royal",
352
- "customer_since": "2023-05-14",
353
- "salesperson": "Jessica",
354
- "ar_open": 0,
355
- "ar_overdue": 0,
356
- "ar_exposure": 0,
357
- "top_category": "Styrofoam",
358
- "top_category_pct": 0.47,
359
- "sku_count": 93,
360
- "top_sku": "AQUAFOAM FLORAL FOAM BRICK | 48-Piece per Pack",
361
- "days_to_pay": 34,
362
- "_created": "2023-05-15 09:14:00",
363
- "lat": 26.1224,
364
- "lon": -80.1373,
365
- "odoo_status": "Active"
366
- },
367
- {
368
- "pid": 106,
369
- "customer": "Dogwood & Fern Co.",
370
- "status": "Dormant",
371
- "agent": "Devon Marsh",
372
- "city": "Asheville",
373
- "state": "North Carolina (US)",
374
- "last_order": "2026-02-11",
375
- "est_missed": 52400,
376
- "notes": "No spring order this year.",
377
- "country": "United States",
378
- "zip": "90210",
379
- "payment_terms": "60 Days",
380
- "pricelist": "Royal 1 (USD)",
381
- "tags": "Royal, Key account",
382
- "customer_since": "2024-06-15",
383
- "salesperson": "Naomi",
384
- "ar_open": 1240.5,
385
- "ar_overdue": 0,
386
- "ar_exposure": 1740.5,
387
- "top_category": "Ribbon",
388
- "top_category_pct": 0.95,
389
- "sku_count": 4,
390
- "top_sku": "2\" X 24\" X 36\" GREEN STYROFOAM BOARD",
391
- "days_to_pay": null,
392
- "_created": "2023-06-15 09:15:00",
393
- "lat": 27.3364,
394
- "lon": -82.5307,
395
- "odoo_status": "Active"
396
- },
397
- {
398
- "pid": 107,
399
- "customer": "Verbena Market Florals",
400
- "status": "Lost",
401
- "agent": "Naomi Linnell Rivera",
402
- "city": "Austin",
403
- "state": "Texas (US)",
404
- "last_order": "2025-11-04",
405
- "est_missed": 78300,
406
- "notes": "Went with a competitor on freight terms.",
407
- "country": "United States",
408
- "zip": "08701",
409
- "payment_terms": "30 Days",
410
- "pricelist": "Fisch 1 (USD)",
411
- "tags": "Fisch",
412
- "customer_since": "2025-07-16",
413
- "salesperson": "Karen",
414
- "ar_open": 0,
415
- "ar_overdue": 5120.25,
416
- "ar_exposure": 5120.25,
417
- "top_category": "Foams & Finishes",
418
- "top_category_pct": 0.31,
419
- "sku_count": 27,
420
- "top_sku": "SATIN RIBBON 2IN",
421
- "days_to_pay": 61,
422
- "_created": "2023-07-15 09:16:00",
423
- "lat": null,
424
- "lon": null,
425
- "odoo_status": "Active"
426
- },
427
- {
428
- "pid": 108,
429
- "customer": "Larkspur Lane Supply",
430
- "status": "New",
431
- "agent": "Carla Jimenez",
432
- "city": "Denver",
433
- "state": "Colorado (US)",
434
- "last_order": "2026-07-14",
435
- "est_missed": 0,
436
- "notes": "First order in April.",
437
- "country": "United States",
438
- "zip": "60614",
439
- "payment_terms": "Immediate Payment",
440
- "pricelist": "Royal 1 (USD)",
441
- "tags": "(none)",
442
- "customer_since": "2026-08-17",
443
- "salesperson": "(none)",
444
- "ar_open": 8300,
445
- "ar_overdue": 940,
446
- "ar_exposure": 11440,
447
- "top_category": "All",
448
- "top_category_pct": 1.0,
449
- "sku_count": 1,
450
- "top_sku": "(none)",
451
- "days_to_pay": 12,
452
- "_created": "2023-08-15 09:17:00",
453
- "lat": 33.749,
454
- "lon": -84.388,
455
- "odoo_status": "Active"
456
- }
457
- ]
458
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "fields": [
3
+ {
4
+ "key": "customer",
5
+ "label": "Customer",
6
+ "type": "text",
7
+ "source": "odoo",
8
+ "pinned": true,
9
+ "default": true,
10
+ "description": "The customer's name in Odoo. One row per customer who ordered in the last 24 months."
11
+ },
12
  {
13
  "key": "odoo_status",
14
+ "label": "Odoo record",
15
+ "type": "status",
16
+ "source": "odoo",
17
+ "default": false,
18
+ "description": "Whether this customer still exists in Odoo. Archived means deleted there."
19
+ },
20
+ {
21
+ "key": "agent",
22
+ "label": "Agent",
23
+ "type": "text",
24
+ "source": "odoo",
25
+ "default": true,
26
+ "description": "The sales agent who owns this account."
27
+ },
28
+ {
29
+ "key": "dba",
30
+ "label": "DBA",
31
+ "type": "select",
32
+ "source": "odoo",
33
+ "default": false,
34
+ "options": [
35
+ "Fisch",
36
+ "Royal",
37
+ "Both"
38
+ ],
39
+ "description": "The brand this customer buys from - Fisch, Royal, or both. Amazon-channel orders are not a DBA."
40
+ },
41
+ {
42
+ "key": "salesperson",
43
+ "label": "Salesperson",
44
+ "type": "text",
45
+ "source": "odoo",
46
+ "default": false,
47
+ "description": "Who keyed in most of this customer's orders — not the Agent, who owns the account."
48
+ },
49
+ {
50
+ "key": "city",
51
+ "label": "City",
52
+ "type": "text",
53
+ "source": "odoo",
54
+ "default": true,
55
+ "description": "City on the customer's Odoo address."
56
+ },
57
+ {
58
+ "key": "state",
59
+ "label": "State",
60
+ "type": "text",
61
+ "source": "odoo",
62
+ "default": true,
63
+ "description": "State or province on the customer's Odoo address."
64
+ },
65
+ {
66
+ "key": "country",
67
+ "label": "Country",
68
+ "type": "text",
69
+ "source": "odoo",
70
+ "default": false,
71
+ "description": "Country on the customer's Odoo address."
72
+ },
73
+ {
74
+ "key": "zip",
75
+ "label": "ZIP",
76
+ "type": "text",
77
+ "source": "odoo",
78
+ "default": false,
79
+ "description": "Postal code on the customer's Odoo address."
80
+ },
81
+ {
82
+ "key": "customer_since",
83
+ "label": "Customer since",
84
+ "type": "date",
85
+ "source": "odoo",
86
+ "default": false,
87
+ "description": "When this customer was first set up in Odoo."
88
+ },
89
+ {
90
+ "key": "tags",
91
+ "label": "Tags",
92
+ "type": "text",
93
+ "source": "odoo",
94
+ "default": false,
95
+ "description": "Odoo labels on this customer, comma-separated."
96
+ },
97
+ {
98
+ "key": "pricelist",
99
+ "label": "Price list",
100
+ "type": "text",
101
+ "source": "odoo",
102
+ "default": false,
103
+ "description": "The price list this customer buys on."
104
+ },
105
+ {
106
+ "key": "payment_terms",
107
+ "label": "Payment terms",
108
+ "type": "text",
109
+ "source": "odoo",
110
+ "default": false,
111
+ "description": "Payment terms on this customer's account — Net 30, for example."
112
+ },
113
+ {
114
+ "key": "last_order",
115
+ "label": "Last order",
116
+ "type": "date",
117
+ "source": "odoo",
118
+ "default": true,
119
+ "description": "Date of the most recent confirmed order."
120
+ },
121
+ {
122
+ "key": "overdue_days",
123
+ "label": "Overdue days",
124
+ "type": "int",
125
+ "source": "odoo",
126
+ "default": true,
127
+ "description": "How many days late this customer is running against their own usual ordering rhythm."
128
+ },
129
+ {
130
+ "_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.",
131
+ "key": "est_missed",
132
+ "label": "Est. missed $",
133
+ "type": "currency",
134
+ "source": "odoo",
135
+ "default": true,
136
+ "agg": "sum",
137
+ "filterable": false,
138
+ "description": "Estimated sales missed while quiet: missed orders (capped at 3) times average order value. An estimate, not money owed."
139
+ },
140
+ {
141
+ "key": "ar_open",
142
+ "label": "AR open $",
143
+ "type": "currency",
144
+ "source": "odoo",
145
+ "default": false,
146
+ "description": "Invoiced money owed, not yet overdue."
147
+ },
148
+ {
149
+ "key": "ar_overdue",
150
+ "label": "AR overdue $",
151
+ "type": "currency",
152
+ "source": "odoo",
153
+ "default": false,
154
+ "description": "Invoiced money past due — same basis as the Collections page."
155
+ },
156
+ {
157
+ "key": "ar_exposure",
158
+ "label": "Credit exposure $",
159
+ "type": "currency",
160
+ "source": "odoo",
161
+ "default": false,
162
+ "description": "The most you could be out if they stopped paying today: open, overdue, draft and not-yet-invoiced."
163
+ },
164
+ {
165
+ "key": "days_to_pay",
166
+ "label": "Days to pay",
167
+ "type": "int",
168
+ "source": "odoo",
169
+ "default": false,
170
+ "description": "Average days to pay an invoice in full. Blank means no fully paid invoice yet."
171
+ },
172
+ {
173
+ "key": "top_category",
174
+ "label": "Top category",
175
+ "type": "text",
176
+ "source": "odoo",
177
+ "default": false,
178
+ "description": "The category this customer spent the most on in the last 12 months."
179
+ },
180
+ {
181
+ "key": "top_category_pct",
182
+ "label": "Top category %",
183
+ "type": "pct",
184
+ "source": "odoo",
185
+ "default": false,
186
+ "description": "Share of last-12-months spend that went to the top category."
187
+ },
188
+ {
189
+ "key": "sku_count",
190
+ "label": "SKUs bought",
191
+ "type": "int",
192
+ "source": "odoo",
193
+ "default": false,
194
+ "description": "Distinct products bought in the last 12 months."
195
+ },
196
+ {
197
+ "key": "top_sku",
198
+ "label": "Top SKU",
199
+ "type": "text",
200
+ "source": "odoo",
201
+ "default": false,
202
+ "description": "The product this customer spent the most on in the last 12 months."
203
+ },
204
+ {
205
+ "key": "days_since",
206
+ "label": "Days since order",
207
+ "type": "int",
208
+ "source": "odoo",
209
+ "default": false,
210
+ "description": "Days since the last confirmed order."
211
+ },
212
+ {
213
+ "key": "typical_gap_days",
214
+ "label": "Typical gap days",
215
+ "type": "int",
216
+ "source": "odoo",
217
+ "default": false,
218
+ "description": "Days this customer usually goes between orders, from their own history."
219
+ },
220
+ {
221
+ "key": "notes",
222
+ "label": "Notes",
223
+ "type": "text",
224
+ "source": "overlay",
225
+ "default": false,
226
+ "description": "Your notes on this customer. Saved in this app only, visible only to you."
227
+ }
228
+ ],
229
+ "rows": [
230
+ {
231
+ "pid": 101,
232
+ "customer": "Poppy Flowers",
233
+ "status": "New",
234
+ "agent": "Naomi Linnell Rivera",
235
+ "city": "Charlottesville",
236
+ "state": "Virginia (US)",
237
+ "last_order": "2026-07-21",
238
+ "est_missed": 0,
239
+ "notes": "",
240
+ "country": "United States",
241
+ "zip": "02720",
242
+ "payment_terms": "30 Days",
243
+ "pricelist": "Fisch 1 (USD)",
244
+ "tags": "Royal",
245
+ "customer_since": "2023-01-10",
246
+ "salesperson": "Jessica",
247
+ "ar_open": 0,
248
+ "ar_overdue": 0,
249
+ "ar_exposure": 0,
250
+ "top_category": "Styrofoam",
251
+ "top_category_pct": 0.47,
252
+ "sku_count": 93,
253
+ "top_sku": "AQUAFOAM FLORAL FOAM BRICK | 48-Piece per Pack",
254
+ "days_to_pay": 34,
255
+ "_created": "2023-01-15 09:10:00",
256
+ "lat": 25.7617,
257
+ "lon": -80.1918,
258
+ "odoo_status": "Archived",
259
+ "dba": "Royal"
260
+ },
261
+ {
262
+ "pid": 102,
263
+ "customer": "Meadow & Vine Wholesale",
264
+ "status": "Growing",
265
+ "agent": "Carla Jimenez",
266
+ "city": "Portland",
267
+ "state": "Oregon (US)",
268
+ "last_order": "2026-07-19",
269
+ "est_missed": 0,
270
+ "notes": "Expanding to a second storefront.",
271
+ "country": "United States",
272
+ "zip": "77041",
273
+ "payment_terms": "Immediate Payment",
274
+ "pricelist": "Royal 1 (USD)",
275
+ "tags": "Royal, Key account",
276
+ "customer_since": "2024-02-11",
277
+ "salesperson": "Naomi",
278
+ "ar_open": 1240.5,
279
+ "ar_overdue": 0,
280
+ "ar_exposure": 1740.5,
281
+ "top_category": "Ribbon",
282
+ "top_category_pct": 0.95,
283
+ "sku_count": 4,
284
+ "top_sku": "2\" X 24\" X 36\" GREEN STYROFOAM BOARD",
285
+ "days_to_pay": null,
286
+ "_created": "2023-02-15 09:11:00",
287
+ "lat": 27.9506,
288
+ "lon": -82.4572,
289
+ "odoo_status": "Active",
290
+ "dba": "Fisch"
291
+ },
292
+ {
293
+ "pid": 103,
294
+ "customer": "Bluestem Floral Supply",
295
+ "status": "Growing",
296
+ "agent": "Naomi Linnell Rivera",
297
+ "city": "Kansas City",
298
+ "state": "Missouri (US)",
299
+ "last_order": "2026-07-17",
300
+ "est_missed": 0,
301
+ "notes": "",
302
+ "country": "United States",
303
+ "zip": "11219",
304
+ "payment_terms": "60 Days",
305
+ "pricelist": "Royal 1 (USD)",
306
+ "tags": "Fisch",
307
+ "customer_since": "2025-03-12",
308
+ "salesperson": "Karen",
309
+ "ar_open": 0,
310
+ "ar_overdue": 5120.25,
311
+ "ar_exposure": 5120.25,
312
+ "top_category": "Foams & Finishes",
313
+ "top_category_pct": 0.31,
314
+ "sku_count": 27,
315
+ "top_sku": "SATIN RIBBON 2IN",
316
+ "days_to_pay": 61,
317
+ "_created": "2023-03-15 09:12:00",
318
+ "lat": 28.5384,
319
+ "lon": -81.3789,
320
+ "odoo_status": "Active",
321
+ "dba": "Both"
322
+ },
323
+ {
324
+ "pid": 104,
325
+ "customer": "Camellia Row Florist",
326
+ "status": "Declining",
327
+ "agent": "Devon Marsh",
328
+ "city": "Savannah",
329
+ "state": "Georgia (US)",
330
+ "last_order": "2026-05-30",
331
+ "est_missed": 41200,
332
+ "notes": "Switched some volume to a local grower.",
333
+ "country": "United States",
334
+ "zip": "07649",
335
+ "payment_terms": "30 Days",
336
+ "pricelist": "Fisch 1 (USD)",
337
+ "tags": "(none)",
338
+ "customer_since": "2026-04-13",
339
+ "salesperson": "(none)",
340
+ "ar_open": 8300,
341
+ "ar_overdue": 940,
342
+ "ar_exposure": 11440,
343
+ "top_category": "All",
344
+ "top_category_pct": 1.0,
345
+ "sku_count": 1,
346
+ "top_sku": "(none)",
347
+ "days_to_pay": 12,
348
+ "_created": "2023-04-15 09:13:00",
349
+ "lat": 30.3322,
350
+ "lon": -81.6557,
351
+ "odoo_status": "Active",
352
+ "dba": "Royal"
353
+ },
354
+ {
355
+ "pid": 105,
356
+ "customer": "Harborlight Wholesale Blooms",
357
+ "status": "Growing",
358
+ "agent": "Carla Jimenez",
359
+ "city": "Seattle",
360
+ "state": "Washington (US)",
361
+ "last_order": "2026-07-22",
362
+ "est_missed": 0,
363
+ "notes": "Top-10 account.",
364
+ "country": "United States",
365
+ "zip": "33125",
366
+ "payment_terms": "Immediate Payment",
367
+ "pricelist": "Royal 1 (USD)",
368
+ "tags": "Royal",
369
+ "customer_since": "2023-05-14",
370
+ "salesperson": "Jessica",
371
+ "ar_open": 0,
372
+ "ar_overdue": 0,
373
+ "ar_exposure": 0,
374
+ "top_category": "Styrofoam",
375
+ "top_category_pct": 0.47,
376
+ "sku_count": 93,
377
+ "top_sku": "AQUAFOAM FLORAL FOAM BRICK | 48-Piece per Pack",
378
+ "days_to_pay": 34,
379
+ "_created": "2023-05-15 09:14:00",
380
+ "lat": 26.1224,
381
+ "lon": -80.1373,
382
+ "odoo_status": "Active",
383
+ "dba": ""
384
+ },
385
+ {
386
+ "pid": 106,
387
+ "customer": "Dogwood & Fern Co.",
388
+ "status": "Dormant",
389
+ "agent": "Devon Marsh",
390
+ "city": "Asheville",
391
+ "state": "North Carolina (US)",
392
+ "last_order": "2026-02-11",
393
+ "est_missed": 52400,
394
+ "notes": "No spring order this year.",
395
+ "country": "United States",
396
+ "zip": "90210",
397
+ "payment_terms": "60 Days",
398
+ "pricelist": "Royal 1 (USD)",
399
+ "tags": "Royal, Key account",
400
+ "customer_since": "2024-06-15",
401
+ "salesperson": "Naomi",
402
+ "ar_open": 1240.5,
403
+ "ar_overdue": 0,
404
+ "ar_exposure": 1740.5,
405
+ "top_category": "Ribbon",
406
+ "top_category_pct": 0.95,
407
+ "sku_count": 4,
408
+ "top_sku": "2\" X 24\" X 36\" GREEN STYROFOAM BOARD",
409
+ "days_to_pay": null,
410
+ "_created": "2023-06-15 09:15:00",
411
+ "lat": 27.3364,
412
+ "lon": -82.5307,
413
+ "odoo_status": "Active",
414
+ "dba": "Fisch"
415
+ },
416
+ {
417
+ "pid": 107,
418
+ "customer": "Verbena Market Florals",
419
+ "status": "Lost",
420
+ "agent": "Naomi Linnell Rivera",
421
+ "city": "Austin",
422
+ "state": "Texas (US)",
423
+ "last_order": "2025-11-04",
424
+ "est_missed": 78300,
425
+ "notes": "Went with a competitor on freight terms.",
426
+ "country": "United States",
427
+ "zip": "08701",
428
+ "payment_terms": "30 Days",
429
+ "pricelist": "Fisch 1 (USD)",
430
+ "tags": "Fisch",
431
+ "customer_since": "2025-07-16",
432
+ "salesperson": "Karen",
433
+ "ar_open": 0,
434
+ "ar_overdue": 5120.25,
435
+ "ar_exposure": 5120.25,
436
+ "top_category": "Foams & Finishes",
437
+ "top_category_pct": 0.31,
438
+ "sku_count": 27,
439
+ "top_sku": "SATIN RIBBON 2IN",
440
+ "days_to_pay": 61,
441
+ "_created": "2023-07-15 09:16:00",
442
+ "lat": null,
443
+ "lon": null,
444
+ "odoo_status": "Active",
445
+ "dba": "Both"
446
+ },
447
+ {
448
+ "pid": 108,
449
+ "customer": "Larkspur Lane Supply",
450
+ "status": "New",
451
+ "agent": "Carla Jimenez",
452
+ "city": "Denver",
453
+ "state": "Colorado (US)",
454
+ "last_order": "2026-07-14",
455
+ "est_missed": 0,
456
+ "notes": "First order in April.",
457
+ "country": "United States",
458
+ "zip": "60614",
459
+ "payment_terms": "Immediate Payment",
460
+ "pricelist": "Royal 1 (USD)",
461
+ "tags": "(none)",
462
+ "customer_since": "2026-08-17",
463
+ "salesperson": "(none)",
464
+ "ar_open": 8300,
465
+ "ar_overdue": 940,
466
+ "ar_exposure": 11440,
467
+ "top_category": "All",
468
+ "top_category_pct": 1.0,
469
+ "sku_count": 1,
470
+ "top_sku": "(none)",
471
+ "days_to_pay": 12,
472
+ "_created": "2023-08-15 09:17:00",
473
+ "lat": 33.749,
474
+ "lon": -84.388,
475
+ "odoo_status": "Active",
476
+ "dba": "Royal"
477
+ }
478
+ ]
479
+ }
web/src/customer-grid/ColumnMenu.tsx CHANGED
@@ -9,25 +9,25 @@ import type { Field, FieldFormat, FieldScope, FieldType, Measure, Viewer } from
9
  import type { WindowSpec } from "./windows";
10
  import { normalizeWindow, windowLabel } from "./windows";
11
  import { WindowPicker } from "./Toolbar";
12
- import { TYPE_LABELS } from "./iconShapes";
13
- import { validateFormula } from "./formulaEngine";
14
- import { defaultOptionColor, normalizeOptionColor, OPTION_PALETTE } from "./choiceColors";
15
 
16
- export interface ColumnMenuState {
17
- fieldKey: string;
18
- anchor: AnchorRect;
19
- }
20
-
21
- interface FieldConfigExtra {
22
- formula?: string;
23
- max?: number;
24
- scope?: FieldScope;
25
- label?: string;
26
- colorCodeOptions?: boolean;
27
- optionColors?: Record<string, string>;
28
- }
29
-
30
- interface ColumnMenuProps {
31
  state: ColumnMenuState;
32
  field: Field;
33
  /** Every field of the table, for "Change field" (owner item 9): the clicked column can be
@@ -53,7 +53,7 @@ interface ColumnMenuProps {
53
  side: "left" | "right" | "end",
54
  options?: string[],
55
  measureSpec?: { key: string; window: WindowSpec },
56
- extra?: FieldConfigExtra
57
  ) => void;
58
  /** Swap THIS column for another field, in place (owner item 9). */
59
  onChangeField: (newKey: string) => void;
@@ -67,7 +67,7 @@ interface ColumnMenuProps {
67
  label: string,
68
  type: FieldType,
69
  options?: string[],
70
- extra?: FieldConfigExtra
71
  ) => void;
72
  /**
73
  * Wave-6 item 2, re-homed by owner item 8 (2026-07-31): supplied for CREATED (`custom_`)
@@ -79,7 +79,7 @@ interface ColumnMenuProps {
79
  onRetype?: (
80
  type: FieldType,
81
  options?: string[],
82
- extra?: FieldConfigExtra
83
  ) => void;
84
  /** Wave-6 item 5 — rename this created field (ordinary field_upsert with a new label).
85
  * Supplied for creatable strata only. */
@@ -304,195 +304,195 @@ type MenuPane = "menu" | "note" | "edit" | "permissions" | "format";
304
  const FIELD_TYPES = CREATABLE_TYPES.map((value) => ({ value, label: TYPE_LABELS[value] }));
305
 
306
  /** Types whose choices are declared in an options editor at creation time. */
307
- function needsOptions(t: FieldType | "measure"): boolean {
308
- return t === "select" || t === "multiselect";
309
- }
310
-
311
- interface OptionDraft {
312
- id: string;
313
- label: string;
314
- color: string;
315
- }
316
-
317
- const DEFAULT_OPTION_LABELS = ["Not started", "In progress", "Blocked", "Done"];
318
- let optionDraftSequence = 0;
319
-
320
- function nextOptionDraftId(): string {
321
- optionDraftSequence += 1;
322
- return `choice-${optionDraftSequence}`;
323
- }
324
-
325
- function optionDrafts(
326
- labels: string[],
327
- saved: Record<string, string> | undefined = undefined
328
- ): OptionDraft[] {
329
- return labels.map((label) => ({
330
- id: nextOptionDraftId(),
331
- label,
332
- color:
333
- normalizeOptionColor(saved?.[label]) ??
334
- normalizeOptionColor(defaultOptionColor(label))!,
335
- }));
336
- }
337
-
338
- function optionSettings(
339
- drafts: OptionDraft[],
340
- type: FieldType | "measure"
341
- ): { options: string[]; colors: Record<string, string> } {
342
- const clean = drafts.map((draft) =>
343
- type === "multiselect" ? draft.label.replace(/,/g, " ") : draft.label
344
- );
345
- const options = parseOptions(clean.join("\n"));
346
- const firstByLabel = new Map<string, OptionDraft>();
347
- drafts.forEach((draft, index) => {
348
- const label = clean[index].trim();
349
- if (label && !firstByLabel.has(label.toLowerCase()))
350
- firstByLabel.set(label.toLowerCase(), draft);
351
- });
352
- const colors: Record<string, string> = {};
353
- for (const option of options) {
354
- const draft = firstByLabel.get(option.toLowerCase());
355
- const color = normalizeOptionColor(draft?.color);
356
- // The deterministic fallback is not durable data. Persist only a genuine user override;
357
- // this keeps an untouched legacy field byte-stable while a renamed row retains its colour.
358
- if (color && color !== normalizeOptionColor(defaultOptionColor(option)))
359
- colors[option] = color;
360
- }
361
- return { options, colors };
362
- }
363
-
364
- function optionAppearanceSignature(
365
- options: string[],
366
- colors: Record<string, string> | undefined
367
- ): string {
368
- return options
369
- .map((option) => {
370
- const custom = colors
371
- ? Object.entries(colors).find(
372
- ([label]) => label.trim().toLowerCase() === option.toLowerCase()
373
- )?.[1]
374
- : undefined;
375
- return `${option}\u0000${
376
- normalizeOptionColor(custom) ?? normalizeOptionColor(defaultOptionColor(option))
377
- }`;
378
- })
379
- .join("\u0001");
380
- }
381
-
382
- function OptionsEditor({
383
- idPrefix,
384
- drafts,
385
- onDrafts,
386
- colorCode,
387
- onColorCode,
388
- type,
389
- }: {
390
- idPrefix: string;
391
- drafts: OptionDraft[];
392
- onDrafts: (next: OptionDraft[]) => void;
393
- colorCode: boolean;
394
- onColorCode: (next: boolean) => void;
395
- type: FieldType | "measure";
396
- }) {
397
- const update = (id: string, patch: Partial<OptionDraft>) =>
398
- onDrafts(drafts.map((draft) => (draft.id === id ? { ...draft, ...patch } : draft)));
399
- const settings = optionSettings(drafts, type);
400
- return (
401
- <div className="cg-options-editor">
402
- <div className="cg-options-head">
403
- <strong>Options</strong>
404
- <label className="cg-option-toggle">
405
- <input
406
- type="checkbox"
407
- checked={colorCode}
408
- onChange={(event) => onColorCode(event.target.checked)}
409
- />
410
- <span>Color-code options</span>
411
- </label>
412
- </div>
413
- <div className="cg-option-list">
414
- {drafts.map((draft, index) => (
415
- <div className="cg-option-row" key={draft.id}>
416
- <input
417
- className="cg-option-color"
418
- type="color"
419
- value={
420
- normalizeOptionColor(draft.color) ??
421
- OPTION_PALETTE[index % OPTION_PALETTE.length].bg
422
- }
423
- disabled={!colorCode}
424
- aria-label={`Color for ${draft.label || `option ${index + 1}`}`}
425
- title="Change option color"
426
- onChange={(event) => update(draft.id, { color: event.target.value })}
427
- />
428
- <input
429
- id={`${idPrefix}-${draft.id}`}
430
- className="cg-input cg-option-name"
431
- type="text"
432
- maxLength={120}
433
- value={draft.label}
434
- placeholder="Option name"
435
- aria-label={`Option ${index + 1}`}
436
- onChange={(event) => {
437
- const label =
438
- type === "multiselect"
439
- ? event.target.value.replace(/,/g, " ")
440
- : event.target.value;
441
- update(draft.id, { label });
442
- }}
443
- onKeyDown={(event) => {
444
- if (event.key !== "Enter") return;
445
- event.preventDefault();
446
- onDrafts([
447
- ...drafts,
448
- {
449
- id: nextOptionDraftId(),
450
- label: "",
451
- color: OPTION_PALETTE[drafts.length % OPTION_PALETTE.length].bg,
452
- },
453
- ]);
454
- }}
455
- />
456
- <button
457
- type="button"
458
- className="cg-option-remove"
459
- aria-label={`Remove ${draft.label || `option ${index + 1}`}`}
460
- title="Remove option"
461
- onClick={() => onDrafts(drafts.filter((item) => item.id !== draft.id))}
462
- >
463
- <svg viewBox="0 0 16 16" aria-hidden="true">
464
- <path d="M4 4l8 8M12 4l-8 8" />
465
- </svg>
466
- </button>
467
- </div>
468
- ))}
469
- </div>
470
- <button
471
- type="button"
472
- className="cg-option-add"
473
- onClick={() =>
474
- onDrafts([
475
- ...drafts,
476
- {
477
- id: nextOptionDraftId(),
478
- label: "",
479
- color: OPTION_PALETTE[drafts.length % OPTION_PALETTE.length].bg,
480
- },
481
- ])
482
- }
483
- >
484
- Add option
485
- </button>
486
- <span className="cg-field-hint">
487
- {settings.options.length} option{settings.options.length === 1 ? "" : "s"}.
488
- {type === "multiselect" && " Commas inside an option are not supported."}
489
- </span>
490
- </div>
491
- );
492
- }
493
-
494
- /**
495
- * The create-picker's kind: a creatable overlay type, or the FORMULA-MEASURE pseudo-kind.
496
  * "measure" is deliberately NOT a FieldType — a measure column's real type comes from the
497
  * measure itself (currency/int/pct), and widening the union would let it leak into every
498
  * switch that renders cells.
@@ -527,8 +527,11 @@ function TypePicker({
527
  : FIELD_TYPES;
528
  const rows: { value: CreateKind; label: string }[] = [
529
  ...base,
 
 
 
530
  ...(offerMeasure
531
- ? [{ value: "measure" as CreateKind, label: "Formula measure (over a period)" }]
532
  : []),
533
  ].filter((r) => !needle || r.label.toLowerCase().includes(needle));
534
  return (
@@ -674,10 +677,10 @@ function ExtraTypeEditor({
674
  formulaText,
675
  onFormulaText,
676
  formulaError,
677
- maxValue,
678
- onMaxValue,
679
- idPrefix,
680
- showFormulaHelp = true,
681
  }: {
682
  kind: FieldType | "measure";
683
  fields: Field[];
@@ -685,9 +688,9 @@ function ExtraTypeEditor({
685
  onFormulaText: (v: string) => void;
686
  formulaError: string | null;
687
  maxValue: number;
688
- onMaxValue: (n: number) => void;
689
- idPrefix: string;
690
- showFormulaHelp?: boolean;
691
  }) {
692
  if (kind === "formula") {
693
  // 2026-07-31 (owner item 2): other FORMULA fields are referencable now — evaluation is
@@ -728,15 +731,15 @@ function ExtraTypeEditor({
728
  </div>
729
  {formulaText.trim() !== "" && formulaError ? (
730
  <div className="cg-field-hint cg-formula-error">{formulaError}</div>
731
- ) : showFormulaHelp ? (
732
- <div className="cg-field-hint">
733
  Excel-style: numbers, text in quotes, {"{field}"} references, + − × ÷ ^ &amp; ( ),
734
  IF · AND · OR · SUM · AVERAGE · COUNT · MIN · MAX · ROUND(UP/DOWN) · ABS · MOD ·
735
  SQRT · CONCATENATE · LEFT · RIGHT · MID · LEN · TRIM · UPPER · LOWER · PROPER ·
736
  TEXT · VALUE · TODAY · DAYS · YEAR · MONTH · DAY · IFERROR · ISBLANK.
737
  Errors show a blank cell.
738
- </div>
739
- ) : null}
740
  </>
741
  );
742
  }
@@ -817,12 +820,12 @@ export default function ColumnMenu({
817
  const [label, setLabel] = useState("");
818
  /** Whether the user has typed their own name — an auto-suggested measure label must never
819
  * overwrite one, but should keep tracking the measure/window until they do. */
820
- const [labelTouched, setLabelTouched] = useState(false);
821
- const [kind, setKind] = useState<CreateKind>("text");
822
- const [createOptionDrafts, setCreateOptionDrafts] = useState<OptionDraft[]>(() =>
823
- optionDrafts(DEFAULT_OPTION_LABELS)
824
- );
825
- const [createColorCode, setCreateColorCode] = useState(true);
826
  const [measureKey, setMeasureKey] = useState(measures[0]?.key ?? "");
827
  const [measureWindow, setMeasureWindow] = useState<WindowSpec>(DEFAULT_MEASURE_WINDOW);
828
  /** Wave-5 item 9/11 — the create form's formula source and rating star count. */
@@ -831,11 +834,11 @@ export default function ColumnMenu({
831
  const [swapTo, setSwapTo] = useState("");
832
  /** The "New field" half of Change-field keeps its own name/options — a half-typed insert
833
  * form must not leak into a swap and vice versa. */
834
- const [swapLabel, setSwapLabel] = useState("");
835
- const [swapOptionDrafts, setSwapOptionDrafts] = useState<OptionDraft[]>(() =>
836
- optionDrafts(DEFAULT_OPTION_LABELS)
837
- );
838
- const [swapColorCode, setSwapColorCode] = useState(true);
839
  const [swapFormulaText, setSwapFormulaText] = useState("");
840
  const [swapMaxValue, setSwapMaxValue] = useState(5);
841
  /** Item 8c — the period DRAFT. null = untouched (the field's own window shows). Buffered
@@ -856,14 +859,14 @@ export default function ColumnMenu({
856
  /** Owner item 8 — the Edit pane's TYPE draft plus the per-type config drafts: options
857
  * prefilled from the field (a select retyped to multi select keeps its choices), star
858
  * count from the field's own max, formula source from the field's own source. */
859
- const [editType, setEditType] = useState<FieldType>(field.type);
860
- const [editOptionDrafts, setEditOptionDrafts] = useState<OptionDraft[]>(() =>
861
- optionDrafts(
862
- choiceOptions(field).length ? choiceOptions(field) : DEFAULT_OPTION_LABELS,
863
- field.optionColors
864
- )
865
- );
866
- const [editColorCode, setEditColorCode] = useState(field.colorCodeOptions !== false);
867
  const [retypeMaxValue, setRetypeMaxValue] = useState(() => ratingMax(field));
868
  const [editFormulaText, setEditFormulaText] = useState(() =>
869
  typeof field.formula === "string" ? field.formula : ""
@@ -873,15 +876,15 @@ export default function ColumnMenu({
873
  ? (swapTo.slice(NEW_PREFIX.length) as FieldType)
874
  : null;
875
 
876
- const createChoice = optionSettings(createOptionDrafts, kind);
877
- const options = createChoice.options;
878
- const swapChoice = swapToNewType
879
- ? optionSettings(swapOptionDrafts, swapToNewType)
880
- : { options: [] as string[], colors: {} as Record<string, string> };
881
- const swapNewOptions = swapChoice.options;
882
- /** Owner item 8 — the Edit pane's parsed choices for the drafted type. */
883
- const editChoice = optionSettings(editOptionDrafts, editType);
884
- const editOptions = editChoice.options;
885
 
886
  // Wave-5 item 9, amended 2026-07-31 (owner item 2) — live formula validation for BOTH
887
  // create surfaces. Refs may now name OTHER formula fields (evaluation is topological);
@@ -934,29 +937,29 @@ export default function ColumnMenu({
934
  (kind !== "measure" || !!chosenMeasure) &&
935
  (kind !== "formula" || formulaCheck.ok);
936
 
937
- const extraFor = (
938
- t: CreateKind,
939
- src: string,
940
- starCount: number
941
- ): FieldConfigExtra | undefined => {
942
- if (t === "formula") return { formula: src.trim() };
943
- if (t === "rating") return { max: starCount };
944
- return undefined;
945
- };
946
- const optionExtraFor = (
947
- t: CreateKind,
948
- colors: Record<string, string>,
949
- colorCode: boolean
950
- ): FieldConfigExtra =>
951
- needsOptions(t)
952
- ? {
953
- colorCodeOptions: colorCode,
954
- ...(Object.keys(colors).length ? { optionColors: colors } : {}),
955
- }
956
- : {};
957
- /** Item 9c — the Scope choice rides the create extras only where the page offers it. */
958
- const withScope = (e?: FieldConfigExtra): FieldConfigExtra | undefined =>
959
- scopeChoice ? { ...(e ?? {}), scope: scopeDraft } : e;
960
 
961
  const create = () => {
962
  const clean = effectiveLabel.trim();
@@ -969,12 +972,12 @@ export default function ColumnMenu({
969
  onClose();
970
  return;
971
  }
972
- onCreate(clean, kind, position === "end" ? null : field.key, position,
973
- needsOptions(kind) ? options : undefined, undefined,
974
- withScope({
975
- ...extraFor(kind, formulaText, maxValue),
976
- ...optionExtraFor(kind, createChoice.colors, createColorCode),
977
- }));
978
  onClose();
979
  };
980
 
@@ -987,13 +990,13 @@ export default function ColumnMenu({
987
  const createAndSwap = () => {
988
  if (!swapToNewType || !canCreateSwap) return;
989
  onCreateAndSwap(
990
- swapLabel.trim(),
991
- swapToNewType,
992
- needsOptions(swapToNewType) ? swapNewOptions : undefined,
993
- withScope({
994
- ...extraFor(swapToNewType, swapFormulaText, swapMaxValue),
995
- ...optionExtraFor(swapToNewType, swapChoice.colors, swapColorCode),
996
- })
997
  );
998
  onClose();
999
  };
@@ -1004,20 +1007,20 @@ export default function ColumnMenu({
1004
  // stale def and the second reverts the first (label rides extra.label / onFormula's label).
1005
  const cleanRename = renameDraft.trim();
1006
  const editNameDirty = !!onRename && cleanRename !== "" && cleanRename !== field.label;
1007
- const editOptionsChanged =
1008
- needsOptions(editType) &&
1009
- editOptions.join("\n") !== choiceOptions(field).join("\n");
1010
- const editAppearanceChanged =
1011
- needsOptions(editType) &&
1012
- (editColorCode !== (field.colorCodeOptions !== false) ||
1013
- optionAppearanceSignature(editOptions, editChoice.colors) !==
1014
- optionAppearanceSignature(choiceOptions(field), field.optionColors));
1015
- const editStarsChanged = editType === "rating" && retypeMaxValue !== ratingMax(field);
1016
  /** The type half was touched: a different type, or the SAME type with edited choices/stars
1017
  * (the owner's named case — "change the list of the single selections"). */
1018
- const editRetypeTouched =
1019
- onRetype != null &&
1020
- (editType !== field.type || editOptionsChanged || editAppearanceChanged || editStarsChanged);
1021
  const editRetypeValid = !needsOptions(editType) || editOptions.length > 0;
1022
  const editFormulaCheck = useMemo(
1023
  () =>
@@ -1044,18 +1047,18 @@ export default function ColumnMenu({
1044
  onRetype(
1045
  editType,
1046
  needsOptions(editType) ? editOptions : undefined,
1047
- {
1048
- ...(editType === "rating" ? { max: retypeMaxValue } : {}),
1049
- ...(needsOptions(editType)
1050
- ? {
1051
- colorCodeOptions: editColorCode,
1052
- ...(Object.keys(editChoice.colors).length
1053
- ? { optionColors: editChoice.colors }
1054
- : {}),
1055
- }
1056
- : {}),
1057
- ...(editNameDirty ? { label: cleanRename } : {}),
1058
- }
1059
  );
1060
  } else if (editFormulaTouched && onFormula) {
1061
  onFormula(editFormulaText.trim(), editNameDirty ? cleanRename : undefined);
@@ -1086,7 +1089,7 @@ export default function ColumnMenu({
1086
  JSON.stringify(draftWindow) !== JSON.stringify(currentWindow);
1087
 
1088
  const typeLineBase = field.measure
1089
- ? "Formula measure, read-only"
1090
  : field.type === "formula"
1091
  ? "Formula field, computed"
1092
  : field.type === "created_time"
@@ -1170,15 +1173,18 @@ export default function ColumnMenu({
1170
  </div>
1171
  {kind === "measure" && (
1172
  <>
 
 
 
1173
  <label>
1174
- <span>Measure</span>
1175
  <select
1176
  className="cg-select"
1177
  value={measureKey}
1178
- aria-label="Measure"
1179
  onChange={(event) => setMeasureKey(event.target.value)}
1180
  >
1181
- {!chosenMeasure && <option value="">Choose a measure…</option>}
1182
  {measures.map((m) => (
1183
  <option key={m.key} value={m.key}>
1184
  {m.label}
@@ -1192,8 +1198,12 @@ export default function ColumnMenu({
1192
  <WindowPicker window={measureWindow} onWindow={setMeasureWindow} />
1193
  </span>
1194
  </label>
 
 
 
1195
  <div className="cg-field-hint">
1196
- Computed over the period you choose. Read-only.
 
1197
  </div>
1198
  </>
1199
  )}
@@ -1206,17 +1216,17 @@ export default function ColumnMenu({
1206
  maxValue={maxValue}
1207
  onMaxValue={setMaxValue}
1208
  idPrefix="cg-create"
1209
- />
1210
- {needsOptions(kind) && (
1211
- <OptionsEditor
1212
- idPrefix="cg-create-option"
1213
- drafts={createOptionDrafts}
1214
- onDrafts={setCreateOptionDrafts}
1215
- colorCode={createColorCode}
1216
- onColorCode={setCreateColorCode}
1217
- type={kind}
1218
- />
1219
- )}
1220
  {kind === "user" && (
1221
  <div className="cg-field-hint">
1222
  {userOptions.length
@@ -1323,17 +1333,17 @@ export default function ColumnMenu({
1323
  }}
1324
  />
1325
  </label>
1326
- )}
1327
- {needsOptions(editType) && (
1328
- <OptionsEditor
1329
- idPrefix="cg-edit-option"
1330
- drafts={editOptionDrafts}
1331
- onDrafts={setEditOptionDrafts}
1332
- colorCode={editColorCode}
1333
- onColorCode={setEditColorCode}
1334
- type={editType}
1335
- />
1336
- )}
1337
  {editType !== field.type && (
1338
  <div className="cg-field-hint">
1339
  Changes {field.label} into a {TYPE_LABELS[editType].toLowerCase()} field,
@@ -1350,11 +1360,11 @@ export default function ColumnMenu({
1350
  formulaText={editFormulaText}
1351
  onFormulaText={setEditFormulaText}
1352
  formulaError={editFormulaCheck.ok ? null : editFormulaCheck.error ?? null}
1353
- maxValue={retypeMaxValue}
1354
- onMaxValue={setRetypeMaxValue}
1355
- idPrefix="cg-edit"
1356
- showFormulaHelp={false}
1357
- />
1358
  )}
1359
  <div className="cg-form-actions">
1360
  <button
@@ -1453,17 +1463,17 @@ export default function ColumnMenu({
1453
  maxValue={swapMaxValue}
1454
  onMaxValue={setSwapMaxValue}
1455
  idPrefix="cg-swap"
1456
- />
1457
- {needsOptions(swapToNewType) && (
1458
- <OptionsEditor
1459
- idPrefix="cg-swap-option"
1460
- drafts={swapOptionDrafts}
1461
- onDrafts={setSwapOptionDrafts}
1462
- colorCode={swapColorCode}
1463
- onColorCode={setSwapColorCode}
1464
- type={swapToNewType}
1465
- />
1466
- )}
1467
  {swapToNewType === "user" && (
1468
  <div className="cg-field-hint">
1469
  {userOptions.length
 
9
  import type { WindowSpec } from "./windows";
10
  import { normalizeWindow, windowLabel } from "./windows";
11
  import { WindowPicker } from "./Toolbar";
12
+ import { TYPE_LABELS } from "./iconShapes";
13
+ import { validateFormula } from "./formulaEngine";
14
+ import { defaultOptionColor, normalizeOptionColor, OPTION_PALETTE } from "./choiceColors";
15
 
16
+ export interface ColumnMenuState {
17
+ fieldKey: string;
18
+ anchor: AnchorRect;
19
+ }
20
+
21
+ interface FieldConfigExtra {
22
+ formula?: string;
23
+ max?: number;
24
+ scope?: FieldScope;
25
+ label?: string;
26
+ colorCodeOptions?: boolean;
27
+ optionColors?: Record<string, string>;
28
+ }
29
+
30
+ interface ColumnMenuProps {
31
  state: ColumnMenuState;
32
  field: Field;
33
  /** Every field of the table, for "Change field" (owner item 9): the clicked column can be
 
53
  side: "left" | "right" | "end",
54
  options?: string[],
55
  measureSpec?: { key: string; window: WindowSpec },
56
+ extra?: FieldConfigExtra
57
  ) => void;
58
  /** Swap THIS column for another field, in place (owner item 9). */
59
  onChangeField: (newKey: string) => void;
 
67
  label: string,
68
  type: FieldType,
69
  options?: string[],
70
+ extra?: FieldConfigExtra
71
  ) => void;
72
  /**
73
  * Wave-6 item 2, re-homed by owner item 8 (2026-07-31): supplied for CREATED (`custom_`)
 
79
  onRetype?: (
80
  type: FieldType,
81
  options?: string[],
82
+ extra?: FieldConfigExtra
83
  ) => void;
84
  /** Wave-6 item 5 — rename this created field (ordinary field_upsert with a new label).
85
  * Supplied for creatable strata only. */
 
304
  const FIELD_TYPES = CREATABLE_TYPES.map((value) => ({ value, label: TYPE_LABELS[value] }));
305
 
306
  /** Types whose choices are declared in an options editor at creation time. */
307
+ function needsOptions(t: FieldType | "measure"): boolean {
308
+ return t === "select" || t === "multiselect";
309
+ }
310
+
311
+ interface OptionDraft {
312
+ id: string;
313
+ label: string;
314
+ color: string;
315
+ }
316
+
317
+ const DEFAULT_OPTION_LABELS = ["Not started", "In progress", "Blocked", "Done"];
318
+ let optionDraftSequence = 0;
319
+
320
+ function nextOptionDraftId(): string {
321
+ optionDraftSequence += 1;
322
+ return `choice-${optionDraftSequence}`;
323
+ }
324
+
325
+ function optionDrafts(
326
+ labels: string[],
327
+ saved: Record<string, string> | undefined = undefined
328
+ ): OptionDraft[] {
329
+ return labels.map((label) => ({
330
+ id: nextOptionDraftId(),
331
+ label,
332
+ color:
333
+ normalizeOptionColor(saved?.[label]) ??
334
+ normalizeOptionColor(defaultOptionColor(label))!,
335
+ }));
336
+ }
337
+
338
+ function optionSettings(
339
+ drafts: OptionDraft[],
340
+ type: FieldType | "measure"
341
+ ): { options: string[]; colors: Record<string, string> } {
342
+ const clean = drafts.map((draft) =>
343
+ type === "multiselect" ? draft.label.replace(/,/g, " ") : draft.label
344
+ );
345
+ const options = parseOptions(clean.join("\n"));
346
+ const firstByLabel = new Map<string, OptionDraft>();
347
+ drafts.forEach((draft, index) => {
348
+ const label = clean[index].trim();
349
+ if (label && !firstByLabel.has(label.toLowerCase()))
350
+ firstByLabel.set(label.toLowerCase(), draft);
351
+ });
352
+ const colors: Record<string, string> = {};
353
+ for (const option of options) {
354
+ const draft = firstByLabel.get(option.toLowerCase());
355
+ const color = normalizeOptionColor(draft?.color);
356
+ // The deterministic fallback is not durable data. Persist only a genuine user override;
357
+ // this keeps an untouched legacy field byte-stable while a renamed row retains its colour.
358
+ if (color && color !== normalizeOptionColor(defaultOptionColor(option)))
359
+ colors[option] = color;
360
+ }
361
+ return { options, colors };
362
+ }
363
+
364
+ function optionAppearanceSignature(
365
+ options: string[],
366
+ colors: Record<string, string> | undefined
367
+ ): string {
368
+ return options
369
+ .map((option) => {
370
+ const custom = colors
371
+ ? Object.entries(colors).find(
372
+ ([label]) => label.trim().toLowerCase() === option.toLowerCase()
373
+ )?.[1]
374
+ : undefined;
375
+ return `${option}\u0000${
376
+ normalizeOptionColor(custom) ?? normalizeOptionColor(defaultOptionColor(option))
377
+ }`;
378
+ })
379
+ .join("\u0001");
380
+ }
381
+
382
+ function OptionsEditor({
383
+ idPrefix,
384
+ drafts,
385
+ onDrafts,
386
+ colorCode,
387
+ onColorCode,
388
+ type,
389
+ }: {
390
+ idPrefix: string;
391
+ drafts: OptionDraft[];
392
+ onDrafts: (next: OptionDraft[]) => void;
393
+ colorCode: boolean;
394
+ onColorCode: (next: boolean) => void;
395
+ type: FieldType | "measure";
396
+ }) {
397
+ const update = (id: string, patch: Partial<OptionDraft>) =>
398
+ onDrafts(drafts.map((draft) => (draft.id === id ? { ...draft, ...patch } : draft)));
399
+ const settings = optionSettings(drafts, type);
400
+ return (
401
+ <div className="cg-options-editor">
402
+ <div className="cg-options-head">
403
+ <strong>Options</strong>
404
+ <label className="cg-option-toggle">
405
+ <input
406
+ type="checkbox"
407
+ checked={colorCode}
408
+ onChange={(event) => onColorCode(event.target.checked)}
409
+ />
410
+ <span>Color-code options</span>
411
+ </label>
412
+ </div>
413
+ <div className="cg-option-list">
414
+ {drafts.map((draft, index) => (
415
+ <div className="cg-option-row" key={draft.id}>
416
+ <input
417
+ className="cg-option-color"
418
+ type="color"
419
+ value={
420
+ normalizeOptionColor(draft.color) ??
421
+ OPTION_PALETTE[index % OPTION_PALETTE.length].bg
422
+ }
423
+ disabled={!colorCode}
424
+ aria-label={`Color for ${draft.label || `option ${index + 1}`}`}
425
+ title="Change option color"
426
+ onChange={(event) => update(draft.id, { color: event.target.value })}
427
+ />
428
+ <input
429
+ id={`${idPrefix}-${draft.id}`}
430
+ className="cg-input cg-option-name"
431
+ type="text"
432
+ maxLength={120}
433
+ value={draft.label}
434
+ placeholder="Option name"
435
+ aria-label={`Option ${index + 1}`}
436
+ onChange={(event) => {
437
+ const label =
438
+ type === "multiselect"
439
+ ? event.target.value.replace(/,/g, " ")
440
+ : event.target.value;
441
+ update(draft.id, { label });
442
+ }}
443
+ onKeyDown={(event) => {
444
+ if (event.key !== "Enter") return;
445
+ event.preventDefault();
446
+ onDrafts([
447
+ ...drafts,
448
+ {
449
+ id: nextOptionDraftId(),
450
+ label: "",
451
+ color: OPTION_PALETTE[drafts.length % OPTION_PALETTE.length].bg,
452
+ },
453
+ ]);
454
+ }}
455
+ />
456
+ <button
457
+ type="button"
458
+ className="cg-option-remove"
459
+ aria-label={`Remove ${draft.label || `option ${index + 1}`}`}
460
+ title="Remove option"
461
+ onClick={() => onDrafts(drafts.filter((item) => item.id !== draft.id))}
462
+ >
463
+ <svg viewBox="0 0 16 16" aria-hidden="true">
464
+ <path d="M4 4l8 8M12 4l-8 8" />
465
+ </svg>
466
+ </button>
467
+ </div>
468
+ ))}
469
+ </div>
470
+ <button
471
+ type="button"
472
+ className="cg-option-add"
473
+ onClick={() =>
474
+ onDrafts([
475
+ ...drafts,
476
+ {
477
+ id: nextOptionDraftId(),
478
+ label: "",
479
+ color: OPTION_PALETTE[drafts.length % OPTION_PALETTE.length].bg,
480
+ },
481
+ ])
482
+ }
483
+ >
484
+ Add option
485
+ </button>
486
+ <span className="cg-field-hint">
487
+ {settings.options.length} option{settings.options.length === 1 ? "" : "s"}.
488
+ {type === "multiselect" && " Commas inside an option are not supported."}
489
+ </span>
490
+ </div>
491
+ );
492
+ }
493
+
494
+ /**
495
+ * The create-picker's kind: a creatable overlay type, or the FORMULA-MEASURE pseudo-kind.
496
  * "measure" is deliberately NOT a FieldType — a measure column's real type comes from the
497
  * measure itself (currency/int/pct), and widening the union would let it leak into every
498
  * switch that renders cells.
 
527
  : FIELD_TYPES;
528
  const rows: { value: CreateKind; label: string }[] = [
529
  ...base,
530
+ // C-NAME (item 9, 2026-08-02): "Formula measure (over a period)" -> "Metric". Two words
531
+ // of jargon and a parenthetical, replaced by the word people already use for the thing.
532
+ // The internal key stays `measure` — see the C-NAME amendment in the wave doc.
533
  ...(offerMeasure
534
+ ? [{ value: "measure" as CreateKind, label: "Metric" }]
535
  : []),
536
  ].filter((r) => !needle || r.label.toLowerCase().includes(needle));
537
  return (
 
677
  formulaText,
678
  onFormulaText,
679
  formulaError,
680
+ maxValue,
681
+ onMaxValue,
682
+ idPrefix,
683
+ showFormulaHelp = true,
684
  }: {
685
  kind: FieldType | "measure";
686
  fields: Field[];
 
688
  onFormulaText: (v: string) => void;
689
  formulaError: string | null;
690
  maxValue: number;
691
+ onMaxValue: (n: number) => void;
692
+ idPrefix: string;
693
+ showFormulaHelp?: boolean;
694
  }) {
695
  if (kind === "formula") {
696
  // 2026-07-31 (owner item 2): other FORMULA fields are referencable now — evaluation is
 
731
  </div>
732
  {formulaText.trim() !== "" && formulaError ? (
733
  <div className="cg-field-hint cg-formula-error">{formulaError}</div>
734
+ ) : showFormulaHelp ? (
735
+ <div className="cg-field-hint">
736
  Excel-style: numbers, text in quotes, {"{field}"} references, + − × ÷ ^ &amp; ( ),
737
  IF · AND · OR · SUM · AVERAGE · COUNT · MIN · MAX · ROUND(UP/DOWN) · ABS · MOD ·
738
  SQRT · CONCATENATE · LEFT · RIGHT · MID · LEN · TRIM · UPPER · LOWER · PROPER ·
739
  TEXT · VALUE · TODAY · DAYS · YEAR · MONTH · DAY · IFERROR · ISBLANK.
740
  Errors show a blank cell.
741
+ </div>
742
+ ) : null}
743
  </>
744
  );
745
  }
 
820
  const [label, setLabel] = useState("");
821
  /** Whether the user has typed their own name — an auto-suggested measure label must never
822
  * overwrite one, but should keep tracking the measure/window until they do. */
823
+ const [labelTouched, setLabelTouched] = useState(false);
824
+ const [kind, setKind] = useState<CreateKind>("text");
825
+ const [createOptionDrafts, setCreateOptionDrafts] = useState<OptionDraft[]>(() =>
826
+ optionDrafts(DEFAULT_OPTION_LABELS)
827
+ );
828
+ const [createColorCode, setCreateColorCode] = useState(true);
829
  const [measureKey, setMeasureKey] = useState(measures[0]?.key ?? "");
830
  const [measureWindow, setMeasureWindow] = useState<WindowSpec>(DEFAULT_MEASURE_WINDOW);
831
  /** Wave-5 item 9/11 — the create form's formula source and rating star count. */
 
834
  const [swapTo, setSwapTo] = useState("");
835
  /** The "New field" half of Change-field keeps its own name/options — a half-typed insert
836
  * form must not leak into a swap and vice versa. */
837
+ const [swapLabel, setSwapLabel] = useState("");
838
+ const [swapOptionDrafts, setSwapOptionDrafts] = useState<OptionDraft[]>(() =>
839
+ optionDrafts(DEFAULT_OPTION_LABELS)
840
+ );
841
+ const [swapColorCode, setSwapColorCode] = useState(true);
842
  const [swapFormulaText, setSwapFormulaText] = useState("");
843
  const [swapMaxValue, setSwapMaxValue] = useState(5);
844
  /** Item 8c — the period DRAFT. null = untouched (the field's own window shows). Buffered
 
859
  /** Owner item 8 — the Edit pane's TYPE draft plus the per-type config drafts: options
860
  * prefilled from the field (a select retyped to multi select keeps its choices), star
861
  * count from the field's own max, formula source from the field's own source. */
862
+ const [editType, setEditType] = useState<FieldType>(field.type);
863
+ const [editOptionDrafts, setEditOptionDrafts] = useState<OptionDraft[]>(() =>
864
+ optionDrafts(
865
+ choiceOptions(field).length ? choiceOptions(field) : DEFAULT_OPTION_LABELS,
866
+ field.optionColors
867
+ )
868
+ );
869
+ const [editColorCode, setEditColorCode] = useState(field.colorCodeOptions !== false);
870
  const [retypeMaxValue, setRetypeMaxValue] = useState(() => ratingMax(field));
871
  const [editFormulaText, setEditFormulaText] = useState(() =>
872
  typeof field.formula === "string" ? field.formula : ""
 
876
  ? (swapTo.slice(NEW_PREFIX.length) as FieldType)
877
  : null;
878
 
879
+ const createChoice = optionSettings(createOptionDrafts, kind);
880
+ const options = createChoice.options;
881
+ const swapChoice = swapToNewType
882
+ ? optionSettings(swapOptionDrafts, swapToNewType)
883
+ : { options: [] as string[], colors: {} as Record<string, string> };
884
+ const swapNewOptions = swapChoice.options;
885
+ /** Owner item 8 — the Edit pane's parsed choices for the drafted type. */
886
+ const editChoice = optionSettings(editOptionDrafts, editType);
887
+ const editOptions = editChoice.options;
888
 
889
  // Wave-5 item 9, amended 2026-07-31 (owner item 2) — live formula validation for BOTH
890
  // create surfaces. Refs may now name OTHER formula fields (evaluation is topological);
 
937
  (kind !== "measure" || !!chosenMeasure) &&
938
  (kind !== "formula" || formulaCheck.ok);
939
 
940
+ const extraFor = (
941
+ t: CreateKind,
942
+ src: string,
943
+ starCount: number
944
+ ): FieldConfigExtra | undefined => {
945
+ if (t === "formula") return { formula: src.trim() };
946
+ if (t === "rating") return { max: starCount };
947
+ return undefined;
948
+ };
949
+ const optionExtraFor = (
950
+ t: CreateKind,
951
+ colors: Record<string, string>,
952
+ colorCode: boolean
953
+ ): FieldConfigExtra =>
954
+ needsOptions(t)
955
+ ? {
956
+ colorCodeOptions: colorCode,
957
+ ...(Object.keys(colors).length ? { optionColors: colors } : {}),
958
+ }
959
+ : {};
960
+ /** Item 9c — the Scope choice rides the create extras only where the page offers it. */
961
+ const withScope = (e?: FieldConfigExtra): FieldConfigExtra | undefined =>
962
+ scopeChoice ? { ...(e ?? {}), scope: scopeDraft } : e;
963
 
964
  const create = () => {
965
  const clean = effectiveLabel.trim();
 
972
  onClose();
973
  return;
974
  }
975
+ onCreate(clean, kind, position === "end" ? null : field.key, position,
976
+ needsOptions(kind) ? options : undefined, undefined,
977
+ withScope({
978
+ ...extraFor(kind, formulaText, maxValue),
979
+ ...optionExtraFor(kind, createChoice.colors, createColorCode),
980
+ }));
981
  onClose();
982
  };
983
 
 
990
  const createAndSwap = () => {
991
  if (!swapToNewType || !canCreateSwap) return;
992
  onCreateAndSwap(
993
+ swapLabel.trim(),
994
+ swapToNewType,
995
+ needsOptions(swapToNewType) ? swapNewOptions : undefined,
996
+ withScope({
997
+ ...extraFor(swapToNewType, swapFormulaText, swapMaxValue),
998
+ ...optionExtraFor(swapToNewType, swapChoice.colors, swapColorCode),
999
+ })
1000
  );
1001
  onClose();
1002
  };
 
1007
  // stale def and the second reverts the first (label rides extra.label / onFormula's label).
1008
  const cleanRename = renameDraft.trim();
1009
  const editNameDirty = !!onRename && cleanRename !== "" && cleanRename !== field.label;
1010
+ const editOptionsChanged =
1011
+ needsOptions(editType) &&
1012
+ editOptions.join("\n") !== choiceOptions(field).join("\n");
1013
+ const editAppearanceChanged =
1014
+ needsOptions(editType) &&
1015
+ (editColorCode !== (field.colorCodeOptions !== false) ||
1016
+ optionAppearanceSignature(editOptions, editChoice.colors) !==
1017
+ optionAppearanceSignature(choiceOptions(field), field.optionColors));
1018
+ const editStarsChanged = editType === "rating" && retypeMaxValue !== ratingMax(field);
1019
  /** The type half was touched: a different type, or the SAME type with edited choices/stars
1020
  * (the owner's named case — "change the list of the single selections"). */
1021
+ const editRetypeTouched =
1022
+ onRetype != null &&
1023
+ (editType !== field.type || editOptionsChanged || editAppearanceChanged || editStarsChanged);
1024
  const editRetypeValid = !needsOptions(editType) || editOptions.length > 0;
1025
  const editFormulaCheck = useMemo(
1026
  () =>
 
1047
  onRetype(
1048
  editType,
1049
  needsOptions(editType) ? editOptions : undefined,
1050
+ {
1051
+ ...(editType === "rating" ? { max: retypeMaxValue } : {}),
1052
+ ...(needsOptions(editType)
1053
+ ? {
1054
+ colorCodeOptions: editColorCode,
1055
+ ...(Object.keys(editChoice.colors).length
1056
+ ? { optionColors: editChoice.colors }
1057
+ : {}),
1058
+ }
1059
+ : {}),
1060
+ ...(editNameDirty ? { label: cleanRename } : {}),
1061
+ }
1062
  );
1063
  } else if (editFormulaTouched && onFormula) {
1064
  onFormula(editFormulaText.trim(), editNameDirty ? cleanRename : undefined);
 
1089
  JSON.stringify(draftWindow) !== JSON.stringify(currentWindow);
1090
 
1091
  const typeLineBase = field.measure
1092
+ ? "Metric, read-only"
1093
  : field.type === "formula"
1094
  ? "Formula field, computed"
1095
  : field.type === "created_time"
 
1173
  </div>
1174
  {kind === "measure" && (
1175
  <>
1176
+ {/* C-NAME — the row asked "Measure"/"Choose a measure…", which named the
1177
+ INTERNAL concept at the user. What the person is picking is the business
1178
+ number ("Sales", "Gross margin"), so the label says that. */}
1179
  <label>
1180
+ <span>Number</span>
1181
  <select
1182
  className="cg-select"
1183
  value={measureKey}
1184
+ aria-label="Number to summarise"
1185
  onChange={(event) => setMeasureKey(event.target.value)}
1186
  >
1187
+ {!chosenMeasure && <option value="">Choose a number…</option>}
1188
  {measures.map((m) => (
1189
  <option key={m.key} value={m.key}>
1190
  {m.label}
 
1198
  <WindowPicker window={measureWindow} onWindow={setMeasureWindow} />
1199
  </span>
1200
  </label>
1201
+ {/* The helper line now carries what the old label's parenthetical was doing —
1202
+ "(over a period)" — plus an example, because "Metric" alone does not say
1203
+ that the answer moves with the window above it. */}
1204
  <div className="cg-field-hint">
1205
+ A total, average or count over the period you choose — e.g. Sales, last 90
1206
+ days. Computed for every customer, and read-only.
1207
  </div>
1208
  </>
1209
  )}
 
1216
  maxValue={maxValue}
1217
  onMaxValue={setMaxValue}
1218
  idPrefix="cg-create"
1219
+ />
1220
+ {needsOptions(kind) && (
1221
+ <OptionsEditor
1222
+ idPrefix="cg-create-option"
1223
+ drafts={createOptionDrafts}
1224
+ onDrafts={setCreateOptionDrafts}
1225
+ colorCode={createColorCode}
1226
+ onColorCode={setCreateColorCode}
1227
+ type={kind}
1228
+ />
1229
+ )}
1230
  {kind === "user" && (
1231
  <div className="cg-field-hint">
1232
  {userOptions.length
 
1333
  }}
1334
  />
1335
  </label>
1336
+ )}
1337
+ {needsOptions(editType) && (
1338
+ <OptionsEditor
1339
+ idPrefix="cg-edit-option"
1340
+ drafts={editOptionDrafts}
1341
+ onDrafts={setEditOptionDrafts}
1342
+ colorCode={editColorCode}
1343
+ onColorCode={setEditColorCode}
1344
+ type={editType}
1345
+ />
1346
+ )}
1347
  {editType !== field.type && (
1348
  <div className="cg-field-hint">
1349
  Changes {field.label} into a {TYPE_LABELS[editType].toLowerCase()} field,
 
1360
  formulaText={editFormulaText}
1361
  onFormulaText={setEditFormulaText}
1362
  formulaError={editFormulaCheck.ok ? null : editFormulaCheck.error ?? null}
1363
+ maxValue={retypeMaxValue}
1364
+ onMaxValue={setRetypeMaxValue}
1365
+ idPrefix="cg-edit"
1366
+ showFormulaHelp={false}
1367
+ />
1368
  )}
1369
  <div className="cg-form-actions">
1370
  <button
 
1463
  maxValue={swapMaxValue}
1464
  onMaxValue={setSwapMaxValue}
1465
  idPrefix="cg-swap"
1466
+ />
1467
+ {needsOptions(swapToNewType) && (
1468
+ <OptionsEditor
1469
+ idPrefix="cg-swap-option"
1470
+ drafts={swapOptionDrafts}
1471
+ onDrafts={setSwapOptionDrafts}
1472
+ colorCode={swapColorCode}
1473
+ onColorCode={setSwapColorCode}
1474
+ type={swapToNewType}
1475
+ />
1476
+ )}
1477
  {swapToNewType === "user" && (
1478
  <div className="cg-field-hint">
1479
  {userOptions.length
web/src/customer-grid/CustomerGrid.tsx CHANGED
@@ -59,25 +59,27 @@ import type { ChartSpec } from "../viz/chartData";
59
  import { MapView } from "./MapView";
60
  import { lightTheme, STATUS_ROW_THEME, HOVER_ROW_THEME, HOVER_NEUTRAL,
61
  ACTIVE_ROW_NEUTRAL } from "./theme";
62
- import { formatDisplay, ratingCellRenderer } from "./cells";
63
- import { optionTint } from "./choiceColors";
64
- import {
65
- EMPTY_GRID_COPY_PROVENANCE,
66
- markGridCopy,
67
- observeCopyEvent,
68
- planFieldPaste,
69
- } from "./clipboard";
70
  import { cellTipText, expandButtonRect, infoMarkRect, tipLeft } from "./overlayPlacement";
71
  import { AnchoredOverlay } from "./OverlaySurface";
72
  import type { AnchorRect } from "./OverlaySurface";
73
  import { StarIcon } from "./Stars";
74
- import { MAX_FROZEN, choiceOptions, clampFrozenCount, cleanDisplay, formulaOf,
 
75
  isDateFamilyType, isFilterGroup, isGroupableField, isNumericFieldType, isPickType, mayEditField,
76
- isModeFrozen, isUndeletableView, mayEditView, mayToggleViewLock,
77
- ratingMax,
78
- tableMode, uniqueDisplayName } from "./types";
79
  import type {
80
  DisplayMode,
 
81
  Field,
82
  FieldScope,
83
  FieldType,
@@ -88,6 +90,9 @@ import type {
88
  SavedView,
89
  ViewConfig,
90
  } from "./types";
 
 
 
91
  import type { WindowSpec } from "./windows";
92
  import { windowLabel } from "./windows";
93
 
@@ -234,26 +239,26 @@ function dropFieldFromTree(nodes: FilterNode[], key: string): FilterNode[] {
234
  // SVG-source builders with no React in it, which is what lets verify_icons.py
235
  // import it under node and assert the (i) actually contrasts.
236
 
237
- function slugify(label: string): string {
238
  return (
239
  label
240
  .toLowerCase()
241
  .replace(/[^a-z0-9]+/g, "_")
242
  .replace(/^_|_$/g, "")
243
  .slice(0, 28) || "field"
244
- );
245
- }
246
-
247
- interface FieldBuildExtra {
248
- formula?: string;
249
- max?: number;
250
- scope?: FieldScope;
251
- label?: string;
252
- colorCodeOptions?: boolean;
253
- optionColors?: Record<string, string>;
254
- }
255
-
256
- /**
257
  * One constructor for a user-created field, shared by "insert field" and Change-field's
258
  * "New field" half (wave-2 item 5) so the two doors cannot drift. A `multiselect` carries its
259
  * declared options AND `multi: true` — the cell is a comma-joined SET, and the flag is what the
@@ -268,11 +273,11 @@ interface FieldBuildExtra {
268
  * client engine over computedRows (this table's counts are client-mode; a windowed table's
269
  * columns come from the semantic model, so the SQL engine never sees these types).
270
  */
271
- function buildOverlayField(
272
- label: string,
273
- type: FieldType,
274
- options?: string[],
275
- extra?: FieldBuildExtra
276
  ): Field {
277
  const key = `custom_${slugify(label)}_${Math.random().toString(36).slice(2, 7)}`;
278
  if (type === "formula" || type === "created_time") {
@@ -297,16 +302,16 @@ function buildOverlayField(
297
  source: "overlay",
298
  default: true,
299
  custom: true,
300
- agg: ["currency", "int"].includes(type) ? "sum" : undefined,
301
- ...((type === "select" || type === "multiselect") && options?.length ? { options } : {}),
302
- ...((type === "select" || type === "multiselect")
303
- ? {
304
- colorCodeOptions: extra?.colorCodeOptions !== false,
305
- ...(extra?.optionColors && Object.keys(extra.optionColors).length
306
- ? { optionColors: extra.optionColors }
307
- : {}),
308
- }
309
- : {}),
310
  ...(type === "multiselect" ? { multi: true } : {}),
311
  ...(type === "rating" ? { max: extra?.max ?? 5 } : {}),
312
  };
@@ -410,29 +415,29 @@ function CustomerGrid({ scope = "customer" }: { scope?: SurfaceScope } = {}) {
410
  * the local workspace because the remount it guards against destroys any ref. */
411
  const reemittedRef = useRef<Record<string, string>>({});
412
  const initializedKey = useRef<string | null>(null);
413
- const saveTimer = useRef<number | null>(null);
414
- const gridRef = useRef<DataEditorRef>(null);
415
- const gridBoxRef = useRef<HTMLDivElement>(null);
416
- /** Internal clipboard provenance. The browser exposes pasted text, not its source column;
417
- * recording the grid's own copy keeps cross-field paste fail-closed without blocking
418
- * ordinary external text pasted into an editable field. */
419
- const copyProvenanceRef = useRef(EMPTY_GRID_COPY_PROVENANCE);
420
- useEffect(() => {
421
- const onCopy = () => {
422
- // The native copy event follows our grid key event. Preserve that provenance once;
423
- // every later copy (address bar, another app surface, another input) invalidates it.
424
- copyProvenanceRef.current = observeCopyEvent(copyProvenanceRef.current, Date.now());
425
- };
426
- const onWindowBlur = () => {
427
- copyProvenanceRef.current = EMPTY_GRID_COPY_PROVENANCE;
428
- };
429
- document.addEventListener("copy", onCopy, true);
430
- window.addEventListener("blur", onWindowBlur);
431
- return () => {
432
- document.removeEventListener("copy", onCopy, true);
433
- window.removeEventListener("blur", onWindowBlur);
434
- };
435
- }, []);
436
  const [gridSize, setGridSize] = useState({ width: 800, height: 600 });
437
 
438
  const storageKey = payload?.workspace?.storageKey ?? "customer-grid-standalone";
@@ -798,7 +803,11 @@ function CustomerGrid({ scope = "customer" }: { scope?: SurfaceScope } = {}) {
798
  serverWindowed,
799
  measureSets,
800
  cohortSets,
801
- today
 
 
 
 
802
  );
803
 
804
  // Owner item 8 — the DISPLAY cap. The pipeline above still ran over the whole book (counts,
@@ -1232,7 +1241,7 @@ function CustomerGrid({ scope = "customer" }: { scope?: SurfaceScope } = {}) {
1232
  },
1233
  [displayRows, visibleCols, fieldByKey, patchOverlay, canEditField]
1234
  );
1235
- const validateCell = useCallback(
1236
  (cell: Item): boolean => {
1237
  const row = displayRows[cell[1]];
1238
  const column = visibleCols[cell[0]];
@@ -1249,36 +1258,36 @@ function CustomerGrid({ scope = "customer" }: { scope?: SurfaceScope } = {}) {
1249
  field.type !== "status"
1250
  );
1251
  },
1252
- [displayRows, visibleCols, fieldByKey, canEditField]
1253
- );
1254
- const onGridPaste = useCallback(
1255
- (target: Item, values: readonly (readonly string[])[]): boolean => {
1256
- const column = visibleCols[target[0]];
1257
- const field = column ? fieldByKey.get(column.id!) : undefined;
1258
- if (!field) return false;
1259
- const targetPids = values.map((_, offset) => {
1260
- const row = displayRows[target[1] + offset];
1261
- return row?.kind === "data" ? row.record.pid : null;
1262
- });
1263
- const patches = planFieldPaste({
1264
- field,
1265
- sourceFieldKey: copyProvenanceRef.current.fieldKey,
1266
- editable: canEditField(field),
1267
- values,
1268
- targetPids,
1269
- allowedChoices: statusValues[field.key] ?? choiceOptions(field),
1270
- });
1271
- if (!patches) return false;
1272
- for (const patch of patches)
1273
- patchOverlay(patch.pid, { [field.key]: patch.value });
1274
- // We handled the write ourselves. Returning false tells glide not to run its cell
1275
- // renderers' generic paste path (Bubble/rating renderers cannot enforce this contract).
1276
- return false;
1277
- },
1278
- [visibleCols, fieldByKey, canEditField, statusValues, displayRows, patchOverlay]
1279
- );
1280
-
1281
- const openHeaderMenu = useCallback(
1282
  (column: number, bounds: Rectangle) => {
1283
  const definition = visibleCols[column];
1284
  if (!definition?.id) return;
@@ -1304,20 +1313,20 @@ function CustomerGrid({ scope = "customer" }: { scope?: SurfaceScope } = {}) {
1304
  },
1305
  [openHeaderMenu]
1306
  );
1307
- const onGridKeyDown = useCallback(
1308
- (event: GridKeyEventArgs) => {
1309
- if (
1310
- event.key.toLowerCase() === "c" &&
1311
- (event.ctrlKey || event.metaKey) &&
1312
- !event.altKey
1313
- ) {
1314
- const range = gridSelection.current?.range;
1315
- const source = range?.width === 1 ? visibleCols[range.x] : undefined;
1316
- copyProvenanceRef.current = markGridCopy(source?.id ?? null, Date.now());
1317
- // Do not prevent default: glide still owns serialization and the OS clipboard write.
1318
- return;
1319
- }
1320
- // Owner item 5 (2026-07-31) — EXCEL-GRADE ENTER. When no editor is open (an open overlay
1321
  // editor swallows its own keys before the canvas sees them), Enter moves the active cell
1322
  // DOWN one record and Shift+Enter moves UP — never opening the record drawer, which is
1323
  // what made keyboard runs down a column "really clunky". Glide's own overlay editor
@@ -1406,6 +1415,37 @@ function CustomerGrid({ scope = "customer" }: { scope?: SurfaceScope } = {}) {
1406
  emitHostEvent({ id: eventId("view"), type: "view_upsert", view });
1407
  }, []);
1408
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1409
  const selectView = useCallback(
1410
  (id: string) => {
1411
  const current = views.find((view) => view.id === activeViewId);
@@ -1428,9 +1468,9 @@ function CustomerGrid({ scope = "customer" }: { scope?: SurfaceScope } = {}) {
1428
  },
1429
  [views, activeViewId, config, persistView, fields]
1430
  );
1431
- const createView = useCallback(
1432
- (name: string, mode: DisplayMode, permissions: ViewPermissions) => {
1433
- const acceptedName = uniqueDisplayName(name, views.map((view) => view.name));
1434
  // I14 — the flyout picked the display mode, so the new view is born in it.
1435
  // cleanDisplay collapses a ref-less grid to ABSENT, so picking "Grid" produces exactly
1436
  // the shape every pre-wave-9 view has (no churn), while the calendar/kanban/map field
@@ -1439,9 +1479,9 @@ function CustomerGrid({ scope = "customer" }: { scope?: SurfaceScope } = {}) {
1439
  ...config,
1440
  display: cleanDisplay({ ...(config.display ?? {}), mode }),
1441
  };
1442
- const view: SavedView = {
1443
- id: nextViewId(),
1444
- name: acceptedName,
1445
  kind: "custom",
1446
  config: nextConfig,
1447
  // I17 (C4) — sent EXPLICITLY. Absent on create means 'personal' host-side, so a user
@@ -1457,19 +1497,19 @@ function CustomerGrid({ scope = "customer" }: { scope?: SurfaceScope } = {}) {
1457
  setConfig(nextConfig);
1458
  setSaveState("saved");
1459
  },
1460
- [config, persistView, views]
1461
- );
1462
- const renameView = useCallback(
1463
- (id: string, name: string) => {
1464
- const view = views.find((item) => item.id === id);
1465
- if (view) {
1466
- const acceptedName = uniqueDisplayName(
1467
- name,
1468
- views.filter((item) => item.id !== id).map((item) => item.name)
1469
- );
1470
- persistView({ ...view, name: acceptedName });
1471
- }
1472
- },
1473
  [views, persistView]
1474
  );
1475
  /**
@@ -1503,13 +1543,13 @@ function CustomerGrid({ scope = "customer" }: { scope?: SurfaceScope } = {}) {
1503
  (id: string) => {
1504
  const source = views.find((view) => view.id === id);
1505
  if (!source) return;
1506
- const copy: SavedView = {
1507
- ...source,
1508
- id: nextViewId(),
1509
- name: uniqueDisplayName(
1510
- `${source.name} copy`,
1511
- views.map((view) => view.name)
1512
- ),
1513
  kind: "custom",
1514
  locked: false,
1515
  // I17 (C4) — a COPY IS THE DUPLICATOR'S OWN, PERSONAL view. Ruled, not inherited:
@@ -1739,7 +1779,8 @@ function CustomerGrid({ scope = "customer" }: { scope?: SurfaceScope } = {}) {
1739
  continue;
1740
  }
1741
  if (pendingMeasures(view.config.filters, measureSets) > 0) {
1742
- skipped.push({ name: view.name, why: "a measure condition has no answer yet" });
 
1743
  continue;
1744
  }
1745
  counted += 1;
@@ -1891,44 +1932,81 @@ function CustomerGrid({ scope = "customer" }: { scope?: SurfaceScope } = {}) {
1891
  // stamped so a lagged echo cannot claw it back at the next remount. Item 9c: `scope` rides
1892
  // the EVENT at create time only; the def itself carries `scope: 'cohort'` so the echo is
1893
  // byte-stable ('global' stays absent — the host normalizes them to one shape).
1894
- const scopeChoice = payload?.workspace?.scopeChoice === true;
1895
- const saveField = useCallback(
1896
- (field: Field, scope?: FieldScope) => {
1897
- const requestId = eventId("field");
1898
- const accepted: Field = {
1899
- ...field,
1900
- label: uniqueDisplayName(
1901
- field.label,
1902
- fields.filter((item) => item.key !== field.key).map((item) => item.label)
1903
- ),
1904
- editRequestId: requestId,
1905
- };
1906
- delete accepted.labelCorrectedFrom;
1907
- delete accepted.labelCorrectionId;
1908
- stampFieldEdit(accepted.key);
1909
- setFields((current) =>
1910
- current.some((item) => item.key === accepted.key)
1911
- ? current.map((item) => (item.key === accepted.key ? accepted : item))
1912
- : [...current, accepted]
1913
- );
1914
- emitHostEvent({
1915
- id: requestId,
1916
- type: "field_upsert",
1917
- field: accepted,
1918
- ...(scope ? { scope } : {}),
1919
- });
1920
- },
1921
- [stampFieldEdit, fields]
1922
- );
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1923
  const createField = useCallback(
1924
  (
1925
  label: string,
1926
  type: FieldType,
1927
  anchorKey: string | null,
1928
  side: "left" | "right" | "end",
1929
- options?: string[],
1930
- measureSpec?: { key: string; window: WindowSpec },
1931
- extra?: FieldBuildExtra
1932
  ) => {
1933
  const scope = scopeChoice ? extra?.scope : undefined;
1934
  const scoped = scope === "cohort" ? ({ scope: "cohort" } as const) : {};
@@ -2026,10 +2104,10 @@ function CustomerGrid({ scope = "customer" }: { scope?: SurfaceScope } = {}) {
2026
  const createAndSwapField = useCallback(
2027
  (
2028
  oldKey: string,
2029
- label: string,
2030
- type: FieldType,
2031
- options?: string[],
2032
- extra?: FieldBuildExtra
2033
  ) => {
2034
  const scope = scopeChoice ? extra?.scope : undefined;
2035
  const field = {
@@ -2053,11 +2131,11 @@ function CustomerGrid({ scope = "customer" }: { scope?: SurfaceScope } = {}) {
2053
  const retypeField = useCallback(
2054
  (
2055
  key: string,
2056
- type: FieldType,
2057
- options?: string[],
2058
  // `label` (owner item 8): rename+retype leave the Edit pane as ONE upsert — two
2059
  // sequential emits would each read the stale def and revert the other.
2060
- extra?: FieldBuildExtra
2061
  ) => {
2062
  const old = fieldByKey.get(key);
2063
  if (!old?.custom || old.source !== "overlay") return;
@@ -2079,18 +2157,18 @@ function CustomerGrid({ scope = "customer" }: { scope?: SurfaceScope } = {}) {
2079
  ...(old.createdBy ? { createdBy: old.createdBy } : {}),
2080
  ...(old.permissions ? { permissions: old.permissions } : {}),
2081
  ...(keepFormat ? { format: old.format } : {}),
2082
- ...((type === "select" || type === "multiselect") && options?.length
2083
- ? { options }
2084
- : {}),
2085
- ...((type === "select" || type === "multiselect")
2086
- ? {
2087
- colorCodeOptions: extra?.colorCodeOptions !== false,
2088
- ...(extra?.optionColors && Object.keys(extra.optionColors).length
2089
- ? { optionColors: extra.optionColors }
2090
- : {}),
2091
- }
2092
- : {}),
2093
- ...(type === "multiselect" ? { multi: true } : {}),
2094
  ...(type === "rating" ? { max: extra?.max ?? 5 } : {}),
2095
  };
2096
  saveField(next);
@@ -2106,24 +2184,24 @@ function CustomerGrid({ scope = "customer" }: { scope?: SurfaceScope } = {}) {
2106
  * source's), and copies overlay VALUES for `custom_` sources; those values arrive with the
2107
  * next payload, so the clone's cells are blank for exactly one round trip.
2108
  */
2109
- const duplicateField = useCallback(
2110
- (source: Field) => {
2111
- const prefix = source.key.startsWith("measure_") ? "measure_" : "custom_";
2112
- const label = uniqueDisplayName(
2113
- `${source.label} copy`,
2114
- fields.map((field) => field.label)
2115
- );
2116
- const key = `${prefix}${slugify(label)}_${Math.random().toString(36).slice(2, 7)}`;
2117
- const requestId = eventId("fielddup");
2118
- const clone: Field = { ...source, key, label, editRequestId: requestId };
2119
- delete clone.createdBy;
2120
- delete clone.permissions;
2121
- delete clone.labelCorrectedFrom;
2122
- delete clone.labelCorrectionId;
2123
  stampFieldEdit(key);
2124
  setFields((current) => [...current, clone]);
2125
- emitHostEvent({
2126
- id: requestId,
2127
  type: "field_duplicate",
2128
  sourceKey: source.key,
2129
  key,
@@ -2134,8 +2212,8 @@ function CustomerGrid({ scope = "customer" }: { scope?: SurfaceScope } = {}) {
2134
  });
2135
  insertColumn(key, source.key, "right");
2136
  },
2137
- [insertColumn, scopeChoice, stampFieldEdit, fields]
2138
- );
2139
 
2140
  /**
2141
  * Wave-2 item 8c — change the PERIOD of a measure-carrying column (user-created `measure_*`
@@ -2326,6 +2404,55 @@ function CustomerGrid({ scope = "customer" }: { scope?: SurfaceScope } = {}) {
2326
  },
2327
  [config, updateConfig]
2328
  );
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2329
  // The calendar's date field: the view's pick when it is still a real date-family field,
2330
  // else `last_order`, else the first date-family field. The kanban's stack field: status or
2331
  // single-select ONLY (a multiselect card in two columns at once is a count lie — contract).
@@ -2391,7 +2518,11 @@ function CustomerGrid({ scope = "customer" }: { scope?: SurfaceScope } = {}) {
2391
  displayMode !== "calendar" &&
2392
  displayMode !== "kanban" &&
2393
  displayMode !== "map" &&
2394
- displayMode !== "chart"
 
 
 
 
2395
  )
2396
  return [];
2397
  const seen = new Set<number>();
@@ -2404,6 +2535,55 @@ function CustomerGrid({ scope = "customer" }: { scope?: SurfaceScope } = {}) {
2404
  }
2405
  return out;
2406
  }, [displayMode, visibleRows, overlayEdits]);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2407
  const kanbanCanMove =
2408
  !!kanbanField && kanbanField.type === "select" && canEditField(kanbanField);
2409
  const kanbanReason = !kanbanField
@@ -2471,6 +2651,18 @@ function CustomerGrid({ scope = "customer" }: { scope?: SurfaceScope } = {}) {
2471
  sizeField={mapSizeField}
2472
  sizeChoices={sizeFieldChoices}
2473
  onPickField={setDisplayField}
 
 
 
 
 
 
 
 
 
 
 
 
2474
  />
2475
  );
2476
  const pickerField = picker ? fieldByKey.get(picker.fieldKey) : undefined;
@@ -2612,6 +2804,8 @@ function CustomerGrid({ scope = "customer" }: { scope?: SurfaceScope } = {}) {
2612
  ) : (
2613
  !hideViews && (
2614
  <ViewSidebar
 
 
2615
  views={views}
2616
  activeViewId={activeViewId}
2617
  saveState={saveState}
@@ -2709,6 +2903,12 @@ function CustomerGrid({ scope = "customer" }: { scope?: SurfaceScope } = {}) {
2709
  )}
2710
  <main className="cg-main">
2711
  <Toolbar
 
 
 
 
 
 
2712
  fields={fields}
2713
  visible={visible}
2714
  lockedKey={lockedKey}
@@ -2792,10 +2992,10 @@ function CustomerGrid({ scope = "customer" }: { scope?: SurfaceScope } = {}) {
2792
  getRowThemeOverride={getRowThemeOverride}
2793
  onItemHovered={onItemHovered}
2794
  onCellClicked={onCellClicked}
2795
- onCellActivated={onCellActivated}
2796
- onCellEdited={onCellEdited}
2797
- onPaste={onGridPaste}
2798
- validateCell={validateCell}
2799
  onColumnResize={onColumnResize}
2800
  onColumnMoved={onColumnMoved}
2801
  onColumnProposeMove={onColumnProposeMove}
@@ -2847,14 +3047,7 @@ function CustomerGrid({ scope = "customer" }: { scope?: SurfaceScope } = {}) {
2847
  visibleKeys={visibleKeys}
2848
  titleKey={lockedKey}
2849
  onOpen={setDetailPid}
2850
- onToggleGroup={(groupKey) =>
2851
- setCollapsed((current) => {
2852
- const next = new Set(current);
2853
- if (next.has(groupKey)) next.delete(groupKey);
2854
- else next.add(groupKey);
2855
- return next;
2856
- })
2857
- }
2858
  />
2859
  )}
2860
  {displayMode === "calendar" &&
@@ -2864,6 +3057,10 @@ function CustomerGrid({ scope = "customer" }: { scope?: SurfaceScope } = {}) {
2864
  field={calendarField}
2865
  today={today}
2866
  titleKey={lockedKey}
 
 
 
 
2867
  onOpen={setDetailPid}
2868
  />
2869
  ) : (
@@ -2877,15 +3074,12 @@ function CustomerGrid({ scope = "customer" }: { scope?: SurfaceScope } = {}) {
2877
  rows={modeDataRows}
2878
  field={kanbanField}
2879
  fieldByKey={fieldByKey}
2880
- cardKeys={visibleKeys
2881
- .filter((k) => k !== lockedKey && k !== kanbanField.key)
2882
- .slice(0, 3)}
2883
  titleKey={lockedKey}
2884
  canMove={kanbanCanMove}
2885
  readOnlyReason={kanbanReason}
2886
- onMove={(pid, value) =>
2887
- patchOverlay(pid, { [kanbanField.key]: value })
2888
- }
2889
  onOpen={setDetailPid}
2890
  />
2891
  ) : (
@@ -2908,6 +3102,20 @@ function CustomerGrid({ scope = "customer" }: { scope?: SurfaceScope } = {}) {
2908
  onCharts={setCharts}
2909
  />
2910
  )}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2911
  {/* Wave-7 item W11c (C3) — Map is a VIEW: same pipeline rows, pins for rows
2912
  with host-supplied coords, click-through to the same record detail, and
2913
  an honest no-location chip. */}
@@ -3428,7 +3636,7 @@ function CustomerGrid({ scope = "customer" }: { scope?: SurfaceScope } = {}) {
3428
  )}
3429
  <div className="cg-pick-list" aria-multiselectable={pickerMulti || undefined}>
3430
  {pickerChoices.map((choice) => {
3431
- const tint = optionTint(pickerField, choice);
3432
  const on = pickerMulti
3433
  ? pickerParts.includes(choice)
3434
  : pickerValue === choice;
@@ -3456,10 +3664,10 @@ function CustomerGrid({ scope = "customer" }: { scope?: SurfaceScope } = {}) {
3456
  closePicker();
3457
  }}
3458
  >
3459
- <span
3460
- className="cg-pick-pill"
3461
- style={tint ? { background: tint.bg, color: tint.fg } : undefined}
3462
- >
3463
  {choice}
3464
  </span>
3465
  </button>
@@ -3509,6 +3717,14 @@ function CustomerGrid({ scope = "customer" }: { scope?: SurfaceScope } = {}) {
3509
  onPrev={() => go(-1)}
3510
  onNext={() => go(1)}
3511
  onClose={() => setDetailPid(null)}
 
 
 
 
 
 
 
 
3512
  docs={payload?.docs?.[String(detailPid)] ?? []}
3513
  docPayload={payload?.docPayload}
3514
  // C5 — documents ride the ordinary event log. The host answers a fetch
 
59
  import { MapView } from "./MapView";
60
  import { lightTheme, STATUS_ROW_THEME, HOVER_ROW_THEME, HOVER_NEUTRAL,
61
  ACTIVE_ROW_NEUTRAL } from "./theme";
62
+ import { formatDisplay, ratingCellRenderer } from "./cells";
63
+ import { optionTint } from "./choiceColors";
64
+ import {
65
+ EMPTY_GRID_COPY_PROVENANCE,
66
+ markGridCopy,
67
+ observeCopyEvent,
68
+ planFieldPaste,
69
+ } from "./clipboard";
70
  import { cellTipText, expandButtonRect, infoMarkRect, tipLeft } from "./overlayPlacement";
71
  import { AnchoredOverlay } from "./OverlaySurface";
72
  import type { AnchorRect } from "./OverlaySurface";
73
  import { StarIcon } from "./Stars";
74
+ import { MAX_CALENDAR_METRICS,
75
+ MAX_FROZEN, choiceOptions, clampFrozenCount, cleanDisplay, formulaOf,
76
  isDateFamilyType, isFilterGroup, isGroupableField, isNumericFieldType, isPickType, mayEditField,
77
+ isModeFrozen, isUndeletableView, mayEditView, mayToggleViewLock,
78
+ ratingMax,
79
+ tableMode, uniqueDisplayName } from "./types";
80
  import type {
81
  DisplayMode,
82
+ DisplaySpec,
83
  Field,
84
  FieldScope,
85
  FieldType,
 
90
  SavedView,
91
  ViewConfig,
92
  } from "./types";
93
+ // Item 7 (C-TS). Default-exported because it is a leaf VIEW like MapView, and because RECORD
94
+ // imports the same default for the record-detail Insights tab (C-EMBED).
95
+ import TimeSeriesPanel from "./TimeSeriesPanel";
96
  import type { WindowSpec } from "./windows";
97
  import { windowLabel } from "./windows";
98
 
 
239
  // SVG-source builders with no React in it, which is what lets verify_icons.py
240
  // import it under node and assert the (i) actually contrasts.
241
 
242
+ function slugify(label: string): string {
243
  return (
244
  label
245
  .toLowerCase()
246
  .replace(/[^a-z0-9]+/g, "_")
247
  .replace(/^_|_$/g, "")
248
  .slice(0, 28) || "field"
249
+ );
250
+ }
251
+
252
+ interface FieldBuildExtra {
253
+ formula?: string;
254
+ max?: number;
255
+ scope?: FieldScope;
256
+ label?: string;
257
+ colorCodeOptions?: boolean;
258
+ optionColors?: Record<string, string>;
259
+ }
260
+
261
+ /**
262
  * One constructor for a user-created field, shared by "insert field" and Change-field's
263
  * "New field" half (wave-2 item 5) so the two doors cannot drift. A `multiselect` carries its
264
  * declared options AND `multi: true` — the cell is a comma-joined SET, and the flag is what the
 
273
  * client engine over computedRows (this table's counts are client-mode; a windowed table's
274
  * columns come from the semantic model, so the SQL engine never sees these types).
275
  */
276
+ function buildOverlayField(
277
+ label: string,
278
+ type: FieldType,
279
+ options?: string[],
280
+ extra?: FieldBuildExtra
281
  ): Field {
282
  const key = `custom_${slugify(label)}_${Math.random().toString(36).slice(2, 7)}`;
283
  if (type === "formula" || type === "created_time") {
 
302
  source: "overlay",
303
  default: true,
304
  custom: true,
305
+ agg: ["currency", "int"].includes(type) ? "sum" : undefined,
306
+ ...((type === "select" || type === "multiselect") && options?.length ? { options } : {}),
307
+ ...((type === "select" || type === "multiselect")
308
+ ? {
309
+ colorCodeOptions: extra?.colorCodeOptions !== false,
310
+ ...(extra?.optionColors && Object.keys(extra.optionColors).length
311
+ ? { optionColors: extra.optionColors }
312
+ : {}),
313
+ }
314
+ : {}),
315
  ...(type === "multiselect" ? { multi: true } : {}),
316
  ...(type === "rating" ? { max: extra?.max ?? 5 } : {}),
317
  };
 
415
  * the local workspace because the remount it guards against destroys any ref. */
416
  const reemittedRef = useRef<Record<string, string>>({});
417
  const initializedKey = useRef<string | null>(null);
418
+ const saveTimer = useRef<number | null>(null);
419
+ const gridRef = useRef<DataEditorRef>(null);
420
+ const gridBoxRef = useRef<HTMLDivElement>(null);
421
+ /** Internal clipboard provenance. The browser exposes pasted text, not its source column;
422
+ * recording the grid's own copy keeps cross-field paste fail-closed without blocking
423
+ * ordinary external text pasted into an editable field. */
424
+ const copyProvenanceRef = useRef(EMPTY_GRID_COPY_PROVENANCE);
425
+ useEffect(() => {
426
+ const onCopy = () => {
427
+ // The native copy event follows our grid key event. Preserve that provenance once;
428
+ // every later copy (address bar, another app surface, another input) invalidates it.
429
+ copyProvenanceRef.current = observeCopyEvent(copyProvenanceRef.current, Date.now());
430
+ };
431
+ const onWindowBlur = () => {
432
+ copyProvenanceRef.current = EMPTY_GRID_COPY_PROVENANCE;
433
+ };
434
+ document.addEventListener("copy", onCopy, true);
435
+ window.addEventListener("blur", onWindowBlur);
436
+ return () => {
437
+ document.removeEventListener("copy", onCopy, true);
438
+ window.removeEventListener("blur", onWindowBlur);
439
+ };
440
+ }, []);
441
  const [gridSize, setGridSize] = useState({ width: 800, height: 600 });
442
 
443
  const storageKey = payload?.workspace?.storageKey ?? "customer-grid-standalone";
 
803
  serverWindowed,
804
  measureSets,
805
  cohortSets,
806
+ today,
807
+ // Item 12 (C-LOCK) — the 14th positional, RECORD's engine input. The lock intersects
808
+ // FIRST, so everything downstream (conditions, memberPids, the ranking domain) operates
809
+ // inside the cohort. Absent = today's behaviour exactly.
810
+ config.cohortLock
811
  );
812
 
813
  // Owner item 8 — the DISPLAY cap. The pipeline above still ran over the whole book (counts,
 
1241
  },
1242
  [displayRows, visibleCols, fieldByKey, patchOverlay, canEditField]
1243
  );
1244
+ const validateCell = useCallback(
1245
  (cell: Item): boolean => {
1246
  const row = displayRows[cell[1]];
1247
  const column = visibleCols[cell[0]];
 
1258
  field.type !== "status"
1259
  );
1260
  },
1261
+ [displayRows, visibleCols, fieldByKey, canEditField]
1262
+ );
1263
+ const onGridPaste = useCallback(
1264
+ (target: Item, values: readonly (readonly string[])[]): boolean => {
1265
+ const column = visibleCols[target[0]];
1266
+ const field = column ? fieldByKey.get(column.id!) : undefined;
1267
+ if (!field) return false;
1268
+ const targetPids = values.map((_, offset) => {
1269
+ const row = displayRows[target[1] + offset];
1270
+ return row?.kind === "data" ? row.record.pid : null;
1271
+ });
1272
+ const patches = planFieldPaste({
1273
+ field,
1274
+ sourceFieldKey: copyProvenanceRef.current.fieldKey,
1275
+ editable: canEditField(field),
1276
+ values,
1277
+ targetPids,
1278
+ allowedChoices: statusValues[field.key] ?? choiceOptions(field),
1279
+ });
1280
+ if (!patches) return false;
1281
+ for (const patch of patches)
1282
+ patchOverlay(patch.pid, { [field.key]: patch.value });
1283
+ // We handled the write ourselves. Returning false tells glide not to run its cell
1284
+ // renderers' generic paste path (Bubble/rating renderers cannot enforce this contract).
1285
+ return false;
1286
+ },
1287
+ [visibleCols, fieldByKey, canEditField, statusValues, displayRows, patchOverlay]
1288
+ );
1289
+
1290
+ const openHeaderMenu = useCallback(
1291
  (column: number, bounds: Rectangle) => {
1292
  const definition = visibleCols[column];
1293
  if (!definition?.id) return;
 
1313
  },
1314
  [openHeaderMenu]
1315
  );
1316
+ const onGridKeyDown = useCallback(
1317
+ (event: GridKeyEventArgs) => {
1318
+ if (
1319
+ event.key.toLowerCase() === "c" &&
1320
+ (event.ctrlKey || event.metaKey) &&
1321
+ !event.altKey
1322
+ ) {
1323
+ const range = gridSelection.current?.range;
1324
+ const source = range?.width === 1 ? visibleCols[range.x] : undefined;
1325
+ copyProvenanceRef.current = markGridCopy(source?.id ?? null, Date.now());
1326
+ // Do not prevent default: glide still owns serialization and the OS clipboard write.
1327
+ return;
1328
+ }
1329
+ // Owner item 5 (2026-07-31) — EXCEL-GRADE ENTER. When no editor is open (an open overlay
1330
  // editor swallows its own keys before the canvas sees them), Enter moves the active cell
1331
  // DOWN one record and Shift+Enter moves UP — never opening the record drawer, which is
1332
  // what made keyboard runs down a column "really clunky". Glide's own overlay editor
 
1415
  emitHostEvent({ id: eventId("view"), type: "view_upsert", view });
1416
  }, []);
1417
 
1418
+ /**
1419
+ * Item 12 (C-LOCK) — set or clear a view's cohort lock, from the rail's menu.
1420
+ *
1421
+ * Works on ANY view, not only the active one, which is why it goes through `persistView`
1422
+ * rather than `updateConfig`: the rail's menu opens on whichever row you clicked. When the
1423
+ * target IS the active view, the live `config` must move too, or the table keeps showing the
1424
+ * old row set until the next select and the lock reads as ignored.
1425
+ *
1426
+ * Clearing DELETES the key rather than storing null — the no-churn rule every other optional
1427
+ * config member follows, and the shape `_clean_display`'s sibling validator expects.
1428
+ */
1429
+ const onViewCohortLock = useCallback(
1430
+ (viewId: string, cohortId: string | null) => {
1431
+ const target = views.find((v) => v.id === viewId);
1432
+ if (!target) return;
1433
+ const nextConfig = { ...target.config };
1434
+ if (cohortId) nextConfig.cohortLock = cohortId;
1435
+ else delete (nextConfig as Record<string, unknown>).cohortLock;
1436
+ persistView({ ...target, config: nextConfig });
1437
+ if (viewId === activeViewId) {
1438
+ setConfig((live) => {
1439
+ const next = { ...live };
1440
+ if (cohortId) next.cohortLock = cohortId;
1441
+ else delete (next as Record<string, unknown>).cohortLock;
1442
+ return next;
1443
+ });
1444
+ }
1445
+ },
1446
+ [views, activeViewId, persistView]
1447
+ );
1448
+
1449
  const selectView = useCallback(
1450
  (id: string) => {
1451
  const current = views.find((view) => view.id === activeViewId);
 
1468
  },
1469
  [views, activeViewId, config, persistView, fields]
1470
  );
1471
+ const createView = useCallback(
1472
+ (name: string, mode: DisplayMode, permissions: ViewPermissions) => {
1473
+ const acceptedName = uniqueDisplayName(name, views.map((view) => view.name));
1474
  // I14 — the flyout picked the display mode, so the new view is born in it.
1475
  // cleanDisplay collapses a ref-less grid to ABSENT, so picking "Grid" produces exactly
1476
  // the shape every pre-wave-9 view has (no churn), while the calendar/kanban/map field
 
1479
  ...config,
1480
  display: cleanDisplay({ ...(config.display ?? {}), mode }),
1481
  };
1482
+ const view: SavedView = {
1483
+ id: nextViewId(),
1484
+ name: acceptedName,
1485
  kind: "custom",
1486
  config: nextConfig,
1487
  // I17 (C4) — sent EXPLICITLY. Absent on create means 'personal' host-side, so a user
 
1497
  setConfig(nextConfig);
1498
  setSaveState("saved");
1499
  },
1500
+ [config, persistView, views]
1501
+ );
1502
+ const renameView = useCallback(
1503
+ (id: string, name: string) => {
1504
+ const view = views.find((item) => item.id === id);
1505
+ if (view) {
1506
+ const acceptedName = uniqueDisplayName(
1507
+ name,
1508
+ views.filter((item) => item.id !== id).map((item) => item.name)
1509
+ );
1510
+ persistView({ ...view, name: acceptedName });
1511
+ }
1512
+ },
1513
  [views, persistView]
1514
  );
1515
  /**
 
1543
  (id: string) => {
1544
  const source = views.find((view) => view.id === id);
1545
  if (!source) return;
1546
+ const copy: SavedView = {
1547
+ ...source,
1548
+ id: nextViewId(),
1549
+ name: uniqueDisplayName(
1550
+ `${source.name} copy`,
1551
+ views.map((view) => view.name)
1552
+ ),
1553
  kind: "custom",
1554
  locked: false,
1555
  // I17 (C4) — a COPY IS THE DUPLICATOR'S OWN, PERSONAL view. Ruled, not inherited:
 
1779
  continue;
1780
  }
1781
  if (pendingMeasures(view.config.filters, measureSets) > 0) {
1782
+ // C-NAME (item 9) — user-facing, so it says "metric" like every other surface.
1783
+ skipped.push({ name: view.name, why: "a metric condition has no answer yet" });
1784
  continue;
1785
  }
1786
  counted += 1;
 
1932
  // stamped so a lagged echo cannot claw it back at the next remount. Item 9c: `scope` rides
1933
  // the EVENT at create time only; the def itself carries `scope: 'cohort'` so the echo is
1934
  // byte-stable ('global' stays absent — the host normalizes them to one shape).
1935
+ const scopeChoice = payload?.workspace?.scopeChoice === true;
1936
+ /**
1937
+ * Item 12 (C-LOCK) — the Filter banner's copy for a cohort-locked view.
1938
+ *
1939
+ * `undefined` when the view is not locked. When it IS locked but the set is not in `lists`,
1940
+ * this returns an EMPTY object: the banner must still appear (the reader is looking at a
1941
+ * narrowed table and deserves to know why), but with no name and no count, because a set we
1942
+ * were given no membership for is a set we must not describe. RECORD's banner reads that
1943
+ * absence and says "locked to a set you cannot see".
1944
+ *
1945
+ * The count is the cohort's OWN size, not the number of rows on screen — the conditions
1946
+ * narrow within the lock, so the two differ and the banner is stating the lock.
1947
+ */
1948
+ const cohortLockChip = useMemo(() => {
1949
+ const id = config.cohortLock;
1950
+ if (!id) return undefined;
1951
+ const set = lists.find((l) => l.id === id);
1952
+ if (!set) return {};
1953
+ return { name: set.name, count: set.pids?.length ?? 0 };
1954
+ }, [config.cohortLock, lists]);
1955
+ // (Setting/clearing the lock lives in `onViewCohortLock` above — the rail's menu operates on
1956
+ // whichever view you clicked, not necessarily the active one, so it goes through
1957
+ // `persistView` and only touches the live `config` when the two are the same view.)
1958
+ /**
1959
+ * Item 5 / contract C-LAYOUT — this user's record-detail field order, for RECORD's
1960
+ * `RecordDetail` (they asked for exactly these two props in the wave mailbox).
1961
+ *
1962
+ * Read straight off the workspace stratum the host echoes, and emitted back as the
1963
+ * `record_layout` event HOST landed. Deliberately NOT reconciled or optimistically merged
1964
+ * here: the event returns False host-side (an autosave hot path like `view_upsert`), so
1965
+ * there is no rerun to race, and `RecordDetail` holds the live order while a drag is in
1966
+ * flight. Nothing else in the grid reads it — the order is the MODAL's, never the grid's
1967
+ * `config.order`.
1968
+ */
1969
+ const recordLayout = payload?.workspace?.recordLayout?.order;
1970
+ const onRecordLayout = useCallback((order: string[]) => {
1971
+ emitHostEvent({ id: eventId("rlayout"), type: "record_layout", order });
1972
+ }, []);
1973
+ const saveField = useCallback(
1974
+ (field: Field, scope?: FieldScope) => {
1975
+ const requestId = eventId("field");
1976
+ const accepted: Field = {
1977
+ ...field,
1978
+ label: uniqueDisplayName(
1979
+ field.label,
1980
+ fields.filter((item) => item.key !== field.key).map((item) => item.label)
1981
+ ),
1982
+ editRequestId: requestId,
1983
+ };
1984
+ delete accepted.labelCorrectedFrom;
1985
+ delete accepted.labelCorrectionId;
1986
+ stampFieldEdit(accepted.key);
1987
+ setFields((current) =>
1988
+ current.some((item) => item.key === accepted.key)
1989
+ ? current.map((item) => (item.key === accepted.key ? accepted : item))
1990
+ : [...current, accepted]
1991
+ );
1992
+ emitHostEvent({
1993
+ id: requestId,
1994
+ type: "field_upsert",
1995
+ field: accepted,
1996
+ ...(scope ? { scope } : {}),
1997
+ });
1998
+ },
1999
+ [stampFieldEdit, fields]
2000
+ );
2001
  const createField = useCallback(
2002
  (
2003
  label: string,
2004
  type: FieldType,
2005
  anchorKey: string | null,
2006
  side: "left" | "right" | "end",
2007
+ options?: string[],
2008
+ measureSpec?: { key: string; window: WindowSpec },
2009
+ extra?: FieldBuildExtra
2010
  ) => {
2011
  const scope = scopeChoice ? extra?.scope : undefined;
2012
  const scoped = scope === "cohort" ? ({ scope: "cohort" } as const) : {};
 
2104
  const createAndSwapField = useCallback(
2105
  (
2106
  oldKey: string,
2107
+ label: string,
2108
+ type: FieldType,
2109
+ options?: string[],
2110
+ extra?: FieldBuildExtra
2111
  ) => {
2112
  const scope = scopeChoice ? extra?.scope : undefined;
2113
  const field = {
 
2131
  const retypeField = useCallback(
2132
  (
2133
  key: string,
2134
+ type: FieldType,
2135
+ options?: string[],
2136
  // `label` (owner item 8): rename+retype leave the Edit pane as ONE upsert — two
2137
  // sequential emits would each read the stale def and revert the other.
2138
+ extra?: FieldBuildExtra
2139
  ) => {
2140
  const old = fieldByKey.get(key);
2141
  if (!old?.custom || old.source !== "overlay") return;
 
2157
  ...(old.createdBy ? { createdBy: old.createdBy } : {}),
2158
  ...(old.permissions ? { permissions: old.permissions } : {}),
2159
  ...(keepFormat ? { format: old.format } : {}),
2160
+ ...((type === "select" || type === "multiselect") && options?.length
2161
+ ? { options }
2162
+ : {}),
2163
+ ...((type === "select" || type === "multiselect")
2164
+ ? {
2165
+ colorCodeOptions: extra?.colorCodeOptions !== false,
2166
+ ...(extra?.optionColors && Object.keys(extra.optionColors).length
2167
+ ? { optionColors: extra.optionColors }
2168
+ : {}),
2169
+ }
2170
+ : {}),
2171
+ ...(type === "multiselect" ? { multi: true } : {}),
2172
  ...(type === "rating" ? { max: extra?.max ?? 5 } : {}),
2173
  };
2174
  saveField(next);
 
2184
  * source's), and copies overlay VALUES for `custom_` sources; those values arrive with the
2185
  * next payload, so the clone's cells are blank for exactly one round trip.
2186
  */
2187
+ const duplicateField = useCallback(
2188
+ (source: Field) => {
2189
+ const prefix = source.key.startsWith("measure_") ? "measure_" : "custom_";
2190
+ const label = uniqueDisplayName(
2191
+ `${source.label} copy`,
2192
+ fields.map((field) => field.label)
2193
+ );
2194
+ const key = `${prefix}${slugify(label)}_${Math.random().toString(36).slice(2, 7)}`;
2195
+ const requestId = eventId("fielddup");
2196
+ const clone: Field = { ...source, key, label, editRequestId: requestId };
2197
+ delete clone.createdBy;
2198
+ delete clone.permissions;
2199
+ delete clone.labelCorrectedFrom;
2200
+ delete clone.labelCorrectionId;
2201
  stampFieldEdit(key);
2202
  setFields((current) => [...current, clone]);
2203
+ emitHostEvent({
2204
+ id: requestId,
2205
  type: "field_duplicate",
2206
  sourceKey: source.key,
2207
  key,
 
2212
  });
2213
  insertColumn(key, source.key, "right");
2214
  },
2215
+ [insertColumn, scopeChoice, stampFieldEdit, fields]
2216
+ );
2217
 
2218
  /**
2219
  * Wave-2 item 8c — change the PERIOD of a measure-carrying column (user-created `measure_*`
 
2404
  },
2405
  [config, updateConfig]
2406
  );
2407
+ /**
2408
+ * Item 3 (C-DISP) — the kanban card clamp.
2409
+ *
2410
+ * ⚠ `undefined` DELETES the key rather than storing `true`. Absent means clamped, so a
2411
+ * stored `true` would be the default wearing a second name — and the host's `_clean_display`
2412
+ * accepts the literal `false` only, so a `true` would be dropped on save and the toggle
2413
+ * would look like it does not persist. Delete-to-default keeps both ends agreeing.
2414
+ */
2415
+ const setKanbanClamp = useCallback(
2416
+ (next: false | undefined) => {
2417
+ const spec = cleanDisplay(config.display);
2418
+ if (!spec) return;
2419
+ const display = { ...spec };
2420
+ if (next === false) display.kanbanClamp = false;
2421
+ else delete (display as Record<string, unknown>).kanbanClamp;
2422
+ updateConfig({ ...config, display });
2423
+ },
2424
+ [config, updateConfig]
2425
+ );
2426
+ /**
2427
+ * Item 4 (C-DISP) — the per-day totals. An EMPTY list deletes the key rather than storing
2428
+ * `[]`: the always-on Records count is what an absent list means, so `[]` would be that
2429
+ * state wearing a second name — and `_clean_display` drops an empty array anyway, which
2430
+ * would make un-picking the last metric look like it did not save.
2431
+ */
2432
+ const setCalendarMetrics = useCallback(
2433
+ (next: { id: string; field: string; agg: string }[]) => {
2434
+ const spec = cleanDisplay(config.display);
2435
+ if (!spec) return;
2436
+ const display = { ...spec };
2437
+ const capped = next.slice(0, MAX_CALENDAR_METRICS);
2438
+ if (capped.length) display.calendarMetrics = capped;
2439
+ else delete (display as Record<string, unknown>).calendarMetrics;
2440
+ updateConfig({ ...config, display });
2441
+ },
2442
+ [config, updateConfig]
2443
+ );
2444
+ /** Item 4 (C-DISP) — records vs summaries. `records` is the default, so it deletes the key. */
2445
+ const setCalendarMode = useCallback(
2446
+ (next: "records" | "summary") => {
2447
+ const spec = cleanDisplay(config.display);
2448
+ if (!spec) return;
2449
+ const display = { ...spec };
2450
+ if (next === "summary") display.calendarMode = "summary";
2451
+ else delete (display as Record<string, unknown>).calendarMode;
2452
+ updateConfig({ ...config, display });
2453
+ },
2454
+ [config, updateConfig]
2455
+ );
2456
  // The calendar's date field: the view's pick when it is still a real date-family field,
2457
  // else `last_order`, else the first date-family field. The kanban's stack field: status or
2458
  // single-select ONLY (a multiselect card in two columns at once is a count lie — contract).
 
2518
  displayMode !== "calendar" &&
2519
  displayMode !== "kanban" &&
2520
  displayMode !== "map" &&
2521
+ displayMode !== "chart" &&
2522
+ // C-TS close-out stitch: the panel's pids come from these rows; without this line the
2523
+ // time-series view asked its question about ZERO customers (caught by the mounted
2524
+ // judge — the node battery is blind here).
2525
+ displayMode !== "timeseries"
2526
  )
2527
  return [];
2528
  const seen = new Set<number>();
 
2535
  }
2536
  return out;
2537
  }, [displayMode, visibleRows, overlayEdits]);
2538
+ // Owner item 1 — the CALL-SITE half of the kanban memo. `KanbanView` is `memo`'d now, but a
2539
+ // memo whose props are rebuilt every render never bails, and these two were: `cardKeys` is a
2540
+ // fresh array from `.filter().slice()`, `onMove` a fresh closure. With them stable, a
2541
+ // `detailPid` change (clicking a card) re-renders the modal and skips the board entirely —
2542
+ // which is the whole of "laggy record-open". Everything else KanbanView takes was already
2543
+ // stable: `modeDataRows`/`fieldByKey` are useMemos, `kanbanField` is a reference INTO the
2544
+ // `stackFieldChoices` useMemo, and `onOpen={setDetailPid}` is a setState identity.
2545
+ const kanbanCardKeys = useMemo(
2546
+ () =>
2547
+ kanbanField
2548
+ ? visibleKeys.filter((k) => k !== lockedKey && k !== kanbanField.key).slice(0, 3)
2549
+ : [],
2550
+ [visibleKeys, lockedKey, kanbanField]
2551
+ );
2552
+ const onKanbanMove = useCallback(
2553
+ (pid: number, value: string) => {
2554
+ if (!kanbanField) return;
2555
+ patchOverlay(pid, { [kanbanField.key]: value });
2556
+ },
2557
+ [kanbanField, patchOverlay]
2558
+ );
2559
+ const onListToggleGroup = useCallback((groupKey: string) => {
2560
+ setCollapsed((current) => {
2561
+ const next = new Set(current);
2562
+ if (next.has(groupKey)) next.delete(groupKey);
2563
+ else next.add(groupKey);
2564
+ return next;
2565
+ });
2566
+ }, []);
2567
+ /**
2568
+ * Item 7 (C-TS) — the pid set the time series asks about: exactly the rows the current
2569
+ * filter kept, so the panel and the toolbar count can never disagree about "who".
2570
+ *
2571
+ * `modeDataRows` is already the de-duplicated data rows for a non-grid mode, so this is a
2572
+ * projection of it and NOT a second pipeline. The server intersects with the caller's book
2573
+ * anyway — this narrows the question, it can never widen the answer.
2574
+ */
2575
+ const timeseriesPids = useMemo(
2576
+ () => (displayMode === "timeseries" ? modeDataRows.map((r) => r.pid) : []),
2577
+ [displayMode, modeDataRows]
2578
+ );
2579
+ /** Persist a bucket/span/metric pick onto the view, the way every other display key rides. */
2580
+ const onTimeseriesDisplay = useCallback(
2581
+ (next: Partial<DisplaySpec>) => {
2582
+ const spec = cleanDisplay(config.display) ?? { mode: "timeseries" as const };
2583
+ updateConfig({ ...config, display: { ...spec, ...next } });
2584
+ },
2585
+ [config, updateConfig]
2586
+ );
2587
  const kanbanCanMove =
2588
  !!kanbanField && kanbanField.type === "select" && canEditField(kanbanField);
2589
  const kanbanReason = !kanbanField
 
2651
  sizeField={mapSizeField}
2652
  sizeChoices={sizeFieldChoices}
2653
  onPickField={setDisplayField}
2654
+ // Items 3 + 4 (C-DISP). `kanbanClamp` is absent-means-clamped, so the boolean handed
2655
+ // down is `!== false` rather than a truthiness test — the one place that distinction
2656
+ // decides whether the user's opt-out survives a reload.
2657
+ clamped={displaySpec?.kanbanClamp !== false}
2658
+ onClamp={setKanbanClamp}
2659
+ calendarMode={displaySpec?.calendarMode ?? "records"}
2660
+ onCalendarMode={setCalendarMode}
2661
+ calendarMetrics={displaySpec?.calendarMetrics}
2662
+ // The numeric family, exactly what C-DISP makes eligible — and the same memo the map's
2663
+ // bubble-size picker feeds from, so "what can be totalled" has one definition.
2664
+ metricChoices={sizeFieldChoices}
2665
+ onCalendarMetrics={setCalendarMetrics}
2666
  />
2667
  );
2668
  const pickerField = picker ? fieldByKey.get(picker.fieldKey) : undefined;
 
2804
  ) : (
2805
  !hideViews && (
2806
  <ViewSidebar
2807
+ // Item 12 (C-LOCK) — the rail's menu is the only emitter of `cohortLock`.
2808
+ onCohortLock={onViewCohortLock}
2809
  views={views}
2810
  activeViewId={activeViewId}
2811
  saveState={saveState}
 
2903
  )}
2904
  <main className="cg-main">
2905
  <Toolbar
2906
+ // Item 12 (C-LOCK) — the banner's copy. ⚠ BOTH fields are omitted when this reader
2907
+ // cannot see the locked set, and that omission is the SIGNAL, not an oversight: it
2908
+ // is what selects RECORD's second sentence ("locked to a set you cannot see").
2909
+ // Inventing a name or a count for a set we were given no membership for would be
2910
+ // disclosing the very thing the permission gate withheld.
2911
+ cohortLock={cohortLockChip}
2912
  fields={fields}
2913
  visible={visible}
2914
  lockedKey={lockedKey}
 
2992
  getRowThemeOverride={getRowThemeOverride}
2993
  onItemHovered={onItemHovered}
2994
  onCellClicked={onCellClicked}
2995
+ onCellActivated={onCellActivated}
2996
+ onCellEdited={onCellEdited}
2997
+ onPaste={onGridPaste}
2998
+ validateCell={validateCell}
2999
  onColumnResize={onColumnResize}
3000
  onColumnMoved={onColumnMoved}
3001
  onColumnProposeMove={onColumnProposeMove}
 
3047
  visibleKeys={visibleKeys}
3048
  titleKey={lockedKey}
3049
  onOpen={setDetailPid}
3050
+ onToggleGroup={onListToggleGroup}
 
 
 
 
 
 
 
3051
  />
3052
  )}
3053
  {displayMode === "calendar" &&
 
3057
  field={calendarField}
3058
  today={today}
3059
  titleKey={lockedKey}
3060
+ // Item 4 (C-DISP) — records vs summaries, and the metrics a summary day shows.
3061
+ mode={displaySpec?.calendarMode ?? "records"}
3062
+ metrics={displaySpec?.calendarMetrics}
3063
+ fieldByKey={fieldByKey}
3064
  onOpen={setDetailPid}
3065
  />
3066
  ) : (
 
3074
  rows={modeDataRows}
3075
  field={kanbanField}
3076
  fieldByKey={fieldByKey}
3077
+ cardKeys={kanbanCardKeys}
 
 
3078
  titleKey={lockedKey}
3079
  canMove={kanbanCanMove}
3080
  readOnlyReason={kanbanReason}
3081
+ clamped={displaySpec?.kanbanClamp !== false}
3082
+ onMove={onKanbanMove}
 
3083
  onOpen={setDetailPid}
3084
  />
3085
  ) : (
 
3102
  onCharts={setCharts}
3103
  />
3104
  )}
3105
+ {/* Owner item 7 (C-TS) — Time series is a VIEW: metric rows x bucket columns over
3106
+ the pids the current filter kept, so the table and the series answer the same
3107
+ question. The panel is HOST-AGNOSTIC by contract (RECORD re-mounts it inside the
3108
+ record modal for item 13), which is why it takes pids and fields rather than
3109
+ reaching into anything here. */}
3110
+ {displayMode === "timeseries" && (
3111
+ <TimeSeriesPanel
3112
+ scope={scope}
3113
+ pids={timeseriesPids}
3114
+ fields={fields}
3115
+ display={displaySpec}
3116
+ onDisplay={onTimeseriesDisplay}
3117
+ />
3118
+ )}
3119
  {/* Wave-7 item W11c (C3) — Map is a VIEW: same pipeline rows, pins for rows
3120
  with host-supplied coords, click-through to the same record detail, and
3121
  an honest no-location chip. */}
 
3636
  )}
3637
  <div className="cg-pick-list" aria-multiselectable={pickerMulti || undefined}>
3638
  {pickerChoices.map((choice) => {
3639
+ const tint = optionTint(pickerField, choice);
3640
  const on = pickerMulti
3641
  ? pickerParts.includes(choice)
3642
  : pickerValue === choice;
 
3664
  closePicker();
3665
  }}
3666
  >
3667
+ <span
3668
+ className="cg-pick-pill"
3669
+ style={tint ? { background: tint.bg, color: tint.fg } : undefined}
3670
+ >
3671
  {choice}
3672
  </span>
3673
  </button>
 
3717
  onPrev={() => go(-1)}
3718
  onNext={() => go(1)}
3719
  onClose={() => setDetailPid(null)}
3720
+ // Item 5 / C-LAYOUT — see `recordLayout` above. Both optional on RECORD's side, so
3721
+ // this compiles whether or not their reorder UI has landed yet.
3722
+ recordLayout={recordLayout}
3723
+ onRecordLayout={onRecordLayout}
3724
+ // Item 13 / C-EMBED — the host names WHICH question Insights asks. Without this the
3725
+ // tab deliberately does not render (RECORD's no-safe-default rule: a wrong scope
3726
+ // succeeds with plausible wrong numbers, so absence must mean absent, not guessed).
3727
+ scope={scope}
3728
  docs={payload?.docs?.[String(detailPid)] ?? []}
3729
  docPayload={payload?.docPayload}
3730
  // C5 — documents ride the ordinary event log. The host answers a fetch
web/src/customer-grid/RecordDetail.css CHANGED
@@ -86,14 +86,253 @@
86
  padding: 16px;
87
  }
88
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89
  .cg-record-main .cg-detail-field {
90
- min-height: 38px;
91
- padding: 8px 0;
 
 
 
 
 
92
  }
93
 
94
  .cg-record-main .cg-detail-label {
95
- flex-basis: 160px;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
96
  color: var(--lp-muted);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
97
  }
98
 
99
  .cg-record-comments {
@@ -332,7 +571,11 @@
332
  padding-inline: 2px;
333
  }
334
 
335
- .cg-record-main .cg-detail-label {
 
 
 
 
336
  flex-basis: 120px;
337
  }
338
  }
 
86
  padding: 16px;
87
  }
88
 
89
+ /* ==========================================================================
90
+ Wave 2026-08-02 item 2 — the record fields: no yellow, one subtle box.
91
+ ==========================================================================
92
+ Owner: "kill yellow, subtle outline for all field types."
93
+
94
+ Before this, exactly one kind of field had a treatment — the editable
95
+ overlay notes, in a gold frame on a gold wash (index.css:2027) — and every
96
+ other field was bare text under a hairline. So the loudest thing in the
97
+ panel was also the least important, and the panel had two layouts: label
98
+ ABOVE a full-width textarea for notes, label BESIDE the value for the rest.
99
+
100
+ Now every field is one row on one grid: label left, a value SLOT right.
101
+ The slot carries a 1px --lp-line hairline and --lp-r-md corners, and the
102
+ fill is what says whether it is yours:
103
+
104
+ --lp-surface-2 (warm grey) read-only — an Odoo attribute, a picked
105
+ choice, a star rating you set from the table
106
+ --lp-surface (white) editable — type here
107
+
108
+ That replaces the signal the yellow wash used to carry (this stratum is
109
+ your data, not the ERP's) with one that is also an affordance: the bright
110
+ slots are the ones that respond. Interaction, not decoration, marks them.
111
+
112
+ EVERY rule here is scoped `.cg-record-main …` so it (a) outranks the
113
+ index.css base block, which is FROZEN for the other sessions this wave,
114
+ and (b) stops at the record modal — the same `.cg-detail-*` classes dress
115
+ surfaces this file does not own. Specificity, never source order: the
116
+ :focus and ::placeholder overrides below exist because their index.css
117
+ counterparts tie at (0,2,0) and (0,1,1), and a tie is decided by bundle
118
+ order — which is not a thing to bet a gold glow on. */
119
+
120
  .cg-record-main .cg-detail-field {
121
+ min-height: 0;
122
+ align-items: flex-start;
123
+ gap: 12px;
124
+ padding: 3px 0;
125
+ /* The hairline separator is REPLACED by the box, not stacked under it —
126
+ a ruled row around a bordered slot reads as a rendering fault. */
127
+ border-bottom: none;
128
  }
129
 
130
  .cg-record-main .cg-detail-label {
131
+ flex: 0 0 160px;
132
+ /* Optical, not arithmetic: 7px lands the 12px label on the same line as the
133
+ 13px value inside its 1px border + 5px padding. */
134
+ padding-top: 7px;
135
+ color: var(--lp-muted);
136
+ font-size: var(--lp-fs-2xs);
137
+ line-height: 1.45;
138
+ }
139
+
140
+ .cg-record-main .cg-detail-value {
141
+ min-height: 30px;
142
+ padding: 5px 9px;
143
+ border: 1px solid var(--lp-line);
144
+ border-radius: var(--lp-r-md);
145
+ background: var(--lp-surface-2);
146
+ line-height: 1.45;
147
+ }
148
+
149
+ /* A rating's marks are 18px inline SVG; on the text baseline they hang their
150
+ descender space below the line box and grow the slot past every neighbour. */
151
+ .cg-record-main .cg-detail-value .cg-stars {
152
+ vertical-align: middle;
153
+ }
154
+
155
+ /* An editable field is the same ROW as every other one now — index.css stacks
156
+ it (flex-direction: column, and a label with `flex: none`), which is what
157
+ made the notes the odd block out. */
158
+ .cg-record-main .cg-detail-field--edit {
159
+ flex-direction: row;
160
+ align-items: flex-start;
161
+ gap: 12px;
162
+ }
163
+
164
+ .cg-record-main .cg-detail-field--edit .cg-detail-label {
165
+ flex: 0 0 160px;
166
+ }
167
+
168
+ /* The value column of an editable row: the box, then its action link. */
169
+ .cg-detail-editwrap {
170
+ flex: 1 1 auto;
171
+ min-width: 0;
172
+ display: flex;
173
+ flex-direction: column;
174
+ }
175
+
176
+ .cg-record-main .cg-detail-textarea {
177
+ /* The owner's "big static box" was min-height: 76px. One row is the resting
178
+ size; AutoTextarea grows it from there, so an empty note is as quiet as an
179
+ empty value and a long one is readable without a scrollbar. */
180
+ min-height: 30px;
181
+ max-height: 260px;
182
+ padding: 5px 9px;
183
+ overflow-y: auto;
184
+ /* The height is measured, so a drag handle would fight the measurement: the
185
+ next keystroke re-fits and snaps back whatever was dragged. */
186
+ resize: none;
187
+ border: 1px solid var(--lp-line);
188
+ background: var(--lp-surface);
189
+ line-height: 1.45;
190
+ }
191
+
192
+ .cg-record-main .cg-detail-textarea:hover:not(:focus) {
193
+ border-color: color-mix(in srgb, var(--lp-line) 45%, var(--lp-muted));
194
+ }
195
+
196
+ .cg-record-main .cg-detail-textarea:focus {
197
+ /* Identical to the comment composer below — same modal, same gesture, so the
198
+ same mark. `box-shadow: none` is load-bearing: without it index.css:2047's
199
+ 3px gold glow survives an override that only changes the border. */
200
+ outline: 2px solid var(--lp-blue-deep);
201
+ outline-offset: -1px;
202
+ border-color: transparent;
203
+ box-shadow: none;
204
+ }
205
+
206
+ .cg-record-main .cg-detail-textarea::placeholder {
207
+ /* --lp-muted is the palette's body-safe grey (4.83:1). The stock #a2a2ac was
208
+ picked against the gold wash and reads as 2.7:1 on white — and "Add
209
+ notes…" is an instruction, not decoration. */
210
+ color: var(--lp-muted);
211
+ opacity: 1;
212
+ }
213
+
214
+ /* A checkbox IS its own control; boxing it would frame a 15px square in a
215
+ 30px slot and say nothing. It only needs to sit on the label's line. */
216
+ .cg-record-main .cg-detail-checkbox {
217
+ margin-top: 7px;
218
+ }
219
+
220
+ /* ==========================================================================
221
+ Wave 2026-08-02 item 5 (C-LAYOUT) — the six-dot reorder handle.
222
+ ==========================================================================
223
+ Hover-revealed, Airtable's own behaviour and the reason it is right here:
224
+ this panel carries ~26 fields, and 26 permanently-visible grips would put a
225
+ dotted column down the left edge louder than any value in the record. The
226
+ handle is an affordance for a gesture, not information.
227
+
228
+ It keeps its 16px gutter at rest (`opacity`, never `display`), so revealing
229
+ it cannot reflow the row under the pointer that is reaching for it — and it
230
+ stays in the tab order at all times, which is what makes the ArrowUp/Down
231
+ fallback reachable without a mouse.
232
+
233
+ ⚠ Known gap, booked rather than papered over: HTML5 drag-and-drop does not
234
+ fire for touch. On a touch device there is no hover, so the grip stays
235
+ invisible and the gesture is simply absent — which is the honest
236
+ degradation. A pointer-events reorder is the fix if it is ever asked for. */
237
+ .cg-detail-grip {
238
+ flex: 0 0 16px;
239
+ height: 22px;
240
+ margin-top: 5px;
241
+ display: grid;
242
+ place-items: center;
243
+ padding: 0;
244
+ border: 0;
245
+ border-radius: var(--lp-r-sm);
246
+ background: transparent;
247
  color: var(--lp-muted);
248
+ cursor: grab;
249
+ opacity: 0;
250
+ transition: opacity 90ms ease;
251
+ }
252
+
253
+ .cg-detail-field:hover .cg-detail-grip,
254
+ .cg-detail-grip:focus-visible {
255
+ opacity: 1;
256
+ }
257
+
258
+ .cg-detail-grip:focus-visible {
259
+ outline: 2px solid var(--lp-blue-deep);
260
+ outline-offset: -1px;
261
+ }
262
+
263
+ .cg-detail-grip:active {
264
+ cursor: grabbing;
265
+ }
266
+
267
+ /* The row under the pointer. It is where the dragged field LANDS (it takes
268
+ this slot), so the whole row is marked rather than an insertion line
269
+ between two — an edge cannot say which side you are on. */
270
+ .cg-detail-field.is-dropzone {
271
+ border-radius: var(--lp-r-md);
272
+ background: var(--lp-blue-tint);
273
+ box-shadow: inset 0 0 0 1px var(--lp-blue-deep);
274
+ }
275
+
276
+ .cg-detail-field.is-dragging {
277
+ opacity: 0.4;
278
+ }
279
+
280
+ /* ==========================================================================
281
+ Wave 2026-08-02 item 13 (C-EMBED) — Fields | Insights.
282
+ ==========================================================================
283
+ An underline tab row, not a segmented pill: these are two READINGS of the
284
+ same record, and a pill group reads as a mode switch that changes what the
285
+ panel is for. Sits under the title, above the scrolling body, so switching
286
+ never moves the customer's name. */
287
+ .cg-record-tabs {
288
+ flex: 0 0 auto;
289
+ display: flex;
290
+ gap: 2px;
291
+ padding: 0 28px;
292
+ border-bottom: 1px solid var(--lp-line);
293
+ }
294
+
295
+ .cg-record-tab {
296
+ padding: 7px 10px 8px;
297
+ border: 0;
298
+ /* The 1px underline lives on the button so the active mark sits ON the row's
299
+ hairline rather than 1px above or below it. */
300
+ border-bottom: 2px solid transparent;
301
+ margin-bottom: -1px;
302
+ background: transparent;
303
+ color: var(--lp-muted);
304
+ font: inherit;
305
+ font-size: var(--lp-fs-2xs);
306
+ font-weight: 600;
307
+ cursor: pointer;
308
+ }
309
+
310
+ .cg-record-tab:hover {
311
+ color: var(--lp-ink);
312
+ }
313
+
314
+ .cg-record-tab.is-on {
315
+ border-bottom-color: var(--lp-blue-solid);
316
+ color: var(--lp-ink);
317
+ }
318
+
319
+ .cg-record-tab:focus-visible {
320
+ outline: 2px solid var(--lp-blue-deep);
321
+ outline-offset: -2px;
322
+ }
323
+
324
+ .cg-record-insights {
325
+ padding: 12px 16px 24px;
326
+ }
327
+
328
+ @media (max-width: 760px) {
329
+ .cg-record-tabs {
330
+ padding-inline: 18px;
331
+ }
332
+
333
+ .cg-record-insights {
334
+ padding-inline: 4px;
335
+ }
336
  }
337
 
338
  .cg-record-comments {
 
571
  padding-inline: 2px;
572
  }
573
 
574
+ /* Both selectors, because the editable row's label is set at (0,3,0) above:
575
+ narrowing only the read-only one would step the two label columns apart at
576
+ exactly the width where the misalignment is most visible. */
577
+ .cg-record-main .cg-detail-label,
578
+ .cg-record-main .cg-detail-field--edit .cg-detail-label {
579
  flex-basis: 120px;
580
  }
581
  }
web/src/customer-grid/RecordDetail.tsx CHANGED
@@ -1,13 +1,21 @@
1
- import { useId, useRef } from "react";
 
2
  import { BodyPortal, useOverlayLayer } from "./OverlaySurface";
3
  import { checkboxOn, formatDisplay } from "./cells";
4
  import { StarRow } from "./Stars";
5
  import { isPickType, mayEditField, ratingMax } from "./types";
6
- import type { CustomerDoc, Field, Row, Viewer } from "./types";
7
- import { Documents } from "./Documents";
8
- import RecordComments from "./RecordComments";
9
- import { isStreamlitComponent } from "./hostBridge";
10
- import "./RecordDetail.css";
 
 
 
 
 
 
 
11
 
12
  export interface RecordDetailProps {
13
  fields: Field[];
@@ -32,6 +40,33 @@ export interface RecordDetailProps {
32
  onDocAdd?: (file: { name: string; mime: string; size: number; data_b64: string }) => void;
33
  onDocFetch?: (docId: string) => void;
34
  onDocDelete?: (docId: string) => void;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35
  }
36
 
37
  /**
@@ -56,6 +91,63 @@ function actionHref(field: Field, v: string): string | null {
56
  return null;
57
  }
58
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59
  export default function RecordDetail({
60
  fields,
61
  record,
@@ -73,12 +165,16 @@ export default function RecordDetail({
73
  docPayload,
74
  onDocAdd,
75
  onDocFetch,
76
- onDocDelete,
77
- }: RecordDetailProps) {
78
- const panelRef = useRef<HTMLDivElement>(null);
79
- const titleId = useId();
80
- const title = String(record[titleKey] ?? "Untitled");
81
- const showComments = !isStreamlitComponent();
 
 
 
 
82
  const overlayFields = fields.filter((field) => field.source === "overlay");
83
  // Picked fields (select / assignee / multiselect) are PICKED, NEVER TYPED — a textarea here
84
  // would let "Done", "done" and "DONE" into a constrained column through the side door. They
@@ -99,29 +195,316 @@ export default function RecordDetail({
99
  (field) => field.source !== "overlay" && field.key !== titleKey
100
  );
101
 
102
- // One modal surface is shared by Grid, List, Calendar, Kanban, and Map.
103
- // Focus stays inside it, then returns to the exact opener on close.
104
- useOverlayLayer({
105
- panelRef,
106
- onDismiss: onClose,
107
- dismissOnOutside: true,
108
- initialFocus: "[data-overlay-autofocus]",
109
- trapFocus: true,
110
- });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
111
 
112
- return (
113
- <BodyPortal>
114
- <div className="cg-record-backdrop">
115
- <div
116
- className={"cg-record-modal" + (showComments ? "" : " cg-record-modal--single")}
117
- ref={panelRef}
118
- role="dialog"
119
- aria-modal="true"
120
- aria-labelledby={titleId}
121
- data-overlay-kind="record-detail"
122
- tabIndex={-1}
123
- >
124
- <div className="cg-detail-header">
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
125
  <div className="cg-detail-nav">
126
  <button
127
  type="button"
@@ -155,144 +538,65 @@ export default function RecordDetail({
155
  >
156
  ×
157
  </button>
158
- </div>
159
-
160
- <div className="cg-record-layout">
161
- <main className="cg-record-main">
162
- <div className="cg-detail-titlewrap">
163
- <div className="cg-detail-title" id={titleId} title={title}>
164
- {title}
165
- </div>
166
- </div>
167
-
168
- <div className="cg-detail-body">
169
- {overlayFields.length > 0 && (
170
- <section className="cg-detail-section">
171
- <div className="cg-detail-section-title">Notes</div>
172
- {typedOverlay.map((field) => {
173
- const raw = String(record[field.key] ?? "");
174
- const href = actionHref(field, raw);
175
- if (!mayEditField(field, viewer)) {
176
- // Permission-restricted: read-only here exactly as on the table.
177
- return (
178
- <div className="cg-detail-field" key={field.key}>
179
- <span className="cg-detail-label">{field.label}</span>
180
- <span
181
- className="cg-detail-value"
182
- title="You do not have permission to edit this field"
183
- >
184
- {formatDisplay(field, record[field.key]) || "—"}
185
- </span>
186
- </div>
187
- );
188
- }
189
- return (
190
- <div
191
- className="cg-detail-field cg-detail-field--edit"
192
- key={field.key}
193
- >
194
- <label
195
- className="cg-detail-label"
196
- htmlFor={`cg-ov-${field.key}`}
197
- >
198
- {field.label}
199
- </label>
200
- <textarea
201
- id={`cg-ov-${field.key}`}
202
- className="cg-detail-textarea"
203
- value={raw}
204
- placeholder={`Add ${field.label.toLowerCase()}…`}
205
- onChange={(event) =>
206
- onNotesChange(field.key, event.target.value)
207
- }
208
- onBlur={(event) =>
209
- onNotesCommit(field.key, event.target.value)
210
- }
211
- />
212
- {/* Wave-5 item 11 — url/email/phone become ACTIONABLE where valid. The
213
- raw text stays the editable truth; the link is an affordance. */}
214
- {href && (
215
- <a
216
- className="cg-detail-action"
217
- href={href}
218
- target={field.type === "url" ? "_blank" : undefined}
219
- rel={field.type === "url" ? "noopener noreferrer" : undefined}
220
- >
221
- {field.type === "url"
222
- ? "Open link"
223
- : field.type === "email"
224
- ? "Send email"
225
- : "Call"}
226
- </a>
227
- )}
228
- </div>
229
- );
230
- })}
231
- {checkboxOverlay.map((field) => {
232
- const editable = mayEditField(field, viewer);
233
- const on = checkboxOn(record[field.key] as string | number | null);
234
- return (
235
- <div className="cg-detail-field" key={field.key}>
236
- <label className="cg-detail-label" htmlFor={`cg-ov-${field.key}`}>
237
- {field.label}
238
- </label>
239
- <input
240
- id={`cg-ov-${field.key}`}
241
- type="checkbox"
242
- className="cg-detail-checkbox"
243
- checked={on}
244
- disabled={!editable}
245
- onChange={(event) =>
246
- onNotesCommit(field.key, event.target.checked ? "1" : "")
247
- }
248
- />
249
- </div>
250
- );
251
- })}
252
- {ratingOverlay.map((field) => {
253
- const n = Math.max(
254
- 0,
255
- Math.min(ratingMax(field), Math.round(Number(record[field.key]) || 0))
256
- );
257
- return (
258
- <div className="cg-detail-field" key={field.key}>
259
- <span className="cg-detail-label">{field.label}</span>
260
- <span
261
- className="cg-detail-value"
262
- title="Set from the column's star picker on the table"
263
- >
264
- <StarRow value={n} max={ratingMax(field)} />
265
- </span>
266
- </div>
267
- );
268
- })}
269
- {pickedOverlay.map((field) => {
270
- const text = formatDisplay(field, record[field.key]);
271
- return (
272
- <div className="cg-detail-field" key={field.key}>
273
- <span className="cg-detail-label">{field.label}</span>
274
- <span
275
- className="cg-detail-value"
276
- title="Picked from the column's choices on the table"
277
- >
278
- {text || "—"}
279
- </span>
280
- </div>
281
- );
282
- })}
283
- </section>
284
- )}
285
 
286
- <section className="cg-detail-section">
287
- <div className="cg-detail-section-title">Customer details</div>
288
- {detailFields.map((field) => {
289
- const text = formatDisplay(field, record[field.key]);
290
- return (
291
- <div className="cg-detail-field" key={field.key}>
292
- <span className="cg-detail-label">{field.label}</span>
293
- <span className="cg-detail-value">{text || "—"}</span>
 
 
 
 
 
 
 
 
 
 
 
294
  </div>
295
- );
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
296
  })}
297
  </section>
298
 
@@ -309,18 +613,20 @@ export default function RecordDetail({
309
  onDelete={onDocDelete}
310
  />
311
  )}
312
- </div>
313
- </main>
314
- {showComments && (
315
- <RecordComments
316
- key={Number(record.pid)}
317
- pid={Number(record.pid)}
318
- viewer={viewer}
319
- />
320
- )}
321
- </div>
322
- </div>
323
- </div>
324
- </BodyPortal>
 
 
325
  );
326
  }
 
1
+ import { useEffect, useId, useLayoutEffect, useMemo, useRef, useState } from "react";
2
+ import type { ReactNode, TextareaHTMLAttributes } from "react";
3
  import { BodyPortal, useOverlayLayer } from "./OverlaySurface";
4
  import { checkboxOn, formatDisplay } from "./cells";
5
  import { StarRow } from "./Stars";
6
  import { isPickType, mayEditField, ratingMax } from "./types";
7
+ import type { CustomerDoc, DisplaySpec, Field, Row, Viewer } from "./types";
8
+ // C-EMBED — the ONLY thing item 13 takes from the grid's side of the house. Not a hook, not a
9
+ // context, not a slice of CustomerGrid's state: the panel was written to receive every input
10
+ // as a prop precisely so it could be mounted twice, and importing anything else from over
11
+ // there is what would make the record modal depend on the table being on screen.
12
+ import TimeSeriesPanel from "./TimeSeriesPanel";
13
+ import type { SurfaceScope } from "./apiBridge";
14
+ import { Documents } from "./Documents";
15
+ import { FIELD_DRAG_TYPE, moveKey, nudgeKey, resolveFieldOrder } from "./recordLayout";
16
+ import RecordComments from "./RecordComments";
17
+ import { isStreamlitComponent } from "./hostBridge";
18
+ import "./RecordDetail.css";
19
 
20
  export interface RecordDetailProps {
21
  fields: Field[];
 
40
  onDocAdd?: (file: { name: string; mime: string; size: number; data_b64: string }) => void;
41
  onDocFetch?: (docId: string) => void;
42
  onDocDelete?: (docId: string) => void;
43
+ /**
44
+ * Wave 2026-08-02 item 5 (C-LAYOUT) — this USER'S field order for the record modal, from
45
+ * `GridWorkspace.recordLayout.order`. Keys the table no longer has are ignored and fields the
46
+ * order does not name append in the default order, so a stale layout degrades to a partial
47
+ * one rather than to a missing field.
48
+ *
49
+ * Optional on purpose: absent, the reordering still works for the life of the modal — it just
50
+ * does not outlive it. That is the honest degradation for a host that serves no layout (the
51
+ * Streamlit embed until its bridge carries the event), and it is what lets this ship before
52
+ * the persistence half lands.
53
+ */
54
+ recordLayout?: string[];
55
+ /** The new order, already pruned and deduped. Wired to the `record_layout` event. */
56
+ onRecordLayout?: (order: string[]) => void;
57
+ /**
58
+ * Wave 2026-08-02 item 13 (C-EMBED) — which surface this modal was opened from, passed
59
+ * through to the Insights panel's fetch.
60
+ *
61
+ * ⚠ ABSENT HIDES THE INSIGHTS TAB. There is no default, and picking one would have been a
62
+ * quiet bug: defaulting to `customer` for a modal opened from the cohort surface asks the
63
+ * customer endpoint about a pid that is usually in the reader's customer book as well — so
64
+ * the server answers happily, with customer-scope numbers under a cohort-scope record. No
65
+ * 403, no marker, a plausible wrong answer. That is the same failure class the rank gate
66
+ * exists to catch, and the fix is the same one: refuse to answer rather than answer a
67
+ * question nobody asked. The tab appears the moment the host says which surface this is.
68
+ */
69
+ scope?: SurfaceScope;
70
  }
71
 
72
  /**
 
91
  return null;
92
  }
93
 
94
+ /**
95
+ * Wave 2026-08-02 item 2 — a note field that is the SIZE OF ITS CONTENT.
96
+ *
97
+ * The owner's complaint was a "big static box": every editable overlay field opened as a
98
+ * 76px-tall textarea whether it held a paragraph or nothing at all, so a record whose notes
99
+ * were all empty read as a column of empty boxes. Here the resting height is one field row —
100
+ * identical to the read-only value slots beside it — and it grows as you type.
101
+ *
102
+ * `height: auto` FIRST is not a formality: `scrollHeight` never reports less than the height
103
+ * already set, so measuring without releasing the previous one makes the box grow and never
104
+ * shrink. The border term is `box-sizing: border-box` (index.css:17) — under it `height`
105
+ * includes the border while `scrollHeight` does not, and the 2px difference is exactly enough
106
+ * to keep a scrollbar permanently visible.
107
+ *
108
+ * Re-measures on `value`, which covers prev/next: this element is reused across records (only
109
+ * RecordComments is keyed by pid), so a stale height would otherwise follow you to the next
110
+ * customer. The width can also change without the value changing — a browser resize — hence
111
+ * the listener; a ResizeObserver on the element itself would observe the height WE set.
112
+ */
113
+ function AutoTextarea({
114
+ value,
115
+ ...rest
116
+ }: TextareaHTMLAttributes<HTMLTextAreaElement> & { value: string }) {
117
+ const ref = useRef<HTMLTextAreaElement>(null);
118
+ useLayoutEffect(() => {
119
+ const el = ref.current;
120
+ if (!el) return;
121
+ const fit = () => {
122
+ el.style.height = "auto";
123
+ const cs = window.getComputedStyle(el);
124
+ const borders =
125
+ cs.boxSizing === "border-box"
126
+ ? (parseFloat(cs.borderTopWidth) || 0) + (parseFloat(cs.borderBottomWidth) || 0)
127
+ : 0;
128
+ el.style.height = `${el.scrollHeight + borders}px`;
129
+ };
130
+ fit();
131
+ window.addEventListener("resize", fit);
132
+ return () => window.removeEventListener("resize", fit);
133
+ }, [value]);
134
+ return <textarea ref={ref} value={value} {...rest} />;
135
+ }
136
+
137
+ /** The six dots. An inline SVG, never a glyph — the owner constant, and `⠿` renders as a
138
+ * different width in every fallback font the grid has been seen in. */
139
+ function SixDots() {
140
+ return (
141
+ <svg width="10" height="14" viewBox="0 0 10 14" aria-hidden focusable="false">
142
+ {[3, 7, 11].map((cy) =>
143
+ [3, 7].map((cx) => (
144
+ <circle key={`${cx}-${cy}`} cx={cx} cy={cy} r="1.15" fill="currentColor" />
145
+ ))
146
+ )}
147
+ </svg>
148
+ );
149
+ }
150
+
151
  export default function RecordDetail({
152
  fields,
153
  record,
 
165
  docPayload,
166
  onDocAdd,
167
  onDocFetch,
168
+ onDocDelete,
169
+ recordLayout,
170
+ onRecordLayout,
171
+ scope,
172
+ }: RecordDetailProps) {
173
+ const panelRef = useRef<HTMLDivElement>(null);
174
+ const titleId = useId();
175
+ const tabsId = useId();
176
+ const title = String(record[titleKey] ?? "Untitled");
177
+ const showComments = !isStreamlitComponent();
178
  const overlayFields = fields.filter((field) => field.source === "overlay");
179
  // Picked fields (select / assignee / multiselect) are PICKED, NEVER TYPED — a textarea here
180
  // would let "Done", "done" and "DONE" into a constrained column through the side door. They
 
195
  (field) => field.source !== "overlay" && field.key !== titleKey
196
  );
197
 
198
+ // --- C-LAYOUT (item 5) — ONE interleaved field list, in THIS user's order -------------
199
+ //
200
+ // The five buckets above survive as the DEFAULT ORDER and nothing else. Definition order
201
+ // would have been the obvious default and is the wrong one: overlay fields are appended
202
+ // AFTER the Odoo columns, so a user's own notes would have sunk to the bottom of every
203
+ // record the day this shipped. Keeping today's arrangement as the default means a user who
204
+ // never touches a grip sees no change at all.
205
+ //
206
+ // The two section headings ("Notes" / "Customer details") are gone with them — see the
207
+ // dated amendment in the wave doc. A heading over an interleaved list would be a caption
208
+ // that stops being true the first time somebody drags across it, and the distinction it
209
+ // carried (your stratum vs the ERP's) is now carried by every row itself: white slot =
210
+ // editable, grey slot = read-only. Item 13's `Fields | Insights` row becomes the label for
211
+ // the list as a whole.
212
+ const fieldByKey = new Map(fields.map((field) => [field.key, field]));
213
+ const defaultOrder = [
214
+ ...typedOverlay,
215
+ ...checkboxOverlay,
216
+ ...ratingOverlay,
217
+ ...pickedOverlay,
218
+ ...detailFields,
219
+ ].map((field) => field.key);
220
+ // The order we have asked for but not yet seen echoed. Without it a drag would snap back
221
+ // for one paint on every round trip (the no-blip law); it clears itself the moment the
222
+ // host's copy agrees, so a REJECTED order reverts visibly instead of lying.
223
+ const [pendingOrder, setPendingOrder] = useState<string[] | null>(null);
224
+ useEffect(() => {
225
+ setPendingOrder((p) =>
226
+ p && JSON.stringify(p) === JSON.stringify(recordLayout ?? []) ? null : p
227
+ );
228
+ }, [recordLayout]);
229
+
230
+ // `defaultOrder` is the whole vocabulary, so this is a PERMUTATION of it and nothing else —
231
+ // a saved layout can reorder the panel, never change what is in it. See recordLayout.ts.
232
+ const orderedKeys = resolveFieldOrder(pendingOrder ?? recordLayout, defaultOrder);
233
+
234
+ // The key being dragged, twice over, written only in `onDragStart`/`onDragEnd` and always
235
+ // together. The REF is what the handlers read: `dragover` must call preventDefault for a
236
+ // drop to be allowed at all, and gating that on state would make the gesture depend on a
237
+ // re-render landing between two mouse events. The STATE is what the class reads, because a
238
+ // ref cannot re-render the row it is meant to fade.
239
+ const dragKeyRef = useRef<string | null>(null);
240
+ const [dragKey, setDragKey] = useState<string | null>(null);
241
+ const [dropKey, setDropKey] = useState<string | null>(null);
242
+ const gripRefs = useRef(new Map<string, HTMLButtonElement | null>());
243
+ // A keyboard move rewrites the list, and React moves the focused button with it — but a
244
+ // moved node does not reliably keep focus, and losing it after one ArrowDown would end the
245
+ // interaction the fallback exists to provide. Re-aimed explicitly, after the paint.
246
+ const refocusGrip = useRef<string | null>(null);
247
+ useLayoutEffect(() => {
248
+ const key = refocusGrip.current;
249
+ if (!key) return;
250
+ refocusGrip.current = null;
251
+ gripRefs.current.get(key)?.focus();
252
+ });
253
+
254
+ // ROVING TABINDEX. `opacity: 0` hides the grips from the eye but not from the tab order —
255
+ // they keep their client rects, so `useOverlayLayer`'s focusable sweep counts every one of
256
+ // them — and a record with 26 fields would have gone from ~6 tab stops to ~32, making the
257
+ // comment box on the far side of the panel 26 presses away. One grip is tabbable; the arrow
258
+ // keys move within the group, which is the same gesture that reorders. Falls back to the
259
+ // first row whenever the remembered one is gone (a deleted field must not strand the group).
260
+ const [activeGrip, setActiveGrip] = useState<string | null>(null);
261
+ const rovingKey =
262
+ activeGrip && orderedKeys.includes(activeGrip) ? activeGrip : orderedKeys[0];
263
+
264
+ const commitOrder = (next: string[]) => {
265
+ if (next === orderedKeys) return; // moveKey/nudgeKey return the input on a no-op
266
+ setPendingOrder(next);
267
+ onRecordLayout?.(next);
268
+ };
269
+
270
+ // --- C-EMBED (item 13) — Fields | Insights ---------------------------------------------
271
+ //
272
+ // The owner's framing: in the record, the FILTER IS THE LOCK — you are looking at one
273
+ // customer, so the pid set is not a control, it is the premise. Hence `locked`, and hence a
274
+ // panel that is otherwise the same component the table mounts, with the same server, the
275
+ // same buckets and the same additivity rules. Two implementations of "sales by month" that
276
+ // could disagree is the thing worth avoiding here, not the duplicated markup.
277
+ //
278
+ // The display state is LOCAL and deliberately not persisted (v1): a bucket chosen while
279
+ // reading one customer is a way of looking, not a property of the record. `onDisplay` is
280
+ // passed all the same — the panel DISABLES its controls without one, and the contract says
281
+ // the controls stay live.
282
+ // No scope, no Insights — see the prop's note. `tab` is forced back rather than merely
283
+ // unreachable, so a host that stops supplying the scope mid-session cannot leave the modal
284
+ // showing a panel it can no longer address.
285
+ const [tab, setTab] = useState<"fields" | "insights">("fields");
286
+ const canInsights = scope != null;
287
+ const activeTab = canInsights ? tab : "fields";
288
+ // `mode: "timeseries"` is the only required member of DisplaySpec and it is a truthful one
289
+ // here: this IS the time-series reading of the record. Every other key is absent, which the
290
+ // panel reads as "use my defaults".
291
+ const [tsDisplay, setTsDisplay] = useState<DisplaySpec>({ mode: "timeseries" });
292
+ // ⚠ Memoised, not `[Number(record.pid)]` inline: the panel's fetch effect depends on `pids`
293
+ // by identity, so a fresh array every render would re-fetch on every render — forever.
294
+ const insightPids = useMemo(() => [Number(record.pid)], [record.pid]);
295
+
296
+ /**
297
+ * The six-dot handle. `draggable` sits HERE and not on the row: a draggable ancestor
298
+ * swallows text selection inside its inputs, and selecting a phrase in a note to retype it
299
+ * is the more common gesture by a wide margin.
300
+ *
301
+ * ⚠ The kanban's post-drag click guard (`viewModes.tsx:483`) has NO counterpart here, and
302
+ * that is a finding rather than an omission — see the dated amendment. It suppresses a
303
+ * post-`dragend` click that would otherwise OPEN a record; a field row has no click action
304
+ * to suppress, and the modal's own outside-dismissal listens on `pointerdown`
305
+ * (`OverlaySurface.tsx:139`), which fires at drag START, inside the panel. A guard here
306
+ * would be a flag nothing reads.
307
+ */
308
+ const grip = (field: Field, index: number) => (
309
+ <button
310
+ type="button"
311
+ className="cg-detail-grip"
312
+ ref={(el) => {
313
+ gripRefs.current.set(field.key, el);
314
+ }}
315
+ draggable
316
+ tabIndex={field.key === rovingKey ? 0 : -1}
317
+ onFocus={() => setActiveGrip(field.key)}
318
+ // The POSITION is in the name, not only in the list: a keyboard move repaints silently,
319
+ // and a fallback whose effect a screen-reader user cannot hear is present rather than
320
+ // usable. Re-read on every move, because the label changes with the position.
321
+ aria-label={`Reorder ${field.label}, position ${index + 1} of ${orderedKeys.length}`}
322
+ title="Drag to reorder — or press the arrow keys"
323
+ onDragStart={(event) => {
324
+ dragKeyRef.current = field.key;
325
+ setDragKey(field.key);
326
+ event.dataTransfer.effectAllowed = "move";
327
+ event.dataTransfer.setData(FIELD_DRAG_TYPE, field.key);
328
+ // The ghost is the whole ROW. Dragging a 10px handle across a 700px panel gives the
329
+ // eye nothing to aim with, and the thing being moved is the field, not the dots.
330
+ const row = event.currentTarget.parentElement;
331
+ if (row) event.dataTransfer.setDragImage(row, 14, row.clientHeight / 2);
332
+ }}
333
+ onDragEnd={() => {
334
+ dragKeyRef.current = null;
335
+ setDragKey(null);
336
+ setDropKey(null);
337
+ }}
338
+ onKeyDown={(event) => {
339
+ if (event.key !== "ArrowUp" && event.key !== "ArrowDown") return;
340
+ event.preventDefault(); // the body scrolls otherwise, chasing the row you moved
341
+ const next = nudgeKey(orderedKeys, field.key, event.key === "ArrowUp" ? -1 : 1);
342
+ if (next === orderedKeys) return;
343
+ refocusGrip.current = field.key;
344
+ commitOrder(next);
345
+ }}
346
+ >
347
+ <SixDots />
348
+ </button>
349
+ );
350
+
351
+ /** One row of the interleaved list: the handle, the label, and the type's own value slot. */
352
+ const renderRow = (field: Field, index: number) => {
353
+ const editable = field.source === "overlay" && mayEditField(field, viewer);
354
+ const isTyped =
355
+ field.source === "overlay" &&
356
+ !isPickType(field.type) &&
357
+ field.type !== "checkbox" &&
358
+ field.type !== "rating";
359
+ const isEdit = editable && isTyped;
360
+ const cls =
361
+ "cg-detail-field" +
362
+ (isEdit ? " cg-detail-field--edit" : "") +
363
+ (dropKey === field.key ? " is-dropzone" : "") +
364
+ (dragKey === field.key ? " is-dragging" : "");
365
 
366
+ let slot: ReactNode;
367
+ if (isEdit) {
368
+ const raw = String(record[field.key] ?? "");
369
+ const href = actionHref(field, raw);
370
+ slot = (
371
+ // Item 2 — the editable slot and its link stack in the VALUE column, so an editable
372
+ // row reads on the same label-left/value-right grid as every read-only one. A wrapper
373
+ // element rather than flex-wrap: the alignment must not depend on a hard-coded label
374
+ // width, which the mobile breakpoint changes.
375
+ <div className="cg-detail-editwrap">
376
+ <AutoTextarea
377
+ id={`cg-ov-${field.key}`}
378
+ className="cg-detail-textarea"
379
+ value={raw}
380
+ placeholder={`Add ${field.label.toLowerCase()}…`}
381
+ onChange={(event) => onNotesChange(field.key, event.target.value)}
382
+ onBlur={(event) => onNotesCommit(field.key, event.target.value)}
383
+ />
384
+ {/* Wave-5 item 11 — url/email/phone become ACTIONABLE where valid. The raw text
385
+ stays the editable truth; the link is an affordance. */}
386
+ {href && (
387
+ <a
388
+ className="cg-detail-action"
389
+ href={href}
390
+ target={field.type === "url" ? "_blank" : undefined}
391
+ rel={field.type === "url" ? "noopener noreferrer" : undefined}
392
+ >
393
+ {field.type === "url"
394
+ ? "Open link"
395
+ : field.type === "email"
396
+ ? "Send email"
397
+ : "Call"}
398
+ </a>
399
+ )}
400
+ </div>
401
+ );
402
+ } else if (field.source === "overlay" && field.type === "checkbox") {
403
+ slot = (
404
+ <input
405
+ id={`cg-ov-${field.key}`}
406
+ type="checkbox"
407
+ className="cg-detail-checkbox"
408
+ checked={checkboxOn(record[field.key] as string | number | null)}
409
+ disabled={!editable}
410
+ onChange={(event) =>
411
+ onNotesCommit(field.key, event.target.checked ? "1" : "")
412
+ }
413
+ />
414
+ );
415
+ } else if (field.source === "overlay" && field.type === "rating") {
416
+ const n = Math.max(
417
+ 0,
418
+ Math.min(ratingMax(field), Math.round(Number(record[field.key]) || 0))
419
+ );
420
+ slot = (
421
+ <span
422
+ className="cg-detail-value"
423
+ title="Set from the column's star picker on the table"
424
+ >
425
+ <StarRow value={n} max={ratingMax(field)} />
426
+ </span>
427
+ );
428
+ } else {
429
+ // Everything read-only, with the reason it is read-only where there is one: a picked
430
+ // field has its own door, and a permission-restricted one is not the drawer's to open.
431
+ const reason =
432
+ field.source !== "overlay"
433
+ ? undefined
434
+ : isPickType(field.type)
435
+ ? "Picked from the column's choices on the table"
436
+ : "You do not have permission to edit this field";
437
+ slot = (
438
+ <span className="cg-detail-value" title={reason}>
439
+ {formatDisplay(field, record[field.key]) || "—"}
440
+ </span>
441
+ );
442
+ }
443
+
444
+ const labelIsFor = isEdit || (field.source === "overlay" && field.type === "checkbox");
445
+ return (
446
+ <div
447
+ className={cls}
448
+ key={field.key}
449
+ onDragOver={(event) => {
450
+ // Only OUR drag. Without the guard the whole list would advertise itself as a drop
451
+ // target for a dragged file or a selection from another tab.
452
+ if (!dragKeyRef.current) return;
453
+ event.preventDefault();
454
+ event.dataTransfer.dropEffect = "move";
455
+ if (dropKey !== field.key) setDropKey(field.key);
456
+ }}
457
+ onDragLeave={(event) => {
458
+ // `dragleave` also fires crossing into a CHILD (the label, the textarea), and
459
+ // clearing on those makes the drop marker strobe under a stationary pointer.
460
+ if (event.currentTarget.contains(event.relatedTarget as Node | null)) return;
461
+ setDropKey((k) => (k === field.key ? null : k));
462
+ }}
463
+ onDrop={(event) => {
464
+ // `drop` bubbles, so cancelling it here also cancels a textarea's native "insert
465
+ // the dragged text" — the second layer under FIELD_DRAG_TYPE.
466
+ event.preventDefault();
467
+ const key = event.dataTransfer.getData(FIELD_DRAG_TYPE) || dragKeyRef.current;
468
+ setDropKey(null);
469
+ if (key) commitOrder(moveKey(orderedKeys, key, field.key));
470
+ }}
471
+ >
472
+ {grip(field, index)}
473
+ {labelIsFor ? (
474
+ <label className="cg-detail-label" htmlFor={`cg-ov-${field.key}`}>
475
+ {field.label}
476
+ </label>
477
+ ) : (
478
+ <span className="cg-detail-label">{field.label}</span>
479
+ )}
480
+ {slot}
481
+ </div>
482
+ );
483
+ };
484
+
485
+ // One modal surface is shared by Grid, List, Calendar, Kanban, and Map.
486
+ // Focus stays inside it, then returns to the exact opener on close.
487
+ useOverlayLayer({
488
+ panelRef,
489
+ onDismiss: onClose,
490
+ dismissOnOutside: true,
491
+ initialFocus: "[data-overlay-autofocus]",
492
+ trapFocus: true,
493
+ });
494
+
495
+ return (
496
+ <BodyPortal>
497
+ <div className="cg-record-backdrop">
498
+ <div
499
+ className={"cg-record-modal" + (showComments ? "" : " cg-record-modal--single")}
500
+ ref={panelRef}
501
+ role="dialog"
502
+ aria-modal="true"
503
+ aria-labelledby={titleId}
504
+ data-overlay-kind="record-detail"
505
+ tabIndex={-1}
506
+ >
507
+ <div className="cg-detail-header">
508
  <div className="cg-detail-nav">
509
  <button
510
  type="button"
 
538
  >
539
  ×
540
  </button>
541
+ </div>
542
+
543
+ <div className="cg-record-layout">
544
+ <main className="cg-record-main">
545
+ <div className="cg-detail-titlewrap">
546
+ <div className="cg-detail-title" id={titleId} title={title}>
547
+ {title}
548
+ </div>
549
+ </div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
550
 
551
+ {/* C-EMBED (item 13) — the two ways of reading one record. This row is also
552
+ what the interleaved field list lost when its two section headings went
553
+ (see C-LAYOUT's amendment): the label for the list as a whole. */}
554
+ {canInsights && (
555
+ <div className="cg-record-tabs" role="tablist" aria-label="Record view">
556
+ {(["fields", "insights"] as const).map((key) => (
557
+ <button
558
+ key={key}
559
+ type="button"
560
+ role="tab"
561
+ id={`${tabsId}-${key}`}
562
+ aria-selected={activeTab === key}
563
+ aria-controls={`${tabsId}-panel`}
564
+ className={"cg-record-tab" + (activeTab === key ? " is-on" : "")}
565
+ onClick={() => setTab(key)}
566
+ >
567
+ {key === "fields" ? "Fields" : "Insights"}
568
+ </button>
569
+ ))}
570
  </div>
571
+ )}
572
+
573
+ <div
574
+ className="cg-detail-body"
575
+ id={`${tabsId}-panel`}
576
+ role={canInsights ? "tabpanel" : undefined}
577
+ aria-labelledby={canInsights ? `${tabsId}-${activeTab}` : undefined}
578
+ >
579
+ {activeTab === "insights" && scope ? (
580
+ // `locked` says the pid set is the PREMISE, not a control: you are reading one
581
+ // customer, so the filter surface is the record itself (the owner's words). The
582
+ // panel keeps its own bucket/span/field controls live against local state.
583
+ <div className="cg-record-insights">
584
+ <TimeSeriesPanel
585
+ scope={scope}
586
+ pids={insightPids}
587
+ fields={fields}
588
+ display={tsDisplay}
589
+ onDisplay={(next) => setTsDisplay((d) => ({ ...d, ...next }))}
590
+ locked
591
+ />
592
+ </div>
593
+ ) : (
594
+ <>
595
+ {/* C-LAYOUT — ONE list, this user's order, every type interleaved. */}
596
+ <section className="cg-detail-section cg-detail-fieldlist">
597
+ {orderedKeys.map((key, index) => {
598
+ const field = fieldByKey.get(key);
599
+ return field ? renderRow(field, index) : null;
600
  })}
601
  </section>
602
 
 
613
  onDelete={onDocDelete}
614
  />
615
  )}
616
+ </>
617
+ )}
618
+ </div>
619
+ </main>
620
+ {showComments && (
621
+ <RecordComments
622
+ key={Number(record.pid)}
623
+ pid={Number(record.pid)}
624
+ viewer={viewer}
625
+ />
626
+ )}
627
+ </div>
628
+ </div>
629
+ </div>
630
+ </BodyPortal>
631
  );
632
  }
web/src/customer-grid/TimeSeriesPanel.tsx ADDED
@@ -0,0 +1,405 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * TimeSeriesPanel.tsx — owner item 7 (contract C-TS): metric ROWS x time-bucket COLUMNS.
3
+ *
4
+ * ⚠ **HOST-AGNOSTIC ON PURPOSE — it reads no CustomerGrid state, ever.** RECORD re-mounts this
5
+ * exact component inside the record modal for item 13 (contract C-EMBED) with `pids=[pid]` and
6
+ * `locked`, so every input arrives as a prop. The moment this file imports a grid hook, the
7
+ * record-detail Insights tab stops being possible.
8
+ *
9
+ * All arithmetic and every honest disclosure live in `timeSeriesData.ts`, which
10
+ * `web/verify_timeseries.py` gates under node. This file is layout, fetch orchestration and
11
+ * one chart adapter — deliberately nothing a wrong number could hide in.
12
+ *
13
+ * `locked` is the item-13 posture: the pid set is FIXED by the caller (one record) and the
14
+ * panel says so rather than pretending the reader chose it. Bucket/span/field controls stay
15
+ * live either way — the owner's words were that the filter surface is the lock, not the
16
+ * controls.
17
+ */
18
+
19
+ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
20
+ import { fetchTimeseries } from "./apiBridge";
21
+ import type { SurfaceScope } from "./apiBridge";
22
+ import { triggerDownload } from "./export";
23
+ import { isStreamlitComponent } from "./hostBridge";
24
+ import {
25
+ DEFAULT_TS_BUCKET,
26
+ DEFAULT_TS_LAST_N,
27
+ buildTsCsv,
28
+ buildTsRequest,
29
+ buildTsTable,
30
+ formatTsDelta,
31
+ formatTsValue,
32
+ tsRowToChartModel,
33
+ } from "./timeSeriesData";
34
+ import type { TsPayload, TsTable, TsTableRow } from "./timeSeriesData";
35
+ import { TS_BUCKETS, TS_MAX_FIELDS } from "./types";
36
+ import type { DisplaySpec, Field, TsBucket } from "./types";
37
+ import { toVegaLiteSpec } from "../viz/vega/toVegaLiteSpec";
38
+ import VegaLiteChart from "../viz/vega/VegaLiteChart";
39
+
40
+ const BUCKET_LABELS: Record<TsBucket, string> = {
41
+ week: "Weekly",
42
+ month: "Monthly",
43
+ quarter: "Quarterly",
44
+ year: "Yearly",
45
+ };
46
+
47
+ /** The rolling spans offered, per bucket. Capped well inside `TS_MAX_LAST_N`. */
48
+ const LAST_N_CHOICES = [6, 12, 24, 36];
49
+
50
+ export interface TimeSeriesPanelProps {
51
+ scope: SurfaceScope;
52
+ /** The rows in scope. The server intersects with the caller's book regardless. */
53
+ pids: number[];
54
+ /** Every field the table has — the panel picks the measure-backed ones itself. */
55
+ fields: Field[];
56
+ /** The view's `config.display`; absent keys fall back to the panel's defaults. */
57
+ display?: DisplaySpec;
58
+ /** Persist a display change. Absent = the panel is ephemeral (RECORD's embed, v1). */
59
+ onDisplay?: (next: Partial<DisplaySpec>) => void;
60
+ /** Item 13 — the pid set is the caller's and cannot be widened from here. */
61
+ locked?: boolean;
62
+ }
63
+
64
+ /**
65
+ * v1 eligibility, per C-TS: measure-backed fields only. A formula field has no time dimension
66
+ * of its own, so it is not offered — and the panel says that plainly instead of showing an
67
+ * empty picker that looks broken.
68
+ */
69
+ function measureFields(fields: Field[]): Field[] {
70
+ return fields.filter((f) => f.key.startsWith("measure_"));
71
+ }
72
+
73
+ export default function TimeSeriesPanel({
74
+ scope,
75
+ pids,
76
+ fields,
77
+ display,
78
+ onDisplay,
79
+ locked,
80
+ }: TimeSeriesPanelProps) {
81
+ const eligible = useMemo(() => measureFields(fields), [fields]);
82
+
83
+ const bucket: TsBucket = (TS_BUCKETS as readonly string[]).includes(display?.tsBucket ?? "")
84
+ ? (display!.tsBucket as TsBucket)
85
+ : DEFAULT_TS_BUCKET;
86
+ const lastN =
87
+ typeof display?.tsSpan?.lastN === "number" ? display.tsSpan.lastN : DEFAULT_TS_LAST_N;
88
+ const selected = useMemo(() => {
89
+ const want = display?.tsFields ?? [];
90
+ const live = want.filter((k) => eligible.some((f) => f.key === k));
91
+ // A view whose stored fields have all been deleted falls back to the first eligible
92
+ // metric rather than to an empty table, which would read as "no data" when the truth is
93
+ // "no fields chosen".
94
+ return live.length ? live : eligible.slice(0, 1).map((f) => f.key);
95
+ }, [display?.tsFields, eligible]);
96
+
97
+ const [payload, setPayload] = useState<TsPayload | null>(null);
98
+ const [state, setState] = useState<"idle" | "loading" | "error">("idle");
99
+ const [errStatus, setErrStatus] = useState(0);
100
+ const [charted, setCharted] = useState<Set<string>>(new Set());
101
+ const [showDelta, setShowDelta] = useState(false);
102
+ // Guards a slow response from overwriting a newer one — the request the user is waiting on
103
+ // is the LAST one they asked for, not the last one to arrive.
104
+ const reqRef = useRef(0);
105
+
106
+ const embedded = isStreamlitComponent();
107
+
108
+ useEffect(() => {
109
+ if (embedded) return;
110
+ if (!selected.length || !pids.length) {
111
+ setPayload(null);
112
+ setState("idle");
113
+ return;
114
+ }
115
+ const seq = ++reqRef.current;
116
+ setState("loading");
117
+ const body = buildTsRequest({ pids, bucket, span: { lastN }, fields: selected });
118
+ fetchTimeseries(body, scope).then(({ payload: p, status }) => {
119
+ if (seq !== reqRef.current) return;
120
+ if (!p) {
121
+ setPayload(null);
122
+ setErrStatus(status);
123
+ setState("error");
124
+ return;
125
+ }
126
+ setPayload(p);
127
+ setState("idle");
128
+ });
129
+ }, [embedded, scope, pids, bucket, lastN, selected]);
130
+
131
+ const table: TsTable = useMemo(() => buildTsTable(payload), [payload]);
132
+
133
+ const onCsv = useCallback(() => {
134
+ const csv = buildTsCsv(table);
135
+ triggerDownload(
136
+ "Time series.csv",
137
+ new Blob(["" + csv], { type: "text/csv;charset=utf-8" })
138
+ );
139
+ }, [table]);
140
+
141
+ const toggleChart = useCallback((key: string) => {
142
+ setCharted((prev) => {
143
+ const next = new Set(prev);
144
+ if (next.has(key)) next.delete(key);
145
+ else next.add(key);
146
+ return next;
147
+ });
148
+ }, []);
149
+
150
+ // ── the Streamlit embed. C-TS: an honest placeholder, and above all it must not crash the
151
+ // component — the grid still runs inside app.py and a throw here would take the page.
152
+ if (embedded) {
153
+ return (
154
+ <div className="cg-mode-empty">
155
+ The time-series view runs in the web app. Open Loopable in a browser tab to see it.
156
+ </div>
157
+ );
158
+ }
159
+
160
+ if (!eligible.length) {
161
+ return (
162
+ <div className="cg-mode-empty">
163
+ This table has no measure fields yet. A time series needs a metric with a time
164
+ dimension — add one from a column menu, then pick it here. Formula fields cannot be
165
+ charted over time.
166
+ </div>
167
+ );
168
+ }
169
+
170
+ return (
171
+ <div className="cg-ts">
172
+ <div className="cg-ts-bar">
173
+ <label className="cg-ts-ctl">
174
+ <span className="cg-ts-ctl-k">Period</span>
175
+ <select
176
+ className="cg-select"
177
+ value={bucket}
178
+ onChange={(e) => onDisplay?.({ tsBucket: e.target.value as TsBucket })}
179
+ disabled={!onDisplay}
180
+ >
181
+ {TS_BUCKETS.map((b) => (
182
+ <option key={b} value={b}>
183
+ {BUCKET_LABELS[b]}
184
+ </option>
185
+ ))}
186
+ </select>
187
+ </label>
188
+ <label className="cg-ts-ctl">
189
+ <span className="cg-ts-ctl-k">Span</span>
190
+ <select
191
+ className="cg-select"
192
+ value={String(lastN)}
193
+ onChange={(e) => onDisplay?.({ tsSpan: { lastN: Number(e.target.value) } })}
194
+ disabled={!onDisplay}
195
+ >
196
+ {LAST_N_CHOICES.map((n) => (
197
+ <option key={n} value={n}>
198
+ Last {n}
199
+ </option>
200
+ ))}
201
+ </select>
202
+ </label>
203
+ <button
204
+ type="button"
205
+ className={"cg-tb-btn" + (showDelta ? " is-on" : "")}
206
+ onClick={() => setShowDelta((v) => !v)}
207
+ aria-pressed={showDelta}
208
+ >
209
+ Change vs prior
210
+ </button>
211
+ <button type="button" className="cg-tb-btn" onClick={onCsv} disabled={table.empty}>
212
+ Export CSV
213
+ </button>
214
+ <span className="cg-ts-pool">
215
+ {locked
216
+ ? "This record"
217
+ : `${table.pool.toLocaleString()} ${table.pool === 1 ? "customer" : "customers"}`}
218
+ </span>
219
+ </div>
220
+
221
+ <div className="cg-ts-fields">
222
+ <span className="cg-ts-ctl-k">Metrics</span>
223
+ {eligible.map((f) => {
224
+ const on = selected.includes(f.key);
225
+ return (
226
+ <button
227
+ key={f.key}
228
+ type="button"
229
+ className={"cg-ts-chip" + (on ? " is-on" : "")}
230
+ aria-pressed={on}
231
+ disabled={!onDisplay}
232
+ onClick={() => {
233
+ const next = on
234
+ ? selected.filter((k) => k !== f.key)
235
+ : [...selected, f.key].slice(0, TS_MAX_FIELDS);
236
+ // Never persist an EMPTY metric list: it would read back as "no data" on the
237
+ // next open. Un-picking the last one is a no-op, the same way the grid
238
+ // refuses to hide its last column.
239
+ if (next.length) onDisplay?.({ tsFields: next });
240
+ }}
241
+ >
242
+ {f.label}
243
+ </button>
244
+ );
245
+ })}
246
+ </div>
247
+
248
+ {state === "error" && (
249
+ <div className="cg-ts-note cg-ts-error">
250
+ {errStatus === 400
251
+ ? "That span is too wide to bucket. Choose a shorter span or a larger period."
252
+ : errStatus === 403
253
+ ? "None of these records are in your book."
254
+ : "The time series could not be loaded. Nothing is shown rather than a guess."}
255
+ </div>
256
+ )}
257
+
258
+ {state === "loading" && !payload && <div className="cg-ts-note">Loading…</div>}
259
+
260
+ {payload && table.empty && (
261
+ <div className="cg-ts-note">No metrics returned a series for this span.</div>
262
+ )}
263
+
264
+ {payload && !table.empty && (
265
+ <div className="cg-ts-scroll">
266
+ <table className="cg-ts-table">
267
+ <thead>
268
+ <tr>
269
+ <th className="cg-ts-stick">Metric</th>
270
+ {table.columns.map((c) => (
271
+ <th key={c.key} className={c.partial ? "is-partial" : undefined}>
272
+ {c.label}
273
+ {c.partial && <span className="cg-ts-partial"> · partial</span>}
274
+ </th>
275
+ ))}
276
+ <th className="cg-ts-total">Total</th>
277
+ </tr>
278
+ </thead>
279
+ <tbody>
280
+ {table.rows.map((r) => (
281
+ <TsRowBlock
282
+ key={r.field}
283
+ row={r}
284
+ table={table}
285
+ showDelta={showDelta}
286
+ charted={charted.has(r.field)}
287
+ onToggleChart={() => toggleChart(r.field)}
288
+ />
289
+ ))}
290
+ </tbody>
291
+ </table>
292
+ </div>
293
+ )}
294
+
295
+ {table.notes.length > 0 && (
296
+ <ul className="cg-ts-notes">
297
+ {table.notes.map((n) => (
298
+ <li key={n}>{n}</li>
299
+ ))}
300
+ </ul>
301
+ )}
302
+ </div>
303
+ );
304
+ }
305
+
306
+ /**
307
+ * One metric: its value row, an optional delta sub-row, and an optional line chart.
308
+ *
309
+ * The chart is built from `tsRowToChartModel`, NOT from `viz/chartData.buildChartData` — see
310
+ * that function's note. `buildChartData` caps at 12 buckets, which for a time series means
311
+ * silently deleting periods.
312
+ */
313
+ function TsRowBlock({
314
+ row,
315
+ table,
316
+ showDelta,
317
+ charted,
318
+ onToggleChart,
319
+ }: {
320
+ row: TsTableRow;
321
+ table: TsTable;
322
+ showDelta: boolean;
323
+ charted: boolean;
324
+ onToggleChart: () => void;
325
+ }) {
326
+ const spec = useMemo(() => {
327
+ if (!charted) return null;
328
+ const model = tsRowToChartModel(row, table.columns);
329
+ if (!model.points.length) return null;
330
+ return toVegaLiteSpec({
331
+ spec: { id: row.field, kind: "line", agg: row.agg as never },
332
+ model,
333
+ yTitle: row.label,
334
+ formatValue: (n) => n.toLocaleString(undefined, { maximumFractionDigits: 2 }),
335
+ });
336
+ }, [charted, row, table.columns]);
337
+
338
+ const colCount = table.columns.length + 2;
339
+
340
+ return (
341
+ <>
342
+ <tr>
343
+ <th scope="row" className="cg-ts-stick">
344
+ <button
345
+ type="button"
346
+ className="cg-ts-rowbtn"
347
+ onClick={onToggleChart}
348
+ aria-pressed={charted}
349
+ title={charted ? "Show as a row of numbers" : "Show as a line"}
350
+ >
351
+ {row.label}
352
+ </button>
353
+ </th>
354
+ {row.cells.map((c, i) => (
355
+ <td
356
+ key={table.columns[i]?.key ?? i}
357
+ className={c.partial ? "is-partial" : undefined}
358
+ >
359
+ {formatTsValue(c.value, (n) =>
360
+ n.toLocaleString(undefined, { maximumFractionDigits: 2 })
361
+ )}
362
+ </td>
363
+ ))}
364
+ <td className="cg-ts-total">
365
+ {/* An avg/min/max row has NO total — the cell stays empty rather than carrying an
366
+ average of averages. See timeSeriesData's header note (2). */}
367
+ {row.total == null
368
+ ? ""
369
+ : row.total.toLocaleString(undefined, { maximumFractionDigits: 2 })}
370
+ </td>
371
+ </tr>
372
+ {showDelta && (
373
+ <tr className="cg-ts-delta">
374
+ <th scope="row" className="cg-ts-stick">
375
+ vs prior
376
+ </th>
377
+ {row.cells.map((c, i) => (
378
+ <td
379
+ key={table.columns[i]?.key ?? i}
380
+ className={
381
+ c.delta == null ? undefined : c.delta >= 0 ? "is-up" : "is-down"
382
+ }
383
+ >
384
+ {formatTsDelta(c.delta)}
385
+ </td>
386
+ ))}
387
+ <td className="cg-ts-total" />
388
+ </tr>
389
+ )}
390
+ {charted && (
391
+ <tr className="cg-ts-chartrow">
392
+ <td colSpan={colCount}>
393
+ {spec ? (
394
+ <VegaLiteChart spec={spec} label={`${row.label} over time`} />
395
+ ) : (
396
+ <div className="cg-ts-note">
397
+ Nothing to plot — every period for this metric is unanswered.
398
+ </div>
399
+ )}
400
+ </td>
401
+ </tr>
402
+ )}
403
+ </>
404
+ );
405
+ }
web/src/customer-grid/Toolbar.tsx CHANGED
@@ -30,9 +30,9 @@ import type {
30
  SortSpec,
31
  } from "./types";
32
  import { COHORT_FIELD, COHORT_OPS, MAX_COHORT_IDS, MAX_FILTER_DEPTH, MEASURE_OPS,
33
- MEASURE_PAIR_OPS, STAT_KINDS, STAT_LABELS, VALUE_FREE_OPS, cohortIds, directionLabel,
34
- filterableFields, isDateFamilyType, isFilterGroup, isGroupableField, isMeasureRule,
35
- isNumericFieldType, normalizeCohortOp, rhsColId } from "./types";
36
  import type { CohortOp, StatKind } from "./types";
37
  import type { AnchorMode, WindowKind, WindowSpec } from "./windows";
38
  import { ANCHOR_LABELS, ANCHOR_MODES, MAX_N, N_KINDS, WINDOW_KINDS, WINDOW_LABELS }
@@ -42,6 +42,7 @@ import { FieldTypeIcon } from "./icons";
42
  import { TYPE_LABELS } from "./iconShapes";
43
  import { countLabel, countLabelCompact, poolProgressLabel } from "./counts";
44
  import type { PoolProgress } from "./counts";
 
45
 
46
  // --- filter/sort operator metadata (the UI vocabulary) ---------------------
47
  // Which ops each field type offers, and how they read to a human. The matching
@@ -107,8 +108,76 @@ function opsForType(t: FieldType): FilterOp[] {
107
  return ["contains", "doesNotContain", "eq", "neq", "isEmpty", "isNotEmpty"]; // text
108
  }
109
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
110
  /** Human label for an operator, read naturally per field type. */
111
  function opLabel(op: FilterOp, t: FieldType): string {
 
 
 
 
112
  // Checkbox first: its two value-free ops READ as states, not as blankness — the storage
113
  // contract ('1' or blank) is an implementation detail the sentence must not leak.
114
  if (t === "checkbox") {
@@ -387,6 +456,16 @@ export interface ToolbarProps {
387
  unresolvedCount?: number;
388
  /** Owner item 5 — the cohorts this user has, for `Where [Cohort] [is part of] […]`. */
389
  lists?: { id: string; name: string }[];
 
 
 
 
 
 
 
 
 
 
390
 
391
  recordCount: number;
392
  /** Server-windowed tables only. When present the count is rendered from the SCOPE, never
@@ -774,6 +853,65 @@ function ConditionValue({
774
  );
775
  }
776
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
777
  /**
778
  * The cohorts a `Where [Cohort] [is any of] […]` condition names (owner, 2026-07-27).
779
  *
@@ -1132,6 +1270,11 @@ function LeafRow({
1132
  // these three" are the same three cohorts asked about differently, and clearing them would
1133
  // make the obvious edit destructive.
1134
  if (isCohort) return patch({ op });
 
 
 
 
 
1135
  if (VALUE_FREE_OPS.has(op as FilterOp))
1136
  return onRule({ ...rule, op, value: "", value2: undefined, rhs: undefined });
1137
  if (op === "within")
@@ -1151,7 +1294,7 @@ function LeafRow({
1151
  && (isNumericType(t) ? isNumericType(f.type) : f.type === t))
1152
  .map((f) => ({ key: f.key, label: f.label }));
1153
  const canCompareField = !isCohort && rule.op !== "within"
1154
- && !VALUE_FREE_OPS.has(rule.op as FilterOp)
1155
  && rhsOptions.length > 0 && (isMeasure || isNumericType(t) || isDateFamily(t));
1156
  const usingStat = rule.rhs?.kind === "stat";
1157
  const usingField = rule.rhs != null && !usingStat;
@@ -1161,6 +1304,23 @@ function LeafRow({
1161
  ? (usingField || usingStat ? MEASURE_PAIR_OP_LIST : MEASURE_OP_LIST)
1162
  : isCohort ? COHORT_OP_LIST : opsForType(t);
1163
  const opValue: FilterOp | CohortOp = isCohort ? normalizeCohortOp(rule.op) : rule.op;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1164
 
1165
  return (
1166
  <span className={"cg-cond-row" + (isMeasure ? " is-measure" : "")
@@ -1204,7 +1364,7 @@ function LeafRow({
1204
  aria-label="Condition"
1205
  onChange={(e) => onOp(e.target.value as FilterOp | CohortOp)}
1206
  >
1207
- {withCurrent(opList, opValue).map((op) => (
1208
  <option key={op} value={op}>
1209
  {/* `op as FilterOp` is safe by construction, not by hope: `opList` is the cohort
1210
  vocabulary EXACTLY when `isCohort`, so the other branch only ever sees the
@@ -1213,6 +1373,15 @@ function LeafRow({
1213
  {isCohort ? cohortOpLabel(op) : opLabel(op as FilterOp, t)}
1214
  </option>
1215
  ))}
 
 
 
 
 
 
 
 
 
1216
  </select>
1217
  {canCompareField && (
1218
  // The switch between "a value I type" and "another attribute". Two options rather than
@@ -1270,6 +1439,8 @@ function LeafRow({
1270
  <RhsPicker rule={rule} options={rhsOptions} isMeasure={isMeasure} onPatch={patch} />
1271
  ) : isCohort ? (
1272
  <CohortPicker rule={rule} lists={lists} onPatch={patch} />
 
 
1273
  ) : rule.op === "within" ? (
1274
  <WindowPicker
1275
  window={rule.dateWindow ?? DEFAULT_DATE_WINDOW}
@@ -1371,6 +1542,7 @@ function FilterBuilder({
1371
  onFilters,
1372
  onFilterConj,
1373
  statusValues,
 
1374
  }: {
1375
  fields: Field[];
1376
  fieldByKey: Map<string, Field>;
@@ -1382,10 +1554,29 @@ function FilterBuilder({
1382
  onFilters: (f: FilterNode[]) => void;
1383
  onFilterConj: (c: Conjunction) => void;
1384
  statusValues: Record<string, string[]>;
 
1385
  }) {
1386
  return (
1387
  <div className="cg-pop-body cg-builder">
1388
  <div className="cg-pop-title">Filter</div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1389
  {filters.length === 0 ? (
1390
  <div className="cg-builder-empty">
1391
  No conditions. Add one to narrow the list.
@@ -1406,6 +1597,18 @@ function FilterBuilder({
1406
  onNodes={onFilters}
1407
  onConj={onFilterConj}
1408
  />
 
 
 
 
 
 
 
 
 
 
 
 
1409
  {filters.length > 0 && (
1410
  <div className="cg-pop-footer cg-builder-footer">
1411
  <button
@@ -1822,6 +2025,7 @@ export default function Toolbar({
1822
  pendingMeasureCount = 0,
1823
  unresolvedCount = 0,
1824
  lists = [],
 
1825
  search,
1826
  onSearch,
1827
  recordCount,
@@ -1955,6 +2159,7 @@ export default function Toolbar({
1955
  onFilters={onFilters}
1956
  onFilterConj={onFilterConj}
1957
  statusValues={statusValues}
 
1958
  />
1959
  )}
1960
  </Popover>
 
30
  SortSpec,
31
  } from "./types";
32
  import { COHORT_FIELD, COHORT_OPS, MAX_COHORT_IDS, MAX_FILTER_DEPTH, MEASURE_OPS,
33
+ MEASURE_PAIR_OPS, RANK_OPS, STAT_KINDS, STAT_LABELS, VALUE_FREE_OPS, cohortIds,
34
+ directionLabel, filterableFields, isDateFamilyType, isFilterGroup, isGroupableField,
35
+ isMeasureRule, isNumericFieldType, isRankOp, normalizeCohortOp, rhsColId } from "./types";
36
  import type { CohortOp, StatKind } from "./types";
37
  import type { AnchorMode, WindowKind, WindowSpec } from "./windows";
38
  import { ANCHOR_LABELS, ANCHOR_MODES, MAX_N, N_KINDS, WINDOW_KINDS, WINDOW_LABELS }
 
42
  import { TYPE_LABELS } from "./iconShapes";
43
  import { countLabel, countLabelCompact, poolProgressLabel } from "./counts";
44
  import type { PoolProgress } from "./counts";
45
+ import "./filters.css";
46
 
47
  // --- filter/sort operator metadata (the UI vocabulary) ---------------------
48
  // Which ops each field type offers, and how they read to a human. The matching
 
108
  return ["contains", "doesNotContain", "eq", "neq", "isEmpty", "isNotEmpty"]; // text
109
  }
110
 
111
+ /**
112
+ * C-OPS — the RANK operators, worded so the row still reads as a sentence.
113
+ *
114
+ * The unit lives in the OPERATOR, not beside the box: "top" followed by a bare 10 is ambiguous
115
+ * between ten records and ten percent, so `top N` and `top N%` are two operators and the box
116
+ * supplies N. The alternative — a "%" suffix element after the input — would put a second
117
+ * thing in the value slot that every gate locating `.cg-cond-val` would have to know about.
118
+ *
119
+ * ⚠ AND THEY ARE SHORT ON PURPOSE. A 136px `.cg-select` has ~97.9px of readable width (see
120
+ * `cohortOpLabel` above, and `withCurrentField` below) — about 15 characters of 12.5px Inter.
121
+ * "is in the bottom N%" is 19 and would have shipped CLIPPED, which no assertion here can see
122
+ * and no screenshot in this session could catch. Dropping the "is " costs nothing: the numeric
123
+ * operators beside these are bare glyphs (`≥ > ≤ <`), so the row already reads without one,
124
+ * and the `Ranked` divider carries the "these are a different kind of question" signal. Fifth
125
+ * time this control has outgrown a label; the label gives way, never the control.
126
+ */
127
+ const RANK_OP_LABELS: Record<string, string> = {
128
+ topN: "top N",
129
+ bottomN: "bottom N",
130
+ inTopPct: "top N%",
131
+ inBottomPct: "bottom N%",
132
+ aboveAvg: "above average",
133
+ belowAvg: "below average",
134
+ inQuartile: "in quartile",
135
+ inDecile: "in decile",
136
+ };
137
+
138
+ /**
139
+ * The value a rank op starts at when it is chosen.
140
+ *
141
+ * Seeded rather than left blank, and this is a deliberate break from how the other operators
142
+ * behave: a blank value makes a rule INACTIVE, so `is in the top N` with nothing typed would
143
+ * sit in the builder narrowing nothing, and "the filter I just added does nothing" reads as a
144
+ * broken control rather than as an unfinished sentence. Every rank op has an obvious default —
145
+ * ten, or the top slice — so there is a right answer to seed. The two averages take none.
146
+ */
147
+ function rankDefault(op: FilterOp): string {
148
+ switch (op) {
149
+ case "topN":
150
+ case "bottomN":
151
+ case "inTopPct":
152
+ case "inBottomPct":
153
+ case "inDecile":
154
+ return "10";
155
+ case "inQuartile":
156
+ return "4";
157
+ default:
158
+ return ""; // aboveAvg / belowAvg — value-free
159
+ }
160
+ }
161
+
162
+ /** Does this tree hold an ACTIVE-looking rank condition? Drives the builder's helper line —
163
+ * the semantics of a quantile are not guessable, so they are stated where they are chosen. */
164
+ function hasRankCondition(nodes: FilterNode[]): boolean {
165
+ for (const node of nodes ?? []) {
166
+ if (isFilterGroup(node)) {
167
+ if (hasRankCondition(node.children)) return true;
168
+ continue;
169
+ }
170
+ if (isRankOp(node.op) && !isMeasureRule(node)) return true;
171
+ }
172
+ return false;
173
+ }
174
+
175
  /** Human label for an operator, read naturally per field type. */
176
  function opLabel(op: FilterOp, t: FieldType): string {
177
+ // Rank first and type-independently: a rank op means the same thing on every numeric
178
+ // family, and a view whose column has since changed type must still SAY what it holds
179
+ // rather than falling through to a raw key.
180
+ if (isRankOp(op)) return RANK_OP_LABELS[op] ?? op;
181
  // Checkbox first: its two value-free ops READ as states, not as blankness — the storage
182
  // contract ('1' or blank) is an implementation detail the sentence must not leak.
183
  if (t === "checkbox") {
 
456
  unresolvedCount?: number;
457
  /** Owner item 5 — the cohorts this user has, for `Where [Cohort] [is part of] […]`. */
458
  lists?: { id: string; name: string }[];
459
+ /**
460
+ * Item 12 (C-LOCK) — this view is LOCKED to a cohort. Present = say so in the filter
461
+ * builder, because the lock narrows the list and is not one of the conditions shown there:
462
+ * without the banner the count and the conditions disagree with no visible reason.
463
+ *
464
+ * `name`/`count` ABSENT means the reader cannot see the set — a shared view locked to
465
+ * somebody else's cohort. The engine matches nothing in that case (fail-closed, the
466
+ * cohort-leaf law), so the banner has to say which kind of nothing this is.
467
+ */
468
+ cohortLock?: { name?: string; count?: number };
469
 
470
  recordCount: number;
471
  /** Server-windowed tables only. When present the count is rendered from the SCOPE, never
 
853
  );
854
  }
855
 
856
+ /**
857
+ * C-OPS — the value control for a rank condition.
858
+ *
859
+ * Two shapes, because the two questions are different: a COUNT (or a percentage) is typed and
860
+ * unbounded-ish, while a quantile is a choice from four or ten. Rendering the quantile as a
861
+ * number box would let somebody type `inQuartile 7`, which the engine refuses outright — the
862
+ * control that cannot express the invalid state is the better one.
863
+ *
864
+ * Bounds are on the input as `min`/`max` AND enforced in the engine, which is not redundancy:
865
+ * a number input's bounds are advisory (typing past them is allowed and only surfaces on form
866
+ * validation), so the box is a hint and `rankOps.bound` is the wall. A value outside the range
867
+ * makes the condition UNANSWERABLE — it matches nothing and says so beside the count.
868
+ */
869
+ function RankValue({
870
+ rule,
871
+ onValue,
872
+ }: {
873
+ rule: FilterRule;
874
+ onValue: (v: string) => void;
875
+ }) {
876
+ const buckets = rule.op === "inQuartile" ? 4 : rule.op === "inDecile" ? 10 : 0;
877
+ if (buckets) {
878
+ return (
879
+ <select
880
+ className="cg-select cg-cond-val"
881
+ value={rule.value}
882
+ aria-label={rule.op === "inQuartile" ? "Quartile" : "Decile"}
883
+ onChange={(e) => onValue(e.target.value)}
884
+ >
885
+ {Array.from({ length: buckets }, (_, i) => String(i + 1)).map((n) => (
886
+ <option key={n} value={n}>
887
+ {/* The ends are the ones people mean, so they say so rather than making the
888
+ reader remember which end 1 is. */}
889
+ {n === "1"
890
+ ? `${n} (lowest)`
891
+ : n === String(buckets)
892
+ ? `${n} (highest)`
893
+ : n}
894
+ </option>
895
+ ))}
896
+ </select>
897
+ );
898
+ }
899
+ const pct = rule.op === "inTopPct" || rule.op === "inBottomPct";
900
+ return (
901
+ <input
902
+ className="cg-input cg-cond-val"
903
+ type="number"
904
+ min={1}
905
+ max={pct ? 100 : 10000}
906
+ step={1}
907
+ placeholder={pct ? "10" : "10"}
908
+ aria-label={pct ? "Percent" : "How many"}
909
+ value={rule.value}
910
+ onChange={(e) => onValue(e.target.value)}
911
+ />
912
+ );
913
+ }
914
+
915
  /**
916
  * The cohorts a `Where [Cohort] [is any of] […]` condition names (owner, 2026-07-27).
917
  *
 
1270
  // these three" are the same three cohorts asked about differently, and clearing them would
1271
  // make the obvious edit destructive.
1272
  if (isCohort) return patch({ op });
1273
+ // C-OPS: a rank op arrives with its N already chosen (see rankDefault) and drops every
1274
+ // comparand — "the top 10 compared with another field" is not a question.
1275
+ if (isRankOp(op as string))
1276
+ return onRule({ ...rule, op: op as FilterOp, value: rankDefault(op as FilterOp),
1277
+ value2: undefined, rhs: undefined, dateWindow: undefined });
1278
  if (VALUE_FREE_OPS.has(op as FilterOp))
1279
  return onRule({ ...rule, op, value: "", value2: undefined, rhs: undefined });
1280
  if (op === "within")
 
1294
  && (isNumericType(t) ? isNumericType(f.type) : f.type === t))
1295
  .map((f) => ({ key: f.key, label: f.label }));
1296
  const canCompareField = !isCohort && rule.op !== "within"
1297
+ && !VALUE_FREE_OPS.has(rule.op as FilterOp) && !isRankOp(rule.op)
1298
  && rhsOptions.length > 0 && (isMeasure || isNumericType(t) || isDateFamily(t));
1299
  const usingStat = rule.rhs?.kind === "stat";
1300
  const usingField = rule.rhs != null && !usingStat;
 
1304
  ? (usingField || usingStat ? MEASURE_PAIR_OP_LIST : MEASURE_OP_LIST)
1305
  : isCohort ? COHORT_OP_LIST : opsForType(t);
1306
  const opValue: FilterOp | CohortOp = isCohort ? normalizeCohortOp(rule.op) : rule.op;
1307
+ // C-OPS — the RANK family, offered under its own divider for the numeric family only.
1308
+ //
1309
+ // A COLUMN only: a measure leaf is answered by a server-side pid set over a window, so
1310
+ // ranking one client-side would be a second answer to the same question (and the host's
1311
+ // MEASURE_OPS deliberately does not carry these). A cohort leaf is set membership.
1312
+ //
1313
+ // Offered separately rather than appended to `opsForType` because these operators are a
1314
+ // different KIND of question — every other one is about this row's value, these are about
1315
+ // where the row sits among the others — and a divider is the cheapest way to say so.
1316
+ const canRank = !isMeasure && !isCohort && isNumericType(t);
1317
+ // `withCurrent` runs over the COMBINED offer so a rule already holding a rank op is not
1318
+ // appended a second time; the split below then puts each op under the right heading. A
1319
+ // rank op on a field that can no longer be ranked still renders — as itself, in the group,
1320
+ // which is what lets somebody see it and change it.
1321
+ const offeredOps = withCurrent(canRank ? [...opList, ...RANK_OPS] : opList, opValue);
1322
+ const plainOps = offeredOps.filter((op) => !isRankOp(op));
1323
+ const rankedOps = offeredOps.filter((op) => isRankOp(op));
1324
 
1325
  return (
1326
  <span className={"cg-cond-row" + (isMeasure ? " is-measure" : "")
 
1364
  aria-label="Condition"
1365
  onChange={(e) => onOp(e.target.value as FilterOp | CohortOp)}
1366
  >
1367
+ {plainOps.map((op) => (
1368
  <option key={op} value={op}>
1369
  {/* `op as FilterOp` is safe by construction, not by hope: `opList` is the cohort
1370
  vocabulary EXACTLY when `isCohort`, so the other branch only ever sees the
 
1373
  {isCohort ? cohortOpLabel(op) : opLabel(op as FilterOp, t)}
1374
  </option>
1375
  ))}
1376
+ {rankedOps.length > 0 && (
1377
+ <optgroup label="Ranked">
1378
+ {rankedOps.map((op) => (
1379
+ <option key={op} value={op}>
1380
+ {opLabel(op as FilterOp, t)}
1381
+ </option>
1382
+ ))}
1383
+ </optgroup>
1384
+ )}
1385
  </select>
1386
  {canCompareField && (
1387
  // The switch between "a value I type" and "another attribute". Two options rather than
 
1439
  <RhsPicker rule={rule} options={rhsOptions} isMeasure={isMeasure} onPatch={patch} />
1440
  ) : isCohort ? (
1441
  <CohortPicker rule={rule} lists={lists} onPatch={patch} />
1442
+ ) : isRankOp(rule.op) ? (
1443
+ <RankValue rule={rule} onValue={(v) => patch({ value: v })} />
1444
  ) : rule.op === "within" ? (
1445
  <WindowPicker
1446
  window={rule.dateWindow ?? DEFAULT_DATE_WINDOW}
 
1542
  onFilters,
1543
  onFilterConj,
1544
  statusValues,
1545
+ cohortLock,
1546
  }: {
1547
  fields: Field[];
1548
  fieldByKey: Map<string, Field>;
 
1554
  onFilters: (f: FilterNode[]) => void;
1555
  onFilterConj: (c: Conjunction) => void;
1556
  statusValues: Record<string, string[]>;
1557
+ cohortLock?: { name?: string; count?: number };
1558
  }) {
1559
  return (
1560
  <div className="cg-pop-body cg-builder">
1561
  <div className="cg-pop-title">Filter</div>
1562
+ {/* C-LOCK (item 12) — the lock is NOT a condition row: it cannot be written here and
1563
+ cannot be removed here (the view menu owns it). So it has to be SAID here, above
1564
+ the conditions it bounds — otherwise the count and the conditions disagree and the
1565
+ builder shows nothing that explains the gap. A reader who cannot see the set gets a
1566
+ different sentence, because the engine shows them nobody and "no records" alone does
1567
+ not distinguish a permission wall from a filter that genuinely matches nobody. */}
1568
+ {cohortLock && (
1569
+ <div className="cg-flt-lockchip">
1570
+ {cohortLock.name
1571
+ ? `Customer list locked to ${cohortLock.name}` +
1572
+ (typeof cohortLock.count === "number"
1573
+ ? ` · ${cohortLock.count.toLocaleString()} ${
1574
+ cohortLock.count === 1 ? "customer" : "customers"
1575
+ }`
1576
+ : "")
1577
+ : "Customer list locked to a set you cannot see"}
1578
+ </div>
1579
+ )}
1580
  {filters.length === 0 ? (
1581
  <div className="cg-builder-empty">
1582
  No conditions. Add one to narrow the list.
 
1597
  onNodes={onFilters}
1598
  onConj={onFilterConj}
1599
  />
1600
+ {/* C-OPS — a ranked condition answers a question about the OTHER records, and there is
1601
+ no way to see from the row which others. Three sentences, shown only while one is in
1602
+ the tree: the population, what is left out of it, and the one thing about quantiles
1603
+ that is genuinely not guessable (equal-size by RANK, so two identical values can
1604
+ land on opposite sides of a boundary). */}
1605
+ {hasRankCondition(filters) && (
1606
+ <div className="cg-pop-note">
1607
+ Ranked among the records your other conditions keep — so “top 10” inside a filtered
1608
+ view means the top 10 of that view. Records with no value are not ranked at all.
1609
+ Quartiles and deciles are equal-size slices BY RANK, not by value.
1610
+ </div>
1611
+ )}
1612
  {filters.length > 0 && (
1613
  <div className="cg-pop-footer cg-builder-footer">
1614
  <button
 
2025
  pendingMeasureCount = 0,
2026
  unresolvedCount = 0,
2027
  lists = [],
2028
+ cohortLock,
2029
  search,
2030
  onSearch,
2031
  recordCount,
 
2159
  onFilters={onFilters}
2160
  onFilterConj={onFilterConj}
2161
  statusValues={statusValues}
2162
+ cohortLock={cohortLock}
2163
  />
2164
  )}
2165
  </Popover>
web/src/customer-grid/ViewSidebar.tsx CHANGED
@@ -59,6 +59,15 @@ interface ViewSidebarProps {
59
  /** Add the customers THIS view currently matches to a cohort. `cohortId` empty = create one
60
  * called `name`. The view need not be the active one — the caller re-runs the engine for it. */
61
  onAddToList?: (viewId: string, cohortId: string, name: string) => void;
 
 
 
 
 
 
 
 
 
62
  /**
63
  * The TENANT'S today (wave-2 item 4) — the payload's `today` string VERBATIM, seeding the
64
  * default cohort name `<view name> · <YYYY-MM-DD>`. Never the browser clock: a viewer a day
@@ -128,6 +137,7 @@ export default function ViewSidebar({
128
  onDelete,
129
  lists = [],
130
  onAddToList,
 
131
  today,
132
  onExport,
133
  folders,
@@ -169,6 +179,11 @@ export default function ViewSidebar({
169
  viewId: string;
170
  anchor: HTMLButtonElement;
171
  } | null>(null);
 
 
 
 
 
172
  const [newListName, setNewListName] = useState("");
173
  /** W2 — the Export format pane, anchored where the "…" menu was. */
174
  const [exportFor, setExportFor] = useState<{
@@ -384,8 +399,8 @@ export default function ViewSidebar({
384
  setCreateMenu((current) => (current ? null : event.currentTarget))
385
  }
386
  >
387
- <span className="cg-create-icon" aria-hidden="true">+</span>
388
- <span className="cg-create-label">Create new…</span>
389
  </button>
390
  </div>
391
 
@@ -715,7 +730,15 @@ export default function ViewSidebar({
715
  const mode = viewDisplayMode(view);
716
  return (
717
  <div
718
- className={"cg-view-row" + (active ? " is-active" : "")}
 
 
 
 
 
 
 
 
719
  key={view.id}
720
  draggable={foldersOn && !renaming && mayEditView(view, viewer)}
721
  onDragStart={(e) => e.dataTransfer.setData("text/plain", view.id)}
@@ -894,6 +917,56 @@ export default function ViewSidebar({
894
  </AnchoredOverlay>
895
  )}
896
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
897
  {/* C4 as amended — the folder-level bulk add. The confirm pane states the
898
  DEDUPED union and names every view it could not compute, because a
899
  partial union that looks complete is the failure this pane exists to
@@ -1048,6 +1121,27 @@ export default function ViewSidebar({
1048
  Add to cohort
1049
  </button>
1050
  )}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1051
  {/* I12 (C3) — freeze the DISPLAY MODE. Offered only to the creator or an admin,
1052
  and only a courtesy: the host enforces the same rule, because a hidden control
1053
  is still a reachable event. */}
 
59
  /** Add the customers THIS view currently matches to a cohort. `cohortId` empty = create one
60
  * called `name`. The view need not be the active one — the caller re-runs the engine for it. */
61
  onAddToList?: (viewId: string, cohortId: string, name: string) => void;
62
+ /**
63
+ * Item 12 (contract C-LOCK) — lock a view to a cohort, or `null` to unlock.
64
+ *
65
+ * ⚠ This menu is the ONLY emitter of `cohortLock` in the client. Optional so the rail still
66
+ * compiles and renders wherever the host has not accepted the key — the same posture every
67
+ * other optional action here takes, and the reason a half-deployed wave degrades to "the
68
+ * action is absent" rather than to "the action silently does nothing".
69
+ */
70
+ onCohortLock?: (viewId: string, cohortId: string | null) => void;
71
  /**
72
  * The TENANT'S today (wave-2 item 4) — the payload's `today` string VERBATIM, seeding the
73
  * default cohort name `<view name> · <YYYY-MM-DD>`. Never the browser clock: a viewer a day
 
137
  onDelete,
138
  lists = [],
139
  onAddToList,
140
+ onCohortLock,
141
  today,
142
  onExport,
143
  folders,
 
179
  viewId: string;
180
  anchor: HTMLButtonElement;
181
  } | null>(null);
182
+ /** Item 12 (C-LOCK) — which view's cohort lock the picker is open for. */
183
+ const [lockFor, setLockFor] = useState<{
184
+ viewId: string;
185
+ anchor: HTMLButtonElement;
186
+ } | null>(null);
187
  const [newListName, setNewListName] = useState("");
188
  /** W2 — the Export format pane, anchored where the "…" menu was. */
189
  const [exportFor, setExportFor] = useState<{
 
399
  setCreateMenu((current) => (current ? null : event.currentTarget))
400
  }
401
  >
402
+ <span className="cg-create-icon" aria-hidden="true">+</span>
403
+ <span className="cg-create-label">Create new…</span>
404
  </button>
405
  </div>
406
 
 
730
  const mode = viewDisplayMode(view);
731
  return (
732
  <div
733
+ // Item 12 (C-LOCK) — `cg-view-lockset` marks a view locked to a cohort. The
734
+ // rail is where someone chooses which table to open, and a locked view shows a
735
+ // different row set than its siblings for a reason no filter states; the mark
736
+ // is what makes that visible before the click rather than after it.
737
+ className={
738
+ "cg-view-row" +
739
+ (active ? " is-active" : "") +
740
+ (view.config?.cohortLock ? " cg-view-lockset" : "")
741
+ }
742
  key={view.id}
743
  draggable={foldersOn && !renaming && mayEditView(view, viewer)}
744
  onDragStart={(e) => e.dataTransfer.setData("text/plain", view.id)}
 
917
  </AnchoredOverlay>
918
  )}
919
 
920
+ {/* Item 12 (C-LOCK) — the lock picker. Lists the cohorts this reader can see, marks the
921
+ current one, and offers Unlock when there is one: a lock removable only from
922
+ somewhere other than where it was applied is a trap, and the owner asked for a
923
+ feature, not a one-way door. */}
924
+ {lockFor && onCohortLock && (() => {
925
+ const target = views.find((v) => v.id === lockFor.viewId);
926
+ const current = target?.config?.cohortLock;
927
+ return (
928
+ <AnchoredOverlay
929
+ anchor={lockFor.anchor}
930
+ className="cg-pop cg-lock-pop"
931
+ placement="bottom-start"
932
+ role="dialog"
933
+ ariaLabel="Lock this view to a cohort"
934
+ onDismiss={() => setLockFor(null)}
935
+ dataKind="view-cohort-lock"
936
+ >
937
+ <div className="cg-pop-title">Lock to cohort</div>
938
+ <div className="cg-pop-note">
939
+ A locked view can only ever show that cohort's customers. Filters still narrow
940
+ within it, and the lock cannot be removed as a condition.
941
+ </div>
942
+ {(lists ?? []).map((l) => (
943
+ <button
944
+ type="button"
945
+ key={l.id}
946
+ className={"cg-pick-row" + (l.id === current ? " is-on" : "")}
947
+ onClick={() => {
948
+ onCohortLock(lockFor.viewId, l.id);
949
+ setLockFor(null);
950
+ }}
951
+ >
952
+ {l.name}
953
+ </button>
954
+ ))}
955
+ {current && (
956
+ <button
957
+ type="button"
958
+ className="cg-pick-row cg-lock-clear"
959
+ onClick={() => {
960
+ onCohortLock(lockFor.viewId, null);
961
+ setLockFor(null);
962
+ }}
963
+ >
964
+ Unlock — show the whole table again
965
+ </button>
966
+ )}
967
+ </AnchoredOverlay>
968
+ );
969
+ })()}
970
  {/* C4 as amended — the folder-level bulk add. The confirm pane states the
971
  DEDUPED union and names every view it could not compute, because a
972
  partial union that looks complete is the failure this pane exists to
 
1121
  Add to cohort
1122
  </button>
1123
  )}
1124
+ {/* Item 12 (C-LOCK) — LOCK the view to a cohort. This menu is the ONLY emitter of
1125
+ `cohortLock`, which is why it lands after RECORD's engine: an emitter for an
1126
+ engine that cannot yet read the key writes a config that silently does nothing.
1127
+
1128
+ Deliberately NOT beside "Add to cohort" in meaning, though it sits beside it in
1129
+ the menu: that one COPIES today's matches into a set; this one makes the set the
1130
+ view's permanent boundary. The submenu lists the cohorts and offers Unlock when
1131
+ one is already set, because a lock that cannot be removed from the same place it
1132
+ was applied is a trap. */}
1133
+ {onCohortLock && lists.length > 0 && canEditMenuView && (
1134
+ <button
1135
+ type="button"
1136
+ role="menuitem"
1137
+ onClick={() => {
1138
+ setLockFor({ viewId: menuView.id, anchor: menu.anchor });
1139
+ setMenu(null);
1140
+ }}
1141
+ >
1142
+ {menuView.config?.cohortLock ? "Change cohort lock…" : "Lock to cohort…"}
1143
+ </button>
1144
+ )}
1145
  {/* I12 (C3) — freeze the DISPLAY MODE. Offered only to the creator or an admin,
1146
  and only a courtesy: the host enforces the same rule, because a hidden control
1147
  is still a reachable event. */}
web/src/customer-grid/apiBridge.ts CHANGED
@@ -51,6 +51,7 @@ import {
51
  } from "../apiContract";
52
  import { setStandaloneSink } from "./hostBridge";
53
  import type { CustomersPayload, GridWorkspace, HostEvent, Row } from "./types";
 
54
 
55
  const JSON_HEADERS = { "Content-Type": "application/json" };
56
 
@@ -197,6 +198,47 @@ export async function patchCustomer(pid: number, updates: Partial<Row>): Promise
197
  }
198
  }
199
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
200
  // --- the WRITE (CP-C) ------------------------------------------------------
201
 
202
  /**
 
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" };
57
 
 
198
  }
199
  }
200
 
201
+ /**
202
+ * Item 7 (contract C-TS) — `POST /api/v1/grid/timeseries`.
203
+ *
204
+ * A READ that is a POST, because the request body carries a pid list that can run to
205
+ * thousands: a URL cannot hold the caller's book, and putting customer ids in a query string
206
+ * would also put them in every access log. The server intersects those pids with the caller's
207
+ * `allowed_pids` regardless, so the body narrows the answer and can never widen it.
208
+ *
209
+ * ⚠ RETURNS `null` ON EVERY FAILURE, AND THE PANEL MUST SAY SO RATHER THAN DRAW ZEROES.
210
+ * That is the difference between this and a payload of empty buckets: "we could not ask" and
211
+ * "the answer is nothing" look identical on a chart and are not the same claim. A 400 is the
212
+ * honest "narrow the span"; a 403 is `out_of_scope` (every requested pid was outside the
213
+ * caller's book); a 401 ends the session like everywhere else.
214
+ */
215
+ export async function fetchTimeseries(
216
+ body: TsRequest,
217
+ scope: SurfaceScope = surfaceScope
218
+ ): Promise<{ payload: TsPayload | null; status: number }> {
219
+ try {
220
+ const res = await fetch(
221
+ `${API_V1}/grid/timeseries?scope=${encodeURIComponent(scope)}`,
222
+ {
223
+ method: "POST",
224
+ credentials: CREDENTIALS,
225
+ headers: JSON_HEADERS,
226
+ body: JSON.stringify(body),
227
+ }
228
+ );
229
+ if (handledUnauthorized(res.status)) return { payload: null, status: res.status };
230
+ if (!res.ok) return { payload: null, status: res.status };
231
+ const json = (await readJson(res)) as TsPayload | null;
232
+ // Shape-check before trusting it: `columns` and `rows` are indexed POSITIONALLY against
233
+ // each other, so a payload missing either would index into undefined all the way down.
234
+ if (!json || !Array.isArray(json.columns) || !Array.isArray(json.rows))
235
+ return { payload: null, status: res.status };
236
+ return { payload: json, status: res.status };
237
+ } catch {
238
+ return { payload: null, status: 0 };
239
+ }
240
+ }
241
+
242
  // --- the WRITE (CP-C) ------------------------------------------------------
243
 
244
  /**
web/src/customer-grid/filters.css ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* ---------------------------------------------------------------------------
2
+ customer-grid / filters.css
3
+ Styles owned by Toolbar.tsx that have no home in index.css this wave.
4
+ Imported by Toolbar.tsx, so it loads wherever the toolbar does — including
5
+ the Streamlit embed, which mounts the same component tree.
6
+ --------------------------------------------------------------------------- */
7
+
8
+ /* ==========================================================================
9
+ Wave 2026-08-02 item 12 (C-LOCK) — the view's cohort lock, said out loud.
10
+ ==========================================================================
11
+ A locked view IS a set of customers; the conditions below narrow WITHIN it.
12
+ The lock is not a condition row — it cannot be written or removed here — so
13
+ without this line the builder shows a count it does not explain.
14
+
15
+ Yellow, matching `.cg-lock-tag` (index.css:1294) rather than inventing a
16
+ colour: the two say the same thing about the same kind of thing (this is
17
+ fixed, not yours to change here), and the palette's `-deep` rule puts the
18
+ weight on the text while the fill stays a tint. A full-width banner instead
19
+ of that class's inline chip because this one is a sentence, not a marker on
20
+ something else — it has the popover's width and should use it. */
21
+ .cg-flt-lockchip {
22
+ margin: 0 8px 8px;
23
+ padding: 6px 9px;
24
+ border-radius: var(--lp-r-sm);
25
+ background: var(--lp-yellow-tint);
26
+ color: var(--lp-yellow-deep);
27
+ font-size: var(--lp-fs-3xs);
28
+ font-weight: 600;
29
+ line-height: 1.45;
30
+ }
web/src/customer-grid/iconShapes.ts CHANGED
@@ -126,6 +126,15 @@ export const MODE_SHAPES: Record<DisplayMode, IconShape[]> = {
126
  { d: "M8 2.6a3.6 3.6 0 0 1 3.6 3.6c0 2.7-3.6 7.2-3.6 7.2S4.4 8.9 4.4 6.2A3.6 3.6 0 0 1 8 2.6z" },
127
  { d: circle(8, 6.1, 1.3) },
128
  ],
 
 
 
 
 
 
 
 
 
129
  };
130
 
131
  /**
@@ -278,6 +287,7 @@ export const MODE_LABELS: Record<DisplayMode, string> = {
278
  calendar: "Calendar",
279
  kanban: "Kanban",
280
  map: "Map",
 
281
  };
282
 
283
  /**
@@ -289,6 +299,13 @@ export const MODE_LABELS: Record<DisplayMode, string> = {
289
  * express both. Living in this pure data module means the gate can assert the offered set
290
  * without importing a React component, and I10 becomes a one-line edit in one file.
291
  */
 
 
 
 
 
 
 
292
  export const CREATABLE_MODES: DisplayMode[] = [
293
  "grid",
294
  "chart",
@@ -296,6 +313,7 @@ export const CREATABLE_MODES: DisplayMode[] = [
296
  "calendar",
297
  "kanban",
298
  "map",
 
299
  ];
300
 
301
  export const MODE_TONE: Record<DisplayMode, FolderTone> = {
@@ -306,6 +324,8 @@ export const MODE_TONE: Record<DisplayMode, FolderTone> = {
306
  calendar: "yellow",
307
  kanban: "yellow",
308
  map: "red",
 
 
309
  };
310
 
311
  /**
 
126
  { d: "M8 2.6a3.6 3.6 0 0 1 3.6 3.6c0 2.7-3.6 7.2-3.6 7.2S4.4 8.9 4.4 6.2A3.6 3.6 0 0 1 8 2.6z" },
127
  { d: circle(8, 6.1, 1.3) },
128
  ],
129
+ // 2026-08-02 item 7 — the time-series view. Drawn as a framed grid with a trend running
130
+ // through it, because that is literally what the panel is: metric ROWS x bucket COLUMNS with
131
+ // a per-row line toggle. Deliberately not the plain `line` chart mark — a chart view and a
132
+ // time-series table must not be the same picture in the same rail.
133
+ timeseries: [
134
+ { d: "M2.6 3.4h10.8v9.2H2.6z" },
135
+ { d: "M2.6 6.6h10.8M6.2 3.4v9.2" },
136
+ { d: "M7.2 10.8l2-2.4 1.6 1.2 1.8-2.6" },
137
+ ],
138
  };
139
 
140
  /**
 
287
  calendar: "Calendar",
288
  kanban: "Kanban",
289
  map: "Map",
290
+ timeseries: "Time series",
291
  };
292
 
293
  /**
 
299
  * express both. Living in this pure data module means the gate can assert the offered set
300
  * without importing a React component, and I10 becomes a one-line edit in one file.
301
  */
302
+ // 2026-08-02 item 7 — `timeseries` was deliberately held OUT of this list until the host
303
+ // accepted the name, because a mode may be READABLE before it is OFFERABLE (the same split C2
304
+ // wrote for 'dashboard', running forwards): `aios_grid._clean_display` drops a mode it does
305
+ // not know, so offering it early would let a user create a view that silently reverts to a
306
+ // grid on the next read with nothing going red. HOST posted "ACCEPTANCE LANDED" with
307
+ // `DISPLAY_MODES += timeseries`, so it is offerable now. Listed last: it is the analytical
308
+ // mode, and it belongs beside Chart rather than in front of the record-shaped ones.
309
  export const CREATABLE_MODES: DisplayMode[] = [
310
  "grid",
311
  "chart",
 
313
  "calendar",
314
  "kanban",
315
  "map",
316
+ "timeseries",
317
  ];
318
 
319
  export const MODE_TONE: Record<DisplayMode, FolderTone> = {
 
324
  calendar: "yellow",
325
  kanban: "yellow",
326
  map: "red",
327
+ // Green with `chart`: it is the other analytical mode, and the two belong to one family.
328
+ timeseries: "green",
329
  };
330
 
331
  /**
web/src/customer-grid/rankOps.ts ADDED
@@ -0,0 +1,316 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // ---------------------------------------------------------------------------
2
+ // customer-grid / rankOps.ts
3
+ // Wave 2026-08-02 item 10 (contract C-OPS) — the RANK operators, pure.
4
+ //
5
+ // Every other filter operator answers a question about ONE cell: `revenue > 5000`
6
+ // is true or false for a row on its own. A rank operator cannot be answered that
7
+ // way at all — "is this customer in the top 10" depends on which OTHER rows are
8
+ // in the question. That is the whole design problem, and it is why this is a
9
+ // separate resolution PASS rather than eight more cases in `matchFilter`:
10
+ //
11
+ // 1. strip every rank leaf from the tree (stripRankLeaves)
12
+ // 2. evaluate the residue -> that match-set is the DOMAIN (the caller does)
13
+ // 3. rank the domain, once per column, and hand each leaf its slice (this file)
14
+ // 4. evaluate the FULL tree, rank leaves as membership tests (useVisibleRows)
15
+ //
16
+ // So "top 10 of agent Naomi" narrows by agent FIRST and then takes ten, which is
17
+ // what the sentence says and not what a naive per-row implementation would do.
18
+ //
19
+ // THE FAIL-CLOSED LAW, restated because a rank leaf is where it bites hardest: a
20
+ // leaf this file cannot answer gets an EMPTY set, never a missing one. A missing
21
+ // set would land in `evalNode`'s "no answer" branch, and the tempting reading of
22
+ // "no answer" is "no narrowing" — which shows every record under a count nobody
23
+ // would doubt. The unanswerable ones are COUNTED instead, so the empty table has
24
+ // a marker beside it saying why.
25
+ // ---------------------------------------------------------------------------
26
+
27
+ import type { Field, FieldType, FilterNode, FilterRule, Row } from "./types";
28
+ import { isFilterGroup, isMeasureRule, isRankOp, isRuleActive } from "./types";
29
+
30
+ /** `leaf -> the pids that satisfy it`. Keyed by the leaf OBJECT: a rank leaf carries no id of
31
+ * its own (only measure rules do), and keying by position would silently re-associate every
32
+ * answer the moment a condition was deleted — the trap `FilterRule.id` exists to avoid. The
33
+ * tree is stable for the life of one pipeline run, which is exactly this map's lifetime. */
34
+ export type RankSets = Map<FilterRule, Set<number>>;
35
+
36
+ export interface RankResolution {
37
+ sets: RankSets;
38
+ /**
39
+ * ACTIVE rank leaves that could not be answered AT ALL — the same distinction
40
+ * `unresolvedConditions` draws for dates and cohorts, and for the same reason: they match
41
+ * nothing, and "0 records" with no marker is indistinguishable from a filter that genuinely
42
+ * matches nobody. Three causes, all of them counted:
43
+ * - the column is gone, or is not of a type that can be ranked
44
+ * - the column has no numeric value ANYWHERE in a non-empty domain (a measure column
45
+ * whose values have not arrived — cold store, or a window still resolving)
46
+ * - the operator's value is junk (a saved view holding `inQuartile 9`)
47
+ */
48
+ unanswerable: number;
49
+ }
50
+
51
+ /** The resolution of a tree with no rank leaves in it. Shared, never mutated. */
52
+ export const NO_RANKING: RankResolution = { sets: new Map(), unanswerable: 0 };
53
+
54
+ /**
55
+ * Types a rank operator may be applied to.
56
+ *
57
+ * The engine's own copy, deliberately — `useVisibleRows.isNumericType` carries the same list
58
+ * with the same comment, because that file is the self-contained reference the Python port
59
+ * mirrors. Two copies pinned by a gate beat one import that quietly widens both.
60
+ */
61
+ function isRankableType(t: FieldType): boolean {
62
+ return t === "currency" || t === "int" || t === "pct" || t === "rating" || t === "formula";
63
+ }
64
+
65
+ /**
66
+ * True when this leaf asks a RANK question.
67
+ *
68
+ * A MEASURE leaf is excluded by construction even if it somehow carried a rank op: a measure
69
+ * condition is answered by a server-side pid set, so ranking it client-side would be a second,
70
+ * disagreeing answer to the same question. (The builder cannot produce one — measure leaves
71
+ * offer `MEASURE_OPS` — so this is the backstop, not the behaviour.)
72
+ */
73
+ export function isRankRule(node: FilterNode): boolean {
74
+ return (
75
+ !isFilterGroup(node) && !isMeasureRule(node) && isRankOp((node as FilterRule).op)
76
+ );
77
+ }
78
+
79
+ /** Does this tree contain ANY rank leaf, active or not? The pipeline's cheap early-out: with
80
+ * no rank leaf, not one line of this file runs and the engine is byte-for-byte as shipped. */
81
+ export function hasRankLeaf(nodes: FilterNode[]): boolean {
82
+ for (const node of nodes ?? []) {
83
+ if (isFilterGroup(node)) {
84
+ if (hasRankLeaf(node.children)) return true;
85
+ continue;
86
+ }
87
+ if (isRankRule(node)) return true;
88
+ }
89
+ return false;
90
+ }
91
+
92
+ /**
93
+ * The tree with every rank leaf removed — the question whose answer is the ranking DOMAIN.
94
+ *
95
+ * A group left with no children is DROPPED rather than kept empty. Both behave identically
96
+ * today (`evalNode` returns null for a group with no active children, and null is ignored),
97
+ * but an empty group is a shape the rest of the engine never otherwise sees, and shapes that
98
+ * only appear in one code path are how a future edit acquires a special case.
99
+ */
100
+ export function stripRankLeaves(nodes: FilterNode[]): FilterNode[] {
101
+ const out: FilterNode[] = [];
102
+ for (const node of nodes ?? []) {
103
+ if (isFilterGroup(node)) {
104
+ const children = stripRankLeaves(node.children);
105
+ if (children.length) out.push({ conj: node.conj, children });
106
+ continue;
107
+ }
108
+ if (isRankRule(node)) continue;
109
+ out.push(node);
110
+ }
111
+ return out;
112
+ }
113
+
114
+ /** Every ACTIVE rank leaf, in tree order. Inactive ones (a `topN` with no N typed yet) are
115
+ * left out for the same reason every other half-typed condition is: they are not asking. */
116
+ export function activeRankLeaves(nodes: FilterNode[]): FilterRule[] {
117
+ const out: FilterRule[] = [];
118
+ for (const node of nodes ?? []) {
119
+ if (isFilterGroup(node)) {
120
+ out.push(...activeRankLeaves(node.children));
121
+ continue;
122
+ }
123
+ if (!isRankRule(node)) continue;
124
+ const rule = node as FilterRule;
125
+ if (isRuleActive(rule)) out.push(rule);
126
+ }
127
+ return out;
128
+ }
129
+
130
+ /** One domain row reduced to what ranking needs. */
131
+ interface Ranked {
132
+ pid: number;
133
+ v: number;
134
+ }
135
+
136
+ /**
137
+ * The domain's rows that HAVE a value for `colId`, ordered.
138
+ *
139
+ * ⚠ `Number(raw)` is used and `toNum` is NOT: the engine's coercion helper turns anything
140
+ * unparseable into 0, which is right for a comparison (`x > 5` against a blank is false either
141
+ * way) and catastrophic here — every blank customer would enter the ranking as a real zero and
142
+ * fill the bottom of every "bottom 10". A blank is not a zero; it is an absence, and an absence
143
+ * has no rank. Note that a genuine 0 stays in: `raw === ""` is the test, not falsiness.
144
+ *
145
+ * The tie-break is `pid` ASCENDING in BOTH directions, never a reversal of the whole order:
146
+ * "keep exactly N, tie-break pid ascending" has to mean the same N whichever end you ask from,
147
+ * or "top 10" and "bottom 10" of a ten-row table would not be the same ten rows.
148
+ */
149
+ function order(domain: Row[], colId: string, dir: "asc" | "desc"): Ranked[] {
150
+ const out: Ranked[] = [];
151
+ for (const r of domain) {
152
+ const raw = r[colId];
153
+ if (raw == null || raw === "") continue;
154
+ const v = typeof raw === "number" ? raw : Number(raw);
155
+ if (!Number.isFinite(v)) continue;
156
+ out.push({ pid: r.pid, v });
157
+ }
158
+ out.sort((a, b) => (a.v === b.v ? a.pid - b.pid : dir === "asc" ? a.v - b.v : b.v - a.v));
159
+ return out;
160
+ }
161
+
162
+ /** The leaf's rhs as a whole number inside [lo, hi], or null when it is junk. Null is an
163
+ * UNANSWERABLE leaf, never a defaulted one — silently reading `inQuartile 9` as 4 would answer
164
+ * a question the view does not ask. */
165
+ function bound(value: string, lo: number, hi: number): number | null {
166
+ const n = Number(value);
167
+ if (!Number.isFinite(n)) return null;
168
+ const i = Math.trunc(n);
169
+ if (i !== n || i < lo || i > hi) return null;
170
+ return i;
171
+ }
172
+
173
+ /**
174
+ * Which of `k` equal slices of the RANK AXIS row `index` falls in. Bucket 1 is the lowest
175
+ * slice and bucket `k` the highest, so `inQuartile 4` is the top quarter — which is how the
176
+ * operator reads.
177
+ *
178
+ * `floor(i * k / n) + 1` — the slice of [0, 1) that i/n lands in — rather than the literal
179
+ * `floor(i / ceil(n / k)) + 1` the contract's "ceil split" first suggests. The difference is
180
+ * not cosmetic: fixed ceil-sized buckets leave the TOP one EMPTY whenever n sits a little
181
+ * above a multiple of k (six rows into quarters gives 2/2/2/0), so "the top quarter" would
182
+ * match nobody while three lower quarters were full. This form gives 2/1/2/1 — every bucket
183
+ * non-empty, sizes differing by at most one. Amendment booked in the wave doc.
184
+ *
185
+ * Buckets are by RANK INDEX, not by value: two rows sharing a value can land either side of a
186
+ * boundary, broken by pid ascending. That is what "equal-size buckets" means and it is the
187
+ * contract's explicit choice over value interpolation — said here because the builder's helper
188
+ * line has to say it to the user in one sentence.
189
+ */
190
+ function slice(index: number, n: number, k: number): number {
191
+ return Math.min(k, Math.floor((index * k) / n) + 1);
192
+ }
193
+
194
+ /** How many rows `pct` percent of `n` is. Ceil: "the top 10%" of 43 must not be 4.3, and
195
+ * rounding DOWN would make the top 1% of anything under 100 rows match nobody. */
196
+ function pctCount(n: number, pct: number): number {
197
+ return Math.min(n, Math.max(1, Math.ceil((n * pct) / 100)));
198
+ }
199
+
200
+ /**
201
+ * Resolve every ACTIVE rank leaf against the domain.
202
+ *
203
+ * `domain` is the rows matching everything EXCEPT the rank leaves — the caller computes it, so
204
+ * that this file never needs to know how a cohort or a measure condition is answered.
205
+ */
206
+ export function resolveRankLeaves(
207
+ filters: FilterNode[],
208
+ domain: Row[],
209
+ fieldByKey: Map<string, Field>
210
+ ): RankResolution {
211
+ const leaves = activeRankLeaves(filters);
212
+ if (!leaves.length) return NO_RANKING;
213
+
214
+ const sets: RankSets = new Map();
215
+ let unanswerable = 0;
216
+ // Several leaves can name the same column ("top 10" AND "above average" by revenue), and the
217
+ // sort is the expensive half. Cached per column PER DIRECTION — see `order`.
218
+ const cache = new Map<string, Ranked[]>();
219
+ const ordered = (colId: string, dir: "asc" | "desc"): Ranked[] => {
220
+ const ck = `${dir}:${colId}`;
221
+ let list = cache.get(ck);
222
+ if (!list) {
223
+ list = order(domain, colId, dir);
224
+ cache.set(ck, list);
225
+ }
226
+ return list;
227
+ };
228
+ const refuse = (leaf: FilterRule) => {
229
+ sets.set(leaf, new Set());
230
+ unanswerable += 1;
231
+ };
232
+
233
+ for (const leaf of leaves) {
234
+ const field = fieldByKey.get(leaf.colId);
235
+ // A rank op on a column that is gone, or on text/date/select. NOT the engine's usual
236
+ // "an operator that does not apply to this type is always-true" case, and the divergence
237
+ // is deliberate: always-true is safe for `contains` on a number (it narrows nothing and
238
+ // asks nothing), but a rank operator is a NARROWING question, and answering "everybody"
239
+ // to "who is in the top ten" is the widening sin wearing a plausible face.
240
+ if (!field || !isRankableType(field.type)) {
241
+ refuse(leaf);
242
+ continue;
243
+ }
244
+
245
+ const asc = ordered(leaf.colId, "asc");
246
+ if (!asc.length) {
247
+ // No value anywhere. With an EMPTY domain that is just "your other conditions matched
248
+ // nobody" — already explained by the rows — so it is not counted twice. With a populated
249
+ // domain it means the column itself has no values: a measure column whose derived cells
250
+ // have not arrived, which is precisely the state that must not read as "top 10 of
251
+ // nothing = everything".
252
+ sets.set(leaf, new Set());
253
+ if (domain.length) unanswerable += 1;
254
+ continue;
255
+ }
256
+
257
+ const n = asc.length;
258
+ let keep: Ranked[] | null = null;
259
+ switch (leaf.op) {
260
+ case "topN": {
261
+ const k = bound(leaf.value, 1, 10000);
262
+ keep = k == null ? null : ordered(leaf.colId, "desc").slice(0, k);
263
+ break;
264
+ }
265
+ case "bottomN": {
266
+ const k = bound(leaf.value, 1, 10000);
267
+ keep = k == null ? null : asc.slice(0, k);
268
+ break;
269
+ }
270
+ case "inTopPct": {
271
+ const p = bound(leaf.value, 1, 100);
272
+ keep = p == null ? null : ordered(leaf.colId, "desc").slice(0, pctCount(n, p));
273
+ break;
274
+ }
275
+ case "inBottomPct": {
276
+ const p = bound(leaf.value, 1, 100);
277
+ keep = p == null ? null : asc.slice(0, pctCount(n, p));
278
+ break;
279
+ }
280
+ case "aboveAvg":
281
+ case "belowAvg": {
282
+ // The mean of the DOMAIN's values, not of the whole table — the same residue rule
283
+ // every other rank op follows, so "above average, among agent Naomi's customers"
284
+ // means what it says.
285
+ const mean = asc.reduce((sum, e) => sum + e.v, 0) / n;
286
+ keep = asc.filter((e) => (leaf.op === "aboveAvg" ? e.v > mean : e.v < mean));
287
+ break;
288
+ }
289
+ case "inQuartile":
290
+ case "inDecile": {
291
+ const k = leaf.op === "inQuartile" ? 4 : 10;
292
+ const want = bound(leaf.value, 1, k);
293
+ // FEWER ROWS THAN BUCKETS is a question the data cannot answer, and it is the one
294
+ // place where inventing a definition would be indefensible: with six ranked rows and
295
+ // ten deciles, SOME decile is empty whatever the rule, so any formula chooses which
296
+ // asks go unanswered. Refusing says so out loud (and gets counted) instead of quietly
297
+ // returning nobody for "the top decile" and everybody's guess for the rest.
298
+ keep = want == null || n < k ? null : asc.filter((_, i) => slice(i, n, k) === want);
299
+ break;
300
+ }
301
+ default:
302
+ // A rank op this file does not implement. Unreachable through `RANK_OPS`, and it
303
+ // REFUSES rather than falling through — the one behaviour that keeps adding an
304
+ // operator to the vocabulary from silently widening every view that uses it.
305
+ keep = null;
306
+ }
307
+
308
+ if (keep == null) {
309
+ refuse(leaf);
310
+ continue;
311
+ }
312
+ sets.set(leaf, new Set(keep.map((e) => e.pid)));
313
+ }
314
+
315
+ return { sets, unanswerable };
316
+ }
web/src/customer-grid/recordLayout.ts ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // ---------------------------------------------------------------------------
2
+ // customer-grid / recordLayout.ts
3
+ // Wave 2026-08-02 item 5 (contract C-LAYOUT) — the PURE half of the record
4
+ // modal's per-user field order: resolve a saved order against the fields that
5
+ // actually exist, and move one key within it.
6
+ //
7
+ // A module of its own rather than four functions inside RecordDetail.tsx for
8
+ // two reasons, one mechanical and one that matters more: a component file that
9
+ // also exports plain functions breaks React fast refresh (the counts.ts /
10
+ // types.ts precedent), and an ORDER is exactly the kind of logic that is
11
+ // trivial to get subtly wrong and impossible to see wrong — a dropped key
12
+ // renders as a missing field, a duplicated one as a field that appears twice,
13
+ // and both look like data problems. Pure and node-gated
14
+ // (web/verify_record_layout.py), neither can ship unnoticed.
15
+ // ---------------------------------------------------------------------------
16
+
17
+ /**
18
+ * The drag payload's MIME type.
19
+ *
20
+ * NOT `text/plain`, and that is correctness rather than taste: a textarea is a native drop
21
+ * target for text, so a `text/plain` payload released over a note would be INSERTED INTO IT —
22
+ * the user reorders a field and finds `notes_2` typed into their note. A private type is
23
+ * invisible to that default. (The row's `onDrop` preventDefault is the second layer: `drop`
24
+ * bubbles, so cancelling it at the row cancels the textarea's insertion too.)
25
+ *
26
+ * Firefox refuses to start a drag unless SOMETHING is set, so this carries the key rather
27
+ * than being a bare marker.
28
+ */
29
+ // Annotated `: string` rather than left as a literal type: it is a MIME string handed to
30
+ // `dataTransfer`, and the literal type made the gate's "this is not text/plain" leg a
31
+ // compile-time tautology TypeScript refused to let the test even write.
32
+ export const FIELD_DRAG_TYPE: string = "application/x-cg-field";
33
+
34
+ /**
35
+ * C-LAYOUT's cap on a stored order. Mirrored here for the host's benefit, NOT applied on
36
+ * read: truncating a long order client-side would hide fields the host is willing to serve,
37
+ * which is the failure this module exists to prevent. It bounds what we SEND.
38
+ */
39
+ export const MAX_RECORD_LAYOUT = 200;
40
+
41
+ /**
42
+ * The order to render in: the saved order first (pruned to fields that exist, deduped),
43
+ * then every remaining field in `defaultOrder`.
44
+ *
45
+ * `defaultOrder` is the whole vocabulary — the exact set of fields the panel renders — so
46
+ * this is a PERMUTATION of it and can never be anything else. A saved layout naming a
47
+ * deleted column, the title column, or a field the viewer cannot see adds nothing; one that
48
+ * names a field twice renders it once. That is the difference between a stale layout
49
+ * degrading to a partial one and a stale layout losing a field.
50
+ *
51
+ * Unlisted fields APPEND, which is also what happens to a field created after this user last
52
+ * dragged: it arrives at the bottom rather than at a position nobody chose (Airtable does the
53
+ * same, and the alternative — guessing an interleaving — would move fields the user placed).
54
+ */
55
+ export function resolveFieldOrder(
56
+ saved: readonly string[] | undefined,
57
+ defaultOrder: readonly string[]
58
+ ): string[] {
59
+ const renderable = new Set(defaultOrder);
60
+ const seen = new Set<string>();
61
+ const out: string[] = [];
62
+ for (const key of saved ?? []) {
63
+ if (!renderable.has(key) || seen.has(key)) continue;
64
+ seen.add(key);
65
+ out.push(key);
66
+ }
67
+ for (const key of defaultOrder) {
68
+ if (seen.has(key)) continue;
69
+ seen.add(key);
70
+ out.push(key);
71
+ }
72
+ return out;
73
+ }
74
+
75
+ /**
76
+ * Move `key` to the slot `target` occupies, returning a NEW array — or the INPUT array,
77
+ * by reference, when nothing moves. The caller compares by identity and skips the write, so a
78
+ * drag that lands where it started costs no event and no round trip.
79
+ *
80
+ * "The slot `target` occupies" is what the splice pair produces and it is worth stating,
81
+ * because the arithmetic reads like an off-by-one: removing an element BEFORE the target
82
+ * shifts the target down one, so inserting at the target's original index lands the dragged
83
+ * field after it — at the index the target used to hold. Dragging down therefore drops below
84
+ * the row under the pointer and dragging up drops above it, which is what the pointer is
85
+ * pointing at in both directions.
86
+ */
87
+ export function moveKey(order: string[], key: string, target: string): string[] {
88
+ const from = order.indexOf(key);
89
+ const to = order.indexOf(target);
90
+ if (from < 0 || to < 0 || from === to) return order;
91
+ const next = [...order];
92
+ next.splice(from, 1);
93
+ next.splice(to, 0, key);
94
+ return next;
95
+ }
96
+
97
+ /** Move `key` one slot in `delta`'s direction (the keyboard fallback). Clamped at both ends:
98
+ * arrowing past an end returns the input array, so the grip keeps focus and nothing commits. */
99
+ export function nudgeKey(order: string[], key: string, delta: -1 | 1): string[] {
100
+ const from = order.indexOf(key);
101
+ const to = from + delta;
102
+ if (from < 0 || to < 0 || to >= order.length) return order;
103
+ const next = [...order];
104
+ next.splice(from, 1);
105
+ next.splice(to, 0, key);
106
+ return next;
107
+ }
web/src/customer-grid/timeSeriesData.ts ADDED
@@ -0,0 +1,351 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * timeSeriesData.ts — owner item 7 (contract C-TS), the PURE half of the time-series view.
3
+ *
4
+ * Rows are metric fields, columns are time buckets. Everything that decides what a cell SAYS
5
+ * lives here so `web/verify_timeseries.py` can gate it under node with no DOM: the panel is
6
+ * then only layout, and none of the arithmetic hides inside a component.
7
+ *
8
+ * The wire shape is HOST's, shipped and gated by `verify_api.py` E1d. Four of its properties
9
+ * are load-bearing and every one of them is a way this table could lie:
10
+ *
11
+ * 1. **Zero-fill is asymmetric.** An empty bucket is `0` for a sum/count measure and `null`
12
+ * for everything else. `null` means UNANSWERABLE (the store was cold for that window), and
13
+ * an unanswerable bucket drawn as 0 is a fabricated data point — the flat stretch on a
14
+ * chart that never happened. `null` renders "—", never 0.
15
+ * 2. **`total` is present only for sum/count rows.** An average is not additive across
16
+ * buckets, so there is no total to show and we do not invent one: avg/min/max rows get an
17
+ * EMPTY totals cell. Computing `mean(values)` there would be an average of averages —
18
+ * exactly the additivity law C-TS names, and wrong by a different amount every time.
19
+ * 3. **A `partial` column is a bucket whose calendar end is past today.** Drawn unmarked
20
+ * beside complete buckets, a half-month reads as a collapse. It is marked.
21
+ * 4. **`meta.dropped` / `meta.problems` are answers, not noise.** A field the server could
22
+ * not series (not a measure; a composite ratio with no single aggregate expression) must
23
+ * be SAID. Silently rendering the rows that worked is the [[no-unverifiable-aggregates]]
24
+ * failure wearing a smaller hat.
25
+ *
26
+ * And one consequence of (1) that only shows up in the delta row: because sum/count buckets
27
+ * zero-fill to 0, "percent change vs the prior bucket" has a GUARANTEED division-by-zero path.
28
+ * See `deltaPct`.
29
+ */
30
+
31
+ import type { ChartAgg, ChartModel } from "../viz/chartData";
32
+ import { TS_MAX_BUCKETS, TS_MAX_FIELDS, TS_MAX_LAST_N, TS_BUCKETS } from "./types";
33
+ import type { TsBucket } from "./types";
34
+
35
+ // ---------------------------------------------------------------- the wire
36
+
37
+ /** One time bucket = one column. `key` is the bucket's START as an ISO date. */
38
+ export interface TsColumn {
39
+ key: string;
40
+ label: string;
41
+ from: string;
42
+ to: string;
43
+ /** The bucket's calendar end is past today — it is still filling. */
44
+ partial?: boolean;
45
+ }
46
+
47
+ /** One metric field = one row. `values` is positional against `columns`. */
48
+ export interface TsRow {
49
+ field: string;
50
+ label: string;
51
+ agg: string;
52
+ values: (number | null)[];
53
+ /** Present ONLY for sum/count. See the header note (2). */
54
+ total?: number | null;
55
+ }
56
+
57
+ export interface TsMeta {
58
+ pool: number;
59
+ today?: string;
60
+ bucket?: string;
61
+ /** Fields the server refused, with why. Rendered, never swallowed. */
62
+ dropped?: { field: string; reason: string }[];
63
+ problems?: string[];
64
+ }
65
+
66
+ export interface TsPayload {
67
+ columns: TsColumn[];
68
+ rows: TsRow[];
69
+ meta: TsMeta;
70
+ }
71
+
72
+ export interface TsRequest {
73
+ pids: number[];
74
+ bucket: TsBucket;
75
+ span: { lastN: number } | { from?: string; to?: string };
76
+ fields: string[];
77
+ }
78
+
79
+ /** The aggregates that ADD UP across buckets, and so may carry a total. */
80
+ const ADDITIVE_AGGS: ReadonlySet<string> = new Set(["sum", "count"]);
81
+
82
+ export function isAdditiveAgg(agg: string): boolean {
83
+ return ADDITIVE_AGGS.has(agg);
84
+ }
85
+
86
+ // ------------------------------------------------------------- the request
87
+
88
+ export const DEFAULT_TS_BUCKET: TsBucket = "month";
89
+ export const DEFAULT_TS_LAST_N = 12;
90
+
91
+ /**
92
+ * Build the POST body, clamped to the SAME caps the server enforces.
93
+ *
94
+ * Clamping here is not belt-and-braces: an over-cap request is a 400, and a 400 renders as
95
+ * "the panel is broken" rather than as the honest "narrow the span". We ask a question the
96
+ * server can answer, and the picker never offers past the cap in the first place.
97
+ *
98
+ * ⚠ `lastN` WINS over `from`/`to` when both are somehow present — the host's documented
99
+ * precedence. Mirroring it means a saved view carrying both resolves to the same window at
100
+ * both ends instead of two different tables that each look right.
101
+ */
102
+ export function buildTsRequest(opts: {
103
+ pids: number[];
104
+ bucket?: TsBucket;
105
+ span?: { from?: string; to?: string; lastN?: number };
106
+ fields: string[];
107
+ }): TsRequest {
108
+ const bucket = (TS_BUCKETS as readonly string[]).includes(opts.bucket ?? "")
109
+ ? (opts.bucket as TsBucket)
110
+ : DEFAULT_TS_BUCKET;
111
+ const s = opts.span ?? {};
112
+ let span: TsRequest["span"];
113
+ if (typeof s.lastN === "number" && Number.isFinite(s.lastN)) {
114
+ span = { lastN: Math.max(1, Math.min(TS_MAX_LAST_N, Math.round(s.lastN))) };
115
+ } else if (s.from || s.to) {
116
+ span = { from: s.from, to: s.to };
117
+ } else {
118
+ span = { lastN: DEFAULT_TS_LAST_N };
119
+ }
120
+ return {
121
+ pids: opts.pids,
122
+ bucket,
123
+ span,
124
+ fields: opts.fields.slice(0, TS_MAX_FIELDS),
125
+ };
126
+ }
127
+
128
+ // ------------------------------------------------------------ the view model
129
+
130
+ export interface TsCell {
131
+ /** Raw value, or null = unanswerable. */
132
+ value: number | null;
133
+ /** Percent change vs the PRIOR bucket, or null when the question has no answer. */
134
+ delta: number | null;
135
+ partial: boolean;
136
+ }
137
+
138
+ export interface TsTableRow {
139
+ field: string;
140
+ label: string;
141
+ agg: string;
142
+ cells: TsCell[];
143
+ /** Only additive rows carry one. `undefined` = render an EMPTY cell, never a computed one. */
144
+ total?: number;
145
+ /** True when every value in the row is null — the row is present but unanswered. */
146
+ allUnanswered: boolean;
147
+ }
148
+
149
+ export interface TsTable {
150
+ columns: TsColumn[];
151
+ rows: TsTableRow[];
152
+ /** Every honest disclosure the payload owes the reader, ready to render. */
153
+ notes: string[];
154
+ pool: number;
155
+ /** No rows at all (before or after drops). */
156
+ empty: boolean;
157
+ }
158
+
159
+ /**
160
+ * Percent change vs the prior bucket.
161
+ *
162
+ * Three refusals, and each one is a number this function will NOT invent:
163
+ * - no prior bucket (the first column) -> null
164
+ * - the prior bucket is unanswerable (null) -> null (not "up from nothing")
165
+ * - the prior bucket is exactly 0 -> null (the change is undefined, not +∞,
166
+ * and NOT 0% — and zero-fill makes
167
+ * this the common case, not the edge)
168
+ * A null current value is also null: "—" cannot have grown.
169
+ *
170
+ * The denominator is `Math.abs(prior)`, so a move from -100 to -50 reads as +50%, not -50%.
171
+ * With a signed denominator the arithmetic is right and the SIGN is backwards, which is the
172
+ * worst kind of wrong on a margin row.
173
+ */
174
+ export function deltaPct(current: number | null, prior: number | null): number | null {
175
+ if (current == null || prior == null) return null;
176
+ if (prior === 0) return null;
177
+ if (!Number.isFinite(current) || !Number.isFinite(prior)) return null;
178
+ return ((current - prior) / Math.abs(prior)) * 100;
179
+ }
180
+
181
+ /** Human text for a cell. `null` is "—" — the number-shaped hole, never a zero. */
182
+ export function formatTsValue(
183
+ value: number | null,
184
+ format?: (n: number) => string
185
+ ): string {
186
+ if (value == null) return "—";
187
+ return format ? format(value) : String(value);
188
+ }
189
+
190
+ /** Human text for a delta. Refusals render as "—", and a real 0 renders as "0.0%". */
191
+ export function formatTsDelta(delta: number | null): string {
192
+ if (delta == null) return "—";
193
+ const sign = delta > 0 ? "+" : "";
194
+ return `${sign}${delta.toFixed(1)}%`;
195
+ }
196
+
197
+ function dropReasonText(reason: string): string {
198
+ switch (reason) {
199
+ case "not_a_measure_field":
200
+ return "not a measure — only measure fields have a time dimension";
201
+ case "unresolvable":
202
+ return "a composite measure has no single aggregate to bucket";
203
+ default:
204
+ return reason;
205
+ }
206
+ }
207
+
208
+ /**
209
+ * Turn the wire payload into the table the panel renders.
210
+ *
211
+ * Nothing here is recovered or filled in. A row the server did not send is not a row; a value
212
+ * it sent as null stays null; a total it withheld stays withheld.
213
+ */
214
+ export function buildTsTable(payload: TsPayload | null): TsTable {
215
+ if (!payload) {
216
+ return { columns: [], rows: [], notes: [], pool: 0, empty: true };
217
+ }
218
+ const columns = payload.columns ?? [];
219
+ const rows: TsTableRow[] = (payload.rows ?? []).map((r) => {
220
+ const values = r.values ?? [];
221
+ const cells: TsCell[] = columns.map((c, i) => ({
222
+ value: values[i] ?? null,
223
+ delta: deltaPct(values[i] ?? null, i > 0 ? (values[i - 1] ?? null) : null),
224
+ partial: c.partial === true,
225
+ }));
226
+ // (2) in the header note. An avg/min/max row gets NO total — not a computed one, not 0.
227
+ const total =
228
+ isAdditiveAgg(r.agg) && typeof r.total === "number" && Number.isFinite(r.total)
229
+ ? r.total
230
+ : undefined;
231
+ return {
232
+ field: r.field,
233
+ label: r.label,
234
+ agg: r.agg,
235
+ cells,
236
+ total,
237
+ allUnanswered: cells.length > 0 && cells.every((c) => c.value == null),
238
+ };
239
+ });
240
+
241
+ const notes: string[] = [];
242
+ const meta = payload.meta ?? { pool: 0 };
243
+ for (const d of meta.dropped ?? [])
244
+ notes.push(`${d.field} is not shown — ${dropReasonText(d.reason)}.`);
245
+ for (const p of meta.problems ?? []) notes.push(p);
246
+ const partials = columns.filter((c) => c.partial).length;
247
+ if (partials > 0)
248
+ notes.push(
249
+ partials === 1
250
+ ? "The last column is a partial period — it is still filling."
251
+ : `${partials} columns are partial periods — they are still filling.`
252
+ );
253
+ const unanswered = rows.filter((r) => r.allUnanswered).length;
254
+ if (unanswered > 0)
255
+ notes.push(
256
+ `${unanswered} of ${rows.length} metrics returned no values for this span (shown as "—").`
257
+ );
258
+
259
+ return {
260
+ columns,
261
+ rows,
262
+ notes,
263
+ pool: meta.pool ?? 0,
264
+ empty: rows.length === 0,
265
+ };
266
+ }
267
+
268
+ // ------------------------------------------------------------------- chart
269
+
270
+ /**
271
+ * One metric row → a `ChartModel` the `viz/vega` adapter can draw.
272
+ *
273
+ * ⚠ Built HERE rather than through `viz/chartData.buildChartData`, and that is the whole
274
+ * point of the function. `buildChartData` applies `MAX_BUCKETS = 12` — a cap that is right for
275
+ * a categorical bar chart of the top groups and CATASTROPHIC for a time series, where dropping
276
+ * buckets means dropping PERIODS. HOST's amendment makes 120 buckets legal, so routing 120
277
+ * months through the 12-cap would silently amputate a decade and still print a total that
278
+ * covered it.
279
+ *
280
+ * The server already decided the column set and refuses past `TS_MAX_BUCKETS`, so there is
281
+ * nothing left to cap: every column the panel holds is drawn. The disclosure fields on
282
+ * `ChartModel` are therefore all zero, honestly — nothing was omitted.
283
+ *
284
+ * Unanswerable buckets are SKIPPED, not zeroed: a line must break where the data does.
285
+ */
286
+ export function tsRowToChartModel(row: TsTableRow, columns: TsColumn[]): ChartModel {
287
+ const points = row.cells
288
+ .map((cell, i) => ({ cell, col: columns[i] }))
289
+ .filter((p) => p.col && p.cell.value != null)
290
+ .map((p) => ({
291
+ key: p.col.key,
292
+ label: p.col.label,
293
+ value: p.cell.value as number,
294
+ n: 1,
295
+ seriesKey: row.field,
296
+ seriesLabel: row.label,
297
+ }));
298
+ return {
299
+ points,
300
+ xOrder: columns.map((c) => c.key),
301
+ seriesOrder: [row.field],
302
+ // Nothing was capped, so nothing is omitted. Reporting a non-zero here would make the
303
+ // card claim a truncation that did not happen.
304
+ omitted: 0,
305
+ omittedValue: 0,
306
+ omittedSeries: 0,
307
+ omittedSeriesValue: 0,
308
+ blanks: row.cells.filter((c) => c.value == null).length,
309
+ missingY: 0,
310
+ rows: points.length,
311
+ nonPositive: 0,
312
+ nonPositiveValue: 0,
313
+ };
314
+ }
315
+
316
+ // --------------------------------------------------------------------- CSV
317
+
318
+ function csvCell(v: string): string {
319
+ return /[",\r\n]/.test(v) ? `"${v.replace(/"/g, '""')}"` : v;
320
+ }
321
+
322
+ /**
323
+ * RFC-4180 CSV of the table AS SHOWN, matching `export.ts`'s shape (CRLF rows, quoted only
324
+ * where needed) so a time-series export opens like every other export this app makes.
325
+ *
326
+ * An unanswerable cell exports as an EMPTY field, not as "—" and not as 0: the reader is a
327
+ * spreadsheet, and there `—` is text that poisons a column while `0` is a lie that sums.
328
+ * A withheld total exports empty for the same reason.
329
+ */
330
+ export function buildTsCsv(table: TsTable): string {
331
+ const head = ["Metric", ...table.columns.map((c) => c.label), "Total"];
332
+ const lines = [head.map(csvCell).join(",")];
333
+ for (const r of table.rows) {
334
+ const cells = [
335
+ csvCell(r.label),
336
+ ...r.cells.map((c) => (c.value == null ? "" : String(c.value))),
337
+ r.total == null ? "" : String(r.total),
338
+ ];
339
+ lines.push(cells.join(","));
340
+ }
341
+ return lines.join("\r\n") + "\r\n";
342
+ }
343
+
344
+ /** The caps, re-exported so the panel and the gate read ONE source. */
345
+ export const TS_LIMITS = {
346
+ maxBuckets: TS_MAX_BUCKETS,
347
+ maxFields: TS_MAX_FIELDS,
348
+ maxLastN: TS_MAX_LAST_N,
349
+ } as const;
350
+
351
+ export type { ChartAgg };
web/src/customer-grid/types.ts CHANGED
@@ -67,7 +67,7 @@ export function isPickType(t: FieldType): boolean {
67
  * Lives here, not in ColumnMenu.tsx — a component file that also exports plain functions
68
  * breaks React fast refresh (the same reason counts.ts is its own module).
69
  */
70
- export function parseOptions(text: string): string[] {
71
  const seen = new Set<string>();
72
  const out: string[] = [];
73
  for (const raw of text.split("\n")) {
@@ -78,36 +78,36 @@ export function parseOptions(text: string): string[] {
78
  seen.add(k);
79
  out.push(v);
80
  }
81
- return out.slice(0, 50);
82
- }
83
-
84
- /**
85
- * A user-facing field/view name that cannot visually shadow an existing sibling.
86
- *
87
- * Identity keys remain separate; this is the label namespace users actually navigate. Casing
88
- * and repeated whitespace do not create distinct names, and suffix room is reserved before
89
- * the host's 120-character cap so the optimistic client copy matches the durable write seam.
90
- */
91
- export function uniqueDisplayName(
92
- wanted: string,
93
- existing: readonly string[],
94
- maxLength = 120
95
- ): string {
96
- const limit = Math.max(1, Math.floor(maxLength));
97
- const clean = (value: string) => value.trim().replace(/\s+/g, " ");
98
- const base = (clean(wanted) || "Untitled").slice(0, limit).trimEnd();
99
- const taken = new Set(existing.map((value) => clean(value).toLocaleLowerCase()));
100
- if (!taken.has(base.toLocaleLowerCase())) return base;
101
- for (let index = 2; ; index += 1) {
102
- const suffix = ` ${index}`;
103
- const stem = base.slice(0, Math.max(0, limit - suffix.length)).trimEnd();
104
- const candidate = stem ? `${stem}${suffix}` : String(index).slice(-limit);
105
- if (!taken.has(candidate.toLocaleLowerCase())) return candidate;
106
- }
107
- }
108
-
109
- /**
110
- * The columns the condition builder offers (owner item 3, 2026-07-26).
111
  *
112
  * `filterable: false` marks a DERIVED ANALYTIC, not a read-only column. "Est. missed $" is
113
  * min(cycles missed, 3) x AOV — our arithmetic, not an object the business has — and a
@@ -180,8 +180,16 @@ export type FieldScope = "cohort" | "global";
180
  // So the union keeps BOTH keys (which also keeps MODE_SHAPES / MODE_LABELS total over them),
181
  // `normalizeDisplayMode` folds the legacy value on read exactly as the host's `_LEGACY_MODES`
182
  // does, and CREATABLE_MODES — the list the UI offers — carries 'chart' and not 'dashboard'.
 
 
 
 
 
 
 
 
183
  export const DISPLAY_MODES = [
184
- "grid", "chart", "dashboard", "list", "calendar", "kanban", "map",
185
  ] as const;
186
  export type DisplayMode = (typeof DISPLAY_MODES)[number];
187
 
@@ -218,8 +226,66 @@ export interface DisplaySpec {
218
  agg: string;
219
  title?: string;
220
  }[];
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
221
  }
222
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
223
  /**
224
  * Client-side normalization of a stored `display`. A ref-less `{mode:'grid'}` normalizes to
225
  * ABSENT so a view that went list-and-back is byte-identical to one that never left the grid
@@ -261,6 +327,48 @@ export function cleanDisplay(raw: unknown): DisplaySpec | undefined {
261
  );
262
  if (charts.length) out.charts = charts.slice(0, 12);
263
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
264
  if (
265
  out.mode === "grid" &&
266
  !out.dateField &&
@@ -268,7 +376,15 @@ export function cleanDisplay(raw: unknown): DisplaySpec | undefined {
268
  !out.titleField &&
269
  !out.colorField &&
270
  !out.sizeField &&
271
- !out.charts
 
 
 
 
 
 
 
 
272
  )
273
  return undefined;
274
  return out;
@@ -354,20 +470,20 @@ export function isGroupableField(field: Field, lockedKey: string): boolean {
354
  );
355
  }
356
 
357
- export interface Field {
358
- key: string;
359
- label: string;
360
- /**
361
- * Host-only acknowledgement: the requested label that was changed to resolve a durable
362
- * collision. Reconciliation consumes it to distinguish a correction from an ordinary
363
- * lagged rename echo; it is never rendered as field metadata.
364
- */
365
- labelCorrectedFrom?: string;
366
- /** Client-only id of the optimistic definition write currently represented by this copy. */
367
- editRequestId?: string;
368
- /** Host-only id paired with `editRequestId` when that exact write needed a label correction. */
369
- labelCorrectionId?: string;
370
- type: FieldType;
371
  source: FieldSource;
372
  /**
373
  * Computed by the HOST per render rather than read off a source row — today the cohort
@@ -407,18 +523,18 @@ export interface Field {
407
  * through a fail-closed whitelist).
408
  */
409
  preset?: boolean;
410
- /** Choices for a `select` / `multiselect` field. Ignored for every other type. */
411
- options?: string[];
412
- /**
413
- * Whether select-family choices render with coloured pills. Absent means true so legacy
414
- * fields keep their existing appearance; an explicit false is the user's opt-out.
415
- */
416
- colorCodeOptions?: boolean;
417
- /**
418
- * User-picked choice colour, keyed by the canonical option label. Values are validated as
419
- * six-digit CSS hex colours at both the client and host boundaries.
420
- */
421
- optionColors?: Record<string, string>;
422
  /**
423
  * Wave-5 item 9 (contract AMENDMENT 2026-07-27 ~20:20): a FORMULA field's source, TOP-LEVEL
424
  * — `options` stays the select-family list; top-level properties are the established
@@ -545,12 +661,101 @@ export type FilterOp =
545
  | "lt"
546
  | "lte"
547
  | "between"
548
- | "within";
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
549
 
550
  /** Ops that take NO value — the UI hides the value control, the engine ignores it. */
551
  export const VALUE_FREE_OPS: ReadonlySet<FilterOp> = new Set<FilterOp>([
552
  "isEmpty",
553
  "isNotEmpty",
 
 
 
554
  ]);
555
 
556
  /** How sibling conditions at ONE nesting level combine. Airtable allows exactly
@@ -903,6 +1108,21 @@ export interface ViewConfig {
903
  /** Wave-6 item 11 — freeze the first N visible columns (host-clamped 1..8). Absent = 1,
904
  * the locked identity column — every legacy view's behavior. */
905
  frozenCount?: number;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
906
  }
907
 
908
  export type ViewKind = "system" | "list" | "custom";
@@ -1299,6 +1519,17 @@ export interface GridWorkspace {
1299
  viewer?: Viewer;
1300
  userOptions?: string[];
1301
  overlays?: Record<string, Record<string, string>>;
 
 
 
 
 
 
 
 
 
 
 
1302
  }
1303
 
1304
  /**
@@ -1560,7 +1791,17 @@ export type HostEvent =
1560
  itemId: string;
1561
  folderId: string | null;
1562
  order?: number;
1563
- };
 
 
 
 
 
 
 
 
 
 
1564
 
1565
  /** C4 — which rail an event is about. */
1566
  export type FolderSurface = "views" | "cohorts";
 
67
  * Lives here, not in ColumnMenu.tsx — a component file that also exports plain functions
68
  * breaks React fast refresh (the same reason counts.ts is its own module).
69
  */
70
+ export function parseOptions(text: string): string[] {
71
  const seen = new Set<string>();
72
  const out: string[] = [];
73
  for (const raw of text.split("\n")) {
 
78
  seen.add(k);
79
  out.push(v);
80
  }
81
+ return out.slice(0, 50);
82
+ }
83
+
84
+ /**
85
+ * A user-facing field/view name that cannot visually shadow an existing sibling.
86
+ *
87
+ * Identity keys remain separate; this is the label namespace users actually navigate. Casing
88
+ * and repeated whitespace do not create distinct names, and suffix room is reserved before
89
+ * the host's 120-character cap so the optimistic client copy matches the durable write seam.
90
+ */
91
+ export function uniqueDisplayName(
92
+ wanted: string,
93
+ existing: readonly string[],
94
+ maxLength = 120
95
+ ): string {
96
+ const limit = Math.max(1, Math.floor(maxLength));
97
+ const clean = (value: string) => value.trim().replace(/\s+/g, " ");
98
+ const base = (clean(wanted) || "Untitled").slice(0, limit).trimEnd();
99
+ const taken = new Set(existing.map((value) => clean(value).toLocaleLowerCase()));
100
+ if (!taken.has(base.toLocaleLowerCase())) return base;
101
+ for (let index = 2; ; index += 1) {
102
+ const suffix = ` ${index}`;
103
+ const stem = base.slice(0, Math.max(0, limit - suffix.length)).trimEnd();
104
+ const candidate = stem ? `${stem}${suffix}` : String(index).slice(-limit);
105
+ if (!taken.has(candidate.toLocaleLowerCase())) return candidate;
106
+ }
107
+ }
108
+
109
+ /**
110
+ * The columns the condition builder offers (owner item 3, 2026-07-26).
111
  *
112
  * `filterable: false` marks a DERIVED ANALYTIC, not a read-only column. "Est. missed $" is
113
  * min(cycles missed, 3) x AOV — our arithmetic, not an object the business has — and a
 
180
  // So the union keeps BOTH keys (which also keeps MODE_SHAPES / MODE_LABELS total over them),
181
  // `normalizeDisplayMode` folds the legacy value on read exactly as the host's `_LEGACY_MODES`
182
  // does, and CREATABLE_MODES — the list the UI offers — carries 'chart' and not 'dashboard'.
183
+ // Wave 2026-08-02 item 7 (contract C-TYPES/C-TS): `timeseries` joins the union — bucketed
184
+ // columns x metric rows over the view's filtered pid set.
185
+ //
186
+ // ⚠ It lands in DISPLAY_MODES (so the type, the icon table and the label table are total over
187
+ // it) but NOT in CREATABLE_MODES until the host's `_clean_display` accepts the name. That split
188
+ // is the whole point: `_clean_display` DROPS an unknown mode, so offering the mode first would
189
+ // let a user create a time-series view that silently reverts to a grid on the next read, with
190
+ // nothing anywhere going red — the wave-9 silent-drop failure, replayed.
191
  export const DISPLAY_MODES = [
192
+ "grid", "chart", "dashboard", "list", "calendar", "kanban", "map", "timeseries",
193
  ] as const;
194
  export type DisplayMode = (typeof DISPLAY_MODES)[number];
195
 
 
226
  agg: string;
227
  title?: string;
228
  }[];
229
+ /**
230
+ * Wave 2026-08-02 item 3 (C-DISP) — kanban card clamp. **Stored ONLY as the literal `false`.**
231
+ *
232
+ * Absent = clamped, which is the new standardized default the owner asked for; `false` = this
233
+ * view opted out. `true` is deliberately unwritable: it would be a second spelling of the
234
+ * default, and two spellings of one state is how a round-trip starts churning. The literal
235
+ * type is what makes that a compile error rather than a convention.
236
+ *
237
+ * ⚠ `viewEcho` must compare ABSENT and `false` as DIFFERENT. A `!!a.kanbanClamp` shortcut
238
+ * folds the opt-out back into the default and the toggle reads as "it doesn't save".
239
+ */
240
+ kanbanClamp?: false;
241
+ /** Item 4 (C-DISP) — calendar renders record chips (default) or per-day aggregates. */
242
+ calendarMode?: "records" | "summary";
243
+ /**
244
+ * Item 4 (C-DISP) — the aggregates a summary-mode day cell shows, max 4.
245
+ *
246
+ * `agg` is typed as a plain string on purpose, exactly like `charts[].agg` above: the real
247
+ * vocabulary is `ChartAgg` in chartData.ts, and chartData imports THIS module, not the
248
+ * reverse. Typing it structurally keeps types.ts the leaf it is. Booked as a dated C-DISP
249
+ * amendment — the WIRE shape is unchanged, only where the union is declared.
250
+ *
251
+ * Invalid entries are dropped INDIVIDUALLY (the charts precedent), never the whole array:
252
+ * one stale field ref must not cost the user their other three metrics.
253
+ */
254
+ calendarMetrics?: { id: string; field: string; agg: string }[];
255
+ /** Item 7 (C-TS) — the time-series column bucket. Absent = month. */
256
+ tsBucket?: TsBucket;
257
+ /**
258
+ * Item 7 (C-TS) — the span the buckets cover: an explicit ISO `{from,to}` window, or the
259
+ * rolling `{lastN}` (1..120 buckets). Absent = the panel's default rolling span.
260
+ */
261
+ tsSpan?: { from?: string; to?: string; lastN?: number };
262
+ /** Item 7 (C-TS) — the measure-backed field keys that become rows, max 12. */
263
+ tsFields?: string[];
264
  }
265
 
266
+ /**
267
+ * C-TS — the time-series bucket vocabulary, mirrored by the host's `_clean_display`. Declared
268
+ * as a const array (not a bare union) so the client validator and the panel's picker read the
269
+ * same list, the way DISPLAY_MODES already does.
270
+ */
271
+ export const TS_BUCKETS = ["week", "month", "quarter", "year"] as const;
272
+ export type TsBucket = (typeof TS_BUCKETS)[number];
273
+
274
+ /**
275
+ * C-TS — the host's cap: a span wider than this is a 400 "narrow the span", not a truncation.
276
+ *
277
+ * 120, per HOST's dated C-TS amendment (2026-08-02). The contract first said 60; that both
278
+ * rationed the wrong resource (the endpoint runs ONE grouped query per field however many
279
+ * buckets come back) and contradicted `tsSpan.lastN ≤ 120`, under which 120 weekly buckets is
280
+ * a legal saved view the server would then have refused.
281
+ */
282
+ export const TS_MAX_BUCKETS = 120;
283
+ /** C-TS — `tsSpan.lastN` bounds, and the cap on `tsFields`. */
284
+ export const TS_MAX_LAST_N = 120;
285
+ export const TS_MAX_FIELDS = 12;
286
+ /** C-DISP — the cap on a calendar view's summary metrics. */
287
+ export const MAX_CALENDAR_METRICS = 4;
288
+
289
  /**
290
  * Client-side normalization of a stored `display`. A ref-less `{mode:'grid'}` normalizes to
291
  * ABSENT so a view that went list-and-back is byte-identical to one that never left the grid
 
327
  );
328
  if (charts.length) out.charts = charts.slice(0, 12);
329
  }
330
+ // ── C-DISP / C-TS (2026-08-02) ──────────────────────────────────────────────────────────
331
+ // Every key below is validated INDIVIDUALLY and mirrors the host's `_clean_display`
332
+ // asymmetries. The old hardcoded string-copy loop above is why this has to be explicit: a
333
+ // key this function does not name is dropped on read, so "the host accepts it" is only half
334
+ // the round trip.
335
+ //
336
+ // ⚠ ONLY the literal `false` survives. `true` is the default's second spelling; see the
337
+ // member's doc comment.
338
+ if (d.kanbanClamp === false) out.kanbanClamp = false;
339
+ if (d.calendarMode === "records" || d.calendarMode === "summary")
340
+ out.calendarMode = d.calendarMode;
341
+ if (Array.isArray(d.calendarMetrics)) {
342
+ const metrics: NonNullable<DisplaySpec["calendarMetrics"]> = [];
343
+ for (const raw2 of d.calendarMetrics) {
344
+ if (!raw2 || typeof raw2 !== "object") continue;
345
+ const m = raw2 as Record<string, unknown>;
346
+ // Field refs are NOT resolved here — the same rule the field-ref loop above follows: the
347
+ // pickers only offer real fields and the renderer falls back when one has gone stale.
348
+ if (typeof m.id !== "string" || !m.id) continue;
349
+ if (typeof m.field !== "string" || !m.field) continue;
350
+ if (typeof m.agg !== "string" || !m.agg) continue;
351
+ metrics.push({ id: m.id, field: m.field, agg: m.agg });
352
+ }
353
+ if (metrics.length) out.calendarMetrics = metrics.slice(0, MAX_CALENDAR_METRICS);
354
+ }
355
+ if ((TS_BUCKETS as readonly string[]).includes(d.tsBucket as string))
356
+ out.tsBucket = d.tsBucket as TsBucket;
357
+ if (d.tsSpan && typeof d.tsSpan === "object" && !Array.isArray(d.tsSpan)) {
358
+ const s = d.tsSpan as Record<string, unknown>;
359
+ const span: NonNullable<DisplaySpec["tsSpan"]> = {};
360
+ if (typeof s.from === "string" && s.from) span.from = s.from;
361
+ if (typeof s.to === "string" && s.to) span.to = s.to;
362
+ if (typeof s.lastN === "number" && Number.isFinite(s.lastN)) {
363
+ const n = Math.round(s.lastN);
364
+ if (n >= 1 && n <= TS_MAX_LAST_N) span.lastN = n;
365
+ }
366
+ if (span.from || span.to || span.lastN != null) out.tsSpan = span;
367
+ }
368
+ if (Array.isArray(d.tsFields)) {
369
+ const keys = d.tsFields.filter((k): k is string => typeof k === "string" && k !== "");
370
+ if (keys.length) out.tsFields = keys.slice(0, TS_MAX_FIELDS);
371
+ }
372
  if (
373
  out.mode === "grid" &&
374
  !out.dateField &&
 
376
  !out.titleField &&
377
  !out.colorField &&
378
  !out.sizeField &&
379
+ !out.charts &&
380
+ // `kanbanClamp` is `false | undefined`, so this must test PRESENCE. A truthiness test would
381
+ // read the opt-out as "nothing here" and normalise the user's pick away.
382
+ out.kanbanClamp === undefined &&
383
+ !out.calendarMode &&
384
+ !out.calendarMetrics &&
385
+ !out.tsBucket &&
386
+ !out.tsSpan &&
387
+ !out.tsFields
388
  )
389
  return undefined;
390
  return out;
 
470
  );
471
  }
472
 
473
+ export interface Field {
474
+ key: string;
475
+ label: string;
476
+ /**
477
+ * Host-only acknowledgement: the requested label that was changed to resolve a durable
478
+ * collision. Reconciliation consumes it to distinguish a correction from an ordinary
479
+ * lagged rename echo; it is never rendered as field metadata.
480
+ */
481
+ labelCorrectedFrom?: string;
482
+ /** Client-only id of the optimistic definition write currently represented by this copy. */
483
+ editRequestId?: string;
484
+ /** Host-only id paired with `editRequestId` when that exact write needed a label correction. */
485
+ labelCorrectionId?: string;
486
+ type: FieldType;
487
  source: FieldSource;
488
  /**
489
  * Computed by the HOST per render rather than read off a source row — today the cohort
 
523
  * through a fail-closed whitelist).
524
  */
525
  preset?: boolean;
526
+ /** Choices for a `select` / `multiselect` field. Ignored for every other type. */
527
+ options?: string[];
528
+ /**
529
+ * Whether select-family choices render with coloured pills. Absent means true so legacy
530
+ * fields keep their existing appearance; an explicit false is the user's opt-out.
531
+ */
532
+ colorCodeOptions?: boolean;
533
+ /**
534
+ * User-picked choice colour, keyed by the canonical option label. Values are validated as
535
+ * six-digit CSS hex colours at both the client and host boundaries.
536
+ */
537
+ optionColors?: Record<string, string>;
538
  /**
539
  * Wave-5 item 9 (contract AMENDMENT 2026-07-27 ~20:20): a FORMULA field's source, TOP-LEVEL
540
  * — `options` stays the select-family list; top-level properties are the established
 
661
  | "lt"
662
  | "lte"
663
  | "between"
664
+ | "within"
665
+ // Wave 2026-08-02 item 10 (contract C-OPS) — RANK operators. See RANK_OPS below.
666
+ | "topN"
667
+ | "bottomN"
668
+ | "inTopPct"
669
+ | "inBottomPct"
670
+ | "aboveAvg"
671
+ | "belowAvg"
672
+ | "inQuartile"
673
+ | "inDecile";
674
+
675
+ /**
676
+ * C-OPS — the RANK family: operators whose truth depends on the OTHER rows, not on this row's
677
+ * value alone.
678
+ *
679
+ * That is what makes them a separate list rather than eight more entries in `opsForType`. Every
680
+ * operator above answers a question about one cell; a rank operator answers "where does this row
681
+ * sit among the rows the rest of the filter kept". So the engine strips every rank leaf, evaluates
682
+ * the residue, and THAT match-set is the ranking DOMAIN — "top 10 of agent Naomi" narrows by agent
683
+ * first, then takes ten. Blank and non-numeric values are OUT of the domain (a blank is not a
684
+ * zero, and ranking it as one would put empty rows at the bottom of every "bottom 10").
685
+ *
686
+ * ⚠ Three copies of this vocabulary exist — `aios_grid.FILTER_OPS` and `filter_sql.FILTER_OPS`
687
+ * are the others — and `verify_filter_engine.py` asserts they are byte-identical name-for-name.
688
+ * The HOST lands the two Python copies and the view-config acceptance FIRST; a saved view
689
+ * carrying an op the host does not know is silently stripped on the next write.
690
+ *
691
+ * rhs encoding (the existing `value` string slot, so no persisted shape changes):
692
+ * topN / bottomN -> "10" (1..10000)
693
+ * inTopPct / inBottomPct -> "10" (1..100)
694
+ * inQuartile -> "1".."4" (4 = the top quarter)
695
+ * inDecile -> "1".."10"
696
+ * aboveAvg / belowAvg -> value-free
697
+ * Offered for the numeric family only (int/currency/pct/rating/formula/measure-typed).
698
+ */
699
+ export const RANK_OPS: readonly FilterOp[] = [
700
+ "topN",
701
+ "bottomN",
702
+ "inTopPct",
703
+ "inBottomPct",
704
+ "aboveAvg",
705
+ "belowAvg",
706
+ "inQuartile",
707
+ "inDecile",
708
+ ] as const;
709
+
710
+ export function isRankOp(op: string): boolean {
711
+ return (RANK_OPS as readonly string[]).includes(op);
712
+ }
713
+
714
+ /**
715
+ * C-LOCK amendment (2026-08-02, from RECORD's widening-gap flag) — the RUNTIME op vocabulary.
716
+ *
717
+ * `FilterOp` is a TYPE, and a type cannot be consulted at runtime. So a leaf carrying an op in
718
+ * NO vocabulary at all — `inTertile` out of a stale localStorage draft, say — reaches
719
+ * `matchFilter`'s `default:` and falls through to "no narrowing", which puts every row on
720
+ * screen under a count nobody would doubt. That is the widening sin the cohort-leaf law
721
+ * already names; this list is what lets the engine guard its `default:` by membership and
722
+ * match NOTHING instead.
723
+ *
724
+ * ⚠ The two `Assert` lines below are the point of the whole construct, not decoration. A hand-
725
+ * maintained list beside a hand-maintained union is two things to remember, and the failure is
726
+ * silent in the direction that matters: an op added to the union but forgotten here would be
727
+ * rejected by the very guard meant to protect it. `_NoneMissing` fails to compile if the union
728
+ * holds an op the list does not; `_NoneExtra` fails if the list holds one the union does not.
729
+ * Drift is a build error, not a bug report.
730
+ */
731
+ const FILTER_OPS_LIST = [
732
+ "contains", "doesNotContain", "eq", "neq", "isEmpty", "isNotEmpty",
733
+ "gt", "gte", "lt", "lte", "between", "within",
734
+ "topN", "bottomN", "inTopPct", "inBottomPct",
735
+ "aboveAvg", "belowAvg", "inQuartile", "inDecile",
736
+ ] as const;
737
+
738
+ /** Compile-time `never` assertion — instantiating it with anything else is an error. */
739
+ type AssertNever<T extends never> = T;
740
+ type _NoneMissing = AssertNever<Exclude<FilterOp, (typeof FILTER_OPS_LIST)[number]>>;
741
+ type _NoneExtra = AssertNever<Exclude<(typeof FILTER_OPS_LIST)[number], FilterOp>>;
742
+ export type { _NoneMissing, _NoneExtra };
743
+
744
+ /** All 20 operators, as data. Mirrors `aios_grid.FILTER_OPS` / `filter_sql.FILTER_OPS`. */
745
+ export const FILTER_OPS: readonly FilterOp[] = FILTER_OPS_LIST;
746
+
747
+ /** Membership test for the engine's fail-closed `default:` branch. */
748
+ export function isKnownFilterOp(op: string): boolean {
749
+ return (FILTER_OPS as readonly string[]).includes(op);
750
+ }
751
 
752
  /** Ops that take NO value — the UI hides the value control, the engine ignores it. */
753
  export const VALUE_FREE_OPS: ReadonlySet<FilterOp> = new Set<FilterOp>([
754
  "isEmpty",
755
  "isNotEmpty",
756
+ // C-OPS — "above the average" names its own threshold; there is nothing for the user to type.
757
+ "aboveAvg",
758
+ "belowAvg",
759
  ]);
760
 
761
  /** How sibling conditions at ONE nesting level combine. Airtable allows exactly
 
1108
  /** Wave-6 item 11 — freeze the first N visible columns (host-clamped 1..8). Absent = 1,
1109
  * the locked identity column — every legacy view's behavior. */
1110
  frozenCount?: number;
1111
+ /**
1112
+ * Item 12 (contract C-LOCK, 2026-08-02) — this view is LOCKED to a cohort: the id of the
1113
+ * set whose members are the only rows it can ever show.
1114
+ *
1115
+ * ⚠ **NOT a filter condition, and deliberately not expressible as one.** The engine
1116
+ * intersects this set FIRST — before the conditions, before the pinned `memberPids` union,
1117
+ * before the ranking domain — so "top 10" in a locked view means the top 10 OF THE COHORT.
1118
+ * A condition row could be deleted; a lock is a property of the view, which is the whole
1119
+ * point of the feature.
1120
+ *
1121
+ * The host validates the id against the sets the SESSION can see and drops it fail-closed
1122
+ * otherwise. A lock naming a set this reader was given no membership for matches NOTHING
1123
+ * (never everything) — the cohort-leaf law one level up.
1124
+ */
1125
+ cohortLock?: string;
1126
  }
1127
 
1128
  export type ViewKind = "system" | "list" | "custom";
 
1519
  viewer?: Viewer;
1520
  userOptions?: string[];
1521
  overlays?: Record<string, Record<string, string>>;
1522
+ /**
1523
+ * Wave 2026-08-02 item 5 (contract C-LAYOUT) — this USER'S field order inside the record
1524
+ * detail modal, persisted by the `record_layout` event and echoed back here.
1525
+ *
1526
+ * Per-user and modal-only by design: it is a reading preference, not a property of the table,
1527
+ * so it deliberately does NOT live on the view (where it would be shared) and does not touch
1528
+ * the grid's own `config.order`. Keys the contract no longer holds are pruned host-side;
1529
+ * fields absent from `order` append in their default order, so a field added after a user
1530
+ * arranged their layout appears rather than disappears.
1531
+ */
1532
+ recordLayout?: { order: string[] };
1533
  }
1534
 
1535
  /**
 
1791
  itemId: string;
1792
  folderId: string | null;
1793
  order?: number;
1794
+ }
1795
+ /**
1796
+ * Item 5 / contract C-LAYOUT (2026-08-02) — this USER'S field order inside the record
1797
+ * detail modal. Per-user, not per-view: it is a reading preference, so it rides a workspace
1798
+ * stratum (`GridWorkspace.recordLayout`) rather than `ViewConfig`.
1799
+ *
1800
+ * The host prunes keys the contract no longer holds and dedupes; an EMPTY order clears the
1801
+ * preference back to the default. Returns False host-side — an autosave hot path like
1802
+ * `view_upsert`, so no rerun to race.
1803
+ */
1804
+ | { id: string; type: "record_layout"; order: string[] };
1805
 
1806
  /** C4 — which rail an event is about. */
1807
  export type FolderSurface = "views" | "cohorts";
web/src/customer-grid/useVisibleRows.ts CHANGED
@@ -22,14 +22,27 @@ import type {
22
  SortSpec,
23
  VisibleRow,
24
  } from "./types";
25
- import { cohortIds, isCohortRule, isFilterGroup, isMeasureRule, isRuleActive,
26
- normalizeCohortOp, rhsColId } from "./types";
27
  import { resolveAnchor, resolveWindow } from "./windows";
28
  import { computeAggs } from "./aggregations";
 
 
29
 
30
  export interface VisibleRowsResult {
31
  visibleRows: VisibleRow[];
32
  pidToIndex: Map<number, number>;
 
 
 
 
 
 
 
 
 
 
 
33
  }
34
 
35
  /** Coerce any cell/input value to a finite number (blank/garbage -> 0). */
@@ -101,6 +114,14 @@ function matchFilter(
101
  if (rule.op === "isEmpty") return isBlank(raw);
102
  if (rule.op === "isNotEmpty") return !isBlank(raw);
103
 
 
 
 
 
 
 
 
 
104
  // --- CG-9: the comparand is another CELL of this row, not a typed value ----------------
105
  // Read once, here, so every type branch below coerces it through the LEFT field's type — the
106
  // same type this function is already dispatching on. `evalNode` has already established that
@@ -306,6 +327,40 @@ function evalNode(
306
  // handled above, so one reaching here is as unusable as a deleted column.
307
  if (node.rhs && !fieldByKey.has(rhsColId(node.rhs) ?? "")) return null;
308
  if (!isRuleActive(node)) return null;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
309
  return matchFilter(node, r, fieldByKey, ctx?.today);
310
  }
311
 
@@ -328,6 +383,12 @@ export interface EvalCtx {
328
  cohortSets?: CohortSets;
329
  /** The TENANT'S today. Never `new Date()` — see CustomersPayload.today. */
330
  today?: string;
 
 
 
 
 
 
331
  }
332
 
333
  /**
@@ -576,6 +637,17 @@ export interface PipelineInput {
576
  measureSets?: MeasureSets;
577
  /** Owner item 5. Cohort membership, `cohortId -> pids`. */
578
  cohortSets?: CohortSets;
 
 
 
 
 
 
 
 
 
 
 
579
  /** The TENANT'S today, from the payload. Required by every relative-date condition and
580
  * never defaulted to the browser clock — see CustomersPayload.today. */
581
  today?: string;
@@ -585,21 +657,29 @@ export function runPipeline(input: PipelineInput): VisibleRowsResult {
585
  const {
586
  rawRows, fields, filters, search, sorts, groupBy, collapsed,
587
  memberPids = [], filterConj = "and", serverWindowed = false, measureSets,
588
- cohortSets, today,
589
  } = input;
590
  const ctx: EvalCtx = { measureSets, cohortSets, today };
591
 
 
 
592
  const asRows = (rows: Row[]): VisibleRowsResult => {
593
  const visibleRows = rows.map((record): VisibleRow => ({ kind: "data", record }));
594
  const pidToIndex = new Map<number, number>();
595
  visibleRows.forEach((vr, i) => {
596
  if (vr.kind === "data") pidToIndex.set(vr.record.pid, i);
597
  });
598
- return { visibleRows, pidToIndex };
599
  };
600
 
601
  // CG-3: the whole client engine, skipped. Not "filters happen to be empty" — SKIPPED, so a
602
  // persisted filter arriving alongside a windowed payload cannot narrow the page twice.
 
 
 
 
 
 
603
  if (serverWindowed) return asRows(rawRows);
604
 
605
  const fieldByKey = new Map<string, Field>();
@@ -611,7 +691,54 @@ export function runPipeline(input: PipelineInput): VisibleRowsResult {
611
  // so its buckets inherit the fully filtered + sorted order.
612
  let out = rawRows;
613
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
614
  if (filters.length) {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
615
  const members = new Set(memberPids);
616
  out = out.filter(
617
  (r) =>
@@ -641,7 +768,7 @@ export function runPipeline(input: PipelineInput): VisibleRowsResult {
641
  visibleRows.forEach((vr, i) => {
642
  if (vr.kind === "data" && !pidToIndex.has(vr.record.pid)) pidToIndex.set(vr.record.pid, i);
643
  });
644
- return { visibleRows, pidToIndex };
645
  }
646
 
647
  export function useVisibleRows(
@@ -657,12 +784,13 @@ export function useVisibleRows(
657
  serverWindowed = false,
658
  measureSets?: MeasureSets,
659
  cohortSets?: CohortSets,
660
- today?: string
 
661
  ): VisibleRowsResult {
662
  return useMemo(
663
  () => runPipeline({ rawRows, fields, filters, search, sorts, groupBy, collapsed,
664
  memberPids, filterConj, serverWindowed, measureSets,
665
- cohortSets, today }),
666
  [rawRows, fields, filters, filterConj, search, sorts, groupBy, collapsed,
667
- memberPids, serverWindowed, measureSets, cohortSets, today]);
668
  }
 
22
  SortSpec,
23
  VisibleRow,
24
  } from "./types";
25
+ import { FILTER_OPS, cohortIds, isCohortRule, isFilterGroup, isMeasureRule, isRankOp,
26
+ isRuleActive, normalizeCohortOp, rhsColId } from "./types";
27
  import { resolveAnchor, resolveWindow } from "./windows";
28
  import { computeAggs } from "./aggregations";
29
+ import { NO_RANKING, hasRankLeaf, resolveRankLeaves, stripRankLeaves } from "./rankOps";
30
+ import type { RankSets } from "./rankOps";
31
 
32
  export interface VisibleRowsResult {
33
  visibleRows: VisibleRow[];
34
  pidToIndex: Map<number, number>;
35
+ /**
36
+ * C-OPS — ACTIVE rank conditions the engine could not answer (see rankOps.RankResolution).
37
+ *
38
+ * It rides the RESULT rather than `unresolvedConditions` because it is the one unresolvable
39
+ * state that cannot be diagnosed from the tree alone: "the top 10 by Sales · last 90 days"
40
+ * is unanswerable exactly when that column has no values yet, and only the pass that walks
41
+ * the rows knows. Add it to the toolbar's `unresolvedCount` — an unexplained empty table is
42
+ * the failure that marker exists to remove. Always present, 0 for every filter without a
43
+ * rank leaf, so a caller that ignores it is unchanged.
44
+ */
45
+ unresolvedRank: number;
46
  }
47
 
48
  /** Coerce any cell/input value to a finite number (blank/garbage -> 0). */
 
114
  if (rule.op === "isEmpty") return isBlank(raw);
115
  if (rule.op === "isNotEmpty") return !isBlank(raw);
116
 
117
+ // --- C-OPS: a RANK op can never be answered from one row --------------------------------
118
+ // `evalNode` routes rank leaves to their resolved pid set and one should never arrive here.
119
+ // The guard is the SECOND layer, and it exists because of what the first layer's absence
120
+ // would do: `cmpNum`'s documented `default: return true` would make `topN` match EVERY row —
121
+ // a filter that widens, under a count that agrees with it. Two layers, because "unreachable"
122
+ // is a property of today's call graph and this file outlives it.
123
+ if (isRankOp(rule.op)) return false;
124
+
125
  // --- CG-9: the comparand is another CELL of this row, not a typed value ----------------
126
  // Read once, here, so every type branch below coerces it through the LEFT field's type — the
127
  // same type this function is already dispatching on. `evalNode` has already established that
 
327
  // handled above, so one reaching here is as unusable as a deleted column.
328
  if (node.rhs && !fieldByKey.has(rhsColId(node.rhs) ?? "")) return null;
329
  if (!isRuleActive(node)) return null;
330
+
331
+ // --- C-OPS: a RANK leaf is a MEMBERSHIP test, like a cohort or a measure ------------------
332
+ // The set was computed in a prior pass over the residue-filtered domain (see rankOps.ts),
333
+ // because "is this row in the top 10" is a question about the other rows.
334
+ //
335
+ // ⚠ No set = REFUSE. Not "ignore", which is what an inactive rule gets, and not "true",
336
+ // which is what an inapplicable operator gets: both of those SHOW rows, and a rank leaf with
337
+ // no answer showing every record is the widening sin — the same one the cohort and measure
338
+ // leaves above are each written to avoid. A caller that evaluates a rank tree without
339
+ // resolving it first (a direct `matchFilterTree`) therefore gets an empty result, which is
340
+ // wrong in a way somebody notices, rather than a full one, which is wrong in a way nobody does.
341
+ if (isRankOp(node.op)) {
342
+ const set = ctx?.rankSets?.get(node);
343
+ return set ? set.has(r.pid) : false;
344
+ }
345
+
346
+ // --- an operator in NO vocabulary at all -------------------------------------------------
347
+ // (C-LOCK's dated amendment, from the widening gap this wave surfaced.) The comparators
348
+ // below end in `default: return true`, which is right for an operator that exists but does
349
+ // not apply to this type — `contains` on a number narrows nothing and asks nothing. It is
350
+ // NOT right for an operator that exists nowhere: `inTertile` from a stale localStorage view
351
+ // would match every row, a filter that widens under a count that agrees with it.
352
+ //
353
+ // The host already refuses these on read (`clean_filter_tree` keeps `op in FILTER_OPS`) and
354
+ // `filter_sql` refuses them too, so this closes the one path they had left — client session
355
+ // state. `FILTER_OPS` is the runtime mirror of the `FilterOp` union, asserted identical to
356
+ // it at compile time in types.ts and to both Python copies by verify_filter_engine, so this
357
+ // guard cannot drift into refusing a real operator.
358
+ // Compared as STRINGS: `FilterRule.op` is typed `FilterOp | CohortOp`, and a cohort leaf is
359
+ // the one thing this line must not judge — it carries `anyOf`/`allOf`/`noneOf`, which are
360
+ // deliberately NOT members of `FilterOp`. Cohort leaves returned above, so none reaches
361
+ // here; the cast says that to the compiler without narrowing what the guard actually checks.
362
+ if (!(FILTER_OPS as readonly string[]).includes(node.op)) return false;
363
+
364
  return matchFilter(node, r, fieldByKey, ctx?.today);
365
  }
366
 
 
383
  cohortSets?: CohortSets;
384
  /** The TENANT'S today. Never `new Date()` — see CustomersPayload.today. */
385
  today?: string;
386
+ /**
387
+ * C-OPS. Resolved rank leaves, `leaf -> the pids in its slice of the domain`. Fits the same
388
+ * property as its two neighbours above: an answer the row cannot compute, whose absence
389
+ * makes the condition match NOTHING rather than everything.
390
+ */
391
+ rankSets?: RankSets;
392
  }
393
 
394
  /**
 
637
  measureSets?: MeasureSets;
638
  /** Owner item 5. Cohort membership, `cohortId -> pids`. */
639
  cohortSets?: CohortSets;
640
+ /**
641
+ * Item 12 (C-LOCK) — this view is LOCKED to a cohort: the id of the set it names.
642
+ *
643
+ * Not a condition, and that is the whole point of it being a separate input. A locked view
644
+ * IS that set of customers; conditions narrow WITHIN it, the builder cannot express it and
645
+ * cannot remove it, and it applies whether or not the view has any conditions at all. The
646
+ * lock therefore bounds everything downstream — the pinned `memberPids` union, the ranking
647
+ * domain, the search, the count — because a view that promised "this cohort" and then showed
648
+ * a row outside it would be lying in the one place a user cannot check.
649
+ */
650
+ cohortLock?: string;
651
  /** The TENANT'S today, from the payload. Required by every relative-date condition and
652
  * never defaulted to the browser clock — see CustomersPayload.today. */
653
  today?: string;
 
657
  const {
658
  rawRows, fields, filters, search, sorts, groupBy, collapsed,
659
  memberPids = [], filterConj = "and", serverWindowed = false, measureSets,
660
+ cohortSets, today, cohortLock,
661
  } = input;
662
  const ctx: EvalCtx = { measureSets, cohortSets, today };
663
 
664
+ let unresolvedRank = 0;
665
+
666
  const asRows = (rows: Row[]): VisibleRowsResult => {
667
  const visibleRows = rows.map((record): VisibleRow => ({ kind: "data", record }));
668
  const pidToIndex = new Map<number, number>();
669
  visibleRows.forEach((vr, i) => {
670
  if (vr.kind === "data") pidToIndex.set(vr.record.pid, i);
671
  });
672
+ return { visibleRows, pidToIndex, unresolvedRank };
673
  };
674
 
675
  // CG-3: the whole client engine, skipped. Not "filters happen to be empty" — SKIPPED, so a
676
  // persisted filter arriving alongside a windowed payload cannot narrow the page twice.
677
+ //
678
+ // C-OPS note: a rank leaf never evaluates here either, and that is correct rather than a
679
+ // gap. A windowed payload is one PAGE of a scope the SQL engine already filtered, so ranking
680
+ // it client-side would rank the page and label the answer with the scope's count — the exact
681
+ // "12 rows under 'showing 200 of 5,728'" failure this bypass exists to prevent. The refusal
682
+ // belongs to `filter_sql`, which maps rank leaves to its UNANSWERABLE tri-state.
683
  if (serverWindowed) return asRows(rawRows);
684
 
685
  const fieldByKey = new Map<string, Field>();
 
691
  // so its buckets inherit the fully filtered + sorted order.
692
  let out = rawRows;
693
 
694
+ // --- C-LOCK (item 12): the cohort lock, FIRST and unconditionally --------------------
695
+ //
696
+ // Before the conditions, before the pinned rows, before the ranking domain. A locked view
697
+ // IS the set it names, so everything after this point operates inside it — which is also
698
+ // what makes "top 10" inside a locked view mean the top 10 OF THAT SET.
699
+ //
700
+ // ⚠ A lock we were given no membership for matches NOTHING. That is the cohort-leaf law
701
+ // (see `evalNode`) applied one level up, and the case is real rather than theoretical: a
702
+ // SHARED view can be locked to a cohort its reader cannot see, and the two candidate
703
+ // behaviours are "show them nobody" and "show them everybody". Only one of those is a
704
+ // permission bug. The toolbar's banner says so in words, because an empty table on its own
705
+ // does not distinguish this from a filter that genuinely matches nobody.
706
+ if (cohortLock) {
707
+ const locked = cohortSets?.[cohortLock];
708
+ if (!locked) return asRows([]);
709
+ out = out.filter((r) => locked.has(r.pid));
710
+ }
711
+
712
  if (filters.length) {
713
+ // --- C-OPS: the RANKING PASS, before the row-by-row one -------------------------------
714
+ //
715
+ // The domain is the rows matching every condition EXCEPT the rank leaves — strip them,
716
+ // evaluate the residue, and rank what is left. That is what makes "top 10 of agent Naomi"
717
+ // narrow by agent and THEN take ten, rather than taking the ten best overall and asking
718
+ // which of them Naomi has.
719
+ //
720
+ // Two deliberate exclusions from the domain, both documented rather than defaulted:
721
+ // • SEARCH — a separate pipeline step below, and the contract's words are "all other
722
+ // CONDITIONS". A search box is a transient way of looking at a view, not part of its
723
+ // definition, and letting it re-rank would mean the top 10 changed as you typed.
724
+ // • memberPids — hand-pinned rows that ride the `||` below without matching anything.
725
+ // They did not satisfy the conditions, so they are not part of the population being
726
+ // ranked; they stay visible regardless, which is what pinning means.
727
+ if (hasRankLeaf(filters)) {
728
+ const residue = stripRankLeaves(filters);
729
+ // `out`, not `rawRows`: at this point it is the pool AS THE LOCK LEFT IT, so a locked
730
+ // view's "top 10" is the top 10 of that cohort and not of the whole book.
731
+ const pool = out;
732
+ const domain = residue.length
733
+ ? pool.filter((r) => matchFilterTree(residue, filterConj, r, fieldByKey, ctx))
734
+ : pool; // nothing else to narrow by -> the whole pool is the population
735
+ const ranking = resolveRankLeaves(filters, domain, fieldByKey);
736
+ ctx.rankSets = ranking.sets;
737
+ unresolvedRank = ranking.unanswerable;
738
+ } else {
739
+ ctx.rankSets = NO_RANKING.sets;
740
+ }
741
+
742
  const members = new Set(memberPids);
743
  out = out.filter(
744
  (r) =>
 
768
  visibleRows.forEach((vr, i) => {
769
  if (vr.kind === "data" && !pidToIndex.has(vr.record.pid)) pidToIndex.set(vr.record.pid, i);
770
  });
771
+ return { visibleRows, pidToIndex, unresolvedRank };
772
  }
773
 
774
  export function useVisibleRows(
 
784
  serverWindowed = false,
785
  measureSets?: MeasureSets,
786
  cohortSets?: CohortSets,
787
+ today?: string,
788
+ cohortLock?: string
789
  ): VisibleRowsResult {
790
  return useMemo(
791
  () => runPipeline({ rawRows, fields, filters, search, sorts, groupBy, collapsed,
792
  memberPids, filterConj, serverWindowed, measureSets,
793
+ cohortSets, today, cohortLock }),
794
  [rawRows, fields, filters, filterConj, search, sorts, groupBy, collapsed,
795
+ memberPids, serverWindowed, measureSets, cohortSets, today, cohortLock]);
796
  }
web/src/customer-grid/viewEcho.ts CHANGED
@@ -155,6 +155,27 @@ export function reconcileEchoView(
155
  out = { ...host, config };
156
  }
157
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
158
  const localFilters = local.config ? local.config.filters : undefined;
159
  if (!Array.isArray(localFilters) || localFilters.length === 0) return out;
160
 
 
155
  out = { ...host, config };
156
  }
157
 
158
+ // Item 12 (C-LOCK, 2026-08-02) — `cohortLock` needs the SAME splice, and it needs its own
159
+ // because it is a sibling of `display` on ViewConfig, not a member of it: everything this
160
+ // function does not name explicitly is taken from the host wholesale.
161
+ //
162
+ // Without this, locking a view and then receiving a `/workspace` echo that predates the
163
+ // write hands back the pre-lock config — the rail mark disappears and the lock reads as
164
+ // ignored for a round trip. Exactly the blip the display half was written to stop, one key
165
+ // over. ABSENT IS A VALUE here too: a local copy that just UNLOCKED must not be flipped
166
+ // back by a lagged echo that still carries the lock, so the comparison is over the member
167
+ // itself rather than over truthy copies.
168
+ //
169
+ // ⚠ Built on `out`, not on `host` — the display splice above may already have replaced it,
170
+ // and rebuilding from `host` here would silently undo that.
171
+ const localLock = local.config ? local.config.cohortLock : undefined;
172
+ if (local.config && localLock !== out.config?.cohortLock) {
173
+ const config = { ...out.config };
174
+ if (localLock === undefined) delete config.cohortLock;
175
+ else config.cohortLock = localLock;
176
+ out = { ...out, config };
177
+ }
178
+
179
  const localFilters = local.config ? local.config.filters : undefined;
180
  if (!Array.isArray(localFilters) || localFilters.length === 0) return out;
181
 
web/src/customer-grid/viewModes.tsx CHANGED
@@ -18,12 +18,26 @@
18
  // the display cap stays the grid's own "Showing first N" bar.
19
  // ---------------------------------------------------------------------------
20
 
21
- import { 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
- import { formatDisplay } from "./cells";
26
- import { optionTint } from "./choiceColors";
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
  import { CREATABLE_MODES, MODE_LABELS } from "./iconShapes";
28
  import { LockMark, ModeIcon } from "./icons";
29
  import { Popover } from "./Toolbar";
@@ -47,6 +61,13 @@ export function ModeSwitch({
47
  sizeField,
48
  sizeChoices,
49
  onPickField,
 
 
 
 
 
 
 
50
  }: {
51
  mode: DisplayMode;
52
  onMode: (m: DisplayMode) => void;
@@ -73,6 +94,17 @@ export function ModeSwitch({
73
  sizeField?: Field;
74
  sizeChoices: Field[];
75
  onPickField: (k: "dateField" | "stackField" | "colorField" | "sizeField", key: string) => void;
 
 
 
 
 
 
 
 
 
 
 
76
  }) {
77
  // Wave-7 item W12: the switcher is a DROPDOWN in the toolbar-button family — the
78
  // same Popover component Fields/Filter/Sort use, radio rows inside (the Rows/Color
@@ -151,6 +183,120 @@ export function ModeSwitch({
151
  ))}
152
  </select>
153
  )}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
154
  {mode === "map" && colorChoices.length > 0 && (
155
  <select
156
  className="cg-select cg-mode-field"
@@ -187,7 +333,9 @@ export function ModeSwitch({
187
 
188
  // ------------------------------------------------------------------- list
189
 
190
- export function ListView({
 
 
191
  rows,
192
  fieldByKey,
193
  visibleKeys,
@@ -255,7 +403,7 @@ export function ListView({
255
  )}
256
  </div>
257
  );
258
- }
259
 
260
  // --------------------------------------------------------------- calendar
261
 
@@ -279,11 +427,18 @@ function monthTitle(month: string): string {
279
  });
280
  }
281
 
282
- export function CalendarView({
 
 
 
 
283
  rows,
284
  field,
285
  today,
286
  titleKey,
 
 
 
287
  onOpen,
288
  }: {
289
  /** DISTINCT data rows from the full pipeline (never the display slice — a
@@ -293,6 +448,11 @@ export function CalendarView({
293
  /** The tenant's today, from the payload. Absent = anchor on the data. */
294
  today?: string;
295
  titleKey: string;
 
 
 
 
 
296
  onOpen: (pid: number) => void;
297
  }) {
298
  const entries = useMemo(
@@ -301,6 +461,7 @@ export function CalendarView({
301
  pid: r.pid,
302
  title: String(r[titleKey] ?? ""),
303
  day: String(r[field.key] ?? "").slice(0, 10),
 
304
  })),
305
  [rows, field.key, titleKey]
306
  );
@@ -318,17 +479,41 @@ export function CalendarView({
318
  const shown = month ?? anchorMonth;
319
 
320
  const byDay = useMemo(() => {
321
- const m = new Map<string, { pid: number; title: string }[]>();
322
  if (!shown) return m;
323
  for (const e of dated) {
324
  if (!e.day.startsWith(shown)) continue;
325
  const bucket = m.get(e.day) ?? [];
326
- bucket.push({ pid: e.pid, title: e.title });
327
  m.set(e.day, bucket);
328
  }
329
  return m;
330
  }, [dated, shown]);
331
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
332
  if (!shown) {
333
  return (
334
  <div className="cg-mode-empty">
@@ -370,8 +555,16 @@ export function CalendarView({
370
  >
371
  ›
372
  </button>
 
 
 
 
 
 
373
  <span className="cg-cal-note">
374
- {monthCount.toLocaleString()} in this month · by {field.label}
 
 
375
  </span>
376
  {noDate > 0 && (
377
  <span
@@ -397,28 +590,75 @@ export function CalendarView({
397
  className={"cg-cal-cell" + (day ? "" : " is-blank") + (iso === today ? " is-today" : "")}
398
  >
399
  {day && <div className="cg-cal-day">{day}</div>}
400
- {bucket.map((e) => (
401
- <button
402
- key={e.pid}
403
- type="button"
404
- className="cg-cal-chip"
405
- title={e.title}
406
- onClick={() => onOpen(e.pid)}
407
- >
408
- {e.title}
409
- </button>
410
- ))}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
411
  </div>
412
  );
413
  })}
414
  </div>
415
  </div>
416
  );
417
- }
418
 
419
  // ----------------------------------------------------------------- kanban
420
 
421
- export function KanbanView({
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
422
  rows,
423
  field,
424
  fieldByKey,
@@ -426,6 +666,7 @@ export function KanbanView({
426
  titleKey,
427
  canMove,
428
  readOnlyReason,
 
429
  onMove,
430
  onOpen,
431
  }: {
@@ -440,6 +681,8 @@ export function KanbanView({
440
  canMove: boolean;
441
  /** Stated when cards cannot move (status = source-computed; permissions). */
442
  readOnlyReason: string | null;
 
 
443
  onMove: (pid: number, value: string) => void;
444
  onOpen: (pid: number) => void;
445
  }) {
@@ -483,13 +726,13 @@ export function KanbanView({
483
  const draggedRef = useRef(false);
484
 
485
  return (
486
- <div className="cg-kbview">
487
  {readOnlyReason && <div className="cg-kb-note">{readOnlyReason}</div>}
488
  <div className="cg-kb-lanes">
489
  {stacks.map((s) => {
490
  const isOpen = expanded.has(s.key);
491
  const shownRows = isOpen ? s.rows : s.rows.slice(0, KANBAN_PAGE);
492
- const tint = s.key ? optionTint(field, s.key) : undefined;
493
  return (
494
  <div
495
  key={s.key || "(empty)"}
@@ -581,4 +824,4 @@ export function KanbanView({
581
  </div>
582
  </div>
583
  );
584
- }
 
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 { Popover } from "./Toolbar";
 
61
  sizeField,
62
  sizeChoices,
63
  onPickField,
64
+ clamped = true,
65
+ onClamp,
66
+ calendarMode = "records",
67
+ onCalendarMode,
68
+ calendarMetrics = [],
69
+ metricChoices = [],
70
+ onCalendarMetrics,
71
  }: {
72
  mode: DisplayMode;
73
  onMode: (m: DisplayMode) => void;
 
94
  sizeField?: Field;
95
  sizeChoices: Field[];
96
  onPickField: (k: "dateField" | "stackField" | "colorField" | "sizeField", key: string) => void;
97
+ /** Item 3 (C-DISP) — cards are clamped unless the view stored the literal `false`. */
98
+ clamped?: boolean;
99
+ /** `false` = opt out of the clamp; `undefined` = back to the default (the key comes OFF). */
100
+ onClamp?: (next: false | undefined) => void;
101
+ /** Item 4 (C-DISP) — calendar days list records (default) or show aggregates. */
102
+ calendarMode?: "records" | "summary";
103
+ onCalendarMode?: (next: "records" | "summary") => void;
104
+ /** Item 4 — the chosen per-day totals, and the numeric-family fields on offer. */
105
+ calendarMetrics?: { id: string; field: string; agg: string }[];
106
+ metricChoices?: Field[];
107
+ onCalendarMetrics?: (next: { id: string; field: string; agg: string }[]) => void;
108
  }) {
109
  // Wave-7 item W12: the switcher is a DROPDOWN in the toolbar-button family — the
110
  // same Popover component Fields/Filter/Sort use, radio rows inside (the Rows/Color
 
183
  ))}
184
  </select>
185
  )}
186
+ {/* Owner item 3 (C-DISP) — the card-length toggle, beside the stack-field select the
187
+ contract names. Cards are CLAMPED by default now (that is the "standardized" the
188
+ owner asked for: a lane of same-height cards is scannable, a lane of ragged ones is
189
+ not), so this button is the opt-out.
190
+
191
+ ⚠ The stored value is the literal `false` and ONLY `false` — absent means clamped.
192
+ `true` would be a second spelling of the default, and two spellings of one state is
193
+ how a save starts churning. That is why the handler sends `false` or `undefined`
194
+ rather than a boolean. */}
195
+ {mode === "kanban" && onClamp && (
196
+ <button
197
+ type="button"
198
+ className={"cg-tb-btn cg-mode-field" + (clamped ? " is-on" : "")}
199
+ aria-pressed={clamped}
200
+ onClick={() => onClamp(clamped ? false : undefined)}
201
+ title={
202
+ clamped
203
+ ? "Cards are trimmed to a standard height. Click to let them grow to their content."
204
+ : "Cards grow to their content. Click to trim them to a standard height."
205
+ }
206
+ >
207
+ {clamped ? "Short cards" : "Full cards"}
208
+ </button>
209
+ )}
210
+ {/* Owner item 4 (C-DISP) — records vs summaries. A toggle rather than a select: there
211
+ are exactly two states and the button can say which one you are in. */}
212
+ {mode === "calendar" && onCalendarMode && (
213
+ <button
214
+ type="button"
215
+ className={"cg-tb-btn cg-mode-field" + (calendarMode === "summary" ? " is-on" : "")}
216
+ aria-pressed={calendarMode === "summary"}
217
+ onClick={() => onCalendarMode(calendarMode === "summary" ? "records" : "summary")}
218
+ title={
219
+ calendarMode === "summary"
220
+ ? "Each day shows totals. Click to list the records instead."
221
+ : "Each day lists its records. Click to show totals instead."
222
+ }
223
+ >
224
+ {calendarMode === "summary" ? "Summaries" : "Records"}
225
+ </button>
226
+ )}
227
+ {/* Item 4 — the metric PICKER, and it is what makes the item's "count/sum/avg" true.
228
+ Without it `summaryMetrics` can only ever be the always-on Records count, so a
229
+ summary day could say "Records: 3" and nothing else — the renderer would be right and
230
+ the feature would be half-delivered.
231
+
232
+ Only shown in summary mode: a picker for a thing that is not on screen is noise. */}
233
+ {mode === "calendar" && calendarMode === "summary" && onCalendarMetrics && (
234
+ <Popover
235
+ label={`Totals · ${calendarMetrics.length + 1}`}
236
+ icon={<ModeIcon mode="chart" />}
237
+ active={calendarMetrics.length > 0}
238
+ >
239
+ {() => (
240
+ <div className="cg-pop-body">
241
+ <div className="cg-pop-title">Totals per day</div>
242
+ <div className="cg-pop-note">
243
+ Records is always counted — every other figure in the cell is computed over it.
244
+ Up to {MAX_CALENDAR_METRICS} more.
245
+ </div>
246
+ {metricChoices.length === 0 && (
247
+ <div className="cg-pop-note">
248
+ This table has no numeric fields to total.
249
+ </div>
250
+ )}
251
+ {metricChoices.map((f) => {
252
+ const chosen = calendarMetrics.find((m) => m.field === f.key);
253
+ const full = calendarMetrics.length >= MAX_CALENDAR_METRICS;
254
+ return (
255
+ <div key={f.key} className="cg-cal-pick">
256
+ <label className="cg-check-row">
257
+ <input
258
+ type="checkbox"
259
+ checked={!!chosen}
260
+ disabled={!chosen && full}
261
+ onChange={() => {
262
+ const next = chosen
263
+ ? calendarMetrics.filter((m) => m.field !== f.key)
264
+ : [
265
+ ...calendarMetrics,
266
+ { id: `cm_${f.key}`, field: f.key, agg: "sum" },
267
+ ];
268
+ onCalendarMetrics(next);
269
+ }}
270
+ />
271
+ <span className="cg-check-label">{f.label}</span>
272
+ </label>
273
+ {chosen && (
274
+ <select
275
+ className="cg-select"
276
+ value={chosen.agg}
277
+ aria-label={`How to total ${f.label}`}
278
+ onChange={(e) =>
279
+ onCalendarMetrics(
280
+ calendarMetrics.map((m) =>
281
+ m.field === f.key ? { ...m, agg: e.target.value } : m
282
+ )
283
+ )
284
+ }
285
+ >
286
+ {CHART_AGGS.filter((a) => a !== "count").map((a) => (
287
+ <option key={a} value={a}>
288
+ {AGG_LABELS[a]}
289
+ </option>
290
+ ))}
291
+ </select>
292
+ )}
293
+ </div>
294
+ );
295
+ })}
296
+ </div>
297
+ )}
298
+ </Popover>
299
+ )}
300
  {mode === "map" && colorChoices.length > 0 && (
301
  <select
302
  className="cg-select cg-mode-field"
 
333
 
334
  // ------------------------------------------------------------------- list
335
 
336
+ /** Item 1 — memoised on the same argument; `onToggleGroup` was an inline arrow at the call
337
+ * site and is now a useCallback, without which this memo could never bail. */
338
+ export const ListView = memo(function ListView({
339
  rows,
340
  fieldByKey,
341
  visibleKeys,
 
403
  )}
404
  </div>
405
  );
406
+ });
407
 
408
  // --------------------------------------------------------------- calendar
409
 
 
427
  });
428
  }
429
 
430
+ /** Item 1 — memoised for the same reason as KanbanView below: a whole month of chips must not
431
+ * be reconciled again just because the record modal opened. All five props are already
432
+ * stable at the call site (`rows` is the `modeDataRows` useMemo, `field` comes out of
433
+ * `dateFieldChoices`, `onOpen` is a setState), so this one needed no call-site change. */
434
+ export const CalendarView = memo(function CalendarView({
435
  rows,
436
  field,
437
  today,
438
  titleKey,
439
+ mode = "records",
440
+ metrics,
441
+ fieldByKey,
442
  onOpen,
443
  }: {
444
  /** DISTINCT data rows from the full pipeline (never the display slice — a
 
448
  /** The tenant's today, from the payload. Absent = anchor on the data. */
449
  today?: string;
450
  titleKey: string;
451
+ /** Item 4 (C-DISP) — chips (default) or per-day aggregates. */
452
+ mode?: "records" | "summary";
453
+ /** The aggregates a summary day shows. Count of records is always shown first. */
454
+ metrics?: { id: string; field: string; agg: string }[];
455
+ fieldByKey?: Map<string, Field>;
456
  onOpen: (pid: number) => void;
457
  }) {
458
  const entries = useMemo(
 
461
  pid: r.pid,
462
  title: String(r[titleKey] ?? ""),
463
  day: String(r[field.key] ?? "").slice(0, 10),
464
+ row: r,
465
  })),
466
  [rows, field.key, titleKey]
467
  );
 
479
  const shown = month ?? anchorMonth;
480
 
481
  const byDay = useMemo(() => {
482
+ const m = new Map<string, { pid: number; title: string; row: Row }[]>();
483
  if (!shown) return m;
484
  for (const e of dated) {
485
  if (!e.day.startsWith(shown)) continue;
486
  const bucket = m.get(e.day) ?? [];
487
+ bucket.push({ pid: e.pid, title: e.title, row: e.row });
488
  m.set(e.day, bucket);
489
  }
490
  return m;
491
  }, [dated, shown]);
492
 
493
+ /**
494
+ * Item 4 (C-DISP) — the aggregates each summary day shows.
495
+ *
496
+ * Count is ALWAYS first and always present: it is the denominator every other figure in the
497
+ * cell is computed over, and a sum with no visible n is a number nobody can check
498
+ * ([[no-unverifiable-aggregates]]). A configured metric whose field has gone stale is
499
+ * dropped individually, the charts precedent — one bad ref must not cost the other three.
500
+ *
501
+ * `aggregateOrNull` (not the chart `reduce`) is deliberate: a day with no usable values
502
+ * renders "—", never a 0 that reads as a real measurement.
503
+ */
504
+ const summaryMetrics = useMemo(() => {
505
+ const out: { id: string; label: string; field?: Field; agg: ChartAgg }[] = [
506
+ { id: "__count__", label: "Records", agg: "count" },
507
+ ];
508
+ for (const m of metrics ?? []) {
509
+ const f = fieldByKey?.get(m.field);
510
+ if (!f) continue;
511
+ if (!(CHART_AGGS as readonly string[]).includes(m.agg)) continue;
512
+ out.push({ id: m.id, label: f.label, field: f, agg: m.agg as ChartAgg });
513
+ }
514
+ return out;
515
+ }, [metrics, fieldByKey]);
516
+
517
  if (!shown) {
518
  return (
519
  <div className="cg-mode-empty">
 
555
  >
556
  ›
557
  </button>
558
+ {/* Item 4 (C-DISP) — the DENOMINATOR, stated. In summary mode every figure in every
559
+ cell is computed over the records this month PLACED, which is not the same set as
560
+ the records the filter matched: a record with no {field.label} is on no day at
561
+ all. Saying "N in this month" beside a wall of sums is what keeps those sums
562
+ checkable, and the "without a date" chip beside it is the other half of the
563
+ sentence. */}
564
  <span className="cg-cal-note">
565
+ {mode === "summary"
566
+ ? `Totals over ${monthCount.toLocaleString()} record${monthCount === 1 ? "" : "s"} placed this month · by ${field.label}`
567
+ : `${monthCount.toLocaleString()} in this month · by ${field.label}`}
568
  </span>
569
  {noDate > 0 && (
570
  <span
 
590
  className={"cg-cal-cell" + (day ? "" : " is-blank") + (iso === today ? " is-today" : "")}
591
  >
592
  {day && <div className="cg-cal-day">{day}</div>}
593
+ {mode === "summary"
594
+ ? day &&
595
+ bucket.length > 0 &&
596
+ summaryMetrics.map((m) => {
597
+ const vals: number[] = [];
598
+ if (m.field)
599
+ for (const e of bucket) {
600
+ const n = asChartNumber(e.row[m.field.key]);
601
+ if (n != null) vals.push(n);
602
+ }
603
+ const v = aggregateOrNull(m.agg, vals, bucket.length);
604
+ return (
605
+ <div key={m.id} className="cg-cal-metric">
606
+ <span className="cg-cal-metric-k">{m.label}</span>
607
+ <span className="cg-cal-metric-v">
608
+ {/* "—" when the day held no usable value. A 0 here would be a
609
+ measurement nobody made. */}
610
+ {v == null
611
+ ? "—"
612
+ : v.toLocaleString(undefined, { maximumFractionDigits: 2 })}
613
+ </span>
614
+ </div>
615
+ );
616
+ })
617
+ : bucket.map((e) => (
618
+ <button
619
+ key={e.pid}
620
+ type="button"
621
+ className="cg-cal-chip"
622
+ title={e.title}
623
+ onClick={() => onOpen(e.pid)}
624
+ >
625
+ {e.title}
626
+ </button>
627
+ ))}
628
  </div>
629
  );
630
  })}
631
  </div>
632
  </div>
633
  );
634
+ });
635
 
636
  // ----------------------------------------------------------------- kanban
637
 
638
+ /**
639
+ * Owner item 1 (2026-08-02) — "kanban: laggy record-open after load".
640
+ *
641
+ * MEASURED, not guessed. On the live board a card costs ~11 DOM nodes and one
642
+ * `formatDisplay` call per card key (36 cards -> 108 cells -> 403 nodes), and the lane cap is
643
+ * per LANE (`KANBAN_PAGE`), not per board — so a real book stacked into 8 lanes rebuilds ~400
644
+ * cards / ~1,200 cells / ~4,500 elements. That cost is fine ONCE. The defect was that it was
645
+ * paid on EVERY CustomerGrid render, because this component was a bare function: clicking a
646
+ * card sets `detailPid`, the grid re-renders, and the whole board was reconciled again before
647
+ * the modal could paint. The click paid for the board.
648
+ *
649
+ * `memo` is only half the fix and the other half is at the CALL SITE — a memo whose props are
650
+ * rebuilt every render never bails. `cardKeys` (a `.filter().slice()`) and `onMove` (an inline
651
+ * arrow) are now memoised in CustomerGrid.tsx; `rows`, `field`, `fieldByKey` and the setState
652
+ * `onOpen` were already stable. So a `detailPid` change now re-renders the modal and nothing
653
+ * else.
654
+ *
655
+ * Two suspects the split doc listed were DISPROVEN by reading the code, and are recorded so
656
+ * nobody re-hunts them: the glide `DataEditor` already unmounts outside grid mode
657
+ * (`CustomerGrid.tsx` renders it under `displayMode === "grid"`), and `stacks` below already
658
+ * memoised correctly — `field` comes out of the `stackFieldChoices` useMemo, so its identity
659
+ * is stable and the memo was hitting.
660
+ */
661
+ export const KanbanView = memo(function KanbanView({
662
  rows,
663
  field,
664
  fieldByKey,
 
666
  titleKey,
667
  canMove,
668
  readOnlyReason,
669
+ clamped = true,
670
  onMove,
671
  onOpen,
672
  }: {
 
681
  canMove: boolean;
682
  /** Stated when cards cannot move (status = source-computed; permissions). */
683
  readOnlyReason: string | null;
684
+ /** Item 3 (C-DISP) — trim every card to a standard height. Default ON. */
685
+ clamped?: boolean;
686
  onMove: (pid: number, value: string) => void;
687
  onOpen: (pid: number) => void;
688
  }) {
 
726
  const draggedRef = useRef(false);
727
 
728
  return (
729
+ <div className={"cg-kbview" + (clamped ? " is-clamped" : "")}>
730
  {readOnlyReason && <div className="cg-kb-note">{readOnlyReason}</div>}
731
  <div className="cg-kb-lanes">
732
  {stacks.map((s) => {
733
  const isOpen = expanded.has(s.key);
734
  const shownRows = isOpen ? s.rows : s.rows.slice(0, KANBAN_PAGE);
735
+ const tint = s.key ? optionTint(field, s.key) : undefined;
736
  return (
737
  <div
738
  key={s.key || "(empty)"}
 
824
  </div>
825
  </div>
826
  );
827
+ });
web/src/index.css CHANGED
@@ -470,10 +470,10 @@ body {
470
  .cg-view-row:hover {
471
  background: var(--lp-surface-2);
472
  }
473
- .cg-view-row.is-active {
474
- background: var(--lp-blue-tint);
475
- }
476
- .cg-view-main {
477
  flex: 1 1 auto;
478
  min-width: 0;
479
  /* Wave-10 item 9: `height` became `min-height`. A row carrying a description is two lines
@@ -996,10 +996,10 @@ body {
996
  flex-direction: column;
997
  }
998
  .cg-pop-title {
999
- font-size: var(--lp-fs-3xs);
1000
  font-weight: 600;
1001
- letter-spacing: 0.03em;
1002
- text-transform: uppercase;
1003
  color: #8a8a96;
1004
  padding: 4px 8px 6px;
1005
  }
@@ -1075,100 +1075,100 @@ body {
1075
  color: #6b6b76;
1076
  font-size: var(--lp-fs-2xs);
1077
  }
1078
- /* Select-family field editor: one ordinary textbox per option, with a compact colour control. */
1079
- .cg-options-editor {
1080
- display: grid;
1081
- gap: 7px;
1082
- }
1083
- .cg-options-head {
1084
- display: flex;
1085
- align-items: center;
1086
- justify-content: space-between;
1087
- gap: 12px;
1088
- font-size: var(--lp-fs-xs);
1089
- }
1090
- .cg-options-head strong {
1091
- font-weight: 650;
1092
- color: var(--lp-ink);
1093
- }
1094
- .cg-option-toggle {
1095
- display: inline-flex;
1096
- align-items: center;
1097
- gap: 6px;
1098
- color: var(--lp-muted);
1099
- font-size: var(--lp-fs-2xs);
1100
- white-space: nowrap;
1101
- }
1102
- .cg-option-toggle input { margin: 0; }
1103
- .cg-option-list {
1104
- display: grid;
1105
- gap: 5px;
1106
- }
1107
- .cg-option-row {
1108
- display: grid;
1109
- grid-template-columns: 26px minmax(0, 1fr) 28px;
1110
- align-items: center;
1111
- gap: 6px;
1112
- }
1113
- .cg-option-color {
1114
- width: 24px;
1115
- height: 24px;
1116
- padding: 2px;
1117
- border: 1px solid var(--lp-line);
1118
- border-radius: 50%;
1119
- background: #fff;
1120
- cursor: pointer;
1121
- }
1122
- .cg-option-color::-webkit-color-swatch-wrapper { padding: 0; }
1123
- .cg-option-color::-webkit-color-swatch {
1124
- border: 0;
1125
- border-radius: 50%;
1126
- }
1127
- .cg-option-color::-moz-color-swatch {
1128
- border: 0;
1129
- border-radius: 50%;
1130
- }
1131
- .cg-option-color:disabled {
1132
- cursor: default;
1133
- opacity: 0.35;
1134
- }
1135
- .cg-option-name {
1136
- min-width: 0;
1137
- height: 31px;
1138
- }
1139
- .cg-option-remove {
1140
- display: inline-grid;
1141
- place-items: center;
1142
- width: 28px;
1143
- height: 28px;
1144
- padding: 0;
1145
- border: 0;
1146
- border-radius: var(--lp-r-sm);
1147
- background: transparent;
1148
- color: var(--lp-muted);
1149
- cursor: pointer;
1150
- }
1151
- .cg-option-remove:hover { background: var(--lp-red-tint); color: var(--lp-red-deep); }
1152
- .cg-option-remove svg {
1153
- width: 14px;
1154
- height: 14px;
1155
- fill: none;
1156
- stroke: currentColor;
1157
- stroke-width: 1.6;
1158
- stroke-linecap: round;
1159
- }
1160
- .cg-option-add {
1161
- justify-self: start;
1162
- padding: 2px 0;
1163
- border: 0;
1164
- background: transparent;
1165
- color: var(--lp-blue-solid);
1166
- font: inherit;
1167
- font-size: var(--lp-fs-2xs);
1168
- font-weight: 600;
1169
- cursor: pointer;
1170
- }
1171
- .cg-option-add:hover { text-decoration: underline; }
1172
  .cg-field-hint {
1173
  display: block;
1174
  font-size: var(--lp-fs-3xs);
@@ -1292,10 +1292,10 @@ body {
1292
  text-overflow: ellipsis;
1293
  }
1294
  .cg-lock-tag {
1295
- font-size: 10px;
1296
  font-weight: 600;
1297
- letter-spacing: 0.02em;
1298
- text-transform: uppercase;
1299
  color: var(--lp-yellow-deep);
1300
  background: var(--lp-yellow-tint);
1301
  border-radius: var(--lp-r-sm);
@@ -1983,10 +1983,10 @@ body {
1983
  margin-top: 6px;
1984
  }
1985
  .cg-detail-section-title {
1986
- font-size: var(--lp-fs-3xs);
1987
  font-weight: 600;
1988
- letter-spacing: 0.03em;
1989
- text-transform: uppercase;
1990
  color: #8a8a96;
1991
  padding: 0 0 8px;
1992
  }
@@ -2052,9 +2052,10 @@ body {
2052
  /* change-field split, the column-menu Period row. */
2053
  /* ------------------------------------------------------------------------- */
2054
 
2055
- /* Item 7 remainder — the Fields panel search box + the Pre-set chip. The chip
2056
- text is literally `Pre-set` (the shared contract's exact label), so no
2057
- text-transform here, unlike .cg-lock-tag. */
 
2058
  .cg-fields-search {
2059
  margin: 0 8px 6px;
2060
  height: 28px;
@@ -2634,10 +2635,8 @@ body {
2634
 
2635
  /* A folder head is a LABEL, not a link: quieter, no hover, no cursor. */
2636
  .shell-nav-group {
2637
- font-size: var(--lp-fs-3xs);
2638
  font-weight: 600;
2639
- letter-spacing: 0.06em;
2640
- text-transform: uppercase;
2641
  color: var(--lp-muted);
2642
  padding-top: 14px;
2643
  }
@@ -2952,10 +2951,39 @@ body {
2952
  min-width: 0;
2953
  }
2954
  .cg-lv-cell { display: inline-flex; gap: 5px; align-items: baseline; max-width: 260px; }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2955
  .cg-lv-k {
2956
  font-size: var(--lp-fs-3xs);
2957
- text-transform: uppercase;
2958
- letter-spacing: 0.03em;
2959
  color: #8a8f98;
2960
  white-space: nowrap;
2961
  }
@@ -2989,9 +3017,7 @@ body {
2989
  }
2990
  .cg-cal-dow {
2991
  padding: 4px 6px;
2992
- font-size: var(--lp-fs-3xs);
2993
- text-transform: uppercase;
2994
- letter-spacing: 0.04em;
2995
  color: #8a8f98;
2996
  border-right: 1px solid #e4e7eb;
2997
  border-bottom: 1px solid #e4e7eb;
@@ -3029,14 +3055,14 @@ body {
3029
 
3030
  /* Item 10 — KANBAN view. */
3031
  .cg-kbview { height: 100%; overflow: hidden; display: flex; flex-direction: column; background: #f7f8fa; }
3032
- .cg-kb-note {
3033
- padding: 6px 12px;
3034
- font-family: inherit;
3035
- font-size: var(--lp-fs-2xs);
3036
- color: #6a6f78;
3037
- background: #fff;
3038
- border-bottom: 1px solid #e4e7eb;
3039
- }
3040
  .cg-kb-lanes {
3041
  flex: 1;
3042
  display: flex;
@@ -3062,12 +3088,12 @@ body {
3062
  background: #dfe3e8;
3063
  color: var(--lp-ink);
3064
  }
3065
- .cg-kb-count {
3066
- font-family: inherit;
3067
- font-size: var(--lp-fs-2xs);
3068
- color: #6a6f78;
3069
- font-variant-numeric: tabular-nums;
3070
- }
3071
  .cg-kb-cards { flex: 1; overflow-y: auto; padding: 4px 8px 10px; }
3072
  .cg-kb-card {
3073
  background: #fff;
@@ -3092,25 +3118,27 @@ body {
3092
  cursor: pointer;
3093
  }
3094
  .cg-kb-title:hover { color: var(--lp-blue-solid); text-decoration: underline; }
3095
- .cg-kb-cell {
3096
- display: flex;
3097
- gap: 6px;
3098
- align-items: baseline;
3099
- font-family: inherit;
3100
- font-size: var(--lp-fs-xs);
3101
- }
3102
- .cg-kb-cell .cg-lv-k,
3103
- .cg-kb-cell .cg-lv-v {
3104
- font-family: inherit;
3105
- font-size: var(--lp-fs-xs);
3106
- line-height: 1.35;
3107
- text-transform: none;
3108
- letter-spacing: normal;
3109
- }
3110
- .cg-kb-cell .cg-lv-k {
3111
- color: var(--lp-muted);
3112
- font-weight: 500;
3113
- }
 
 
3114
  .cg-kb-more { display: block; margin: 2px 0 4px; }
3115
 
3116
  /* Item 4 — the header-row "+" (insert at end). */
@@ -3789,9 +3817,9 @@ a.cg-map-ctl-b { text-decoration: none; }
3789
  border: none;
3790
  background: transparent;
3791
  font: inherit;
3792
- /* Wave-10 item 2 (SC-1): 11px → 13px, the SAME size as the view rows under it. Weight still
3793
- distinguishes the folder heading; the name itself is promoted to primary ink below while
3794
- the chevron/count retain this muted control colour. */
3795
  font-size: var(--lp-fs-xs);
3796
  font-weight: 600;
3797
  color: var(--lp-muted);
@@ -3829,13 +3857,13 @@ a.cg-map-ctl-b { text-decoration: none; }
3829
  `rotate(-90deg)` here would drop the centring and the collapsed chevron would jump half its
3830
  own height. Measured both states in the harness. */
3831
  .cg-fold-chev.is-shut { transform: translateY(-50%) rotate(-90deg); }
3832
- .cg-fold-name {
3833
- flex: 1 1 auto;
3834
- overflow: hidden;
3835
- color: var(--lp-ink);
3836
- text-overflow: ellipsis;
3837
- white-space: nowrap;
3838
- }
3839
  .cg-fold-count { flex: 0 0 auto; font-variant-numeric: tabular-nums; font-weight: 400; }
3840
  .cg-fold-rename { flex: 1 1 auto; height: 24px; font-weight: 400; }
3841
  .cg-fold-empty {
@@ -3880,26 +3908,26 @@ a.cg-map-ctl-b { text-decoration: none; }
3880
  /* Owner item 9 (2026-07-31): the create row is a QUIET affordance, not a headline — regular
3881
  weight, flush-left with the search and the view names under it. */
3882
  .cg-create-new { padding: 2px 2px 0; }
3883
- .cg-create-btn {
3884
- width: 100%;
3885
- min-height: 28px;
3886
- display: flex;
3887
- align-items: center;
3888
- gap: 6px;
3889
- text-align: left;
3890
- padding: 0 8px;
3891
- color: var(--lp-ink);
3892
- font-weight: 400;
3893
- }
3894
- .cg-create-icon {
3895
- width: 14px;
3896
- flex: 0 0 14px;
3897
- color: var(--lp-muted);
3898
- text-align: center;
3899
- }
3900
- .cg-create-label {
3901
- min-width: 0;
3902
- }
3903
  /* Wave-10 item 13 — the trigger stays HELD while its flyout is open. Driven off the
3904
  `aria-expanded` the button already publishes, so the visual state cannot drift from the
3905
  accessible one: there is no second source of truth to forget to update. Neutral grey
@@ -4038,10 +4066,8 @@ a.cg-map-ctl-b { text-decoration: none; }
4038
  margin: 6px 0 2px;
4039
  }
4040
  .cg-perm-title {
4041
- font-size: var(--lp-fs-3xs);
4042
  font-weight: 600;
4043
- letter-spacing: 0.03em;
4044
- text-transform: uppercase;
4045
  color: var(--lp-muted);
4046
  padding-bottom: 2px;
4047
  }
@@ -4255,10 +4281,8 @@ a.cg-map-ctl-b { text-decoration: none; }
4255
  .pg-controls { display: flex; align-items: flex-end; gap: 14px; }
4256
  .pg-control { display: flex; flex-direction: column; gap: 3px; }
4257
  .pg-control-label {
4258
- font-size: var(--lp-fs-3xs);
4259
  font-weight: 600;
4260
- letter-spacing: 0.03em;
4261
- text-transform: uppercase;
4262
  color: var(--lp-muted);
4263
  }
4264
  .pg-select {
@@ -4321,10 +4345,8 @@ a.cg-map-ctl-b { text-decoration: none; }
4321
  .pg-kpi.is-clickable:hover { border-color: var(--lp-blue-deep); background: var(--lp-blue-tint); }
4322
  .pg-kpi.is-clickable:focus-visible { outline: 2px solid var(--lp-blue-deep); outline-offset: 1px; }
4323
  .pg-kpi-label {
4324
- font-size: var(--lp-fs-3xs);
4325
  font-weight: 600;
4326
- letter-spacing: 0.03em;
4327
- text-transform: uppercase;
4328
  color: var(--lp-muted);
4329
  }
4330
  .pg-kpi-value {
@@ -4352,10 +4374,8 @@ a.cg-map-ctl-b { text-decoration: none; }
4352
  padding: 7px 10px;
4353
  border-bottom: 1px solid var(--lp-line);
4354
  text-align: left;
4355
- font-size: var(--lp-fs-3xs);
4356
  font-weight: 600;
4357
- letter-spacing: 0.03em;
4358
- text-transform: uppercase;
4359
  color: var(--lp-muted);
4360
  white-space: nowrap;
4361
  }
@@ -4532,10 +4552,8 @@ a.cg-map-ctl-b { text-decoration: none; }
4532
  }
4533
  .pg-drill-head { display: flex; align-items: flex-start; justify-content: space-between; gap: 12px; }
4534
  .pg-drill-kind {
4535
- font-size: var(--lp-fs-3xs);
4536
  font-weight: 600;
4537
- letter-spacing: 0.04em;
4538
- text-transform: uppercase;
4539
  color: var(--lp-muted);
4540
  }
4541
  .pg-drill-title {
@@ -4617,10 +4635,8 @@ a.cg-map-ctl-b { text-decoration: none; }
4617
  }
4618
  .set-rail-cap {
4619
  padding: 0 10px 10px;
4620
- font-size: var(--lp-fs-3xs);
4621
  font-weight: 600;
4622
- letter-spacing: 0.04em;
4623
- text-transform: uppercase;
4624
  color: var(--lp-muted);
4625
  }
4626
  .set-rail-item {
@@ -4692,10 +4708,8 @@ a.cg-map-ctl-b { text-decoration: none; }
4692
  .set-label {
4693
  display: block;
4694
  margin-bottom: 3px;
4695
- font-size: var(--lp-fs-3xs);
4696
  font-weight: 600;
4697
- letter-spacing: 0.03em;
4698
- text-transform: uppercase;
4699
  color: var(--lp-muted);
4700
  }
4701
  .set-input {
@@ -4738,3 +4752,253 @@ a.cg-map-ctl-b { text-decoration: none; }
4738
  session the account has open — the sentence above the button says it in
4739
  words, and this says it before the words are read. */
4740
  .set-danger { margin-top: 18px; padding-top: 14px; border-top: 1px solid var(--lp-red-deep); }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
470
  .cg-view-row:hover {
471
  background: var(--lp-surface-2);
472
  }
473
+ .cg-view-row.is-active {
474
+ background: var(--lp-blue-tint);
475
+ }
476
+ .cg-view-main {
477
  flex: 1 1 auto;
478
  min-width: 0;
479
  /* Wave-10 item 9: `height` became `min-height`. A row carrying a description is two lines
 
996
  flex-direction: column;
997
  }
998
  .cg-pop-title {
999
+ font-size: var(--lp-fs-2xs);
1000
  font-weight: 600;
1001
+ letter-spacing: normal;
1002
+ /* item 11 (2026-08-02): sentence case — this is the "FILTER" the owner called out. */
1003
  color: #8a8a96;
1004
  padding: 4px 8px 6px;
1005
  }
 
1075
  color: #6b6b76;
1076
  font-size: var(--lp-fs-2xs);
1077
  }
1078
+ /* Select-family field editor: one ordinary textbox per option, with a compact colour control. */
1079
+ .cg-options-editor {
1080
+ display: grid;
1081
+ gap: 7px;
1082
+ }
1083
+ .cg-options-head {
1084
+ display: flex;
1085
+ align-items: center;
1086
+ justify-content: space-between;
1087
+ gap: 12px;
1088
+ font-size: var(--lp-fs-xs);
1089
+ }
1090
+ .cg-options-head strong {
1091
+ font-weight: 650;
1092
+ color: var(--lp-ink);
1093
+ }
1094
+ .cg-option-toggle {
1095
+ display: inline-flex;
1096
+ align-items: center;
1097
+ gap: 6px;
1098
+ color: var(--lp-muted);
1099
+ font-size: var(--lp-fs-2xs);
1100
+ white-space: nowrap;
1101
+ }
1102
+ .cg-option-toggle input { margin: 0; }
1103
+ .cg-option-list {
1104
+ display: grid;
1105
+ gap: 5px;
1106
+ }
1107
+ .cg-option-row {
1108
+ display: grid;
1109
+ grid-template-columns: 26px minmax(0, 1fr) 28px;
1110
+ align-items: center;
1111
+ gap: 6px;
1112
+ }
1113
+ .cg-option-color {
1114
+ width: 24px;
1115
+ height: 24px;
1116
+ padding: 2px;
1117
+ border: 1px solid var(--lp-line);
1118
+ border-radius: 50%;
1119
+ background: #fff;
1120
+ cursor: pointer;
1121
+ }
1122
+ .cg-option-color::-webkit-color-swatch-wrapper { padding: 0; }
1123
+ .cg-option-color::-webkit-color-swatch {
1124
+ border: 0;
1125
+ border-radius: 50%;
1126
+ }
1127
+ .cg-option-color::-moz-color-swatch {
1128
+ border: 0;
1129
+ border-radius: 50%;
1130
+ }
1131
+ .cg-option-color:disabled {
1132
+ cursor: default;
1133
+ opacity: 0.35;
1134
+ }
1135
+ .cg-option-name {
1136
+ min-width: 0;
1137
+ height: 31px;
1138
+ }
1139
+ .cg-option-remove {
1140
+ display: inline-grid;
1141
+ place-items: center;
1142
+ width: 28px;
1143
+ height: 28px;
1144
+ padding: 0;
1145
+ border: 0;
1146
+ border-radius: var(--lp-r-sm);
1147
+ background: transparent;
1148
+ color: var(--lp-muted);
1149
+ cursor: pointer;
1150
+ }
1151
+ .cg-option-remove:hover { background: var(--lp-red-tint); color: var(--lp-red-deep); }
1152
+ .cg-option-remove svg {
1153
+ width: 14px;
1154
+ height: 14px;
1155
+ fill: none;
1156
+ stroke: currentColor;
1157
+ stroke-width: 1.6;
1158
+ stroke-linecap: round;
1159
+ }
1160
+ .cg-option-add {
1161
+ justify-self: start;
1162
+ padding: 2px 0;
1163
+ border: 0;
1164
+ background: transparent;
1165
+ color: var(--lp-blue-solid);
1166
+ font: inherit;
1167
+ font-size: var(--lp-fs-2xs);
1168
+ font-weight: 600;
1169
+ cursor: pointer;
1170
+ }
1171
+ .cg-option-add:hover { text-decoration: underline; }
1172
  .cg-field-hint {
1173
  display: block;
1174
  font-size: var(--lp-fs-3xs);
 
1292
  text-overflow: ellipsis;
1293
  }
1294
  .cg-lock-tag {
1295
+ font-size: var(--lp-fs-3xs);
1296
  font-weight: 600;
1297
+ letter-spacing: normal;
1298
+ /* item 11: sentence case, and the 10px one-off gives way to the 3xs token. */
1299
  color: var(--lp-yellow-deep);
1300
  background: var(--lp-yellow-tint);
1301
  border-radius: var(--lp-r-sm);
 
1983
  margin-top: 6px;
1984
  }
1985
  .cg-detail-section-title {
1986
+ font-size: var(--lp-fs-2xs);
1987
  font-weight: 600;
1988
+ letter-spacing: normal;
1989
+ /* item 11: sentence case. Line-count-neutral — the frozen 1994-2050 block must not move. */
1990
  color: #8a8a96;
1991
  padding: 0 0 8px;
1992
  }
 
2052
  /* change-field split, the column-menu Period row. */
2053
  /* ------------------------------------------------------------------------- */
2054
 
2055
+ /* Item 7 remainder — the Fields panel search box + the Pre-set chip. The chip text is
2056
+ literally `Pre-set` (the shared contract's exact label), and it renders as written.
2057
+ (This note used to contrast with `.cg-lock-tag`, which uppercased; item 11 took that
2058
+ transform off, so every label in this file now renders exactly as it is authored.) */
2059
  .cg-fields-search {
2060
  margin: 0 8px 6px;
2061
  height: 28px;
 
2635
 
2636
  /* A folder head is a LABEL, not a link: quieter, no hover, no cursor. */
2637
  .shell-nav-group {
2638
+ font-size: var(--lp-fs-2xs);
2639
  font-weight: 600;
 
 
2640
  color: var(--lp-muted);
2641
  padding-top: 14px;
2642
  }
 
2951
  min-width: 0;
2952
  }
2953
  .cg-lv-cell { display: inline-flex; gap: 5px; align-items: baseline; max-width: 260px; }
2954
+ /* ---------------------------------------------------------------------------
2955
+ Item 11 (2026-08-02) — the uppercase sweep. THE RULE, applied at all 13 sites:
2956
+
2957
+ Every one of them was the same micro-kicker — 3xs + 600 + positive tracking +
2958
+ `text-transform: uppercase` — and the owner wants sentence case. Deleting the
2959
+ transform alone is not the fix: caps carry ~30% more optical weight than
2960
+ lowercase at the same px, and the positive letter-spacing only exists BECAUSE
2961
+ caps need opening up. Left as-is, an 11px muted label becomes genuinely hard to
2962
+ read and the tracking reads as loose. So each site takes three changes together:
2963
+ 3xs -> 2xs (one step up, buying back what the caps were carrying)
2964
+ letter-spacing -> normal (tracking is a caps device)
2965
+ font-weight: 600 STAYS (it is what still says "label, not value")
2966
+ TWO SITES STAY AT 3xs, and both were decided by looking at the rendered page
2967
+ rather than by applying the rule (A/B'd live on the Space, 2026-08-02):
2968
+ `.cg-lock-tag` — a pill annotating 13px text; it must stay smaller than what
2969
+ it annotates, and it sits inches from the sentence-case `Pre-set` chip,
2970
+ which is now its typographic twin.
2971
+ `.cg-lv-k` BELOW — the "caps were carrying legibility" argument does NOT
2972
+ apply to it. Every other site is a LONE kicker with nothing beside it; this
2973
+ one always sits immediately left of its value, so the pair itself carries
2974
+ the legibility. Side by side, 3xs is the better of the two: the size step
2975
+ reinforces the label/value split that colour already states (at 2xs the
2976
+ distinction leans on colour alone), and it keeps the density the list view
2977
+ exists for — a 2xs key wraps pairs onto a second line sooner.
2978
+
2979
+ The source strings were ALREADY sentence case everywhere ("Filter", "Sort",
2980
+ "Notes", "Locked"), so this file was the whole of the bug.
2981
+
2982
+ Kanban is untouched by all of this: `.cg-kb-cell .cg-lv-k` (0,2,0) already
2983
+ overrode both the size and the transform, so those cards were never uppercase.
2984
+ --------------------------------------------------------------------------- */
2985
  .cg-lv-k {
2986
  font-size: var(--lp-fs-3xs);
 
 
2987
  color: #8a8f98;
2988
  white-space: nowrap;
2989
  }
 
3017
  }
3018
  .cg-cal-dow {
3019
  padding: 4px 6px;
3020
+ font-size: var(--lp-fs-2xs);
 
 
3021
  color: #8a8f98;
3022
  border-right: 1px solid #e4e7eb;
3023
  border-bottom: 1px solid #e4e7eb;
 
3055
 
3056
  /* Item 10 — KANBAN view. */
3057
  .cg-kbview { height: 100%; overflow: hidden; display: flex; flex-direction: column; background: #f7f8fa; }
3058
+ .cg-kb-note {
3059
+ padding: 6px 12px;
3060
+ font-family: inherit;
3061
+ font-size: var(--lp-fs-2xs);
3062
+ color: #6a6f78;
3063
+ background: #fff;
3064
+ border-bottom: 1px solid #e4e7eb;
3065
+ }
3066
  .cg-kb-lanes {
3067
  flex: 1;
3068
  display: flex;
 
3088
  background: #dfe3e8;
3089
  color: var(--lp-ink);
3090
  }
3091
+ .cg-kb-count {
3092
+ font-family: inherit;
3093
+ font-size: var(--lp-fs-2xs);
3094
+ color: #6a6f78;
3095
+ font-variant-numeric: tabular-nums;
3096
+ }
3097
  .cg-kb-cards { flex: 1; overflow-y: auto; padding: 4px 8px 10px; }
3098
  .cg-kb-card {
3099
  background: #fff;
 
3118
  cursor: pointer;
3119
  }
3120
  .cg-kb-title:hover { color: var(--lp-blue-solid); text-decoration: underline; }
3121
+ .cg-kb-cell {
3122
+ display: flex;
3123
+ gap: 6px;
3124
+ align-items: baseline;
3125
+ font-family: inherit;
3126
+ font-size: var(--lp-fs-xs);
3127
+ }
3128
+ /* The `text-transform: none` / `letter-spacing: normal` this block used to carry came off
3129
+ with item 11 — `.cg-lv-k` no longer uppercases anything, so overriding it here would be
3130
+ a reset of a rule that no longer exists. The font-size override stays: kanban cards read
3131
+ at card size, not list-row size. */
3132
+ .cg-kb-cell .cg-lv-k,
3133
+ .cg-kb-cell .cg-lv-v {
3134
+ font-family: inherit;
3135
+ font-size: var(--lp-fs-xs);
3136
+ line-height: 1.35;
3137
+ }
3138
+ .cg-kb-cell .cg-lv-k {
3139
+ color: var(--lp-muted);
3140
+ font-weight: 500;
3141
+ }
3142
  .cg-kb-more { display: block; margin: 2px 0 4px; }
3143
 
3144
  /* Item 4 — the header-row "+" (insert at end). */
 
3817
  border: none;
3818
  background: transparent;
3819
  font: inherit;
3820
+ /* Wave-10 item 2 (SC-1): 11px → 13px, the SAME size as the view rows under it. Weight still
3821
+ distinguishes the folder heading; the name itself is promoted to primary ink below while
3822
+ the chevron/count retain this muted control colour. */
3823
  font-size: var(--lp-fs-xs);
3824
  font-weight: 600;
3825
  color: var(--lp-muted);
 
3857
  `rotate(-90deg)` here would drop the centring and the collapsed chevron would jump half its
3858
  own height. Measured both states in the harness. */
3859
  .cg-fold-chev.is-shut { transform: translateY(-50%) rotate(-90deg); }
3860
+ .cg-fold-name {
3861
+ flex: 1 1 auto;
3862
+ overflow: hidden;
3863
+ color: var(--lp-ink);
3864
+ text-overflow: ellipsis;
3865
+ white-space: nowrap;
3866
+ }
3867
  .cg-fold-count { flex: 0 0 auto; font-variant-numeric: tabular-nums; font-weight: 400; }
3868
  .cg-fold-rename { flex: 1 1 auto; height: 24px; font-weight: 400; }
3869
  .cg-fold-empty {
 
3908
  /* Owner item 9 (2026-07-31): the create row is a QUIET affordance, not a headline — regular
3909
  weight, flush-left with the search and the view names under it. */
3910
  .cg-create-new { padding: 2px 2px 0; }
3911
+ .cg-create-btn {
3912
+ width: 100%;
3913
+ min-height: 28px;
3914
+ display: flex;
3915
+ align-items: center;
3916
+ gap: 6px;
3917
+ text-align: left;
3918
+ padding: 0 8px;
3919
+ color: var(--lp-ink);
3920
+ font-weight: 400;
3921
+ }
3922
+ .cg-create-icon {
3923
+ width: 14px;
3924
+ flex: 0 0 14px;
3925
+ color: var(--lp-muted);
3926
+ text-align: center;
3927
+ }
3928
+ .cg-create-label {
3929
+ min-width: 0;
3930
+ }
3931
  /* Wave-10 item 13 — the trigger stays HELD while its flyout is open. Driven off the
3932
  `aria-expanded` the button already publishes, so the visual state cannot drift from the
3933
  accessible one: there is no second source of truth to forget to update. Neutral grey
 
4066
  margin: 6px 0 2px;
4067
  }
4068
  .cg-perm-title {
4069
+ font-size: var(--lp-fs-2xs);
4070
  font-weight: 600;
 
 
4071
  color: var(--lp-muted);
4072
  padding-bottom: 2px;
4073
  }
 
4281
  .pg-controls { display: flex; align-items: flex-end; gap: 14px; }
4282
  .pg-control { display: flex; flex-direction: column; gap: 3px; }
4283
  .pg-control-label {
4284
+ font-size: var(--lp-fs-2xs);
4285
  font-weight: 600;
 
 
4286
  color: var(--lp-muted);
4287
  }
4288
  .pg-select {
 
4345
  .pg-kpi.is-clickable:hover { border-color: var(--lp-blue-deep); background: var(--lp-blue-tint); }
4346
  .pg-kpi.is-clickable:focus-visible { outline: 2px solid var(--lp-blue-deep); outline-offset: 1px; }
4347
  .pg-kpi-label {
4348
+ font-size: var(--lp-fs-2xs);
4349
  font-weight: 600;
 
 
4350
  color: var(--lp-muted);
4351
  }
4352
  .pg-kpi-value {
 
4374
  padding: 7px 10px;
4375
  border-bottom: 1px solid var(--lp-line);
4376
  text-align: left;
4377
+ font-size: var(--lp-fs-2xs);
4378
  font-weight: 600;
 
 
4379
  color: var(--lp-muted);
4380
  white-space: nowrap;
4381
  }
 
4552
  }
4553
  .pg-drill-head { display: flex; align-items: flex-start; justify-content: space-between; gap: 12px; }
4554
  .pg-drill-kind {
4555
+ font-size: var(--lp-fs-2xs);
4556
  font-weight: 600;
 
 
4557
  color: var(--lp-muted);
4558
  }
4559
  .pg-drill-title {
 
4635
  }
4636
  .set-rail-cap {
4637
  padding: 0 10px 10px;
4638
+ font-size: var(--lp-fs-2xs);
4639
  font-weight: 600;
 
 
4640
  color: var(--lp-muted);
4641
  }
4642
  .set-rail-item {
 
4708
  .set-label {
4709
  display: block;
4710
  margin-bottom: 3px;
4711
+ font-size: var(--lp-fs-2xs);
4712
  font-weight: 600;
 
 
4713
  color: var(--lp-muted);
4714
  }
4715
  .set-input {
 
4752
  session the account has open — the sentence above the button says it in
4753
  words, and this says it before the words are read. */
4754
  .set-danger { margin-top: 18px; padding-top: 14px; border-top: 1px solid var(--lp-red-deep); }
4755
+
4756
+ /* ------------------------------------------------------------------------- */
4757
+ /* Owner item 7 (2026-08-02, contract C-TS): the TIME SERIES view — metric */
4758
+ /* rows x time-bucket columns. Also mounted inside the record modal for item */
4759
+ /* 13, so nothing here may depend on the grid's own layout. */
4760
+ /* ------------------------------------------------------------------------- */
4761
+
4762
+ .cg-ts {
4763
+ display: flex;
4764
+ flex-direction: column;
4765
+ min-height: 0;
4766
+ padding: 12px 14px 18px;
4767
+ gap: 10px;
4768
+ }
4769
+ .cg-ts-bar,
4770
+ .cg-ts-fields {
4771
+ display: flex;
4772
+ align-items: center;
4773
+ flex-wrap: wrap;
4774
+ gap: 8px;
4775
+ }
4776
+ .cg-ts-ctl { display: inline-flex; align-items: center; gap: 6px; }
4777
+ .cg-ts-ctl-k {
4778
+ font-size: var(--lp-fs-2xs);
4779
+ font-weight: 600;
4780
+ color: var(--lp-muted);
4781
+ }
4782
+ /* The pool statement. It is not decoration: a series over "everyone" and a series over one
4783
+ filtered book are different claims, and the reader has to be able to tell which they are
4784
+ looking at without leaving the panel. */
4785
+ .cg-ts-pool {
4786
+ margin-left: auto;
4787
+ font-size: var(--lp-fs-2xs);
4788
+ color: var(--lp-muted);
4789
+ font-variant-numeric: tabular-nums;
4790
+ }
4791
+ /* A metric chip. Tint FILLS and the -deep weight carries the text, per the brand rule —
4792
+ the base pastel is 1.88:1 and would not be readable as ink at this size. */
4793
+ .cg-ts-chip {
4794
+ height: 26px;
4795
+ padding: 0 10px;
4796
+ border: 1px solid var(--lp-line);
4797
+ border-radius: var(--lp-r-lg);
4798
+ background: var(--lp-surface);
4799
+ color: var(--lp-muted);
4800
+ font: inherit;
4801
+ font-size: var(--lp-fs-2xs);
4802
+ cursor: pointer;
4803
+ }
4804
+ .cg-ts-chip.is-on {
4805
+ border-color: var(--lp-blue-deep);
4806
+ background: var(--lp-blue-tint);
4807
+ color: var(--lp-blue-deep);
4808
+ font-weight: 600;
4809
+ }
4810
+ .cg-ts-chip:disabled { cursor: default; opacity: 0.55; }
4811
+ .cg-ts-chip:focus-visible { outline: 2px solid var(--lp-blue-deep); outline-offset: 1px; }
4812
+
4813
+ .cg-ts-scroll {
4814
+ overflow: auto;
4815
+ border: 1px solid var(--lp-line);
4816
+ border-radius: var(--lp-r-md);
4817
+ background: var(--lp-surface);
4818
+ }
4819
+ .cg-ts-table {
4820
+ border-collapse: separate;
4821
+ border-spacing: 0;
4822
+ width: max-content;
4823
+ min-width: 100%;
4824
+ font-size: var(--lp-fs-xs);
4825
+ }
4826
+ .cg-ts-table th,
4827
+ .cg-ts-table td {
4828
+ padding: 7px 12px;
4829
+ border-bottom: 1px solid var(--lp-line);
4830
+ white-space: nowrap;
4831
+ text-align: right;
4832
+ font-variant-numeric: tabular-nums;
4833
+ }
4834
+ .cg-ts-table thead th {
4835
+ position: sticky;
4836
+ top: 0;
4837
+ z-index: 2;
4838
+ background: var(--lp-surface-2);
4839
+ font-size: var(--lp-fs-2xs);
4840
+ font-weight: 600;
4841
+ color: var(--lp-muted);
4842
+ }
4843
+ /* THE sticky first column — a 120-bucket row scrolls a long way, and a number whose metric
4844
+ has scrolled off the left is an unlabelled number. */
4845
+ .cg-ts-stick {
4846
+ position: sticky;
4847
+ left: 0;
4848
+ z-index: 1;
4849
+ text-align: left;
4850
+ background: var(--lp-surface);
4851
+ border-right: 1px solid var(--lp-line);
4852
+ font-weight: 500;
4853
+ color: var(--lp-ink);
4854
+ }
4855
+ .cg-ts-table thead .cg-ts-stick { z-index: 3; background: var(--lp-surface-2); }
4856
+ .cg-ts-rowbtn {
4857
+ border: 0;
4858
+ background: transparent;
4859
+ padding: 0;
4860
+ font: inherit;
4861
+ font-weight: 500;
4862
+ color: var(--lp-ink);
4863
+ cursor: pointer;
4864
+ text-align: left;
4865
+ }
4866
+ .cg-ts-rowbtn:hover { color: var(--lp-blue-deep); }
4867
+ .cg-ts-rowbtn:focus-visible { outline: 2px solid var(--lp-blue-deep); outline-offset: 2px; }
4868
+ /* A bucket whose calendar end is past today. Drawn like every other column it would read as
4869
+ a collapse, so it is dimmed and the header says the word. */
4870
+ .cg-ts-table .is-partial { color: var(--lp-muted); }
4871
+ .cg-ts-partial { font-weight: 400; }
4872
+ .cg-ts-total { border-left: 1px solid var(--lp-line); font-weight: 600; }
4873
+ .cg-ts-delta td { font-size: var(--lp-fs-2xs); color: var(--lp-muted); }
4874
+ .cg-ts-delta .cg-ts-stick { font-size: var(--lp-fs-2xs); color: var(--lp-muted); font-weight: 400; }
4875
+ .cg-ts-delta .is-up { color: var(--lp-green-deep); }
4876
+ .cg-ts-delta .is-down { color: var(--lp-red-deep); }
4877
+ .cg-ts-chartrow td { padding: 10px 12px; background: var(--lp-wash); text-align: left; }
4878
+
4879
+ .cg-ts-note {
4880
+ padding: 10px 2px;
4881
+ font-size: var(--lp-fs-2xs);
4882
+ color: var(--lp-muted);
4883
+ }
4884
+ .cg-ts-error { color: var(--lp-red-deep); }
4885
+ /* The disclosure list: dropped fields, partial periods, all-unanswered metrics. It sits UNDER
4886
+ the table on purpose — these are footnotes to a number that is already on screen, and a
4887
+ banner above the data would make every ordinary read feel like an error state. */
4888
+ .cg-ts-notes {
4889
+ margin: 0;
4890
+ padding-left: 18px;
4891
+ font-size: var(--lp-fs-2xs);
4892
+ color: var(--lp-muted);
4893
+ }
4894
+ .cg-ts-notes li { margin-top: 3px; }
4895
+
4896
+ /* ------------------------------------------------------------------------- */
4897
+ /* Owner items 3 + 4 (2026-08-02, contract C-DISP): standardized kanban card */
4898
+ /* height, and calendar days that can show totals instead of records. */
4899
+ /* ------------------------------------------------------------------------- */
4900
+
4901
+ /* Item 3 — the clamp. The owner asked for cards "standardized in length", and the reason a
4902
+ ragged lane is worse than a short one is scanning: eyes track down a column by the rhythm of
4903
+ its edges, and one card three times the height of its neighbours breaks the rhythm for every
4904
+ card below it. So: title one line, each value two, and a uniform max-height so a card with
4905
+ three short values and a card with three long ones still line up.
4906
+
4907
+ `-webkit-line-clamp` (with `display:-webkit-box`) rather than a plain `max-height`, because
4908
+ a bare max-height cuts a line of text in HALF horizontally — the reader sees the top of the
4909
+ letters and cannot tell whether the word ended. Clamping ends on a whole line and adds the
4910
+ ellipsis that says "there is more". The full text stays one click away in the record. */
4911
+ .cg-kbview.is-clamped .cg-kb-title {
4912
+ display: -webkit-box;
4913
+ -webkit-line-clamp: 1;
4914
+ line-clamp: 1;
4915
+ -webkit-box-orient: vertical;
4916
+ overflow: hidden;
4917
+ }
4918
+ .cg-kbview.is-clamped .cg-kb-cell .cg-lv-v {
4919
+ display: -webkit-box;
4920
+ -webkit-line-clamp: 2;
4921
+ line-clamp: 2;
4922
+ -webkit-box-orient: vertical;
4923
+ overflow: hidden;
4924
+ white-space: normal;
4925
+ }
4926
+ /* ⚠ THERE IS DELIBERATELY NO `max-height` ON THE CARD, and the first draft of this block had
4927
+ one (132px). It was removed because it contradicted the paragraph above at shipped sizes:
4928
+ `.cg-kb-cell` is 13.8px at line-height 1.35 (~18.6px/line), so three card keys clamped to
4929
+ two lines each is ~112px, plus the title line, plus 14px of card padding and the borders —
4930
+ about 148px before anything else. A 132px ceiling would have sliced the third value
4931
+ mid-line, which is the exact failure `-webkit-line-clamp` was chosen to avoid.
4932
+
4933
+ None is needed. `cardKeys` is board-wide (one array for every card), so every card renders
4934
+ the SAME number of cells and the per-element clamps bound all of them identically: a card
4935
+ can never exceed 1 title line + 2 lines per key. That is the standardization the owner
4936
+ asked for, and it is enforced by the clamps rather than by a second, redundant cap that can
4937
+ disagree with them the moment a font token moves. */
4938
+
4939
+ /* Item 4 — a summary day. Key left, value right, one metric per line: the same key/value
4940
+ rhythm the list cards use, so a day cell reads like the rest of the app rather than like a
4941
+ spreadsheet dropped into a calendar. */
4942
+ .cg-cal-metric {
4943
+ display: flex;
4944
+ align-items: baseline;
4945
+ justify-content: space-between;
4946
+ gap: 8px;
4947
+ padding: 1px 0;
4948
+ }
4949
+ .cg-cal-metric-k {
4950
+ font-size: var(--lp-fs-3xs);
4951
+ color: var(--lp-muted);
4952
+ overflow: hidden;
4953
+ text-overflow: ellipsis;
4954
+ white-space: nowrap;
4955
+ }
4956
+ .cg-cal-metric-v {
4957
+ font-size: var(--lp-fs-2xs);
4958
+ font-weight: 600;
4959
+ color: var(--lp-ink);
4960
+ font-variant-numeric: tabular-nums;
4961
+ white-space: nowrap;
4962
+ }
4963
+
4964
+ /* ------------------------------------------------------------------------- */
4965
+ /* Owner item 12 (2026-08-02, contract C-LOCK): a view LOCKED to a cohort. */
4966
+ /* GRID's half of the chrome — the rail mark and the lock picker. RECORD owns */
4967
+ /* the Filter-popover banner (.cg-flt-lockchip, in their filters.css). */
4968
+ /* ------------------------------------------------------------------------- */
4969
+
4970
+ /* The rail mark. Yellow, matching `.cg-lock-tag` and RECORD's banner, because all three make
4971
+ the same claim about the same kind of thing and a third colour would read as a third
4972
+ concept. A 2px inset bar rather than a badge: the row is already carrying a mode icon, a
4973
+ name, a note and a "…" — one more chip would crowd it, while an edge mark is legible at a
4974
+ glance and costs no width. Per the brand rule the mark takes the -deep weight; the base
4975
+ pastel measures too low to read as a line this thin. */
4976
+ .cg-view-row.cg-view-lockset {
4977
+ box-shadow: inset 2px 0 0 var(--lp-yellow-deep);
4978
+ }
4979
+ /* The picker. `is-on` marks the cohort currently locked, so re-opening the menu says which one
4980
+ it is instead of making the reader remember. */
4981
+ .cg-lock-pop { min-width: 240px; }
4982
+ .cg-lock-pop .cg-pick-row.is-on {
4983
+ background: var(--lp-yellow-tint);
4984
+ color: var(--lp-yellow-deep);
4985
+ font-weight: 600;
4986
+ }
4987
+ /* Unlock is separated by a hairline: it is the one row here that WIDENS what the view shows,
4988
+ and it should not sit in the list of narrowing choices as if it were another cohort. */
4989
+ .cg-lock-pop .cg-lock-clear {
4990
+ margin-top: 4px;
4991
+ border-top: 1px solid var(--lp-line);
4992
+ color: var(--lp-muted);
4993
+ }
4994
+ /* Item 4 — one row of the Totals picker: the field checkbox, and (once picked) how to total
4995
+ it. The select only appears for a chosen field, so the panel does not present four dead
4996
+ dropdowns for fields nobody selected. */
4997
+ .cg-cal-pick {
4998
+ display: flex;
4999
+ align-items: center;
5000
+ gap: 8px;
5001
+ padding: 2px 8px;
5002
+ }
5003
+ .cg-cal-pick .cg-check-row { flex: 1 1 auto; min-width: 0; }
5004
+ .cg-cal-pick .cg-select { flex: 0 0 auto; }
web/src/shell/NavExtras.tsx ADDED
@@ -0,0 +1,445 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // ---------------------------------------------------------------------------
2
+ // shell/NavExtras.tsx — C-SCHEMA (wave 2026-08-02): the database list's
3
+ // three-dots menu, folder heads, and the schema drawer.
4
+ //
5
+ // Kept out of Shell.tsx so the shell's frame stays readable: Shell owns the
6
+ // STATE (prefs, open folders, which schema is open) and the save round-trip;
7
+ // these components own only their own popover/drawer chrome. Menus are
8
+ // position:fixed against the trigger — the rail scrolls and clips, so an
9
+ // absolutely-positioned child could never escape it (the same lesson as the
10
+ // collapsed-rail tooltip).
11
+ // ---------------------------------------------------------------------------
12
+
13
+ import { useEffect, useRef, useState } from "react";
14
+ import type { ReactNode } from "react";
15
+ import { fetchSchema } from "./nav";
16
+ import type { NavFolder, SchemaPayload } from "./nav";
17
+ import "./navExtras.css";
18
+
19
+ function DotsIcon() {
20
+ return (
21
+ <svg viewBox="0 0 16 16" aria-hidden="true" className="shell-dots-icon">
22
+ <circle cx="8" cy="3.2" r="1.35" />
23
+ <circle cx="8" cy="8" r="1.35" />
24
+ <circle cx="8" cy="12.8" r="1.35" />
25
+ </svg>
26
+ );
27
+ }
28
+
29
+ function ChevronIcon({ open }: { open: boolean }) {
30
+ return (
31
+ <svg
32
+ viewBox="0 0 16 16"
33
+ aria-hidden="true"
34
+ className={"shell-folder-chev" + (open ? " is-open" : "")}
35
+ >
36
+ <path d="M5.5 3.5 10.5 8l-5 4.5" fill="none" strokeWidth="1.6" />
37
+ </svg>
38
+ );
39
+ }
40
+
41
+ function FolderIcon() {
42
+ return (
43
+ <svg viewBox="0 0 16 16" aria-hidden="true" className="shell-nav-icon">
44
+ <path d="M2.2 4.4c0-.66.54-1.2 1.2-1.2h3l1.4 1.6h4.8c.66 0 1.2.54 1.2 1.2v6c0 .66-.54 1.2-1.2 1.2H3.4c-.66 0-1.2-.54-1.2-1.2z" />
45
+ </svg>
46
+ );
47
+ }
48
+
49
+ /** A fixed-position popover anchored to a trigger rect, closed on outside
50
+ * click or Escape. Small on purpose — the shell does not import the grid's
51
+ * Popover, so the two chrome trees stay independently deletable. */
52
+ function useMenu() {
53
+ const [at, setAt] = useState<{ x: number; y: number } | null>(null);
54
+ const ref = useRef<HTMLDivElement>(null);
55
+ useEffect(() => {
56
+ if (!at) return;
57
+ const onDown = (e: MouseEvent) => {
58
+ if (ref.current && !ref.current.contains(e.target as Node)) setAt(null);
59
+ };
60
+ const onKey = (e: KeyboardEvent) => {
61
+ if (e.key === "Escape") setAt(null);
62
+ };
63
+ document.addEventListener("mousedown", onDown, true);
64
+ document.addEventListener("keydown", onKey, true);
65
+ return () => {
66
+ document.removeEventListener("mousedown", onDown, true);
67
+ document.removeEventListener("keydown", onKey, true);
68
+ };
69
+ }, [at]);
70
+ const openFrom = (el: HTMLElement) => {
71
+ const r = el.getBoundingClientRect();
72
+ setAt({ x: Math.round(r.right + 4), y: Math.round(r.top) });
73
+ };
74
+ return { at, ref, openFrom, close: () => setAt(null) };
75
+ }
76
+
77
+ function MenuShell({
78
+ at,
79
+ menuRef,
80
+ children,
81
+ }: {
82
+ at: { x: number; y: number };
83
+ menuRef: React.RefObject<HTMLDivElement>;
84
+ children: ReactNode;
85
+ }) {
86
+ // Clamp to the viewport so a row near the bottom does not spill the menu off it.
87
+ const style = {
88
+ left: Math.min(at.x, Math.max(8, window.innerWidth - 248)),
89
+ top: Math.min(at.y, Math.max(8, window.innerHeight - 260)),
90
+ };
91
+ return (
92
+ <div className="shell-navmenu" style={style} ref={menuRef} role="menu">
93
+ {children}
94
+ </div>
95
+ );
96
+ }
97
+
98
+ export function RowMenu({
99
+ entryLabel,
100
+ folders,
101
+ placedIn,
102
+ canSchema,
103
+ onMove,
104
+ onCreateFolder,
105
+ onSchema,
106
+ }: {
107
+ entryLabel: string;
108
+ folders: NavFolder[];
109
+ placedIn?: string;
110
+ canSchema: boolean;
111
+ onMove: (folderId: string | null) => void;
112
+ onCreateFolder: (name: string) => void;
113
+ onSchema: () => void;
114
+ }) {
115
+ const { at, ref, openFrom, close } = useMenu();
116
+ const [naming, setNaming] = useState(false);
117
+ const [name, setName] = useState("");
118
+ const submitNew = () => {
119
+ const clean = name.trim().replace(/\s+/g, " ");
120
+ if (!clean) return;
121
+ onCreateFolder(clean);
122
+ setName("");
123
+ setNaming(false);
124
+ close();
125
+ };
126
+ return (
127
+ <>
128
+ <button
129
+ type="button"
130
+ className="shell-dots"
131
+ aria-label={`Options for ${entryLabel}`}
132
+ aria-haspopup="menu"
133
+ onClick={(e) => {
134
+ e.preventDefault();
135
+ e.stopPropagation();
136
+ setNaming(false);
137
+ openFrom(e.currentTarget);
138
+ }}
139
+ >
140
+ <DotsIcon />
141
+ </button>
142
+ {at && (
143
+ <MenuShell at={at} menuRef={ref}>
144
+ {canSchema && (
145
+ <button
146
+ type="button"
147
+ className="shell-navmenu-item"
148
+ onClick={() => {
149
+ close();
150
+ onSchema();
151
+ }}
152
+ >
153
+ View schema
154
+ </button>
155
+ )}
156
+ <div className="shell-navmenu-kicker">Move to folder</div>
157
+ {folders.map((f) => (
158
+ <button
159
+ key={f.id}
160
+ type="button"
161
+ className={
162
+ "shell-navmenu-item" + (placedIn === f.id ? " is-current" : "")
163
+ }
164
+ onClick={() => {
165
+ close();
166
+ if (placedIn !== f.id) onMove(f.id);
167
+ }}
168
+ >
169
+ {f.name}
170
+ {placedIn === f.id ? <span className="shell-navmenu-tick">Current</span> : null}
171
+ </button>
172
+ ))}
173
+ {placedIn && (
174
+ <button
175
+ type="button"
176
+ className="shell-navmenu-item"
177
+ onClick={() => {
178
+ close();
179
+ onMove(null);
180
+ }}
181
+ >
182
+ Remove from folder
183
+ </button>
184
+ )}
185
+ {naming ? (
186
+ <form
187
+ className="shell-navmenu-form"
188
+ onSubmit={(e) => {
189
+ e.preventDefault();
190
+ submitNew();
191
+ }}
192
+ >
193
+ <input
194
+ className="shell-navmenu-input"
195
+ autoFocus
196
+ maxLength={40}
197
+ placeholder="Folder name"
198
+ value={name}
199
+ onChange={(e) => setName(e.target.value)}
200
+ />
201
+ <button type="submit" className="shell-navmenu-go" disabled={!name.trim()}>
202
+ Add
203
+ </button>
204
+ </form>
205
+ ) : (
206
+ <button
207
+ type="button"
208
+ className="shell-navmenu-item is-new"
209
+ onClick={() => setNaming(true)}
210
+ >
211
+ New folder…
212
+ </button>
213
+ )}
214
+ </MenuShell>
215
+ )}
216
+ </>
217
+ );
218
+ }
219
+
220
+ export function FolderHead({
221
+ folder,
222
+ count,
223
+ open,
224
+ collapsed,
225
+ onToggle,
226
+ onRename,
227
+ onDelete,
228
+ }: {
229
+ folder: NavFolder;
230
+ count: number;
231
+ open: boolean;
232
+ collapsed: boolean;
233
+ onToggle: () => void;
234
+ onRename: (name: string) => void;
235
+ onDelete: () => void;
236
+ }) {
237
+ const { at, ref, openFrom, close } = useMenu();
238
+ const [renaming, setRenaming] = useState(false);
239
+ const [name, setName] = useState(folder.name);
240
+ const submit = () => {
241
+ const clean = name.trim().replace(/\s+/g, " ");
242
+ if (clean && clean !== folder.name) onRename(clean);
243
+ setRenaming(false);
244
+ close();
245
+ };
246
+ if (collapsed) {
247
+ // The folded rail has no room for folder chrome; members render flat and the
248
+ // folder simply waits for the rail to open again.
249
+ return null;
250
+ }
251
+ return (
252
+ <div className="shell-nav-folder">
253
+ <button
254
+ type="button"
255
+ className="shell-nav-folderbtn"
256
+ aria-expanded={open}
257
+ onClick={onToggle}
258
+ >
259
+ <ChevronIcon open={open} />
260
+ <FolderIcon />
261
+ <span className="shell-nav-label">{folder.name}</span>
262
+ <span className="shell-nav-foldercount">{count}</span>
263
+ </button>
264
+ <button
265
+ type="button"
266
+ className="shell-dots"
267
+ aria-label={`Options for folder ${folder.name}`}
268
+ aria-haspopup="menu"
269
+ onClick={(e) => {
270
+ e.stopPropagation();
271
+ setName(folder.name);
272
+ setRenaming(false);
273
+ openFrom(e.currentTarget);
274
+ }}
275
+ >
276
+ <DotsIcon />
277
+ </button>
278
+ {at && (
279
+ <MenuShell at={at} menuRef={ref}>
280
+ {renaming ? (
281
+ <form
282
+ className="shell-navmenu-form"
283
+ onSubmit={(e) => {
284
+ e.preventDefault();
285
+ submit();
286
+ }}
287
+ >
288
+ <input
289
+ className="shell-navmenu-input"
290
+ autoFocus
291
+ maxLength={40}
292
+ value={name}
293
+ onChange={(e) => setName(e.target.value)}
294
+ />
295
+ <button type="submit" className="shell-navmenu-go" disabled={!name.trim()}>
296
+ Save
297
+ </button>
298
+ </form>
299
+ ) : (
300
+ <button
301
+ type="button"
302
+ className="shell-navmenu-item"
303
+ onClick={() => setRenaming(true)}
304
+ >
305
+ Rename folder
306
+ </button>
307
+ )}
308
+ <button
309
+ type="button"
310
+ className="shell-navmenu-item is-danger"
311
+ onClick={() => {
312
+ close();
313
+ onDelete();
314
+ }}
315
+ >
316
+ Delete folder
317
+ </button>
318
+ <div className="shell-navmenu-note">Databases inside fall back to the list.</div>
319
+ </MenuShell>
320
+ )}
321
+ </div>
322
+ );
323
+ }
324
+
325
+ export function SchemaDrawer({
326
+ schemaKey,
327
+ onClose,
328
+ }: {
329
+ schemaKey: string;
330
+ onClose: () => void;
331
+ }) {
332
+ const [state, setState] = useState<
333
+ { phase: "loading" } | { phase: "ready"; schema: SchemaPayload } | { phase: "error" }
334
+ >({ phase: "loading" });
335
+ useEffect(() => {
336
+ let cancelled = false;
337
+ setState({ phase: "loading" });
338
+ fetchSchema(schemaKey).then((schema) => {
339
+ if (cancelled) return;
340
+ setState(schema ? { phase: "ready", schema } : { phase: "error" });
341
+ });
342
+ return () => {
343
+ cancelled = true;
344
+ };
345
+ }, [schemaKey]);
346
+ useEffect(() => {
347
+ const onKey = (e: KeyboardEvent) => {
348
+ if (e.key === "Escape") onClose();
349
+ };
350
+ document.addEventListener("keydown", onKey, true);
351
+ return () => document.removeEventListener("keydown", onKey, true);
352
+ }, [onClose]);
353
+ return (
354
+ <div className="shell-schema-backdrop" onMouseDown={onClose}>
355
+ <aside
356
+ className="shell-schema"
357
+ role="dialog"
358
+ aria-label="Database schema"
359
+ onMouseDown={(e) => e.stopPropagation()}
360
+ >
361
+ {state.phase === "loading" && <div className="shell-schema-empty">Loading schema…</div>}
362
+ {state.phase === "error" && (
363
+ <div className="shell-schema-empty">
364
+ The schema could not be loaded. Close this panel and try again.
365
+ </div>
366
+ )}
367
+ {state.phase === "ready" && (
368
+ <>
369
+ <header className="shell-schema-head">
370
+ <div>
371
+ <div className="shell-schema-title">{state.schema.label}</div>
372
+ {state.schema.source && (
373
+ <div className="shell-schema-sub">Source · {state.schema.source}</div>
374
+ )}
375
+ </div>
376
+ <button
377
+ type="button"
378
+ className="shell-schema-close"
379
+ aria-label="Close schema"
380
+ onClick={onClose}
381
+ >
382
+ ×
383
+ </button>
384
+ </header>
385
+ <div className="shell-schema-body">
386
+ {state.schema.note && (
387
+ <div className="shell-schema-note">{state.schema.note}</div>
388
+ )}
389
+ {state.schema.fields.length > 0 && (
390
+ <>
391
+ <div className="shell-schema-kicker">
392
+ Fields · {state.schema.fields.length}
393
+ </div>
394
+ <table className="shell-schema-table">
395
+ <thead>
396
+ <tr>
397
+ <th>Field</th>
398
+ <th>Type</th>
399
+ <th>Source</th>
400
+ </tr>
401
+ </thead>
402
+ <tbody>
403
+ {state.schema.fields.map((f) => (
404
+ <tr key={f.key}>
405
+ <td>
406
+ <div className="shell-schema-fname">{f.label}</div>
407
+ {f.description && (
408
+ <div className="shell-schema-fdesc">{f.description}</div>
409
+ )}
410
+ {f.options && (
411
+ <div className="shell-schema-fdesc">
412
+ Choices: {f.options.join(" · ")}
413
+ </div>
414
+ )}
415
+ </td>
416
+ <td className="shell-schema-type">{f.type}</td>
417
+ <td className="shell-schema-type">{f.source}</td>
418
+ </tr>
419
+ ))}
420
+ </tbody>
421
+ </table>
422
+ </>
423
+ )}
424
+ {state.schema.measures.length > 0 && (
425
+ <>
426
+ <div className="shell-schema-kicker">
427
+ Semantic measures · {state.schema.measures.length}
428
+ </div>
429
+ <div className="shell-schema-measures">
430
+ {state.schema.measures.map((m) => (
431
+ <div key={m.key} className="shell-schema-measure">
432
+ <span className="shell-schema-fname">{m.label}</span>
433
+ <span className="shell-schema-type">{m.type}</span>
434
+ </div>
435
+ ))}
436
+ </div>
437
+ </>
438
+ )}
439
+ </div>
440
+ </>
441
+ )}
442
+ </aside>
443
+ </div>
444
+ );
445
+ }
web/src/shell/Shell.tsx CHANGED
@@ -41,8 +41,9 @@ import { SettingsModal } from "../settings/SettingsModal";
41
  import type { SettingsSection } from "../settings/SettingsModal";
42
  import { Brand } from "./Brand";
43
  import LoginPage from "./LoginPage";
44
- import { ENVELOPE_KEYS, appLink, defaultRoute, fetchNav, resolveRoute, shapeNav, splitChrome } from "./nav";
45
- import type { NavEntry, NavPage } from "./nav";
 
46
  import { isAdmin, logout, me } from "./session";
47
  import type { SessionUser } from "./session";
48
 
@@ -407,6 +408,96 @@ export default function Shell() {
407
  // re-run the hash effect below on every render for no reason.
408
  const entries = nav.phase === "ready" ? nav.entries : NO_ENTRIES;
409
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
410
  // Keep the URL honest in both directions: an anonymous shell sits on
411
  // `#/login`, and a signed-in one never does.
412
  useEffect(() => {
@@ -507,56 +598,98 @@ export default function Shell() {
507
  ) : null}
508
 
509
  <div className="shell-nav-list">
510
- {entries.map((item) => {
511
- const cls =
512
- "shell-nav-item" +
513
- (item.depth > 0 ? " is-child" : "") +
514
- (active && active.key === item.key ? " is-active" : "");
515
- const inner = (
516
- <>
517
- <DbIcon />
518
- <span className="shell-nav-label">{item.label}</span>
519
- {/* A hand-off opens the current application in a new tab; the
520
- arrow declares that before the click finds out. */}
521
- {item.kind === "handoff" ? <ExtIcon /> : null}
522
- {/* The provenance badge, right-aligned and quiet — wave-9 I8's
523
- "light grey subtle label 'Odoo'", same as the host nav. */}
524
- {item.source ? <span className="shell-nav-badge">{item.source}</span> : null}
525
- </>
526
- );
527
- if (item.kind === "group") {
528
- // A folder head is not a destination — the app has no page for
529
- // it either. A label, never a link.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
530
  return (
531
- <div key={item.key} className="shell-nav-group">
532
- {inner}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
533
  </div>
534
  );
535
  }
536
- // Owner item 3 — collapsed, the icon names its database on hover.
537
- const tip = navCollapsed
538
- ? {
539
- onMouseEnter: tipEnter(item.label),
540
- onMouseLeave: tipLeave,
541
- }
542
- : {};
543
- return item.kind === "native" ? (
544
- <a key={item.key} className={cls} href={item.href} {...tip}>
545
- {inner}
546
- </a>
547
- ) : (
548
- <a
549
- key={item.key}
550
- className={cls}
551
- href={item.href}
552
- target="_blank"
553
- rel="noreferrer"
554
- {...tip}
555
- >
556
- {inner}
557
- </a>
558
- );
559
- })}
560
  </div>
561
  {nav.phase === "loading" ? <div className="shell-nav-note">Loading…</div> : null}
562
  {/* Honest, and it names the fix. Inventing a nav here would show
@@ -664,6 +797,11 @@ export default function Shell() {
664
  />
665
  ) : null}
666
 
 
 
 
 
 
667
  {toast ? (
668
  <div className="shell-toast" role="status" aria-live="polite">
669
  {toast}
 
41
  import type { SettingsSection } from "../settings/SettingsModal";
42
  import { Brand } from "./Brand";
43
  import LoginPage from "./LoginPage";
44
+ import { EMPTY_NAV_PREFS, ENVELOPE_KEYS, MAX_NAV_FOLDERS, appLink, defaultRoute, fetchNav, fetchNavPrefs, foldNav, resolveRoute, saveNavPrefs, shapeNav, splitChrome } from "./nav";
45
+ import type { NavEntry, NavPage, NavPrefs } from "./nav";
46
+ import { FolderHead, RowMenu, SchemaDrawer } from "./NavExtras";
47
  import { isAdmin, logout, me } from "./session";
48
  import type { SessionUser } from "./session";
49
 
 
408
  // re-run the hash effect below on every render for no reason.
409
  const entries = nav.phase === "ready" ? nav.entries : NO_ENTRIES;
410
 
411
+ // ── C-SCHEMA (2026-08-02): per-user folders over the database list + the
412
+ // schema drawer. Placement is cosmetic per-user state — the server-filtered
413
+ // nav still decides what exists; prefs only arrange it.
414
+ const [navPrefs, setNavPrefs] = useState<NavPrefs>(EMPTY_NAV_PREFS);
415
+ const navPrefsRef = useRef(navPrefs);
416
+ navPrefsRef.current = navPrefs;
417
+ const [closedFolders, setClosedFolders] = useState<ReadonlySet<string>>(new Set());
418
+ const [schemaFor, setSchemaFor] = useState<string | null>(null);
419
+ useEffect(() => {
420
+ if (who === null) {
421
+ setNavPrefs(EMPTY_NAV_PREFS);
422
+ setSchemaFor(null);
423
+ return;
424
+ }
425
+ let dead = false;
426
+ void fetchNavPrefs().then((p) => {
427
+ if (!dead) setNavPrefs(p);
428
+ });
429
+ return () => {
430
+ dead = true;
431
+ };
432
+ }, [who]);
433
+ // Optimistic with an honest revert: the rail moves now; a refused write puts
434
+ // it back and says so rather than leaving a lie on screen.
435
+ const commitPrefs = useCallback((next: NavPrefs) => {
436
+ const prev = navPrefsRef.current;
437
+ setNavPrefs(next);
438
+ void saveNavPrefs(next).then((ok) => {
439
+ if (!ok) {
440
+ setNavPrefs(prev);
441
+ setToast("The folder change was not saved — the store refused the write.");
442
+ }
443
+ });
444
+ }, []);
445
+ const movePage = useCallback(
446
+ (key: string, folderId: string | null) => {
447
+ const cur = navPrefsRef.current;
448
+ const placement = { ...cur.placement };
449
+ if (folderId) placement[key] = folderId;
450
+ else delete placement[key];
451
+ commitPrefs({ folders: cur.folders, placement });
452
+ },
453
+ [commitPrefs]
454
+ );
455
+ const createFolderFor = useCallback(
456
+ (key: string, name: string) => {
457
+ const cur = navPrefsRef.current;
458
+ if (cur.folders.length >= MAX_NAV_FOLDERS) {
459
+ setToast(`At most ${MAX_NAV_FOLDERS} folders.`);
460
+ return;
461
+ }
462
+ const id = `nf_${Date.now().toString(36)}${Math.floor(Math.random() * 1e6).toString(36)}`;
463
+ commitPrefs({
464
+ folders: [...cur.folders, { id, name }],
465
+ placement: { ...cur.placement, [key]: id },
466
+ });
467
+ },
468
+ [commitPrefs]
469
+ );
470
+ const renameFolder = useCallback(
471
+ (id: string, name: string) => {
472
+ const cur = navPrefsRef.current;
473
+ commitPrefs({
474
+ folders: cur.folders.map((f) => (f.id === id ? { ...f, name } : f)),
475
+ placement: cur.placement,
476
+ });
477
+ },
478
+ [commitPrefs]
479
+ );
480
+ const deleteFolder = useCallback(
481
+ (id: string) => {
482
+ const cur = navPrefsRef.current;
483
+ commitPrefs({
484
+ folders: cur.folders.filter((f) => f.id !== id),
485
+ placement: Object.fromEntries(
486
+ Object.entries(cur.placement).filter(([, v]) => v !== id)
487
+ ),
488
+ });
489
+ },
490
+ [commitPrefs]
491
+ );
492
+ const toggleFolder = useCallback((id: string) => {
493
+ setClosedFolders((prev) => {
494
+ const next = new Set(prev);
495
+ if (next.has(id)) next.delete(id);
496
+ else next.add(id);
497
+ return next;
498
+ });
499
+ }, []);
500
+
501
  // Keep the URL honest in both directions: an anonymous shell sits on
502
  // `#/login`, and a signed-in one never does.
503
  useEffect(() => {
 
598
  ) : null}
599
 
600
  <div className="shell-nav-list">
601
+ {/* C-SCHEMA: the list folds under the user's folders. The collapsed
602
+ rail renders FLAT (folder chrome has no room at 44px) — members
603
+ stay reachable, the folders wait for the rail to open. */}
604
+ {foldNav(entries, navCollapsed ? EMPTY_NAV_PREFS : navPrefs, closedFolders).map(
605
+ (row) => {
606
+ if (row.kind === "folder") {
607
+ return (
608
+ <FolderHead
609
+ key={`folder:${row.folder.id}`}
610
+ folder={row.folder}
611
+ count={row.count}
612
+ open={row.open}
613
+ collapsed={navCollapsed}
614
+ onToggle={() => toggleFolder(row.folder.id)}
615
+ onRename={(name) => renameFolder(row.folder.id, name)}
616
+ onDelete={() => deleteFolder(row.folder.id)}
617
+ />
618
+ );
619
+ }
620
+ const item = row.entry;
621
+ const cls =
622
+ "shell-nav-item" +
623
+ (item.depth > 0 ? " is-child" : "") +
624
+ (active && active.key === item.key ? " is-active" : "");
625
+ const inner = (
626
+ <>
627
+ <DbIcon />
628
+ <span className="shell-nav-label">{item.label}</span>
629
+ {/* A hand-off opens the current application in a new tab; the
630
+ arrow declares that before the click finds out. */}
631
+ {item.kind === "handoff" ? <ExtIcon /> : null}
632
+ {/* The provenance badge, right-aligned and quiet — wave-9 I8's
633
+ "light grey subtle label 'Odoo'", same as the host nav. */}
634
+ {item.source ? <span className="shell-nav-badge">{item.source}</span> : null}
635
+ </>
636
+ );
637
+ if (item.kind === "group") {
638
+ // A registry family head is not a destination — the app has no
639
+ // page for it either. A label, never a link.
640
+ return (
641
+ <div key={item.key} className="shell-nav-group">
642
+ {inner}
643
+ </div>
644
+ );
645
+ }
646
+ // Owner item 3 — collapsed, the icon names its database on hover.
647
+ const tip = navCollapsed
648
+ ? {
649
+ onMouseEnter: tipEnter(item.label),
650
+ onMouseLeave: tipLeave,
651
+ }
652
+ : {};
653
+ const link =
654
+ item.kind === "native" ? (
655
+ <a className={cls} href={item.href} {...tip}>
656
+ {inner}
657
+ </a>
658
+ ) : (
659
+ <a
660
+ className={cls}
661
+ href={item.href}
662
+ target="_blank"
663
+ rel="noreferrer"
664
+ {...tip}
665
+ >
666
+ {inner}
667
+ </a>
668
+ );
669
+ // The three-dots rides TOP-LEVEL rows in the open rail only —
670
+ // children move with their family, and the folded rail has no
671
+ // horizontal room for a second control.
672
  return (
673
+ <div
674
+ key={item.key}
675
+ className={"shell-nav-row" + (row.folderId ? " is-foldered" : "")}
676
+ >
677
+ {link}
678
+ {!navCollapsed && item.depth === 0 && (
679
+ <RowMenu
680
+ entryLabel={item.label}
681
+ folders={navPrefs.folders}
682
+ placedIn={navPrefs.placement[item.key]}
683
+ canSchema
684
+ onMove={(fid) => movePage(item.key, fid)}
685
+ onCreateFolder={(name) => createFolderFor(item.key, name)}
686
+ onSchema={() => setSchemaFor(item.key)}
687
+ />
688
+ )}
689
  </div>
690
  );
691
  }
692
+ )}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
693
  </div>
694
  {nav.phase === "loading" ? <div className="shell-nav-note">Loading…</div> : null}
695
  {/* Honest, and it names the fix. Inventing a nav here would show
 
797
  />
798
  ) : null}
799
 
800
+ {/* C-SCHEMA: the database schema drawer, over everything but the toast. */}
801
+ {schemaFor ? (
802
+ <SchemaDrawer schemaKey={schemaFor} onClose={() => setSchemaFor(null)} />
803
+ ) : null}
804
+
805
  {toast ? (
806
  <div className="shell-toast" role="status" aria-live="polite">
807
  {toast}
web/src/shell/nav.ts CHANGED
@@ -107,6 +107,202 @@ export async function fetchNav(): Promise<NavResult> {
107
  }
108
  }
109
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
110
  /**
111
  * What the shell does with an entry:
112
  * native — this tree renders it (a hash route)
 
107
  }
108
  }
109
 
110
+ // ── C-SCHEMA (wave 2026-08-02): per-user folders over the database list ─────────────────────
111
+
112
+ export interface NavFolder {
113
+ id: string;
114
+ name: string;
115
+ }
116
+
117
+ /** Per-user, cosmetic, server-validated — placement never grants or hides a surface. */
118
+ export interface NavPrefs {
119
+ folders: NavFolder[];
120
+ placement: Record<string, string>;
121
+ }
122
+
123
+ export const EMPTY_NAV_PREFS: NavPrefs = { folders: [], placement: {} };
124
+ export const MAX_NAV_FOLDERS = 16;
125
+
126
+ /** Mirror of the server's `_clean_nav_prefs` pruning (minus the page-key check — the client
127
+ * prunes against folders only; a stale page key is harmless and drops on the next save). */
128
+ export function parseNavPrefs(body: unknown): NavPrefs {
129
+ const raw = (body as { prefs?: unknown } | null)?.prefs ?? body;
130
+ if (!raw || typeof raw !== "object") return EMPTY_NAV_PREFS;
131
+ const p = raw as { folders?: unknown; placement?: unknown };
132
+ const folders: NavFolder[] = [];
133
+ const seen = new Set<string>();
134
+ if (Array.isArray(p.folders)) {
135
+ for (const f of p.folders.slice(0, MAX_NAV_FOLDERS)) {
136
+ if (!f || typeof f !== "object") continue;
137
+ const id = String((f as NavFolder).id ?? "").trim().slice(0, 40);
138
+ const name = String((f as NavFolder).name ?? "").trim().replace(/\s+/g, " ").slice(0, 40);
139
+ if (!id || seen.has(id) || !name) continue;
140
+ seen.add(id);
141
+ folders.push({ id, name });
142
+ }
143
+ }
144
+ const placement: Record<string, string> = {};
145
+ if (p.placement && typeof p.placement === "object") {
146
+ for (const [k, v] of Object.entries(p.placement as Record<string, unknown>)) {
147
+ const fid = String(v ?? "").slice(0, 40);
148
+ if (k && seen.has(fid)) placement[k.slice(0, 60)] = fid;
149
+ }
150
+ }
151
+ return { folders, placement };
152
+ }
153
+
154
+ export async function fetchNavPrefs(): Promise<NavPrefs> {
155
+ try {
156
+ const res = await fetch(`${API_V1}/nav/prefs`, { credentials: CREDENTIALS });
157
+ if (!res.ok) return EMPTY_NAV_PREFS;
158
+ return parseNavPrefs(await res.json());
159
+ } catch {
160
+ return EMPTY_NAV_PREFS;
161
+ }
162
+ }
163
+
164
+ /** Wholesale replace, like the table folder stratum. Resolves false on any failure so the
165
+ * caller can revert its optimistic copy and say so. */
166
+ export async function saveNavPrefs(prefs: NavPrefs): Promise<boolean> {
167
+ try {
168
+ const res = await fetch(`${API_V1}/nav/prefs`, {
169
+ method: "POST",
170
+ credentials: CREDENTIALS,
171
+ headers: { "Content-Type": "application/json" },
172
+ body: JSON.stringify(prefs),
173
+ });
174
+ return res.ok;
175
+ } catch {
176
+ return false;
177
+ }
178
+ }
179
+
180
+ /** One rendered row of the folded nav: a folder head, or an entry (optionally inside one). */
181
+ export type NavRow =
182
+ | { kind: "folder"; folder: NavFolder; count: number; open: boolean }
183
+ | { kind: "entry"; entry: NavEntry; folderId?: string };
184
+
185
+ /**
186
+ * Fold the shaped entries under the user's folders. A BLOCK (a top-level entry plus its
187
+ * depth-1 children) moves as one unit — filing a family head files the family. Folders render
188
+ * in prefs order first, loose blocks after in registry order; a folder with no members still
189
+ * renders (it was just created — it must exist on screen to receive its first member).
190
+ * A closed folder contributes only its head row.
191
+ */
192
+ export function foldNav(
193
+ entries: NavEntry[],
194
+ prefs: NavPrefs,
195
+ closed: ReadonlySet<string>
196
+ ): NavRow[] {
197
+ interface Block {
198
+ head: NavEntry;
199
+ children: NavEntry[];
200
+ }
201
+ const blocks: Block[] = [];
202
+ for (const e of entries) {
203
+ if (e.depth > 0 && blocks.length > 0) blocks[blocks.length - 1].children.push(e);
204
+ else blocks.push({ head: e, children: [] });
205
+ }
206
+ const byFolder = new Map<string, Block[]>();
207
+ const loose: Block[] = [];
208
+ const ids = new Set(prefs.folders.map((f) => f.id));
209
+ for (const b of blocks) {
210
+ const fid = prefs.placement[b.head.key];
211
+ if (fid && ids.has(fid)) {
212
+ const list = byFolder.get(fid);
213
+ if (list) list.push(b);
214
+ else byFolder.set(fid, [b]);
215
+ } else {
216
+ loose.push(b);
217
+ }
218
+ }
219
+ const out: NavRow[] = [];
220
+ const emit = (b: Block, folderId?: string) => {
221
+ out.push({ kind: "entry", entry: b.head, ...(folderId ? { folderId } : {}) });
222
+ for (const c of b.children)
223
+ out.push({ kind: "entry", entry: c, ...(folderId ? { folderId } : {}) });
224
+ };
225
+ for (const f of prefs.folders) {
226
+ const members = byFolder.get(f.id) ?? [];
227
+ const open = !closed.has(f.id);
228
+ out.push({ kind: "folder", folder: f, count: members.length, open });
229
+ if (open) for (const b of members) emit(b, f.id);
230
+ }
231
+ for (const b of loose) emit(b);
232
+ return out;
233
+ }
234
+
235
+ // ── C-SCHEMA: the schema drawer payload ─────────────────────────────────────────────────────
236
+
237
+ export interface SchemaField {
238
+ key: string;
239
+ label: string;
240
+ type: string;
241
+ source: string;
242
+ description: string;
243
+ options?: string[];
244
+ }
245
+
246
+ export interface SchemaPayload {
247
+ key: string;
248
+ label: string;
249
+ source: string;
250
+ fields: SchemaField[];
251
+ measures: { key: string; label: string; type: string }[];
252
+ note?: string;
253
+ }
254
+
255
+ export function parseSchema(body: unknown): SchemaPayload | null {
256
+ if (!body || typeof body !== "object") return null;
257
+ const b = body as Record<string, unknown>;
258
+ if (typeof b.key !== "string" || typeof b.label !== "string") return null;
259
+ const fields: SchemaField[] = [];
260
+ if (Array.isArray(b.fields)) {
261
+ for (const f of b.fields) {
262
+ if (!f || typeof f !== "object") continue;
263
+ const r = f as Record<string, unknown>;
264
+ if (typeof r.key !== "string" || typeof r.label !== "string") continue;
265
+ fields.push({
266
+ key: r.key,
267
+ label: r.label,
268
+ type: String(r.type ?? ""),
269
+ source: String(r.source ?? ""),
270
+ description: String(r.description ?? ""),
271
+ ...(Array.isArray(r.options) ? { options: r.options.map(String) } : {}),
272
+ });
273
+ }
274
+ }
275
+ const measures: SchemaPayload["measures"] = [];
276
+ if (Array.isArray(b.measures)) {
277
+ for (const m of b.measures) {
278
+ if (!m || typeof m !== "object") continue;
279
+ const r = m as Record<string, unknown>;
280
+ if (typeof r.key !== "string" || !r.key) continue;
281
+ measures.push({ key: r.key, label: String(r.label ?? r.key), type: String(r.type ?? "") });
282
+ }
283
+ }
284
+ return {
285
+ key: b.key,
286
+ label: b.label,
287
+ source: String(b.source ?? ""),
288
+ fields,
289
+ measures,
290
+ ...(typeof b.note === "string" && b.note ? { note: b.note } : {}),
291
+ };
292
+ }
293
+
294
+ export async function fetchSchema(key: string): Promise<SchemaPayload | null> {
295
+ try {
296
+ const res = await fetch(`${API_V1}/nav/schema/${encodeURIComponent(key)}`, {
297
+ credentials: CREDENTIALS,
298
+ });
299
+ if (!res.ok) return null;
300
+ return parseSchema(await res.json());
301
+ } catch {
302
+ return null;
303
+ }
304
+ }
305
+
306
  /**
307
  * What the shell does with an entry:
308
  * native — this tree renders it (a hash route)
web/src/shell/navExtras.css ADDED
@@ -0,0 +1,352 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* shell/navExtras.css — C-SCHEMA (2026-08-02): nav folders, three-dots, schema drawer.
2
+ New classes only; the shell's own rail classes stay in index.css untouched. */
3
+
4
+ .shell-nav-row {
5
+ position: relative;
6
+ display: flex;
7
+ align-items: stretch;
8
+ min-width: 0;
9
+ }
10
+
11
+ .shell-nav-row > .shell-nav-item {
12
+ flex: 1 1 auto;
13
+ min-width: 0;
14
+ }
15
+
16
+ .shell-nav-row > .shell-dots,
17
+ .shell-nav-folder > .shell-dots {
18
+ flex: 0 0 auto;
19
+ width: 24px;
20
+ border: 0;
21
+ padding: 0;
22
+ margin: 2px 2px 2px 0;
23
+ border-radius: 6px;
24
+ background: transparent;
25
+ color: var(--lp-muted);
26
+ cursor: pointer;
27
+ opacity: 0;
28
+ display: grid;
29
+ place-items: center;
30
+ }
31
+
32
+ .shell-nav-row:hover > .shell-dots,
33
+ .shell-nav-row:focus-within > .shell-dots,
34
+ .shell-nav-folder:hover > .shell-dots,
35
+ .shell-nav-folder:focus-within > .shell-dots {
36
+ opacity: 1;
37
+ }
38
+
39
+ .shell-nav-row > .shell-dots:hover,
40
+ .shell-nav-folder > .shell-dots:hover {
41
+ background: var(--lp-wash);
42
+ color: var(--lp-ink);
43
+ }
44
+
45
+ .shell-dots-icon {
46
+ width: 14px;
47
+ height: 14px;
48
+ fill: currentColor;
49
+ }
50
+
51
+ .shell-nav-row.is-foldered > .shell-nav-item {
52
+ padding-left: 30px;
53
+ }
54
+
55
+ /* ── folder heads ─────────────────────────────────────────────────────────── */
56
+
57
+ .shell-nav-folder {
58
+ display: flex;
59
+ align-items: stretch;
60
+ min-width: 0;
61
+ }
62
+
63
+ .shell-nav-folderbtn {
64
+ flex: 1 1 auto;
65
+ min-width: 0;
66
+ display: flex;
67
+ align-items: center;
68
+ gap: 7px;
69
+ border: 0;
70
+ background: transparent;
71
+ padding: 6px 8px;
72
+ border-radius: 7px;
73
+ color: var(--lp-ink);
74
+ font: inherit;
75
+ font-size: var(--lp-fs-xs);
76
+ cursor: pointer;
77
+ text-align: left;
78
+ }
79
+
80
+ .shell-nav-folderbtn:hover {
81
+ background: var(--lp-wash);
82
+ }
83
+
84
+ .shell-folder-chev {
85
+ width: 11px;
86
+ height: 11px;
87
+ flex: 0 0 auto;
88
+ stroke: var(--lp-muted);
89
+ transition: transform 0.14s ease;
90
+ }
91
+
92
+ .shell-folder-chev.is-open {
93
+ transform: rotate(90deg);
94
+ }
95
+
96
+ .shell-nav-foldercount {
97
+ margin-left: auto;
98
+ font-size: var(--lp-fs-3xs);
99
+ color: var(--lp-muted);
100
+ }
101
+
102
+ /* ── the fixed popover menu ───────────────────────────────────────────────── */
103
+
104
+ .shell-navmenu {
105
+ position: fixed;
106
+ z-index: 80;
107
+ min-width: 196px;
108
+ max-width: 240px;
109
+ padding: 5px;
110
+ border: 1px solid var(--lp-line);
111
+ border-radius: 9px;
112
+ background: var(--lp-surface);
113
+ box-shadow: 0 10px 34px rgba(20, 30, 43, 0.16);
114
+ font-size: var(--lp-fs-xs);
115
+ }
116
+
117
+ .shell-navmenu-item {
118
+ display: flex;
119
+ align-items: center;
120
+ gap: 8px;
121
+ width: 100%;
122
+ border: 0;
123
+ background: transparent;
124
+ padding: 6px 8px;
125
+ border-radius: 6px;
126
+ font: inherit;
127
+ color: var(--lp-ink);
128
+ cursor: pointer;
129
+ text-align: left;
130
+ }
131
+
132
+ .shell-navmenu-item:hover {
133
+ background: var(--lp-wash);
134
+ }
135
+
136
+ .shell-navmenu-item.is-current {
137
+ color: var(--lp-muted);
138
+ cursor: default;
139
+ }
140
+
141
+ .shell-navmenu-item.is-danger {
142
+ color: var(--lp-red-deep);
143
+ }
144
+
145
+ .shell-navmenu-tick {
146
+ margin-left: auto;
147
+ font-size: var(--lp-fs-3xs);
148
+ color: var(--lp-muted);
149
+ }
150
+
151
+ .shell-navmenu-kicker {
152
+ padding: 7px 8px 3px;
153
+ font-size: var(--lp-fs-3xs);
154
+ font-weight: 600;
155
+ color: var(--lp-muted);
156
+ }
157
+
158
+ .shell-navmenu-note {
159
+ padding: 4px 8px 6px;
160
+ font-size: var(--lp-fs-3xs);
161
+ color: var(--lp-muted);
162
+ }
163
+
164
+ .shell-navmenu-form {
165
+ display: flex;
166
+ gap: 5px;
167
+ padding: 5px 6px 6px;
168
+ }
169
+
170
+ .shell-navmenu-input {
171
+ flex: 1 1 auto;
172
+ min-width: 0;
173
+ border: 1px solid var(--lp-line);
174
+ border-radius: 6px;
175
+ padding: 4px 7px;
176
+ font: inherit;
177
+ font-size: var(--lp-fs-xs);
178
+ background: var(--lp-surface);
179
+ color: var(--lp-ink);
180
+ }
181
+
182
+ .shell-navmenu-input:focus {
183
+ outline: none;
184
+ border-color: var(--lp-blue-deep);
185
+ }
186
+
187
+ .shell-navmenu-go {
188
+ flex: 0 0 auto;
189
+ border: 1px solid var(--lp-line);
190
+ border-radius: 6px;
191
+ background: var(--lp-surface);
192
+ padding: 4px 9px;
193
+ font: inherit;
194
+ font-size: var(--lp-fs-xs);
195
+ color: var(--lp-ink);
196
+ cursor: pointer;
197
+ }
198
+
199
+ .shell-navmenu-go:disabled {
200
+ color: var(--lp-muted);
201
+ cursor: default;
202
+ }
203
+
204
+ /* ── the schema drawer ────────────────────────────────────────────────────── */
205
+
206
+ .shell-schema-backdrop {
207
+ position: fixed;
208
+ inset: 0;
209
+ z-index: 90;
210
+ background: rgba(25, 34, 46, 0.28);
211
+ }
212
+
213
+ .shell-schema {
214
+ position: absolute;
215
+ top: 0;
216
+ right: 0;
217
+ bottom: 0;
218
+ width: min(430px, 92vw);
219
+ display: flex;
220
+ flex-direction: column;
221
+ background: var(--lp-surface);
222
+ border-left: 1px solid var(--lp-line);
223
+ box-shadow: -18px 0 48px rgba(20, 30, 43, 0.16);
224
+ animation: shell-schema-in 160ms cubic-bezier(0.2, 0, 0, 1);
225
+ }
226
+
227
+ @keyframes shell-schema-in {
228
+ from {
229
+ transform: translateX(14px);
230
+ opacity: 0;
231
+ }
232
+ }
233
+
234
+ .shell-schema-head {
235
+ display: flex;
236
+ align-items: flex-start;
237
+ justify-content: space-between;
238
+ gap: 10px;
239
+ padding: 16px 18px 12px;
240
+ border-bottom: 1px solid var(--lp-line);
241
+ }
242
+
243
+ .shell-schema-title {
244
+ font-size: var(--lp-fs-md);
245
+ font-weight: 600;
246
+ color: var(--lp-ink);
247
+ }
248
+
249
+ .shell-schema-sub {
250
+ margin-top: 2px;
251
+ font-size: var(--lp-fs-2xs);
252
+ color: var(--lp-muted);
253
+ }
254
+
255
+ .shell-schema-close {
256
+ border: 0;
257
+ background: transparent;
258
+ font-size: 19px;
259
+ line-height: 1;
260
+ color: var(--lp-muted);
261
+ cursor: pointer;
262
+ padding: 2px 6px;
263
+ border-radius: 6px;
264
+ }
265
+
266
+ .shell-schema-close:hover {
267
+ background: var(--lp-wash);
268
+ color: var(--lp-ink);
269
+ }
270
+
271
+ .shell-schema-body {
272
+ flex: 1 1 auto;
273
+ min-height: 0;
274
+ overflow-y: auto;
275
+ padding: 12px 18px 22px;
276
+ }
277
+
278
+ .shell-schema-empty {
279
+ padding: 26px 18px;
280
+ color: var(--lp-muted);
281
+ font-size: var(--lp-fs-xs);
282
+ }
283
+
284
+ .shell-schema-note {
285
+ padding: 9px 11px;
286
+ border: 1px solid var(--lp-line);
287
+ border-radius: 8px;
288
+ background: var(--lp-wash);
289
+ color: var(--lp-muted);
290
+ font-size: var(--lp-fs-xs);
291
+ margin-bottom: 12px;
292
+ }
293
+
294
+ .shell-schema-kicker {
295
+ margin: 14px 0 7px;
296
+ font-size: var(--lp-fs-2xs);
297
+ font-weight: 600;
298
+ color: var(--lp-muted);
299
+ }
300
+
301
+ .shell-schema-table {
302
+ width: 100%;
303
+ border-collapse: collapse;
304
+ font-size: var(--lp-fs-xs);
305
+ }
306
+
307
+ .shell-schema-table th {
308
+ text-align: left;
309
+ font-weight: 600;
310
+ font-size: var(--lp-fs-3xs);
311
+ color: var(--lp-muted);
312
+ padding: 4px 8px 4px 0;
313
+ border-bottom: 1px solid var(--lp-line);
314
+ }
315
+
316
+ .shell-schema-table td {
317
+ vertical-align: top;
318
+ padding: 7px 8px 7px 0;
319
+ border-bottom: 1px solid color-mix(in srgb, var(--lp-line) 55%, transparent);
320
+ }
321
+
322
+ .shell-schema-fname {
323
+ color: var(--lp-ink);
324
+ }
325
+
326
+ .shell-schema-fdesc {
327
+ margin-top: 2px;
328
+ font-size: var(--lp-fs-2xs);
329
+ color: var(--lp-muted);
330
+ line-height: 1.4;
331
+ }
332
+
333
+ .shell-schema-type {
334
+ white-space: nowrap;
335
+ color: var(--lp-muted);
336
+ font-size: var(--lp-fs-2xs);
337
+ }
338
+
339
+ .shell-schema-measures {
340
+ display: flex;
341
+ flex-direction: column;
342
+ }
343
+
344
+ .shell-schema-measure {
345
+ display: flex;
346
+ align-items: baseline;
347
+ justify-content: space-between;
348
+ gap: 10px;
349
+ padding: 5px 0;
350
+ border-bottom: 1px solid color-mix(in srgb, var(--lp-line) 55%, transparent);
351
+ font-size: var(--lp-fs-xs);
352
+ }
web/src/viz/chartData.ts CHANGED
@@ -109,7 +109,7 @@ export interface Bucket {
109
  n: number;
110
  }
111
 
112
- export interface ChartData {
113
  buckets: Bucket[];
114
  /** Buckets not drawn because of MAX_BUCKETS. Never silently dropped. */
115
  omitted: number;
@@ -119,45 +119,45 @@ export interface ChartData {
119
  blanks: number;
120
  /** Rows the aggregate could not use (non-numeric/empty y under sum/avg/...). */
121
  missingY: number;
122
- /** Total rows considered — always the grid's row count for this view. */
123
- rows: number;
124
- /** Aggregate buckets across the FULL domain, before the display cap. */
125
- negativeBuckets?: number;
126
- negativeValue?: number;
127
- zeroBuckets?: number;
128
- /** Populated when the spec cannot be drawn; the card shows this verbatim. */
129
- problem?: string;
130
- }
131
-
132
- /**
133
- * The renderer-neutral data model consumed by Chart View.
134
- *
135
- * This is intentionally not a Vega-Lite type. Saved views persist `ChartSpec`,
136
- * the arithmetic produces this small table, and the current renderer translates
137
- * it at the final boundary. Replacing Vega later therefore changes one adapter
138
- * rather than every saved view and every aggregation rule.
139
- */
140
- export interface ChartPoint extends Bucket {
141
- seriesKey: string;
142
- seriesLabel: string;
143
- }
144
-
145
- export interface ChartModel extends Omit<ChartData, "buckets"> {
146
- points: ChartPoint[];
147
- xOrder: string[];
148
- seriesOrder: string[];
149
- omittedSeries: number;
150
- omittedSeriesValue: number;
151
- /** Donut-only: zero/negative groups cannot be represented as angular share. */
152
- nonPositive: number;
153
- nonPositiveValue: number;
154
- }
155
-
156
- /** A legend with dozens of entries is a data dump, not a chart. */
157
- export const MAX_CHART_SERIES = 12;
158
-
159
- /** A date value bucketed to its month, the only date bucket wave 8 offers. */
160
- function monthOf(v: unknown): string | null {
161
  const s = String(v ?? "");
162
  return /^\d{4}-\d{2}/.test(s) ? s.slice(0, 7) : null;
163
  }
@@ -195,6 +195,33 @@ function reduce(agg: ChartAgg, vals: number[], n: number): number {
195
  }
196
  }
197
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
198
  /**
199
  * Build one chart's data from the view's rows.
200
  *
@@ -303,19 +330,19 @@ export function chartData(
303
 
304
  // Time reads chronologically; categories read biggest-first. Sorting a date
305
  // axis by value would turn a trend line into a sawtooth that means nothing.
306
- if (byMonth) {
307
  buckets.sort((a, b) => (a.key === "" ? 1 : b.key === "" ? -1 : a.key.localeCompare(b.key)));
308
  } else {
309
- buckets.sort((a, b) => b.value - a.value || a.label.localeCompare(b.label));
310
- }
311
-
312
- // Signed-domain facts are computed BEFORE the display cap. A negative group
313
- // that sorts below the top 12 must still block a donut; otherwise the cap
314
- // would turn invalid source data into a plausible positive composition.
315
- const negativeBuckets = buckets.filter((bucket) => bucket.value < 0);
316
- const zeroBuckets = buckets.filter((bucket) => bucket.value === 0).length;
317
- const negativeValue = negativeBuckets.reduce((sum, bucket) => sum + bucket.value, 0);
318
-
319
  let omitted = 0;
320
  let omittedValue = 0;
321
  if (buckets.length > MAX_BUCKETS) {
@@ -326,182 +353,182 @@ export function chartData(
326
  buckets = kept;
327
  }
328
 
329
- return {
330
- ...base,
331
- buckets,
332
- omitted,
333
- omittedValue,
334
- blanks,
335
- missingY,
336
- negativeBuckets: negativeBuckets.length,
337
- negativeValue,
338
- zeroBuckets,
339
- };
340
  }
341
 
342
- /**
343
- * Expand the flat aggregation into the renderer-neutral table used at the
344
- * chart boundary. `splitBy` becomes a real series dimension here; saved view
345
- * state remains independent of Vega-Lite (or whichever renderer replaces it).
346
- */
347
- export function chartModel(
348
- spec: ChartSpec,
349
- rows: Row[],
350
- fieldByKey: Map<string, Field>
351
- ): ChartModel {
352
- const base = chartData({ ...spec, splitBy: undefined }, rows, fieldByKey);
353
- const empty: ChartModel = {
354
- points: [],
355
- xOrder: [],
356
- seriesOrder: [],
357
- omitted: base.omitted,
358
- omittedValue: base.omittedValue,
359
- omittedSeries: 0,
360
- omittedSeriesValue: 0,
361
- nonPositive: 0,
362
- nonPositiveValue: 0,
363
- blanks: base.blanks,
364
- missingY: base.missingY,
365
- rows: base.rows,
366
- problem: base.problem,
367
- };
368
- if (base.problem) return empty;
369
-
370
- if (spec.kind === "donut") {
371
- // Arc length encodes a share of a positive whole. Vega (like most chart
372
- // engines) can accept signed theta values syntactically, but the resulting
373
- // geometry has no truthful business meaning. Zero groups preserve the old
374
- // positive-only omission (with disclosure); one negative group blocks the
375
- // entire composition and directs the user to a signed chart.
376
- const positive = base.buckets.filter((bucket) => bucket.value > 0);
377
- const negativeCount =
378
- base.negativeBuckets ?? base.buckets.filter((bucket) => bucket.value < 0).length;
379
- const zeroCount =
380
- base.zeroBuckets ?? base.buckets.filter((bucket) => bucket.value === 0).length;
381
- const nonPositive = negativeCount + zeroCount;
382
- const nonPositiveValue =
383
- base.negativeValue ??
384
- base.buckets
385
- .filter((bucket) => bucket.value < 0)
386
- .reduce((sum, bucket) => sum + bucket.value, 0);
387
- if (negativeCount > 0) {
388
- return {
389
- ...empty,
390
- nonPositive,
391
- nonPositiveValue,
392
- problem:
393
- "A donut cannot represent negative values without misrepresenting the whole. Use a bar or line chart for signed values.",
394
- };
395
- }
396
- if (base.buckets.length > 0 && positive.length === 0) {
397
- return {
398
- ...empty,
399
- nonPositive,
400
- nonPositiveValue,
401
- problem:
402
- "A donut needs at least one positive value. Zero-value groups cannot be drawn as slices.",
403
- };
404
- }
405
- return {
406
- ...empty,
407
- points: positive.map((bucket) => ({
408
- ...bucket,
409
- seriesKey: "",
410
- seriesLabel: "",
411
- })),
412
- xOrder: positive.map((bucket) => bucket.key),
413
- nonPositive,
414
- nonPositiveValue,
415
- };
416
- }
417
-
418
- if (!spec.splitBy || spec.kind === "kpi") {
419
- return {
420
- ...empty,
421
- points: base.buckets.map((bucket) => ({
422
- ...bucket,
423
- seriesKey: "",
424
- seriesLabel: "",
425
- })),
426
- xOrder: base.buckets.map((bucket) => bucket.key),
427
- };
428
- }
429
-
430
- const splitField = fieldByKey.get(spec.splitBy);
431
- const xField = spec.x ? fieldByKey.get(spec.x) : undefined;
432
- if (!splitField)
433
- return { ...empty, problem: "The field this chart split into series no longer exists." };
434
- if (!xField)
435
- return { ...empty, problem: "The field this chart grouped by no longer exists." };
436
-
437
- const xKey = (row: Row): string => {
438
- if (isDateFamilyType(xField.type)) return monthOf(row[xField.key]) ?? "";
439
- return String(row[xField.key] ?? "").trim();
440
- };
441
- const seriesKey = (row: Row): string => String(row[splitField.key] ?? "").trim();
442
- const xAllowed = new Set(base.buckets.map((bucket) => bucket.key));
443
- const bySeries = new Map<string, Row[]>();
444
- for (const row of rows) {
445
- if (!xAllowed.has(xKey(row))) continue;
446
- const key = seriesKey(row);
447
- const group = bySeries.get(key);
448
- if (group) group.push(row);
449
- else bySeries.set(key, [row]);
450
- }
451
-
452
- const computed = [...bySeries.entries()].map(([key, seriesRows]) => {
453
- const data = chartData(
454
- { ...spec, splitBy: undefined },
455
- seriesRows,
456
- fieldByKey
457
- );
458
- return {
459
- key,
460
- label: key || "(blank)",
461
- data,
462
- weight: data.buckets.reduce((sum, bucket) => sum + Math.abs(bucket.value), 0),
463
- };
464
- });
465
- computed.sort((a, b) => b.weight - a.weight || a.label.localeCompare(b.label));
466
- const kept = computed.slice(0, MAX_CHART_SERIES);
467
- const omittedSeries = Math.max(0, computed.length - kept.length);
468
- const omittedSeriesValue = computed
469
- .slice(MAX_CHART_SERIES)
470
- .reduce((sum, series) => sum + series.weight, 0);
471
- const xOrder = base.buckets.map((bucket) => bucket.key);
472
- const labelByX = new Map(base.buckets.map((bucket) => [bucket.key, bucket.label]));
473
- const points: ChartPoint[] = [];
474
- for (const series of kept) {
475
- const byX = new Map(series.data.buckets.map((bucket) => [bucket.key, bucket]));
476
- for (const key of xOrder) {
477
- const bucket = byX.get(key);
478
- points.push({
479
- key,
480
- label: labelByX.get(key) ?? key,
481
- value: bucket?.value ?? 0,
482
- n: bucket?.n ?? 0,
483
- seriesKey: series.key,
484
- seriesLabel: series.label,
485
- });
486
- }
487
- }
488
- return {
489
- ...empty,
490
- points,
491
- xOrder,
492
- seriesOrder: kept.map((series) => series.key),
493
- omittedSeries,
494
- omittedSeriesValue,
495
- };
496
- }
497
-
498
- /** The default spec for a freshly added chart — count of rows by the first
499
- * groupable field, which draws something real immediately rather than an empty
500
- * card the user has to configure before seeing anything. */
501
- export function defaultChart(id: string, fields: Field[]): ChartSpec {
502
- const x = fields.find((f) => f.type === "status" || f.type === "select")?.key;
503
- return { id, kind: "bar", x, agg: "count", size: { w: 6, h: 280 } };
504
- }
505
 
506
  /** Fields offerable as a chart's x (group-by): categorical or date-family. */
507
  export function groupableForChart(fields: Field[]): Field[] {
 
109
  n: number;
110
  }
111
 
112
+ export interface ChartData {
113
  buckets: Bucket[];
114
  /** Buckets not drawn because of MAX_BUCKETS. Never silently dropped. */
115
  omitted: number;
 
119
  blanks: number;
120
  /** Rows the aggregate could not use (non-numeric/empty y under sum/avg/...). */
121
  missingY: number;
122
+ /** Total rows considered — always the grid's row count for this view. */
123
+ rows: number;
124
+ /** Aggregate buckets across the FULL domain, before the display cap. */
125
+ negativeBuckets?: number;
126
+ negativeValue?: number;
127
+ zeroBuckets?: number;
128
+ /** Populated when the spec cannot be drawn; the card shows this verbatim. */
129
+ problem?: string;
130
+ }
131
+
132
+ /**
133
+ * The renderer-neutral data model consumed by Chart View.
134
+ *
135
+ * This is intentionally not a Vega-Lite type. Saved views persist `ChartSpec`,
136
+ * the arithmetic produces this small table, and the current renderer translates
137
+ * it at the final boundary. Replacing Vega later therefore changes one adapter
138
+ * rather than every saved view and every aggregation rule.
139
+ */
140
+ export interface ChartPoint extends Bucket {
141
+ seriesKey: string;
142
+ seriesLabel: string;
143
+ }
144
+
145
+ export interface ChartModel extends Omit<ChartData, "buckets"> {
146
+ points: ChartPoint[];
147
+ xOrder: string[];
148
+ seriesOrder: string[];
149
+ omittedSeries: number;
150
+ omittedSeriesValue: number;
151
+ /** Donut-only: zero/negative groups cannot be represented as angular share. */
152
+ nonPositive: number;
153
+ nonPositiveValue: number;
154
+ }
155
+
156
+ /** A legend with dozens of entries is a data dump, not a chart. */
157
+ export const MAX_CHART_SERIES = 12;
158
+
159
+ /** A date value bucketed to its month, the only date bucket wave 8 offers. */
160
+ function monthOf(v: unknown): string | null {
161
  const s = String(v ?? "");
162
  return /^\d{4}-\d{2}/.test(s) ? s.slice(0, 7) : null;
163
  }
 
195
  }
196
  }
197
 
198
+ /** The numeric coercion the aggregates use — exported for item 4's calendar summaries so the
199
+ * two surfaces agree on what counts as a number. */
200
+ export { numOf as asChartNumber };
201
+
202
+ /**
203
+ * Owner item 4 (C-DISP) — the aggregate, for callers OUTSIDE a chart card.
204
+ *
205
+ * ⚠ Deliberately a different return type from the private `reduce` above, and the difference
206
+ * is honesty, not style. `reduce` answers `0` when a bucket collected no usable values,
207
+ * because a bar chart needs a height and the card states its `missingY` separately. A calendar
208
+ * day cell has no such companion disclosure: a lone "0" in a Wednesday IS the whole claim, and
209
+ * "the average of nothing is zero" is false. So this returns **null** for an empty
210
+ * sum/avg/min/max bucket, which the caller renders as "—".
211
+ *
212
+ * `count` is exempt — the count of no rows really is 0, and that is a fact rather than a
213
+ * substitute for one.
214
+ *
215
+ * `reduce` itself is untouched: `verify_charts.py` holds 12 negative controls against its
216
+ * behaviour, and changing the shared function to suit a second caller is how a gated rule
217
+ * quietly stops being the rule.
218
+ */
219
+ export function aggregateOrNull(agg: ChartAgg, vals: number[], n: number): number | null {
220
+ if (agg === "count") return n;
221
+ if (vals.length === 0) return null;
222
+ return reduce(agg, vals, n);
223
+ }
224
+
225
  /**
226
  * Build one chart's data from the view's rows.
227
  *
 
330
 
331
  // Time reads chronologically; categories read biggest-first. Sorting a date
332
  // axis by value would turn a trend line into a sawtooth that means nothing.
333
+ if (byMonth) {
334
  buckets.sort((a, b) => (a.key === "" ? 1 : b.key === "" ? -1 : a.key.localeCompare(b.key)));
335
  } else {
336
+ buckets.sort((a, b) => b.value - a.value || a.label.localeCompare(b.label));
337
+ }
338
+
339
+ // Signed-domain facts are computed BEFORE the display cap. A negative group
340
+ // that sorts below the top 12 must still block a donut; otherwise the cap
341
+ // would turn invalid source data into a plausible positive composition.
342
+ const negativeBuckets = buckets.filter((bucket) => bucket.value < 0);
343
+ const zeroBuckets = buckets.filter((bucket) => bucket.value === 0).length;
344
+ const negativeValue = negativeBuckets.reduce((sum, bucket) => sum + bucket.value, 0);
345
+
346
  let omitted = 0;
347
  let omittedValue = 0;
348
  if (buckets.length > MAX_BUCKETS) {
 
353
  buckets = kept;
354
  }
355
 
356
+ return {
357
+ ...base,
358
+ buckets,
359
+ omitted,
360
+ omittedValue,
361
+ blanks,
362
+ missingY,
363
+ negativeBuckets: negativeBuckets.length,
364
+ negativeValue,
365
+ zeroBuckets,
366
+ };
367
  }
368
 
369
+ /**
370
+ * Expand the flat aggregation into the renderer-neutral table used at the
371
+ * chart boundary. `splitBy` becomes a real series dimension here; saved view
372
+ * state remains independent of Vega-Lite (or whichever renderer replaces it).
373
+ */
374
+ export function chartModel(
375
+ spec: ChartSpec,
376
+ rows: Row[],
377
+ fieldByKey: Map<string, Field>
378
+ ): ChartModel {
379
+ const base = chartData({ ...spec, splitBy: undefined }, rows, fieldByKey);
380
+ const empty: ChartModel = {
381
+ points: [],
382
+ xOrder: [],
383
+ seriesOrder: [],
384
+ omitted: base.omitted,
385
+ omittedValue: base.omittedValue,
386
+ omittedSeries: 0,
387
+ omittedSeriesValue: 0,
388
+ nonPositive: 0,
389
+ nonPositiveValue: 0,
390
+ blanks: base.blanks,
391
+ missingY: base.missingY,
392
+ rows: base.rows,
393
+ problem: base.problem,
394
+ };
395
+ if (base.problem) return empty;
396
+
397
+ if (spec.kind === "donut") {
398
+ // Arc length encodes a share of a positive whole. Vega (like most chart
399
+ // engines) can accept signed theta values syntactically, but the resulting
400
+ // geometry has no truthful business meaning. Zero groups preserve the old
401
+ // positive-only omission (with disclosure); one negative group blocks the
402
+ // entire composition and directs the user to a signed chart.
403
+ const positive = base.buckets.filter((bucket) => bucket.value > 0);
404
+ const negativeCount =
405
+ base.negativeBuckets ?? base.buckets.filter((bucket) => bucket.value < 0).length;
406
+ const zeroCount =
407
+ base.zeroBuckets ?? base.buckets.filter((bucket) => bucket.value === 0).length;
408
+ const nonPositive = negativeCount + zeroCount;
409
+ const nonPositiveValue =
410
+ base.negativeValue ??
411
+ base.buckets
412
+ .filter((bucket) => bucket.value < 0)
413
+ .reduce((sum, bucket) => sum + bucket.value, 0);
414
+ if (negativeCount > 0) {
415
+ return {
416
+ ...empty,
417
+ nonPositive,
418
+ nonPositiveValue,
419
+ problem:
420
+ "A donut cannot represent negative values without misrepresenting the whole. Use a bar or line chart for signed values.",
421
+ };
422
+ }
423
+ if (base.buckets.length > 0 && positive.length === 0) {
424
+ return {
425
+ ...empty,
426
+ nonPositive,
427
+ nonPositiveValue,
428
+ problem:
429
+ "A donut needs at least one positive value. Zero-value groups cannot be drawn as slices.",
430
+ };
431
+ }
432
+ return {
433
+ ...empty,
434
+ points: positive.map((bucket) => ({
435
+ ...bucket,
436
+ seriesKey: "",
437
+ seriesLabel: "",
438
+ })),
439
+ xOrder: positive.map((bucket) => bucket.key),
440
+ nonPositive,
441
+ nonPositiveValue,
442
+ };
443
+ }
444
+
445
+ if (!spec.splitBy || spec.kind === "kpi") {
446
+ return {
447
+ ...empty,
448
+ points: base.buckets.map((bucket) => ({
449
+ ...bucket,
450
+ seriesKey: "",
451
+ seriesLabel: "",
452
+ })),
453
+ xOrder: base.buckets.map((bucket) => bucket.key),
454
+ };
455
+ }
456
+
457
+ const splitField = fieldByKey.get(spec.splitBy);
458
+ const xField = spec.x ? fieldByKey.get(spec.x) : undefined;
459
+ if (!splitField)
460
+ return { ...empty, problem: "The field this chart split into series no longer exists." };
461
+ if (!xField)
462
+ return { ...empty, problem: "The field this chart grouped by no longer exists." };
463
+
464
+ const xKey = (row: Row): string => {
465
+ if (isDateFamilyType(xField.type)) return monthOf(row[xField.key]) ?? "";
466
+ return String(row[xField.key] ?? "").trim();
467
+ };
468
+ const seriesKey = (row: Row): string => String(row[splitField.key] ?? "").trim();
469
+ const xAllowed = new Set(base.buckets.map((bucket) => bucket.key));
470
+ const bySeries = new Map<string, Row[]>();
471
+ for (const row of rows) {
472
+ if (!xAllowed.has(xKey(row))) continue;
473
+ const key = seriesKey(row);
474
+ const group = bySeries.get(key);
475
+ if (group) group.push(row);
476
+ else bySeries.set(key, [row]);
477
+ }
478
+
479
+ const computed = [...bySeries.entries()].map(([key, seriesRows]) => {
480
+ const data = chartData(
481
+ { ...spec, splitBy: undefined },
482
+ seriesRows,
483
+ fieldByKey
484
+ );
485
+ return {
486
+ key,
487
+ label: key || "(blank)",
488
+ data,
489
+ weight: data.buckets.reduce((sum, bucket) => sum + Math.abs(bucket.value), 0),
490
+ };
491
+ });
492
+ computed.sort((a, b) => b.weight - a.weight || a.label.localeCompare(b.label));
493
+ const kept = computed.slice(0, MAX_CHART_SERIES);
494
+ const omittedSeries = Math.max(0, computed.length - kept.length);
495
+ const omittedSeriesValue = computed
496
+ .slice(MAX_CHART_SERIES)
497
+ .reduce((sum, series) => sum + series.weight, 0);
498
+ const xOrder = base.buckets.map((bucket) => bucket.key);
499
+ const labelByX = new Map(base.buckets.map((bucket) => [bucket.key, bucket.label]));
500
+ const points: ChartPoint[] = [];
501
+ for (const series of kept) {
502
+ const byX = new Map(series.data.buckets.map((bucket) => [bucket.key, bucket]));
503
+ for (const key of xOrder) {
504
+ const bucket = byX.get(key);
505
+ points.push({
506
+ key,
507
+ label: labelByX.get(key) ?? key,
508
+ value: bucket?.value ?? 0,
509
+ n: bucket?.n ?? 0,
510
+ seriesKey: series.key,
511
+ seriesLabel: series.label,
512
+ });
513
+ }
514
+ }
515
+ return {
516
+ ...empty,
517
+ points,
518
+ xOrder,
519
+ seriesOrder: kept.map((series) => series.key),
520
+ omittedSeries,
521
+ omittedSeriesValue,
522
+ };
523
+ }
524
+
525
+ /** The default spec for a freshly added chart — count of rows by the first
526
+ * groupable field, which draws something real immediately rather than an empty
527
+ * card the user has to configure before seeing anything. */
528
+ export function defaultChart(id: string, fields: Field[]): ChartSpec {
529
+ const x = fields.find((f) => f.type === "status" || f.type === "select")?.key;
530
+ return { id, kind: "bar", x, agg: "count", size: { w: 6, h: 280 } };
531
+ }
532
 
533
  /** Fields offerable as a chart's x (group-by): categorical or date-family. */
534
  export function groupableForChart(fields: Field[]): Field[] {