fsanyoto commited on
Commit
ecd307d
·
verified ·
1 Parent(s): 4201a03

Deploy AIOS web (React glide grid + FastAPI slice)

Browse files
RELEASES.json CHANGED
@@ -1,5 +1,5 @@
1
  {
2
- "current": "d4e3e31",
3
  "releases": [
4
  {
5
  "version": "v68",
 
1
  {
2
+ "current": "c4dc318",
3
  "releases": [
4
  {
5
  "version": "v68",
VERSION CHANGED
@@ -1 +1 @@
1
- d4e3e31
 
1
+ c4dc318
api/routes_admin.py CHANGED
@@ -1321,6 +1321,22 @@ def _server_side_vocabularies(session=None):
1321
  import modules.inventory as inventory
1322
  return {"stock_bucket": list(inventory.COVERAGE_LABELS or ())}
1323
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1324
  def _categories():
1325
  import modules.inventory as inventory
1326
  # W40-T06: the root maps to None now, so "All" cannot reach either list. The sentinel is
@@ -1403,8 +1419,8 @@ def _server_side_vocabularies(session=None):
1403
  return {"salesperson": [O.m2o_name(r.get("user_id")) or BLANK for r in rows]}
1404
 
1405
  complete = all([arm(source) for source in
1406
- (_stock_bucket, _categories, _suppliers, _masters, _partner_dims,
1407
- _agents, _salespeople)])
1408
  if complete:
1409
  _VOCAB_CACHE = dict(out)
1410
  # Tenant-owned choices are deliberately added AFTER the process cache is stamped. Caching
 
1321
  import modules.inventory as inventory
1322
  return {"stock_bucket": list(inventory.COVERAGE_LABELS or ())}
1323
 
1324
+ def _inventory_state():
1325
+ # W48C-T09 (2026-09-01): `inventory_value_per_quantity_state` is the second CLOSED,
1326
+ # code-minted vocabulary after `stock_bucket`. IMPORTED, NEVER RESTATED - the seven
1327
+ # constants `product_data` stamps per row, so a renamed state cannot leave a second
1328
+ # vocabulary behind here [[constant-two-features-share]].
1329
+ import modules.products as products
1330
+ return {"inventory_value_per_quantity_state": [
1331
+ products.INVENTORY_VALUE_PER_QUANTITY_AVAILABLE,
1332
+ products.INVENTORY_VALUE_PER_QUANTITY_SOURCE_UNAVAILABLE,
1333
+ products.INVENTORY_VALUE_PER_QUANTITY_NO_RECORD,
1334
+ products.INVENTORY_VALUE_PER_QUANTITY_ON_HAND_MISSING,
1335
+ products.INVENTORY_VALUE_PER_QUANTITY_STOCK_VALUE_MISSING,
1336
+ products.INVENTORY_VALUE_PER_QUANTITY_INVALID_INPUT,
1337
+ products.INVENTORY_VALUE_PER_QUANTITY_ZERO_ON_HAND,
1338
+ ]}
1339
+
1340
  def _categories():
1341
  import modules.inventory as inventory
1342
  # W40-T06: the root maps to None now, so "All" cannot reach either list. The sentinel is
 
1419
  return {"salesperson": [O.m2o_name(r.get("user_id")) or BLANK for r in rows]}
1420
 
1421
  complete = all([arm(source) for source in
1422
+ (_stock_bucket, _inventory_state, _categories, _suppliers, _masters,
1423
+ _partner_dims, _agents, _salespeople)])
1424
  if complete:
1425
  _VOCAB_CACHE = dict(out)
1426
  # Tenant-owned choices are deliberately added AFTER the process cache is stamped. Caching
api/routes_grid.py CHANGED
@@ -112,6 +112,176 @@ def _scope_or_400(raw):
112
  return scope
113
 
114
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
115
  def _audit_timestamps(scope, pids, hidden_keys, runtime):
116
  """Permission-scoped latest record and field writes for grid Last updated sorting."""
117
  from core import user_tables
 
112
  return scope
113
 
114
 
115
+ def _product_seeded_rows(g, key, fold, multi, session):
116
+ """Product rows whose MASTERSHEET default for `key` is a retired option and which hold no
117
+ shared override - exactly the rows `routes_products._seed_shared` would put the option back
118
+ onto after the shared cells were purged. `(pid, seeded value)` pairs."""
119
+ import modules.product_data as pd
120
+ from core import choice_removal as _cr
121
+
122
+ if key not in set(pd.SHARED_KEYS()):
123
+ return []
124
+ pids = list(g.get("pids") or ())
125
+ stored = pd.shared_cells(pids, st=session.runtime) if pids else {}
126
+ allowed = set(pids)
127
+ out = []
128
+ for src in g.get("rows_src") or ():
129
+ if not isinstance(src, dict):
130
+ continue
131
+ pid = src.get("pid")
132
+ if pid not in allowed or not _cr.uses(src.get(key), fold, multi=multi):
133
+ continue
134
+ held = (stored.get(str(pid)) or {}).get(key)
135
+ if held in (None, ""):
136
+ out.append((pid, src.get(key)))
137
+ return out
138
+
139
+
140
+ @router.post("/grid/choice-remove")
141
+ def grid_choice_remove(scope: str = "customer", body: dict = Body(default=None),
142
+ session: Session = Depends(require_session)):
143
+ """Retire one or more OPTIONS of a select / multiselect field, together with the cells that
144
+ hold them. Owner, 2026-09-02: *"Removing an Option ... if the option is already being used by
145
+ a cell should give a warning before deleting. And after confirmation, it should allow the
146
+ user to immediately delete the option and that option's values in all the cells in the
147
+ field."*
148
+
149
+ TWO PHASES, ONE DOOR. `confirm: false` COUNTS and writes nothing - the client shows the
150
+ warning from that number. `confirm: true` performs the removal. The count is taken server-
151
+ side because the browser holds one page of rows and the standing rule says the field's
152
+ universe is uncapped; a warning computed from a page would be wrong exactly when it matters.
153
+
154
+ ⛔ THE WALL IS THE DEFINITION WALL, not the cell wall: removing an option is a change to the
155
+ field CONTRACT, so it rides `grid_events.may_edit_field_definition` (customer/product) or
156
+ `user_tables.may_edit_field` (a user database) - the same predicates a rename rides - and a
157
+ hidden column is refused as unknown before either is asked.
158
+
159
+ THE STRATA THAT HOLD A CHOICE VALUE, each written by its own owner:
160
+ * this user's personal workspace (definition of a personal custom field, overlay cells,
161
+ view filters) - `TableStore.remove_choice_values`;
162
+ * the tenant-wide shared stratum (a shared or spreadsheet field's definition and cells) -
163
+ `shared_overlay.purge_choice_values`;
164
+ * a user database's contract and rows - `user_tables.remove_choice_values`;
165
+ * Product Supplier's MASTERSHEET defaults, which are not stored at all: those rows receive
166
+ the `(none)` tombstone the column already uses for "no supplier", because an empty shared
167
+ cell there falls back to the default being retired.
168
+ """
169
+ from core import grid_events, shared_overlay
170
+ from core import choice_removal as _cr
171
+
172
+ body = body if isinstance(body, dict) else {}
173
+ scope = _scope_or_400(scope)
174
+ key = str(body.get("key") or "").strip()[:80]
175
+ options = _cr.normalise(body.get("options") if isinstance(body.get("options"), list) else [])
176
+ confirm = body.get("confirm") is True
177
+ if not key or not options:
178
+ raise err(400, "bad_request", "name the field and at least one option to remove")
179
+
180
+ if scope == "product":
181
+ from routes_products import MODULE as PRODUCT_MODULE, product_assembly
182
+
183
+ session.require(PRODUCT_MODULE)
184
+ g = product_assembly(session, consume_corrections=False)
185
+ elif scope.startswith("ut_"):
186
+ from routes_tables import ut_write_ctx
187
+
188
+ g = ut_write_ctx(session, scope)
189
+ else:
190
+ from routes_customers import grid_assembly
191
+
192
+ session.require(MODULE)
193
+ g = grid_assembly(session, scope=scope, consume_corrections=False)
194
+
195
+ field = next((f for f in (g.get("fields") or ()) if isinstance(f, dict) and f.get("key") == key),
196
+ None)
197
+ ctx = _ctx(session, g["fields"], g["pids"], scope_key=scope)
198
+ if field is None or key in (ctx.hidden_keys or frozenset()):
199
+ # 404 for "no such column" and "not yours to see" alike: this door is not an oracle.
200
+ raise err(404, "unknown_field", "that field is not in this database")
201
+ if field.get("type") not in ("select", "multiselect"):
202
+ raise err(400, "not_a_choice_field",
203
+ "only a single select or multi select field has options to remove")
204
+ multi = field.get("type") == "multiselect"
205
+
206
+ if scope.startswith("ut_"):
207
+ import core.user_tables as ut
208
+
209
+ if not ut.may_edit_field(scope, key, session.uname, is_admin=session.admin,
210
+ st=session.runtime):
211
+ raise err(403, "field_read_only",
212
+ "you can only change this field's options if you created it or have Can edit access")
213
+ elif not grid_events.may_edit_field_definition(ctx, key, field):
214
+ raise err(403, "field_read_only",
215
+ "you can only change this field's options if you created it or have Can edit access")
216
+
217
+ fold = _cr.folded(options)
218
+ table = ctx.table
219
+ table_key = str(getattr(table, "table_key", "") or "")
220
+ shared_keys = set()
221
+ if not scope.startswith("ut_"):
222
+ try:
223
+ shared_keys = set(shared_overlay.fields(table_key, st=session.runtime) or ())
224
+ except Exception: # noqa: BLE001
225
+ shared_keys = set()
226
+ if scope == "product":
227
+ import modules.product_data as pd
228
+
229
+ shared_keys |= set(pd.SHARED_KEYS())
230
+ is_shared = key in shared_keys
231
+
232
+ usage = {"personal": 0, "shared": 0, "seeded": 0, "records": 0}
233
+ try:
234
+ if scope.startswith("ut_"):
235
+ import core.user_tables as ut
236
+
237
+ usage["records"] = ut.choice_usage(scope, key, options, st=session.runtime)
238
+ usage["personal"] = table.choice_usage(session.uname, key, options, multi=multi)
239
+ if is_shared:
240
+ usage["shared"] = shared_overlay.choice_usage(table_key, key, options, multi=multi,
241
+ st=session.runtime)
242
+ if scope == "product":
243
+ usage["seeded"] = len(_product_seeded_rows(g, key, fold, multi, session))
244
+ except grid_events.StoreUnavailable:
245
+ raise err(503, "store_unavailable", "the tenant store is unavailable")
246
+ result = {"key": key, "options": options, "cells": sum(usage.values()), "usage": usage,
247
+ "applied": False}
248
+ if not confirm:
249
+ return result
250
+
251
+ written = {}
252
+ try:
253
+ if scope.startswith("ut_"):
254
+ import core.user_tables as ut
255
+
256
+ written["records"] = ut.remove_choice_values(scope, key, options, st=session.runtime)
257
+ written["personal"] = table.remove_choice_values(session.uname, key, options, multi=multi)
258
+ if is_shared:
259
+ blank = ""
260
+ if scope == "product":
261
+ import modules.product_data as pd
262
+
263
+ if key in set(pd.SHARED_KEYS()):
264
+ blank = "(none)"
265
+ written["shared"] = shared_overlay.purge_choice_values(
266
+ table_key, key, options, multi=multi, blank=blank, st=session.runtime)
267
+ if scope == "product":
268
+ import modules.product_data as pd
269
+
270
+ seeded = {}
271
+ for pid, seed in _product_seeded_rows(g, key, fold, multi, session):
272
+ new, _changed = _cr.strip_value(seed, fold, multi=multi, blank="(none)")
273
+ seeded[pid] = {key: new}
274
+ if seeded:
275
+ shared_overlay.put_rows(pd.TABLE_KEY, seeded, st=session.runtime)
276
+ written["seeded"] = len(seeded)
277
+ except grid_events.StoreUnavailable:
278
+ raise err(503, "store_unavailable",
279
+ "the tenant store is unavailable - the option was not removed")
280
+ result["applied"] = True
281
+ result["written"] = written
282
+ return result
283
+
284
+
285
  def _audit_timestamps(scope, pids, hidden_keys, runtime):
286
  """Permission-scoped latest record and field writes for grid Last updated sorting."""
287
  from core import user_tables
api/routes_products.py CHANGED
@@ -543,6 +543,16 @@ def product_assembly(session: Session, scope: str = "product", storage_key: str
543
  ws["overlays"] = {str(pid): {k: v for k, v in (row or {}).items()
544
  if k not in _ov_hidden}
545
  for pid, row in _ovc.items()}
 
 
 
 
 
 
 
 
 
 
546
  return {"rows_src": rows_src, "pids": pids, "ws": ws, "workspace": workspace,
547
  "fields": fields, "views": views, "lists": lists,
548
  "derived": derived,
 
543
  ws["overlays"] = {str(pid): {k: v for k, v in (row or {}).items()
544
  if k not in _ov_hidden}
545
  for pid, row in _ovc.items()}
546
+ # ⛔ THE SERVER-OWNED AXES RIDE EVERY PRODUCT FIELD, EXACTLY AS `/customers` AND `/workspace`
547
+ # ALREADY DO (`routes_customers.py` and `routes_grid.py` map through `field_axes`; this
548
+ # assembly did not). `field_axes` is what publishes `limits.maxOptions`, and the client's
549
+ # `serverOptionLimit()` FAILS CLOSED when no served field carries it — so on the Product grid
550
+ # every choice edit died with *"Choices cannot be saved because the server did not publish an
551
+ # option limit"* (owner, 2026-09-02, editing Supplier's options). One projection for all three
552
+ # doors, applied here so `/products` and `/workspace?scope=product` cannot disagree again.
553
+ from core import route_system
554
+ fields = [route_system.field_axes(field) if isinstance(field, dict) else field
555
+ for field in fields]
556
  return {"rows_src": rows_src, "pids": pids, "ws": ws, "workspace": workspace,
557
  "fields": fields, "views": views, "lists": lists,
558
  "derived": derived,
api/routes_starred.py CHANGED
@@ -385,7 +385,18 @@ def _find_view(session, vid, database=""):
385
  if not ws_key:
386
  continue
387
  views = table_store.make(ws_key, st=session.runtime)
388
- found = views.find_view(vid)
 
 
 
 
 
 
 
 
 
 
 
389
  if not found:
390
  continue
391
  owner, view = found
@@ -421,6 +432,11 @@ def _may_star_view(session, owner, view):
421
  is_admin=session.admin, st=session.runtime)
422
 
423
 
 
 
 
 
 
424
  def _write_view_star(session, ws_key, stratum, vid, on):
425
  """Set `config.important` IN PLACE, in the view's own bucket. Returns True when it landed.
426
 
@@ -450,10 +466,23 @@ def _write_view_star(session, ws_key, stratum, vid, on):
450
  data = data if isinstance(data, dict) else {}
451
  block = data.get(stratum)
452
  if not isinstance(block, dict):
453
- return data
 
 
454
  views = block.get("views")
455
- if not isinstance(views, dict) or str(vid) not in views:
456
- return data
 
 
 
 
 
 
 
 
 
 
 
457
  view = views[str(vid)]
458
  if not isinstance(view, dict):
459
  return data
 
385
  if not ws_key:
386
  continue
387
  views = table_store.make(ws_key, st=session.runtime)
388
+ # ⛔ THE CALLER'S OWN RECORD FIRST (W48C-T02, 2026-09-02). See `TableStore.find_view`:
389
+ # the pinned system id exists in as many personal strata as have ever saved its config,
390
+ # and a first-hit scan starred a colleague's copy while the caller's rail stayed dark.
391
+ found = views.find_view(vid, prefer_owner=session.uname)
392
+ if not found and vid == SYSTEM_VIEW_ID and database:
393
+ # The system view is PROJECTED, not stored, until somebody saves its config. A first
394
+ # star on a database the caller may open is exactly that first save: hand back the
395
+ # caller's own (still absent) record so `_write_view_star` can materialise it.
396
+ # `database` is required here on purpose - a scan-mode lookup has no single bucket
397
+ # to materialise into, and it already answers every stored record.
398
+ return (key, ws_key, session.uname,
399
+ {"id": vid, "kind": "system", "config": {}}, cache)
400
  if not found:
401
  continue
402
  owner, view = found
 
432
  is_admin=session.admin, st=session.runtime)
433
 
434
 
435
+ #: The one view id every database pins (`aios_grid.views_from_defs`): projected from the field
436
+ #: contract, stored only once somebody saves its config, undeletable on the client.
437
+ SYSTEM_VIEW_ID = "all-customers"
438
+
439
+
440
  def _write_view_star(session, ws_key, stratum, vid, on):
441
  """Set `config.important` IN PLACE, in the view's own bucket. Returns True when it landed.
442
 
 
466
  data = data if isinstance(data, dict) else {}
467
  block = data.get(stratum)
468
  if not isinstance(block, dict):
469
+ if str(vid) != SYSTEM_VIEW_ID:
470
+ return data
471
+ block = data.setdefault(stratum, {})
472
  views = block.get("views")
473
+ if not isinstance(views, dict):
474
+ if str(vid) != SYSTEM_VIEW_ID:
475
+ return data
476
+ views = block.setdefault("views", {})
477
+ if str(vid) not in views:
478
+ if str(vid) != SYSTEM_VIEW_ID:
479
+ return data
480
+ # ⭐ W48C-T02 (2026-09-02): the pinned system view is projected from the field contract
481
+ # and has no stored record until its config is first saved. A star IS that first save,
482
+ # so materialise the minimal saved-config record `views_from_defs` overlays by id -
483
+ # `{id, kind, config}` - in the CALLER's stratum. Anything less than `config: {}`
484
+ # would be skipped by the overlay loop and the star would land nowhere, twice.
485
+ views[str(vid)] = {"id": str(vid), "kind": "system", "config": {}}
486
  view = views[str(vid)]
487
  if not isinstance(view, dict):
488
  return data
platform/core/choice_removal.py ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Removing a select / multiselect OPTION carries its stored VALUES out with it.
2
+
3
+ Owner, 2026-09-02: *"Removing an Option from the Single-select / Multi-select if the option is
4
+ already being used by a cell should give a warning before deleting. And after confirmation, it
5
+ should allow the user to immediately delete the option and that option's values in all the cells
6
+ in the field."*
7
+
8
+ This module is the PURE half: it knows how a choice value is shaped in each stratum and how to
9
+ strip one option out of it, and it counts. It reads no store and writes none. The strata each
10
+ own their write (`table_store.TableStore.remove_choice_values` for a person's workspace,
11
+ `shared_overlay.purge_choice_values` for the tenant-wide bucket, `user_tables.remove_choice_values`
12
+ for a user database), and `routes_grid` composes them behind one door, so the client asks one
13
+ question - *how many cells use it?* - and issues one confirmed write.
14
+
15
+ Three cell shapes exist, and every one of them has shipped:
16
+ * a SCALAR string (`select`, and a `multiselect` written by the connector as a comma-joined
17
+ SET - `aios_grid_fields.json` documents that shape for customer tags and product supplier);
18
+ * a LIST of member strings (a `multiselect` written by the grid's own overlay patch);
19
+ * `None` / `''`, which is "no value" and never a member.
20
+ Matching is case-insensitive, exactly as `aios_grid._clean_options` de-duplicates the vocabulary:
21
+ a cell holding `acme` is a use of the option `Acme`, because the picker would show them as one.
22
+ """
23
+
24
+
25
+ def normalise(options):
26
+ """Trimmed, non-empty, case-insensitively de-duplicated option labels, order kept."""
27
+ out, seen = [], set()
28
+ for raw in list(options or ()):
29
+ if isinstance(raw, bool) or not isinstance(raw, (str, int, float)):
30
+ continue
31
+ label = str(raw).strip()[:120]
32
+ if not label or label.casefold() in seen:
33
+ continue
34
+ seen.add(label.casefold())
35
+ out.append(label)
36
+ return out
37
+
38
+
39
+ def folded(options):
40
+ """The case-insensitive match set for `options`."""
41
+ return {label.casefold() for label in normalise(options)}
42
+
43
+
44
+ def _members(value, multi):
45
+ """The individual labels a stored cell represents, or None when it holds no value."""
46
+ if value is None or isinstance(value, bool):
47
+ return None
48
+ if isinstance(value, (list, tuple, set)):
49
+ parts = [str(v).strip() for v in value if str(v or '').strip()]
50
+ return parts
51
+ text = str(value).strip()
52
+ if not text:
53
+ return None
54
+ if multi:
55
+ return [p.strip() for p in text.split(',') if p.strip()]
56
+ return [text]
57
+
58
+
59
+ def uses(value, removed_fold, *, multi):
60
+ """True when this cell holds at least one of the removed options."""
61
+ parts = _members(value, multi)
62
+ if not parts:
63
+ return False
64
+ return any(p.casefold() in removed_fold for p in parts)
65
+
66
+
67
+ def strip_value(value, removed_fold, *, multi, blank=''):
68
+ """`(new_value, changed)` - the cell with every removed option taken out.
69
+
70
+ The SHAPE is preserved: a list stays a list, a comma-joined string stays comma-joined, and a
71
+ scalar becomes `blank`. `blank` is the stratum's own "no value" - `''` for a person's overlay
72
+ and a user database, and whatever sentinel a seeded column uses (Product Supplier keeps
73
+ `'(none)'`, because an EMPTY shared cell there means "fall back to the mastersheet default",
74
+ which would put the removed option straight back on the row).
75
+ """
76
+ parts = _members(value, multi)
77
+ if not parts:
78
+ return value, False
79
+ kept = [p for p in parts if p.casefold() not in removed_fold]
80
+ if len(kept) == len(parts):
81
+ return value, False
82
+ if isinstance(value, (list, tuple, set)):
83
+ return (list(kept) if kept else (blank if blank not in ('', None) else [])), True
84
+ if multi:
85
+ return (', '.join(dict.fromkeys(kept)) if kept else blank), True
86
+ return blank, True
87
+
88
+
89
+ def count_cells(rows, key, removed_fold, *, multi):
90
+ """How many of `rows` (an iterable of `{field_key: value}` dicts) use a removed option."""
91
+ n = 0
92
+ for row in rows or ():
93
+ if isinstance(row, dict) and key in row and uses(row.get(key), removed_fold, multi=multi):
94
+ n += 1
95
+ return n
96
+
97
+
98
+ def without(options, removed_fold):
99
+ """The vocabulary with the removed labels taken out. Accepts the two stored shapes -
100
+ plain strings, and legacy `{'name': ...}` choice objects - and keeps whichever it got."""
101
+ out = []
102
+ for choice in list(options or ()):
103
+ if isinstance(choice, dict):
104
+ label = str(choice.get('name') or '').strip()
105
+ else:
106
+ label = str(choice or '').strip()
107
+ if label and label.casefold() in removed_fold:
108
+ continue
109
+ out.append(choice)
110
+ return out
platform/core/grid_events.py CHANGED
@@ -324,6 +324,16 @@ def _may_edit_field_definition(ctx, key, definition):
324
  str(user).lower() for user in (perms.get('users') or [])})
325
 
326
 
 
 
 
 
 
 
 
 
 
 
327
  def _may_edit_field_value(ctx, key, definition):
328
  """The value-write wall; ordinary source-overlay fields remain collaborative by default."""
329
  if not isinstance(definition, dict):
 
324
  str(user).lower() for user in (perms.get('users') or [])})
325
 
326
 
327
+ def may_edit_field_definition(ctx, key, definition):
328
+ """The definition wall, for doors outside the event bus (`routes_grid.grid_choice_remove`).
329
+
330
+ ONE evaluator for "may this caller change this field's definition": the REST door asks the
331
+ same function `field_upsert` and `choice_rename` ask, so removing an option cannot be
332
+ admitted for a caller who could not have renamed one.
333
+ """
334
+ return _may_edit_field_definition(ctx, key, definition)
335
+
336
+
337
  def _may_edit_field_value(ctx, key, definition):
338
  """The value-write wall; ordinary source-overlay fields remain collaborative by default."""
339
  if not isinstance(definition, dict):
platform/core/shared_overlay.py CHANGED
@@ -649,3 +649,68 @@ def prune(table_key, live_pids, st=None):
649
 
650
  _write(table_key, _prune, st, flush='sync')
651
  return dropped[0]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
649
 
650
  _write(table_key, _prune, st, flush='sync')
651
  return dropped[0]
652
+
653
+
654
+ # ----------------------------------------------------------------- choice removal (2026-09-02)
655
+ def choice_usage(table_key, field_key, options, *, multi=False, st=None):
656
+ """How many tenant-wide cells of `field_key` hold one of `options` - over EVERY row.
657
+
658
+ ⛔ DELIBERATELY UNSCOPED, unlike `cells()`, and stated rather than smuggled: this answers a
659
+ question about the FIELD DEFINITION (what does retiring this option cost?), not about rows a
660
+ reader may see. It returns a COUNT and no value, so the row wall is not crossed, and the door
661
+ that calls it (`routes_grid.grid_choice_remove`) has already applied the definition wall.
662
+ """
663
+ from core import choice_removal as _cr
664
+ fold = _cr.folded(options)
665
+ if not fold:
666
+ return 0
667
+ stored = _read(table_key, st)['cells']
668
+ return _cr.count_cells(stored.values(), str(field_key or ''), fold, multi=multi)
669
+
670
+
671
+ def purge_choice_values(table_key, field_key, options, *, multi=False, blank='', st=None):
672
+ """Retire `options` from the shared DEFINITION and strip them from every shared CELL, in ONE
673
+ store update. Returns `{'options': n, 'cells': n}`.
674
+
675
+ Owner, 2026-09-02: an option a cell still uses may be removed after a warning, and the
676
+ removal takes the values with it. Definition and cells move together here for the same
677
+ reason `table_store.rename_choice_values` insists on one transaction: a vocabulary that
678
+ dropped the label while cells kept it would re-hydrate the option on the next read
679
+ (`aios_grid.hydrate_choice_options_from_rows` builds the picker from served values).
680
+
681
+ `blank` is what a stripped scalar becomes. `''` for an ordinary shared column; a SEEDED
682
+ column passes its own sentinel (Product Supplier's `'(none)'`), because an empty shared cell
683
+ there means "show the mastersheet default", which is the very value being retired.
684
+ """
685
+ from core import choice_removal as _cr
686
+ fold = _cr.folded(options)
687
+ key = str(field_key or '').strip()
688
+ counts = {'options': 0, 'cells': 0}
689
+ if not fold or not key:
690
+ return counts
691
+
692
+ def _purge(data):
693
+ defn = data['fields'].get(key)
694
+ if isinstance(defn, dict):
695
+ if isinstance(defn.get('options'), list):
696
+ before = len(defn['options'])
697
+ defn['options'] = _cr.without(defn['options'], fold)
698
+ counts['options'] = before - len(defn['options'])
699
+ colors = defn.get('optionColors')
700
+ if isinstance(colors, dict):
701
+ for label in list(colors):
702
+ if str(label).casefold() in fold:
703
+ colors.pop(label, None)
704
+ for row in data['cells'].values():
705
+ if not isinstance(row, dict) or key not in row:
706
+ continue
707
+ new, changed = _cr.strip_value(row[key], fold, multi=multi, blank=blank)
708
+ if changed:
709
+ # a shared cell is a SCALAR (`_value` raises on a list); `strip_value` keeps the
710
+ # shape it was given, so a stored string comes back as a string.
711
+ row[key] = _value(new if not isinstance(new, (list, tuple, set))
712
+ else ', '.join(str(v) for v in new))
713
+ counts['cells'] += 1
714
+
715
+ _write(table_key, _purge, st, flush='sync')
716
+ return counts
platform/core/table_store.py CHANGED
@@ -496,13 +496,21 @@ class TableStore:
496
  same tenant's buckets this workspace lives in (wave 21, C1)."""
497
  return self._st
498
 
499
- def find_view(self, view_id):
500
  """`(owner_username, view)` for a view living in ANY personal stratum, else None.
501
 
502
  ⭐ Wave 21 (item 9, C1): the R10 grant registry names bare ids, so projecting a granted
503
  view means locating the OWNER's record inside this topic's bucket. Saved Views have
504
  one home only: a personal source record. The tenant-wide member is reserved for field
505
- annotations, so serving a View from a second home cannot reappear by accident."""
 
 
 
 
 
 
 
 
506
  # A direct lookup is a runtime read too. Do not leave a stale compatibility-shaped
507
  # personal record reachable merely because this caller did not first go through the grid
508
  # workspace assembler.
@@ -514,6 +522,12 @@ class TableStore:
514
  data = self._st.get(self.table_key) or {}
515
  except Exception:
516
  return None
 
 
 
 
 
 
517
  for username, ws in data.items():
518
  if username in (SHARED_KEY, ASSIGNED_KEY) or not isinstance(ws, dict):
519
  continue
@@ -664,6 +678,10 @@ class TableStore:
664
  window is real rather than theoretical. One `update`, one flush, one failure mode.
665
  """
666
  def _up(data):
 
 
 
 
667
  ws = data.setdefault(username, {})
668
  ws.setdefault('views', {})
669
  ws.setdefault('fields', {})
@@ -700,6 +718,80 @@ class TableStore:
700
  """
701
  return self._update(username, change)
702
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
703
  def save_active_view(self, username, view_id):
704
  """Remember which view this user last opened (owner item 3, 2026-07-31).
705
 
@@ -818,6 +910,13 @@ class TableStore:
818
  except Exception as exc: # no migration decision may start from a display fallback
819
  raise LegacySharedViewMigrationError(
820
  'legacy shared-view migration could not read the workspace document') from exc
 
 
 
 
 
 
 
821
  if not isinstance(data, dict):
822
  raise LegacySharedViewMigrationError(
823
  'legacy shared-view migration found a non-object workspace document')
 
496
  same tenant's buckets this workspace lives in (wave 21, C1)."""
497
  return self._st
498
 
499
+ def find_view(self, view_id, prefer_owner=None):
500
  """`(owner_username, view)` for a view living in ANY personal stratum, else None.
501
 
502
  ⭐ Wave 21 (item 9, C1): the R10 grant registry names bare ids, so projecting a granted
503
  view means locating the OWNER's record inside this topic's bucket. Saved Views have
504
  one home only: a personal source record. The tenant-wide member is reserved for field
505
+ annotations, so serving a View from a second home cannot reappear by accident.
506
+
507
+ ⛔ `prefer_owner` (2026-09-02, wave-48 go-live QA, W48C-T02). The SYSTEM view id
508
+ `all-customers` is pinned on every database, and every user who has ever touched the
509
+ system view's config holds their OWN saved-config record under that id. A bare first-hit
510
+ scan therefore answered whichever stratum the dict happened to yield first - so starring
511
+ `All products` wrote `important` onto a colleague's overlay record and the caller's own
512
+ rail never changed, with a 200 and nothing red. A caller that names itself gets its own
513
+ record when one exists; the scan below is unchanged otherwise."""
514
  # A direct lookup is a runtime read too. Do not leave a stale compatibility-shaped
515
  # personal record reachable merely because this caller did not first go through the grid
516
  # workspace assembler.
 
522
  data = self._st.get(self.table_key) or {}
523
  except Exception:
524
  return None
525
+ mine = str(prefer_owner or '').strip()
526
+ if mine and mine not in (SHARED_KEY, ASSIGNED_KEY):
527
+ own = data.get(mine)
528
+ v = (own.get('views') or {}).get(vid) if isinstance(own, dict) else None
529
+ if isinstance(v, dict):
530
+ return mine, dict(v)
531
  for username, ws in data.items():
532
  if username in (SHARED_KEY, ASSIGNED_KEY) or not isinstance(ws, dict):
533
  continue
 
678
  window is real rather than theoretical. One `update`, one flush, one failure mode.
679
  """
680
  def _up(data):
681
+ # A store that has never held this table hands the callback its "absent" value; the
682
+ # real stores spell that `{}`, an in-memory double may spell it `None`. A write must
683
+ # start from an empty document either way, never crash on the spelling.
684
+ data = data if isinstance(data, dict) else {}
685
  ws = data.setdefault(username, {})
686
  ws.setdefault('views', {})
687
  ws.setdefault('fields', {})
 
718
  """
719
  return self._update(username, change)
720
 
721
+ def choice_usage(self, username, key, options, *, multi=False):
722
+ """How many of THIS user's overlay cells for `key` hold one of `options`."""
723
+ from core import choice_removal as _cr
724
+ fold = _cr.folded(options)
725
+ if not fold:
726
+ return 0
727
+ ws = self.workspace(username)
728
+ return _cr.count_cells((ws.get('overlays') or {}).values(), str(key or ''), fold,
729
+ multi=multi)
730
+
731
+ def remove_choice_values(self, username, key, options, *, multi=False):
732
+ """Retire `options` from this user's field definition, overlay cells and view filters, in
733
+ ONE transaction - the removal twin of `rename_choice_values` (owner, 2026-09-02).
734
+
735
+ Three strata move together for the reason the rename docstring gives: a definition that
736
+ lost the label while cells kept it would re-hydrate the option from values, and a saved
737
+ view that still filtered `is "Acme"` would silently match nothing. List-valued filter
738
+ rules drop the member; a scalar rule naming the retired option is left as it is, because
739
+ deleting a rule changes what a view SHOWS and that is the owner's call, not this door's.
740
+ Returns `{'options': n, 'cells': n, 'views': n}`.
741
+ """
742
+ from core import choice_removal as _cr
743
+ fold = _cr.folded(options)
744
+ key = str(key or '').strip()
745
+ counts = {'options': 0, 'cells': 0, 'views': 0}
746
+ if not fold or not key or username == SHARED_KEY:
747
+ return counts
748
+
749
+ def _remove(ws):
750
+ fld = (ws.get('fields') or {}).get(key)
751
+ if isinstance(fld, dict):
752
+ for member in ('options', 'choices'):
753
+ if isinstance(fld.get(member), list):
754
+ before = len(fld[member])
755
+ fld[member] = _cr.without(fld[member], fold)
756
+ counts['options'] += before - len(fld[member])
757
+ colors = fld.get('optionColors')
758
+ if isinstance(colors, dict):
759
+ for label in list(colors):
760
+ if str(label).casefold() in fold:
761
+ colors.pop(label, None)
762
+ for row in (ws.get('overlays') or {}).values():
763
+ if not isinstance(row, dict) or key not in row:
764
+ continue
765
+ new, changed = _cr.strip_value(row[key], fold, multi=multi, blank='')
766
+ if changed:
767
+ row[key] = new
768
+ counts['cells'] += 1
769
+ for view in (ws.get('views') or {}).values():
770
+ if not isinstance(view, dict):
771
+ continue
772
+ cfg = view.get('config') if isinstance(view.get('config'), dict) else view
773
+
774
+ def _walk(nodes):
775
+ for n in nodes or ():
776
+ if not isinstance(n, dict):
777
+ continue
778
+ if isinstance(n.get('children'), list):
779
+ _walk(n['children'])
780
+ continue
781
+ if str(n.get('colId') or '') != key:
782
+ continue
783
+ v = n.get('value')
784
+ if isinstance(v, list):
785
+ kept = [x for x in v if str(x).casefold() not in fold]
786
+ if len(kept) != len(v):
787
+ n['value'] = kept
788
+ counts['views'] += 1
789
+
790
+ _walk(cfg.get('filters') or [])
791
+
792
+ self._update(username, _remove)
793
+ return counts
794
+
795
  def save_active_view(self, username, view_id):
796
  """Remember which view this user last opened (owner item 3, 2026-07-31).
797
 
 
910
  except Exception as exc: # no migration decision may start from a display fallback
911
  raise LegacySharedViewMigrationError(
912
  'legacy shared-view migration could not read the workspace document') from exc
913
+ if data is None:
914
+ # ABSENT is not UNREADABLE. A store that has never held this table's workspace
915
+ # answers None (the in-memory doubles do; the strict readers answer {}), and a brand
916
+ # new table or tenant has nothing to migrate. A transient read error still RAISES
917
+ # above; only the honest "no document" degrades to the empty workspace. Found by
918
+ # `web_rollup_editor` and `api_automation` going red over fixtures with no views.
919
+ return {}
920
  if not isinstance(data, dict):
921
  raise LegacySharedViewMigrationError(
922
  'legacy shared-view migration found a non-object workspace document')
platform/core/user_tables.py CHANGED
@@ -4616,3 +4616,65 @@ def nav_entries(viewer=None, is_admin=False, st=None):
4616
  'source': source, 'sourceGroup': source_group,
4617
  'user_table': True, 'nav': True, 'validate': False})
4618
  return out
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4616
  'source': source, 'sourceGroup': source_group,
4617
  'user_table': True, 'nav': True, 'validate': False})
4618
  return out
4619
+
4620
+
4621
+ # ----------------------------------------------------------------- choice removal (2026-09-02)
4622
+ def choice_usage(table_key, fkey, options, st=None):
4623
+ """How many rows of a user database hold one of `options` in column `fkey`."""
4624
+ from core import choice_removal as _cr
4625
+ fold = _cr.folded(options)
4626
+ t = get(table_key, st) or {}
4627
+ if not fold or not t:
4628
+ return 0
4629
+ multi = any(f.get('key') == str(fkey) and f.get('type') == 'multiselect'
4630
+ for f in (t.get('fields') or []) if isinstance(f, dict))
4631
+ return _cr.count_cells((t.get('rows') or {}).values(), str(fkey), fold, multi=multi)
4632
+
4633
+
4634
+ def remove_choice_values(table_key, fkey, options, st=None):
4635
+ """Retire `options` from a user-database column's vocabulary AND its stored cells - the
4636
+ removal twin of `rename_choice_values`, one store update. Returns `{'options': n, 'cells': n}`.
4637
+
4638
+ A stripped cell that ends up empty is POPPED, which is how `patch_cells` spells "no value"
4639
+ for a user table; a multiselect keeps its remaining members comma-joined.
4640
+ """
4641
+ from core import choice_removal as _cr
4642
+ fold = _cr.folded(options)
4643
+ if not fold or not is_user_table(table_key, st):
4644
+ return {'options': 0, 'cells': 0}
4645
+ counts = {'options': 0, 'cells': 0}
4646
+
4647
+ def _apply(cur):
4648
+ t = cur.get(str(table_key))
4649
+ if t is None:
4650
+ return cur
4651
+ multi = False
4652
+ for f in (t.get('fields') or []):
4653
+ if not isinstance(f, dict) or f.get('key') != str(fkey):
4654
+ continue
4655
+ multi = f.get('type') == 'multiselect'
4656
+ opts = f.get('options') or []
4657
+ kept = _cr.without(opts, fold)
4658
+ counts['options'] = len(opts) - len(kept)
4659
+ if opts:
4660
+ f['options'] = kept
4661
+ colors = f.get('optionColors')
4662
+ if isinstance(colors, dict):
4663
+ for label in list(colors):
4664
+ if str(label).casefold() in fold:
4665
+ colors.pop(label, None)
4666
+ for row in (t.get('rows') or {}).values():
4667
+ if not isinstance(row, dict) or str(fkey) not in row:
4668
+ continue
4669
+ new, changed = _cr.strip_value(row.get(str(fkey)), fold, multi=multi, blank='')
4670
+ if not changed:
4671
+ continue
4672
+ if new in ('', None) or new == []:
4673
+ row.pop(str(fkey), None)
4674
+ else:
4675
+ row[str(fkey)] = new
4676
+ counts['cells'] += 1
4677
+ return cur
4678
+
4679
+ _st(st).update(STORE_KEY, _apply, flush='sync')
4680
+ return counts
web/src/customer-grid/ColumnMenu.tsx CHANGED
@@ -20,7 +20,7 @@ import { columnDefinitionOffer } from "./display";
20
  // `columnDefinitionOffer` sits in `display.ts`: this file imports React, so nothing stated inside
21
  // it can be LOADED by a node gate, and "which types are advanced" is exactly the kind of decision
22
  // that must be runnable rather than read back to itself as source text.
23
- import { CODE_LANGUAGE_LABELS, CODE_LANGUAGES, CREATABLE_TYPES, choiceOptions, choiceRenames,
24
  codeLanguageOf, directionLabel, groupTypePickerRows, isDerivedLink, isMachineOwned,
25
  isOfferableField, isProfileField, offerableCreateKind, parseOptions, ratingMax,
26
  ROLLUP_FN_LABELS, ROLLUP_FNS, ROLLUP_PRESET_FNS, ROLLUP_PRESETS, rollupPresetOf,
@@ -60,6 +60,7 @@ import { BRAND_SWATCHES, defaultOptionColor, nearestSwatch, normalizeOptionColor
60
  OPTION_PALETTE } from "./choiceColors";
61
  import { fieldDeletionLocked } from "./FieldProperties";
62
 
 
63
  export interface ColumnMenuState {
64
  fieldKey: string;
65
  anchor: AnchorRect;
@@ -243,6 +244,13 @@ interface ColumnMenuProps {
243
  options?: string[],
244
  extra?: FieldConfigExtra
245
  ) => void;
 
 
 
 
 
 
 
246
  /**
247
  * ⭐⭐ 2026-08-09 (owner) — RECONFIGURE an existing `link`/`rollup` column's bag.
248
  *
@@ -302,7 +310,12 @@ interface ColumnMenuProps {
302
  * caller emits the ordinary `field_upsert` (and auto-renames the header when the user never
303
  * renamed it).
304
  */
305
- onPeriod?: (window: WindowSpec) => void;
 
 
 
 
 
306
  /**
307
  * Delete this USER-CREATED column outright (owner gap closed 2026-07-27). Supplied ONLY for
308
  * the deletable strata (`custom_` overlay fields, `measure_` formula columns) — absent means
@@ -837,6 +850,7 @@ function OptionsEditor({
837
  onColorCode,
838
  type,
839
  maxOptions,
 
840
  }: {
841
  idPrefix: string;
842
  drafts: OptionDraft[];
@@ -845,6 +859,9 @@ function OptionsEditor({
845
  onColorCode: (next: boolean) => void;
846
  type: CreateKind;
847
  maxOptions: number | null;
 
 
 
848
  }) {
849
  const update = (id: string, patch: Partial<OptionDraft>) =>
850
  onDrafts(drafts.map((draft) => (draft.id === id ? { ...draft, ...patch } : draft)));
@@ -907,7 +924,11 @@ function OptionsEditor({
907
  className="cg-option-remove"
908
  aria-label={`Remove ${draft.label || `option ${index + 1}`}`}
909
  title="Remove option"
910
- onClick={() => onDrafts(drafts.filter((item) => item.id !== draft.id))}
 
 
 
 
911
  >
912
  <svg viewBox="0 0 16 16" aria-hidden="true">
913
  <path d="M4 4l8 8M12 4l-8 8" />
@@ -2442,6 +2463,7 @@ export default function ColumnMenu({
2442
  onCreateAndSwap,
2443
  onProfileFlag,
2444
  onRetype,
 
2445
  onFieldConfig,
2446
  onRename,
2447
  onFormula,
@@ -2687,6 +2709,67 @@ export default function ColumnMenu({
2687
  editOptionOrigin.current = new Map(
2688
  editOptionDrafts.map((draft) => [draft.id, draft.label.trim()])
2689
  );
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2690
  const [editColorCode, setEditColorCode] = useState(field.colorCodeOptions !== false);
2691
  const [retypeMaxValue, setRetypeMaxValue] = useState(() => ratingMax(field));
2692
  const [editFormulaText, setEditFormulaText] = useState(() =>
@@ -3113,6 +3196,8 @@ export default function ColumnMenu({
3113
  draftWindow != null &&
3114
  JSON.stringify(draftWindow) !== JSON.stringify(currentWindow);
3115
  const canPeriod = !!field.measure && !!onPeriod;
 
 
3116
  /**
3117
  * ⭐⭐ 2026-08-09 — THE RELATIONAL EDIT: is this pane driving a `link`/`rollup` bag?
3118
  *
@@ -3185,7 +3270,7 @@ export default function ColumnMenu({
3185
  (field.type !== "link" ||
3186
  (editLinkTable !== "" && !hopIncomplete(editHopDraft, hopScopeKey))))
3187
  : (editNameDirty || editRetypeTouched || editFormulaTouched ||
3188
- (canPeriod && periodChanged) || editNoteDirty)));
3189
  /**
3190
  * Item 15 — the renames, by ROW IDENTITY. A row that kept its id and changed its label was
3191
  * renamed; a row with an id nobody has seen is new; an id that is gone was deleted. Empty
@@ -3306,7 +3391,9 @@ export default function ColumnMenu({
3306
  // the identity edit, so it applies ALONGSIDE whatever the chain above did rather than
3307
  // instead of it: renaming "Sales YTD" to "Sales" and re-pointing it at the last 90 days
3308
  // is one edit to the user and must not silently drop half of itself.
3309
- if (canPeriod && periodChanged && draftWindow) onPeriod!(draftWindow);
 
 
3310
  if (editNoteDirty) onNote(note);
3311
  onClose();
3312
  };
@@ -4094,8 +4181,39 @@ export default function ColumnMenu({
4094
  onColorCode={setEditColorCode}
4095
  type={editType}
4096
  maxOptions={optionLimit}
 
4097
  />
4098
  )}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4099
  {editType !== field.type && (
4100
  <div className="cg-field-hint">
4101
  Changes {field.label} into a {TYPE_LABELS[editType].toLowerCase()} field,
@@ -4113,6 +4231,22 @@ export default function ColumnMenu({
4113
  It shares this pane's ONE Save (`applyEdit` applies it alongside a rename) —
4114
  the old "Apply period" button became a second primary action in a pane that
4115
  already had one, which is the ambiguity the move was supposed to remove. */}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4116
  {canPeriod && (
4117
  <label className="cg-edit-period">
4118
  <span>Period</span>
 
20
  // `columnDefinitionOffer` sits in `display.ts`: this file imports React, so nothing stated inside
21
  // it can be LOADED by a node gate, and "which types are advanced" is exactly the kind of decision
22
  // that must be runnable rather than read back to itself as source text.
23
+ import { CODE_LANGUAGE_LABELS, CODE_LANGUAGES, CREATABLE_TYPES, choiceOptions, choiceRemovalMessage, choiceRenames,
24
  codeLanguageOf, directionLabel, groupTypePickerRows, isDerivedLink, isMachineOwned,
25
  isOfferableField, isProfileField, offerableCreateKind, parseOptions, ratingMax,
26
  ROLLUP_FN_LABELS, ROLLUP_FNS, ROLLUP_PRESET_FNS, ROLLUP_PRESETS, rollupPresetOf,
 
60
  OPTION_PALETTE } from "./choiceColors";
61
  import { fieldDeletionLocked } from "./FieldProperties";
62
 
63
+ import type { ChoiceRemoval } from "./apiBridge";
64
  export interface ColumnMenuState {
65
  fieldKey: string;
66
  anchor: AnchorRect;
 
244
  options?: string[],
245
  extra?: FieldConfigExtra
246
  ) => void;
247
+ /**
248
+ * Owner, 2026-09-02 - retire a SAVED option of this choice field, with the cells that hold it.
249
+ * `confirm: false` answers how many cells use it (the warning); `confirm: true` removes the
250
+ * option and clears those values, immediately. Supplied beside `onRetype`, for the same fields,
251
+ * by the same predicate, so a field whose type cannot be edited cannot lose options either.
252
+ */
253
+ onChoiceRemove?: (option: string, confirm: boolean) => Promise<ChoiceRemoval | null>;
254
  /**
255
  * ⭐⭐ 2026-08-09 (owner) — RECONFIGURE an existing `link`/`rollup` column's bag.
256
  *
 
310
  * caller emits the ordinary `field_upsert` (and auto-renames the header when the user never
311
  * renamed it).
312
  */
313
+ /**
314
+ * W48C-T12 (go-live QA 2026-09-02): the Edit pane exposes the SAME Metric controls as Create -
315
+ * the Number (which measure) and the Period. `measureKey` rides beside the window when the
316
+ * person picked a different number; absent, the number is unchanged. One upsert either way.
317
+ */
318
+ onPeriod?: (window: WindowSpec, measureKey?: string) => void;
319
  /**
320
  * Delete this USER-CREATED column outright (owner gap closed 2026-07-27). Supplied ONLY for
321
  * the deletable strata (`custom_` overlay fields, `measure_` formula columns) — absent means
 
850
  onColorCode,
851
  type,
852
  maxOptions,
853
+ onRemove,
854
  }: {
855
  idPrefix: string;
856
  drafts: OptionDraft[];
 
859
  onColorCode: (next: boolean) => void;
860
  type: CreateKind;
861
  maxOptions: number | null;
862
+ /** When supplied, the X on a row asks the parent (which may need to warn) instead of
863
+ * dropping the draft itself. The create pane never supplies it: nothing there is saved. */
864
+ onRemove?: (draft: OptionDraft) => void;
865
  }) {
866
  const update = (id: string, patch: Partial<OptionDraft>) =>
867
  onDrafts(drafts.map((draft) => (draft.id === id ? { ...draft, ...patch } : draft)));
 
924
  className="cg-option-remove"
925
  aria-label={`Remove ${draft.label || `option ${index + 1}`}`}
926
  title="Remove option"
927
+ onClick={() =>
928
+ onRemove
929
+ ? onRemove(draft)
930
+ : onDrafts(drafts.filter((item) => item.id !== draft.id))
931
+ }
932
  >
933
  <svg viewBox="0 0 16 16" aria-hidden="true">
934
  <path d="M4 4l8 8M12 4l-8 8" />
 
2463
  onCreateAndSwap,
2464
  onProfileFlag,
2465
  onRetype,
2466
+ onChoiceRemove,
2467
  onFieldConfig,
2468
  onRename,
2469
  onFormula,
 
2709
  editOptionOrigin.current = new Map(
2710
  editOptionDrafts.map((draft) => [draft.id, draft.label.trim()])
2711
  );
2712
+ /** W48C-T12 - the Edit pane's NUMBER draft for a Metric column, seeded from the field itself.
2713
+ * The create pane has always offered "Number" beside "Period"; the edit pane offered only the
2714
+ * period, so a saved Metric could never be pointed at a different measure (the go-live QA of
2715
+ * 2026-09-02 reproduced exactly that). */
2716
+ const [editMeasureKey, setEditMeasureKey] = useState<string>(() => field.measure?.key ?? "");
2717
+ /**
2718
+ * Owner, 2026-09-02 - REMOVING A SAVED OPTION WARNS, THEN CLEARS ITS CELLS. The X on an option
2719
+ * row used to drop the draft and let Save write a shorter list, which orphaned every cell that
2720
+ * held the label (they rendered as a value that was no longer an option). Now a row whose
2721
+ * ORIGIN label is a saved option asks the server how many cells use it: none, and it is removed
2722
+ * at once; some, and a confirmation names the count and the consequence before anything moves.
2723
+ * A draft that was never saved simply leaves the list, as before.
2724
+ */
2725
+ const [pendingRemoval, setPendingRemoval] =
2726
+ useState<{ draftId: string; label: string; cells: number } | null>(null);
2727
+ const [removalBusy, setRemovalBusy] = useState(false);
2728
+ const [removalError, setRemovalError] = useState<string | null>(null);
2729
+ const dropEditDraft = (draftId: string) => {
2730
+ setEditOptionDrafts((current) => current.filter((item) => item.id !== draftId));
2731
+ editOptionOrigin.current.delete(draftId);
2732
+ };
2733
+ const requestOptionRemoval = async (draft: OptionDraft) => {
2734
+ const savedLabel = editOptionOrigin.current.get(draft.id) ?? "";
2735
+ const isSaved =
2736
+ !!savedLabel &&
2737
+ choiceOptions(field).some((o) => o.toLowerCase() === savedLabel.toLowerCase());
2738
+ if (!onChoiceRemove || !isSaved) {
2739
+ dropEditDraft(draft.id);
2740
+ return;
2741
+ }
2742
+ setRemovalError(null);
2743
+ setRemovalBusy(true);
2744
+ const probe = await onChoiceRemove(savedLabel, false);
2745
+ if (!probe) {
2746
+ setRemovalBusy(false);
2747
+ setRemovalError("Could not check where this option is used. Reload the database, then try again.");
2748
+ return;
2749
+ }
2750
+ if (probe.cells === 0) {
2751
+ const done = await onChoiceRemove(savedLabel, true);
2752
+ setRemovalBusy(false);
2753
+ if (done?.applied) dropEditDraft(draft.id);
2754
+ else setRemovalError("The option was not removed. Reload the database, then try again.");
2755
+ return;
2756
+ }
2757
+ setRemovalBusy(false);
2758
+ setPendingRemoval({ draftId: draft.id, label: savedLabel, cells: probe.cells });
2759
+ };
2760
+ const confirmOptionRemoval = async () => {
2761
+ if (!pendingRemoval || !onChoiceRemove) return;
2762
+ setRemovalError(null);
2763
+ setRemovalBusy(true);
2764
+ const done = await onChoiceRemove(pendingRemoval.label, true);
2765
+ setRemovalBusy(false);
2766
+ if (!done?.applied) {
2767
+ setRemovalError("The option was not removed. Reload the database, then try again.");
2768
+ return;
2769
+ }
2770
+ dropEditDraft(pendingRemoval.draftId);
2771
+ setPendingRemoval(null);
2772
+ };
2773
  const [editColorCode, setEditColorCode] = useState(field.colorCodeOptions !== false);
2774
  const [retypeMaxValue, setRetypeMaxValue] = useState(() => ratingMax(field));
2775
  const [editFormulaText, setEditFormulaText] = useState(() =>
 
3196
  draftWindow != null &&
3197
  JSON.stringify(draftWindow) !== JSON.stringify(currentWindow);
3198
  const canPeriod = !!field.measure && !!onPeriod;
3199
+ const measureChanged =
3200
+ canPeriod && !!editMeasureKey && editMeasureKey !== (field.measure?.key ?? "");
3201
  /**
3202
  * ⭐⭐ 2026-08-09 — THE RELATIONAL EDIT: is this pane driving a `link`/`rollup` bag?
3203
  *
 
3270
  (field.type !== "link" ||
3271
  (editLinkTable !== "" && !hopIncomplete(editHopDraft, hopScopeKey))))
3272
  : (editNameDirty || editRetypeTouched || editFormulaTouched ||
3273
+ (canPeriod && (periodChanged || measureChanged)) || editNoteDirty)));
3274
  /**
3275
  * Item 15 — the renames, by ROW IDENTITY. A row that kept its id and changed its label was
3276
  * renamed; a row with an id nobody has seen is new; an id that is gone was deleted. Empty
 
3391
  // the identity edit, so it applies ALONGSIDE whatever the chain above did rather than
3392
  // instead of it: renaming "Sales YTD" to "Sales" and re-pointing it at the last 90 days
3393
  // is one edit to the user and must not silently drop half of itself.
3394
+ if (canPeriod && (periodChanged || measureChanged))
3395
+ onPeriod!(draftWindow ?? field.measure!.window,
3396
+ measureChanged ? editMeasureKey : undefined);
3397
  if (editNoteDirty) onNote(note);
3398
  onClose();
3399
  };
 
4181
  onColorCode={setEditColorCode}
4182
  type={editType}
4183
  maxOptions={optionLimit}
4184
+ onRemove={onChoiceRemove ? (draft) => void requestOptionRemoval(draft) : undefined}
4185
  />
4186
  )}
4187
+ {needsOptions(editType) && (pendingRemoval || removalError) && (
4188
+ <div className="cg-option-confirm" role="alert">
4189
+ {pendingRemoval ? (
4190
+ <>
4191
+ <strong>Remove {pendingRemoval.label}?</strong>
4192
+ <span>{choiceRemovalMessage(pendingRemoval.cells)}</span>
4193
+ <div className="cg-option-confirm-actions">
4194
+ <button
4195
+ type="button"
4196
+ className="cg-btn"
4197
+ disabled={removalBusy}
4198
+ onClick={() => setPendingRemoval(null)}
4199
+ >
4200
+ Cancel
4201
+ </button>
4202
+ <button
4203
+ type="button"
4204
+ className="cg-btn cg-btn--primary"
4205
+ disabled={removalBusy}
4206
+ onClick={() => void confirmOptionRemoval()}
4207
+ >
4208
+ {removalBusy ? "Removing" : "Remove option"}
4209
+ </button>
4210
+ </div>
4211
+ </>
4212
+ ) : (
4213
+ <span>{removalError}</span>
4214
+ )}
4215
+ </div>
4216
+ )}
4217
  {editType !== field.type && (
4218
  <div className="cg-field-hint">
4219
  Changes {field.label} into a {TYPE_LABELS[editType].toLowerCase()} field,
 
4231
  It shares this pane's ONE Save (`applyEdit` applies it alongside a rename) —
4232
  the old "Apply period" button became a second primary action in a pane that
4233
  already had one, which is the ambiguity the move was supposed to remove. */}
4234
+ {canPeriod && measures.length > 0 && (
4235
+ <label className="cg-edit-measure">
4236
+ <span>Number</span>
4237
+ {/* W48C-T12 - the SAME picker the create pane renders, same aria-label, so the
4238
+ two flows are equivalent by construction rather than by resemblance. */}
4239
+ <FieldSelectButton
4240
+ ariaLabel="Number to summarise"
4241
+ placeholder="Choose a number…"
4242
+ value={editMeasureKey || undefined}
4243
+ onChange={setEditMeasureKey}
4244
+ fields={measures.map((m) => ({
4245
+ key: m.key, label: m.label, type: "measure" as const,
4246
+ }))}
4247
+ />
4248
+ </label>
4249
+ )}
4250
  {canPeriod && (
4251
  <label className="cg-edit-period">
4252
  <span>Period</span>
web/src/customer-grid/CustomerGrid.tsx CHANGED
@@ -86,7 +86,7 @@ import { API_V1, CREDENTIALS, NAV_MINIMIZE_EVENT, ROWS_STALE_EVENT, TOAST_EVENT,
86
  import type { ViewOpenDetail } from "../apiContract";
87
  import { addTableField, addTableRow, clearTopicRowsCache, deleteTableField,
88
  deleteTableFields, deleteTableRow, dropTableRowsCache, fetchLinkTargets, refusalMessage,
89
- fetchHopTopics, fetchRollupSources, patchTableField, enrichField } from "./apiBridge";
90
  import type { FieldDeleteResult, HopTopicOffer, LinkTarget, RollupSourceOffer } from "./apiBridge";
91
  import SelectFromFile from "./SelectFromFile";
92
  import ImportDialog from "./ImportDialog";
@@ -6964,6 +6964,40 @@ function CustomerGridSurface({
6964
  * blank (Airtable behavior, disclosed in the pane). A display `format` survives only within
6965
  * its own family (number→number); anything else would be junk the host drops anyway.
6966
  */
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6967
  const retypeField = useCallback(
6968
  (
6969
  key: string,
@@ -7132,16 +7166,22 @@ function CustomerGridSurface({
7132
  * the next payload; the ordinary `field_upsert` is the whole protocol.
7133
  */
7134
  const changeMeasurePeriod = useCallback(
7135
- (key: string, window: WindowSpec) => {
7136
  const f = fieldByKey.get(key);
7137
  if (!f?.measure) return;
7138
- const m = measures.find((item) => item.key === f.measure?.key);
7139
- const oldAuto = m ? `${m.label} · ${windowLabel(f.measure.window)}` : null;
 
 
 
 
 
 
7140
  const label =
7141
- m && oldAuto && f.label === oldAuto
7142
- ? `${m.label} · ${windowLabel(window)}`
7143
  : f.label;
7144
- saveField({ ...f, label, measure: { ...f.measure, window } });
7145
  },
7146
  [fieldByKey, measures, saveField]
7147
  );
@@ -9886,6 +9926,13 @@ function CustomerGridSurface({
9886
  : undefined
9887
  }
9888
  onCopyFieldLink={() => copyFieldDataLink(menuField.key)}
 
 
 
 
 
 
 
9889
  onRetype={
9890
  // Item 2 — a CREATED field retypes IN PLACE from the pane.
9891
  //
@@ -9954,7 +10001,7 @@ function CustomerGridSurface({
9954
  }
9955
  onPeriod={
9956
  menuField.measure
9957
- ? (w) => changeMeasurePeriod(menuField.key, w)
9958
  : undefined
9959
  }
9960
  /**
 
86
  import type { ViewOpenDetail } from "../apiContract";
87
  import { addTableField, addTableRow, clearTopicRowsCache, deleteTableField,
88
  deleteTableFields, deleteTableRow, dropTableRowsCache, fetchLinkTargets, refusalMessage,
89
+ fetchHopTopics, fetchRollupSources, patchTableField, enrichField, removeChoice } from "./apiBridge";
90
  import type { FieldDeleteResult, HopTopicOffer, LinkTarget, RollupSourceOffer } from "./apiBridge";
91
  import SelectFromFile from "./SelectFromFile";
92
  import ImportDialog from "./ImportDialog";
 
6964
  * blank (Airtable behavior, disclosed in the pane). A display `format` survives only within
6965
  * its own family (number→number); anything else would be junk the host drops anyway.
6966
  */
6967
+ /**
6968
+ * Owner, 2026-09-02 - retire a SAVED option of a choice field WITH the cells that hold it. The
6969
+ * count and the write are the server's (`POST /grid/choice-remove`); this keeps the local field
6970
+ * list honest and tells the rows and the workspace to re-read, so the cleared cells and the
6971
+ * shorter picker arrive from the store rather than from a guess.
6972
+ */
6973
+ const removeChoiceValues = useCallback(
6974
+ async (key: string, option: string, confirm: boolean) => {
6975
+ const result = await removeChoice(scope, key, [option], confirm);
6976
+ if (result?.applied) {
6977
+ setFields((current) =>
6978
+ current.map((f) =>
6979
+ f.key === key && Array.isArray(f.options)
6980
+ ? { ...f, options: f.options.filter((o) => o.toLowerCase() !== option.toLowerCase()) }
6981
+ : f
6982
+ )
6983
+ );
6984
+ signal(ROWS_STALE_EVENT);
6985
+ signal(WORKSPACE_STALE_EVENT);
6986
+ const label = fieldByKey.get(key)?.label ?? key;
6987
+ signal(
6988
+ TOAST_EVENT,
6989
+ result.cells === 0
6990
+ ? `Removed ${option} from ${label}.`
6991
+ : `Removed ${option} from ${label} and cleared ${result.cells.toLocaleString("en-US")} ${
6992
+ result.cells === 1 ? "cell" : "cells"
6993
+ }.`
6994
+ );
6995
+ }
6996
+ return result;
6997
+ },
6998
+ [scope, fieldByKey]
6999
+ );
7000
+
7001
  const retypeField = useCallback(
7002
  (
7003
  key: string,
 
7166
  * the next payload; the ordinary `field_upsert` is the whole protocol.
7167
  */
7168
  const changeMeasurePeriod = useCallback(
7169
+ (key: string, window: WindowSpec, measureKey?: string) => {
7170
  const f = fieldByKey.get(key);
7171
  if (!f?.measure) return;
7172
+ // W48C-T12: the Edit pane may change the NUMBER as well as the period. The auto-name
7173
+ // ("Sales · the last 12 months") follows whichever half moved, and a hand-typed name is
7174
+ // left alone exactly as before; the server re-validates the measure key against this
7175
+ // caller's offer (`clean_measure_field`), so an unadmitted number is refused there.
7176
+ const nextKey = measureKey && measureKey !== f.measure.key ? measureKey : f.measure.key;
7177
+ const oldM = measures.find((item) => item.key === f.measure?.key);
7178
+ const nextM = measures.find((item) => item.key === nextKey);
7179
+ const oldAuto = oldM ? `${oldM.label} · ${windowLabel(f.measure.window)}` : null;
7180
  const label =
7181
+ nextM && oldAuto && f.label === oldAuto
7182
+ ? `${nextM.label} · ${windowLabel(window)}`
7183
  : f.label;
7184
+ saveField({ ...f, label, measure: { ...f.measure, key: nextKey, window } });
7185
  },
7186
  [fieldByKey, measures, saveField]
7187
  );
 
9926
  : undefined
9927
  }
9928
  onCopyFieldLink={() => copyFieldDataLink(menuField.key)}
9929
+ onChoiceRemove={
9930
+ // Same predicate as `onRetype` below: a field whose type this pane may edit is a field
9931
+ // whose options it may retire, and no other.
9932
+ isUserSchemaField(menuField, isUserTable)
9933
+ ? (option, confirm) => removeChoiceValues(menuField.key, option, confirm)
9934
+ : undefined
9935
+ }
9936
  onRetype={
9937
  // Item 2 — a CREATED field retypes IN PLACE from the pane.
9938
  //
 
10001
  }
10002
  onPeriod={
10003
  menuField.measure
10004
+ ? (w, measureKey) => changeMeasurePeriod(menuField.key, w, measureKey)
10005
  : undefined
10006
  }
10007
  /**
web/src/customer-grid/apiBridge.ts CHANGED
@@ -1038,6 +1038,55 @@ export async function patchTableField(
1038
  }
1039
  }
1040
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1041
  /**
1042
  * ⭐⭐ 2026-08-10 — REMOVE a column from a user database's SHARED definition.
1043
  *
 
1038
  }
1039
  }
1040
 
1041
+ /**
1042
+ * Owner, 2026-09-02 - REMOVE a select / multiselect OPTION together with the cells that hold it.
1043
+ * TWO PHASES through one door: `confirm: false` COUNTS server-side (the browser holds one page of
1044
+ * rows and the field's universe is uncapped, so a count taken here would be wrong exactly when it
1045
+ * matters); `confirm: true` retires the option and clears its values in this user's stratum, the
1046
+ * tenant-wide stratum and a user database's rows alike. The server owns the wall.
1047
+ */
1048
+ export interface ChoiceRemoval {
1049
+ key: string;
1050
+ options: string[];
1051
+ cells: number;
1052
+ applied: boolean;
1053
+ usage?: Record<string, number>;
1054
+ }
1055
+
1056
+ export async function removeChoice(
1057
+ scope: SurfaceScope,
1058
+ key: string,
1059
+ options: string[],
1060
+ confirm: boolean
1061
+ ): Promise<ChoiceRemoval | null> {
1062
+ try {
1063
+ const res = await fetch(`${API_V1}/grid/choice-remove?scope=${encodeURIComponent(scope)}`, {
1064
+ method: "POST", credentials: CREDENTIALS, headers: JSON_HEADERS,
1065
+ body: JSON.stringify({ key, options, confirm }),
1066
+ });
1067
+ if (handledSession(res)) return null;
1068
+ const body = await readJson(res);
1069
+ if (!res.ok) {
1070
+ signal(TOAST_EVENT, refusalMessage(body, res.status, "That option could not be removed."));
1071
+ return null;
1072
+ }
1073
+ const got = body as Partial<ChoiceRemoval> | null;
1074
+ if (!got || typeof got.cells !== "number") return null;
1075
+ return {
1076
+ key: String(got.key ?? key),
1077
+ options: Array.isArray(got.options) ? got.options.map(String) : options,
1078
+ cells: got.cells,
1079
+ applied: got.applied === true,
1080
+ ...(got.usage && typeof got.usage === "object"
1081
+ ? { usage: got.usage as Record<string, number> }
1082
+ : {}),
1083
+ };
1084
+ } catch {
1085
+ signal(TOAST_EVENT, "That change did not reach the server.");
1086
+ return null;
1087
+ }
1088
+ }
1089
+
1090
  /**
1091
  * ⭐⭐ 2026-08-10 — REMOVE a column from a user database's SHARED definition.
1092
  *
web/src/customer-grid/types.ts CHANGED
@@ -3261,6 +3261,17 @@ export function isRuleActive(rule: FilterRule): boolean {
3261
  * Lives in types.ts, not beside the editor, for the usual reason: ColumnMenu imports React and
3262
  * cannot be loaded by a node gate, and this is the half that has to be right.
3263
  */
 
 
 
 
 
 
 
 
 
 
 
3264
  export function choiceRenames(
3265
  rows: readonly { id: string; label: string }[],
3266
  origin: ReadonlyMap<string, string>,
 
3261
  * Lives in types.ts, not beside the editor, for the usual reason: ColumnMenu imports React and
3262
  * cannot be loaded by a node gate, and this is the half that has to be right.
3263
  */
3264
+ /**
3265
+ * Owner, 2026-09-02 - the sentence the Remove-option warning shows. The count is the SERVER's
3266
+ * (the browser holds one page of rows); the copy names the consequence and carries no dash
3267
+ * (standing rule 2).
3268
+ */
3269
+ export function choiceRemovalMessage(cells: number): string {
3270
+ const n = Math.max(0, Math.floor(cells));
3271
+ if (n === 1) return "1 cell uses it. Its value will be cleared.";
3272
+ return `${n.toLocaleString("en-US")} cells use it. Their values will be cleared.`;
3273
+ }
3274
+
3275
  export function choiceRenames(
3276
  rows: readonly { id: string; label: string }[],
3277
  origin: ReadonlyMap<string, string>,
web/src/index.css CHANGED
@@ -1865,6 +1865,27 @@ body > .cg-overlay {
1865
  stroke-width: 1.6;
1866
  stroke-linecap: round;
1867
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1868
  .cg-option-add {
1869
  justify-self: start;
1870
  padding: 2px 0;
 
1865
  stroke-width: 1.6;
1866
  stroke-linecap: round;
1867
  }
1868
+ /* Owner, 2026-09-02: the warning under the options list when a SAVED option in use is removed.
1869
+ Sibling of the option rows (same radius, same line), red-tinted like the remove hover so the
1870
+ eye connects the two, and it holds its own actions so nothing else on the pane moves. */
1871
+ .cg-option-confirm {
1872
+ display: grid;
1873
+ gap: 8px;
1874
+ margin-top: 8px;
1875
+ padding: 10px 12px;
1876
+ border: 1px solid var(--lp-line);
1877
+ border-left: 3px solid var(--lp-red-deep);
1878
+ border-radius: var(--lp-r-md);
1879
+ background: var(--lp-red-tint);
1880
+ font-size: var(--lp-fs-xs);
1881
+ line-height: 1.4;
1882
+ }
1883
+ .cg-option-confirm strong { color: var(--lp-ink); }
1884
+ .cg-option-confirm-actions {
1885
+ display: flex;
1886
+ gap: 8px;
1887
+ justify-content: flex-end;
1888
+ }
1889
  .cg-option-add {
1890
  justify-self: start;
1891
  padding: 2px 0;