fsanyoto commited on
Commit
d4eb395
·
verified ·
1 Parent(s): dab6f70

Deploy AIOS web (React glide grid + FastAPI slice)

Browse files
RELEASES.json CHANGED
@@ -1,6 +1,12 @@
1
  {
2
- "current": "bb8985c",
3
  "releases": [
 
 
 
 
 
 
4
  {
5
  "version": "v63",
6
  "sha": "ec75cb8",
 
1
  {
2
+ "current": "43e061e",
3
  "releases": [
4
+ {
5
+ "version": "v64",
6
+ "sha": "bb8985c",
7
+ "date": "2026-08-31",
8
+ "subject": "release v64"
9
+ },
10
  {
11
  "version": "v63",
12
  "sha": "ec75cb8",
VERSION CHANGED
@@ -1 +1 @@
1
- bb8985c
 
1
+ 43e061e
api/routes_customers.py CHANGED
@@ -24,13 +24,12 @@ proof is single-process and would report green on exactly the thing that is stil
24
  import datetime as _dt
25
  import hashlib
26
  import json
27
- import math
28
  import time
29
 
30
  from fastapi import APIRouter, Body, Depends
31
 
32
  import scope_cache
33
- from deps import Session, err, module_gate, perms
34
 
35
  router = APIRouter(prefix="/api/v1")
36
 
@@ -395,15 +394,11 @@ def grid_assembly(session: Session, scope: str = "customer", storage_key: str =
395
  # only order in which the per-field grant marker is ever presented to `hidden_keys`.
396
  _strata = {}
397
  fields = _merge_shared_fields(fields, _defs, session=session, strata=_strata)
398
- # Legacy `Destination N` definitions remain in the shared document for rollback/audit, but
399
- # once the dedicated migration recorded its independent parity proof they are display-hidden.
400
- # This is intentionally a projection only: no field or cell is deleted here.
401
- from core import route_system
402
- _legacy_migrations = route_system.read(rt).get("legacyMigrations") or {}
403
- fields = [field for field in fields if not (
404
- isinstance(field, dict) and (_legacy_migrations.get(str(field.get("key"))) or {}).get("verified"))]
405
- # Presentation only: legacy route-order definitions remain served/manageable where W44 has
406
- # not migrated them, but no generic field picker may offer one as a data dimension.
407
  fields = _mark_offerability(fields)
408
  # ⭐⭐ W41-T01 / RULING R5 / CONTRACTS C1 + C8 — **THE THREE BADGES, STAMPED ONCE, HERE.**
409
  #
@@ -567,6 +562,7 @@ def grid_assembly(session: Session, scope: str = "customer", storage_key: str =
567
  # read-only customer fields; neither is a generic Link or an editable user-table cell.
568
  # Route names and membership are object data too: a private Route must not leak through the
569
  # derived customer column while its navigator correctly hides it.
 
570
  normalized_routes = [route for route, _mark in _visible_normalized_routes(session)]
571
  normalized_zones = route_system.list_zones(rt, rows_src)
572
  fields = [field for field in fields if field.get("key") not in {"routes", "zone"}]
@@ -792,29 +788,6 @@ def _reject_client_create_id(raw, subject):
792
  f"to update an existing {subject}")
793
 
794
 
795
- def _legacy_route_defs_readonly(session):
796
- """Visible legacy route definitions from the shared stratum, with no reconciliation write."""
797
- import aios_grid
798
- import core.perm_scope as perm_scope
799
- from core import route_system, shared_overlay
800
-
801
- try:
802
- all_defs = shared_overlay.fields(_shared_key(), st=session.runtime) or {}
803
- except Exception:
804
- all_defs = {}
805
- migrated = route_system.read(session.runtime).get("legacyMigrations") or {}
806
- defs = {key: definition for key, definition in all_defs.items()
807
- if isinstance(definition, dict) and definition.get("kind") == ROUTE_KIND
808
- and not _is_route_share_bridge(definition)
809
- and not bool((migrated.get(key) or {}).get("verified"))}
810
- if not defs:
811
- return {}
812
- hidden = perm_scope.hidden_keys(
813
- session.user, MODULE, _merge_shared_fields(list(aios_grid.FIELDS), all_defs),
814
- st=session.runtime)
815
- return {key: definition for key, definition in defs.items() if key not in hidden}
816
-
817
-
818
  def _route_share_records(session):
819
  """One normalized registry read for list visibility and every share mark."""
820
  from core import field_permissions
@@ -858,25 +831,21 @@ def _visible_normalized_routes(session, records=None):
858
  return visible
859
 
860
 
861
- def _compatible_routes(session, permitted=None, records=None):
862
- """Visible normalized Routes plus a read-only projection of legacy route-order fields.
 
 
 
 
 
 
 
 
863
 
864
- Wave 44 introduced a normalized Route store while production already held saved route-order
865
- columns. Requiring an administrator to run the migration before a GET made those existing
866
- Routes disappear from the Map. This projection uses the same field and row walls as the old
867
- route-order picker and performs no store update; the explicit migration remains a separate,
868
- independently verified write operation.
869
  """
870
- from core import route_system
871
- permitted = allowed_pids(session) if permitted is None else frozenset(permitted)
872
- normalized = [route for route, _mark in _visible_normalized_routes(session, records)]
873
- return route_system.compatible_routes(
874
- normalized,
875
- _legacy_route_defs_readonly(session),
876
- shared_cells(permitted, st=session.runtime),
877
- tenant_id=session.tenant,
878
- created_by=session.uname,
879
- )
880
 
881
 
882
  def _legacy_route_navigation(session):
@@ -905,7 +874,6 @@ def _route_dto(route, allowed, active, session, share_mark=None):
905
  if int(stop.get("customerPid")) in allowed]
906
  visible = [int(stop["customerPid"]) for stop in stops]
907
  active = {int(pid) for pid in active if int(pid) in allowed}
908
- compatibility = route.get("compatibility")
909
  mark = share_mark if isinstance(share_mark, dict) else _route_share_mark(session, route)
910
  owns_route = bool(session.admin or (
911
  mark.get("owner") and mark.get("owner") == str(session.uname or "").strip().lower()))
@@ -925,8 +893,9 @@ def _route_dto(route, allowed, active, session, share_mark=None):
925
  # `owns_route`), an explicit `edit` share on the Route, then an editor of the source View.
926
  # `can_duplicate` stays `source_edit` alone, because `duplicate_route` genuinely does raise
927
  # `route_view_read_only` without it — that door is not the one R6 corrected.
928
- can_edit = bool(not compatibility and (
929
- owns_route or mark.get("sharedRole") == "edit" or source_edit))
 
930
  dto = {"id": route["id"], "name": route["name"], "color": route["color"],
931
  "number": route["number"], "visibleStopIds": visible,
932
  "outsideFilter": bool(active) and not bool(active.intersection(visible)),
@@ -947,8 +916,6 @@ def _route_dto(route, allowed, active, session, share_mark=None):
947
  "sharedOut": mark["sharedOut"], "hasShares": mark["hasShares"],
948
  "sharedRole": mark["sharedRole"], "shareId": mark["shareId"],
949
  "folderId": route.get("folderId"), "navOrder": route.get("navOrder", 0)}
950
- if compatibility == "legacy-route-order":
951
- dto["compatibility"] = compatibility
952
  if route.get("mapsUrl"):
953
  dto["mapsUrl"] = route["mapsUrl"]
954
  return dto
@@ -1057,7 +1024,7 @@ def _drop_route_share_bridge(session, route):
1057
 
1058
 
1059
  def _route_nav_mutation_context(session):
1060
- routes = _compatible_routes(session)
1061
  folders, placements = _legacy_route_navigation(session)
1062
  return routes, folders, placements
1063
 
@@ -1155,7 +1122,7 @@ def routes(session: Session = Depends(module_gate(MODULE))):
1155
  """
1156
  allowed = allowed_pids(session)
1157
  records = _route_share_records(session)
1158
- navigation = _route_navigation(session, _compatible_routes(session, allowed, records))
1159
  return {"routes": [_route_dto(
1160
  route, allowed, (), session,
1161
  _route_share_mark(session, route, records))
@@ -1410,7 +1377,7 @@ def route_selection(body: dict = Body(default=None), session: Session = Depends(
1410
  from core import route_system
1411
  raw = dict(body or {})
1412
  chosen = [str(item) for item in raw.get("routeIds") or ()]
1413
- compatible = _compatible_routes(session)
1414
  known = {route["id"] for route in compatible}
1415
  if any(route_id not in known for route_id in chosen):
1416
  raise err(404, "route_not_found", "a selected Route does not exist")
@@ -1486,32 +1453,6 @@ def selected_view_export(body: dict = Body(default=None),
1486
  return {"today": g["today"], "exports": exports}
1487
 
1488
 
1489
- @router.post("/customers/routes/migrate-legacy")
1490
- def migrate_legacy_destination_fields(session: Session = Depends(module_gate(MODULE))):
1491
- """Copy legacy Destination N ranks, prove parity, then hide the retained columns.
1492
-
1493
- The explicit whole-book check is important: a partial manager scope may copy a useful subset,
1494
- but it can never prove a tenant-wide route complete and therefore may not hide anything.
1495
- """
1496
- if not session.admin:
1497
- raise err(403, "legacy_migration_admin_only", "only an administrator may migrate legacy Routes")
1498
- from core import route_system
1499
- raw_rows = _pool_rows(session)
1500
- whole_book = {int(row["pid"]) for row in raw_rows if row.get("pid") is not None}
1501
- if whole_book != set(allowed_pids(session)):
1502
- raise err(409, "legacy_migration_scope_limited",
1503
- "legacy Route migration needs an unrestricted customer scope to prove parity")
1504
- defs = shared_fields(st=session.runtime)
1505
- result = route_system.migrate_legacy_routes(
1506
- session.runtime, defs, shared_cells(whole_book, st=session.runtime),
1507
- tenant_id=session.tenant, created_by=session.uname,
1508
- zones=route_system.list_zones(session.runtime, raw_rows))
1509
- # `legacyMigrations` lives with the normalized system data. The source field definition and
1510
- # every scalar rank cell are retained byte-for-byte; the persisted proof is the read-side
1511
- # hide/read-only marker rather than a generic field rewrite or a delete.
1512
- return result
1513
-
1514
-
1515
  def _zone_can_edit(session, source_view_id):
1516
  return bool(session.admin) or _route_view_can_edit(session, source_view_id)
1517
 
@@ -1597,130 +1538,6 @@ def remove_zone(zone_id: str, session: Session = Depends(module_gate(MODULE))):
1597
  return {"deleted": True}
1598
 
1599
 
1600
- def _split_route_updates(session, updates):
1601
- """Split a cell PATCH into `(route order updates, everything else)`.
1602
-
1603
- ⛔ MATCHED ON THE DECLARED `kind`, NEVER ON THE `route_` PREFIX — the rule `route_order_delete`
1604
- and the column menu both state. A prefix is a naming convention; the kind is a declaration.
1605
- """
1606
- defs = shared_fields(st=session.runtime) or {}
1607
- route, rest = {}, {}
1608
- for key, value in (updates or {}).items():
1609
- defn = defs.get(key)
1610
- from core import route_system
1611
- migrated = bool((route_system.read(session.runtime).get("legacyMigrations") or {}).get(key, {}).get("verified"))
1612
- if isinstance(defn, dict) and defn.get("kind") == ROUTE_KIND and not migrated:
1613
- route[key] = value
1614
- else:
1615
- rest[key] = value
1616
- return route, rest
1617
-
1618
-
1619
- def _patch_route_ranks(session, ctx, pid, pool, updates):
1620
- """Write visit numbers into the SHARED stratum, keeping the column a permutation.
1621
-
1622
- ⭐⭐ OWNER ITEM 7 (2026-08-23) — THE AUTO-DEDUPE, IN THE OWNER'S OWN WORDS: *"when you edit a
1623
- number from say 13 to 14, what ever was record 14 should automatically change to 13 so its
1624
- auto dedupe that way."* That is a TRANSPOSITION, and it is the whole rule: the number you
1625
- typed goes on your record, and the number you displaced goes to whoever was holding it. Two
1626
- rows move, the set of numbers in the column is unchanged, and no other record is renumbered.
1627
-
1628
- Three cases, and each one is the same rule read honestly:
1629
-
1630
- · the target number is FREE -> plain assignment. A gap is not a duplicate, and the owner's
1631
- rule is about duplicates.
1632
- · the target is HELD and this record already had a number -> the two swap. The named case.
1633
- · the target is HELD and this record had NO number (it was not on the route) -> there is no
1634
- old number to hand over, so the displaced record goes to the end (`max + 1`). Still one
1635
- other row moved, still no duplicate, and nothing loses its place on the route silently.
1636
-
1637
- Blanking a cell takes the record OFF the route and frees its number. It renumbers nothing:
1638
- re-solving is what closes the gaps, and doing it here would silently rewrite a day somebody
1639
- is driving.
1640
-
1641
- ⛔⛔ THE WALLS ARE `grid_events`' OWN, CALLED AND NOT COPIED, AND THAT IS THE PRICE OF
1642
- STEPPING OUT OF `overlay_patch`. `_may_edit_field_value` is where the shared-field Share role,
1643
- the creator rule and the admin rule already meet; the hidden-key wall is applied first for the
1644
- reason `overlay_patch` applies it, namely that `hidden_keys` decides what this caller may READ
1645
- and a column they cannot read is not one they may write by naming its key. A second spelling
1646
- of either here would be a second one to keep in step — which is the whole reason
1647
- `patch_customer` routes everything else through `grid_events` rather than writing the store.
1648
-
1649
- ⚠ UNIQUENESS IS MAINTAINED OVER THE ROWS THIS CALLER CAN SEE, and that is a limit worth
1650
- stating rather than hiding. `shared_overlay.transpose_rank` requires the scoped pool BY
1651
- SIGNATURE, then reads it inside the same store-update callback that writes both rows. The
1652
- holder of a displaced number is therefore looked for inside this session's book, but never
1653
- from a stale pre-write snapshot. In practice the whole column lives there anyway:
1654
- `route_order_write` REFUSES a body carrying a pid outside the writer's pool, so every number in
1655
- a route order was written by somebody whose book contained all of them.
1656
- """
1657
- from core import grid_events, shared_overlay
1658
-
1659
- defs = shared_fields(st=session.runtime) or {}
1660
- hidden = _hidden_for(session)
1661
- #: `{key: what the store holds for THIS record now}`, for every key asked about — refused ones
1662
- #: included. See the `_stored` note below.
1663
- accepted = {}
1664
- #: The keys that actually moved. `patch_customer` reports everything else as REFUSED, so this
1665
- #: has to be separate from `accepted`: a refused key still reports a value, and it is the
1666
- #: value the caller did NOT ask for.
1667
- taken, swaps = set(), []
1668
-
1669
- def _stored(key):
1670
- """The current rank for a refused key, scoped to this one admitted row.
1671
-
1672
- Valid nonblank assignments never use this read: ``transpose_rank`` reads the whole scoped
1673
- column inside the atomic update that writes it. This helper exists only so a refusal can
1674
- repaint the store's truth in the optimistic client.
1675
- """
1676
- row = ((shared_cells([pid], st=session.runtime) or {}).get(str(pid)) or {})
1677
- cell = row.get(key) if isinstance(row, dict) else None
1678
- if cell in (None, ""):
1679
- return ""
1680
- try:
1681
- return str(int(str(cell).strip()))
1682
- except (TypeError, ValueError):
1683
- return ""
1684
-
1685
- for key, raw in updates.items():
1686
- defn = defs.get(key) or {}
1687
-
1688
- if key in hidden:
1689
- accepted[key] = _stored(key)
1690
- continue
1691
- if not grid_events._may_edit_field_value(ctx, key, defn):
1692
- accepted[key] = _stored(key)
1693
- continue
1694
- # An empty cell is "not on this route". Legal, and the only way to take a stop off the
1695
- # day without re-solving the whole column.
1696
- if raw is None or (isinstance(raw, str) and not raw.strip()):
1697
- shared_overlay.put_rows(_shared_key(), {pid: {key: ""}}, st=session.runtime)
1698
- accepted[key] = ""
1699
- taken.add(key)
1700
- continue
1701
- # ⛔ A BOOL IS AN `int` IN PYTHON, so `True` would store as visit number 1. Excluded by
1702
- # name here exactly as `route_order_write` excludes it, rather than by hoping.
1703
- if isinstance(raw, bool):
1704
- accepted[key] = _stored(key)
1705
- continue
1706
- try:
1707
- want = int(str(raw).strip())
1708
- except (TypeError, ValueError):
1709
- accepted[key] = _stored(key)
1710
- continue
1711
- if want < 1:
1712
- accepted[key] = _stored(key)
1713
- continue
1714
-
1715
- moved = shared_overlay.transpose_rank(
1716
- _shared_key(), pid, key, want, pool, st=session.runtime)
1717
- if moved.get("swap"):
1718
- swaps.append(moved["swap"])
1719
- accepted[key] = moved["value"]
1720
- taken.add(key)
1721
- return accepted, swaps, taken
1722
-
1723
-
1724
  @router.patch("/customers/{pid}")
1725
  def patch_customer(pid: int, body: dict = Body(default=None),
1726
  session: Session = Depends(module_gate(MODULE))):
@@ -1777,8 +1594,6 @@ def patch_customer(pid: int, body: dict = Body(default=None),
1777
  # paste, fill, undo, the record drawer — comes through this one door; a client-side branch
1778
  # would have to be repeated at each of them and would be wrong at the first one nobody
1779
  # remembered.
1780
- route_updates, updates = _split_route_updates(session, updates)
1781
-
1782
  if updates:
1783
  try:
1784
  grid_events.handle_one(
@@ -1788,10 +1603,11 @@ def patch_customer(pid: int, body: dict = Body(default=None),
1788
  raise err(503, "store_unavailable",
1789
  "the tenant store is unavailable. Your change was not saved")
1790
 
 
 
 
1791
  route_accepted, route_swaps, route_taken = ({}, [], set())
1792
- if route_updates:
1793
- route_accepted, route_swaps, route_taken = _patch_route_ranks(
1794
- session, ctx, pid, pool, route_updates)
1795
 
1796
  # What actually landed, read back from the store rather than echoed from the request: a
1797
  # refused key or a truncated value must not be reported as accepted.
@@ -1890,712 +1706,6 @@ ROUTE_FIELD_NOTE = ("The visit order of a saved route. Each number is that custo
1890
  SHARE_TOPIC = MODULE
1891
 
1892
 
1893
- def _route_slug(label):
1894
- """A stable store key from a human label. Lower case, non-alphanumerics collapsed to `_`."""
1895
- import re as _re
1896
- slug = _re.sub(r"[^a-z0-9]+", "_", str(label or "").strip().lower()).strip("_")
1897
- return f"{ROUTE_KEY_PREFIX}{slug[:48]}" if slug else ""
1898
-
1899
-
1900
- def _occupied(defs, base_fields=()):
1901
- """The keys and case-folded labels a new route column must not land on."""
1902
- occupied_keys = {str(key) for key in (defs or {})}
1903
- occupied_labels = set()
1904
- for field in list((defs or {}).values()) + list(base_fields or ()):
1905
- if not isinstance(field, dict):
1906
- continue
1907
- label = " ".join(str(field.get("label") or "").split()).casefold()
1908
- if label:
1909
- occupied_labels.add(label)
1910
- key = str(field.get("key") or "").strip()
1911
- if key:
1912
- occupied_keys.add(key)
1913
- return occupied_keys, occupied_labels
1914
-
1915
-
1916
- def _next_route_label(defs, base_fields=()):
1917
- """Return the next human route-field label without colliding with a visible field.
1918
-
1919
- ⭐ OWNER ITEM 5 (2026-08-23) — THE WORD IS "ROUTE", NOT "DESTINATION". Owner: *"Instead of
1920
- calling it 'Destination 1' etc. for when we saved the route to a field, we just call it
1921
- 'Route 1' so it's Route 1, Route 2, Route 3."* A saved column holds the ORDER of a whole day,
1922
- so "Destination 1" read as the first stop rather than as the first route, which is exactly
1923
- backwards from what the numbers in it mean.
1924
-
1925
- ⛔ NO MIGRATION, AND THAT IS DELIBERATE. Columns already minted as `Destination N` keep their
1926
- label: rewriting a tenant-wide column name that other people's saved views point at is not a
1927
- rename this door was asked for. The owner renames one through `route_order_rename` below, per
1928
- owner item 6 of the same instruction.
1929
-
1930
- ⚠ THE KEY IS STILL DERIVED FROM THE LABEL, so the default now slugs to `route_route_1`. The
1931
- redundant segment is NOT tidied away: `ROUTE_KEY_PREFIX` is what keeps a route column out of
1932
- the namespace this database owns, and stripping it here would make the labels "Route 1" and
1933
- "1" collide on one key. The key is never on screen.
1934
- """
1935
- occupied_keys, occupied_labels = _occupied(defs, base_fields)
1936
- n = 1
1937
- while True:
1938
- label = f"Route {n}"
1939
- if label.casefold() not in occupied_labels and _route_slug(label) not in occupied_keys:
1940
- return label
1941
- n += 1
1942
-
1943
-
1944
- def _clean_route_depot(raw):
1945
- """The optional origin stored once on a route-order definition, never on a customer cell."""
1946
- if raw is None:
1947
- return None
1948
- if not isinstance(raw, dict):
1949
- raise err(400, "bad_depot", "a depot is an address with latitude and longitude, or null")
1950
- address = " ".join(str(raw.get("address") or "").split())[:200]
1951
- lat, lon = raw.get("lat"), raw.get("lon")
1952
- if (not address or isinstance(lat, bool) or isinstance(lon, bool) or
1953
- not isinstance(lat, (int, float)) or not isinstance(lon, (int, float))):
1954
- raise err(400, "bad_depot", "a depot needs an address and numeric latitude and longitude")
1955
- lat, lon = float(lat), float(lon)
1956
- if not (math.isfinite(lat) and math.isfinite(lon) and abs(lat) <= 90 and abs(lon) <= 180):
1957
- raise err(400, "bad_depot", "the depot latitude or longitude is outside the map")
1958
- return {"address": address, "lat": lat, "lon": lon}
1959
-
1960
-
1961
- def _route_defs(session: Session):
1962
- """This topic's route-order columns MINUS the ones this session was not granted.
1963
-
1964
- ⛔ THE WALL IS THE SAME ONE THE GRID USES, NOT A SECOND OPINION. `hidden_keys` is where T16
1965
- put the per-field grant check, so filtering on it here means the listing, the grid contract
1966
- and the row payload agree by construction. A column a reader cannot see must not appear here
1967
- either: the done-when says *does not see the field at all*, and a picker that names a column
1968
- whose values are withheld has already leaked its existence.
1969
- """
1970
- import aios_grid
1971
- import core.perm_scope as perm_scope
1972
-
1973
- all_defs = shared_fields(st=session.runtime) or {}
1974
- from core import route_system
1975
- migrated = route_system.read(session.runtime).get("legacyMigrations") or {}
1976
- defs = {k: v for k, v in all_defs.items()
1977
- if isinstance(v, dict) and v.get("kind") == ROUTE_KIND
1978
- and not bool((migrated.get(k) or {}).get("verified"))}
1979
- if not defs:
1980
- return {}
1981
- hide = perm_scope.hidden_keys(
1982
- session.user, MODULE, _merge_shared_fields(list(aios_grid.FIELDS), all_defs),
1983
- st=session.runtime)
1984
- return {k: v for k, v in defs.items() if k not in hide}
1985
-
1986
-
1987
- def _own_route_fork(session: Session, key: str):
1988
- """This caller's PRIVATE copy of a route column, if a per-user write ever forked one.
1989
-
1990
- ⛔⛔ THE FORK IS REAL, AND IT IS WHAT BROKE DELETE. Traced through `grid_events.field_upsert`
1991
- rather than assumed: `shared_field` is `bool(shared_prior.get('custom'))` and a route
1992
- definition carries no `custom` key, so the shared branch does not take it; the key is neither
1993
- `custom_` nor `measure_`; it IS in the merged contract, so the `key in field_by_key` branch
1994
- does — and that branch's own body is what writes `note`, `format` and `agg`, landing them in
1995
- THIS USER'S field definitions through `TableStore.save_field`. `_merge_shared_fields` then
1996
- SKIPS the tenant-wide definition, because a key the contract already declares wins, and from
1997
- that moment the person is reading a private copy of a shared column.
1998
-
1999
- ⚠ WHICH DOORS STILL FORK, AS OF 2026-08-23, because "the fork is fixed" would be too broad.
2000
- The Description and the Name are CLOSED: owner item 6 routed `onNote` and `onRename` to
2001
- `route_order_rename` below. The Edit-field pane's **Format** row (`onFormat`, unconditional)
2002
- and its **Summary** row (`onAggregate`, whose `isUserTable` arm is false on this registry
2003
- topic) both still reach `saveField`, so either one still mints a fork. They are left open on
2004
- purpose: closing them needs this door to accept `format` and `agg`, which is a wider change
2005
- than the delete the owner reported. This function is what keeps that recoverable rather than
2006
- permanent.
2007
-
2008
- ⛔ WHY THAT MADE THE DELETE 404 RATHER THAN MERELY MISBEHAVE. The first delete found the
2009
- tenant-wide definition, dropped it and answered 200 — and the column came straight back on the
2010
- next read, because the fork was still declaring it. The second attempt found nothing in
2011
- `shared_fields` and answered *"that column is not a route order column on this database"*
2012
- about a column sitting on screen. Owner, 2026-08-23: *"I can't even delete the Field route
2013
- now?"* Both halves are answered here: a fork is FOUND, and `route_order_delete` drops it WITH
2014
- the definition rather than leaving it to redeclare the column.
2015
-
2016
- ⚠ `kind` IS THE TEST, NEVER MERE PRESENCE. `TableStore.workspace` merges the tenant-wide
2017
- column summary over this stratum and will mint a bare `{'agg': ...}` entry for a key the user
2018
- has never touched (W36-T25, whose own comment says it must be able to CREATE an entry).
2019
- Reading presence would call that stub a fork and scrub a column nobody had forked.
2020
- """
2021
- try:
2022
- ws = _customer_table(session).workspace(session.uname, consume_corrections=False)
2023
- except Exception: # noqa: BLE001
2024
- return None
2025
- entry = (ws.get("fields") or {}).get(key)
2026
- if not isinstance(entry, dict) or entry.get("kind") != ROUTE_KIND:
2027
- return None
2028
- return entry
2029
-
2030
-
2031
- @router.get("/customers/route-order")
2032
- def route_order_list(session: Session = Depends(module_gate(MODULE))):
2033
- """The route-order columns this session may see, with the fingerprint each was solved from.
2034
-
2035
- ⭐⭐ THE FINGERPRINT IS WHY THIS ROUTE EXISTS RATHER THAN THE CLIENT READING `fields`.
2036
- Staleness is DERIVED, never stored: what is written down is the INPUT FINGERPRINT the numbers
2037
- were produced from, so *is this order still current* is a question asked at READ time against
2038
- what is on screen NOW, and can never itself be out of date. A stored `stale: true` is a fact
2039
- about a moment that has already passed.
2040
- """
2041
- out = []
2042
- for key, defn in sorted(_route_defs(session).items()):
2043
- route = defn.get("route") if isinstance(defn.get("route"), dict) else {}
2044
- out.append({
2045
- "key": key,
2046
- "label": defn.get("label") or key,
2047
- "inputsHash": str(route.get("inputsHash") or ""),
2048
- "roundTrip": bool(route.get("roundTrip")),
2049
- "startPid": route.get("startPid"),
2050
- "stops": route.get("stops"),
2051
- "depot": route.get("depot") if isinstance(route.get("depot"), dict) else None,
2052
- "solvedAt": route.get("solvedAt") or "",
2053
- "solvedBy": defn.get("createdBy") or "",
2054
- # The route index's gear edits the same named detail the field editor owns. Serving
2055
- # it here prevents a rename from accidentally clearing an existing description.
2056
- "note": str(defn.get("note") or ""),
2057
- # Who may re-solve it. The same creator-or-admin wall the write door enforces, said on
2058
- # the way out so the client can grey the control instead of discovering a 403.
2059
- "mine": bool(session.admin
2060
- or str(defn.get("createdBy") or "") == session.uname),
2061
- })
2062
- # ⭐⭐ OWNER ITEM 5 — THE DEFAULT NAME IS ALLOCATED **HERE**, NEVER ON THE CLIENT.
2063
- #
2064
- # The panel prompts for a route name and pre-fills it. Computing that pre-fill from the
2065
- # `fields` list above would compute it from the columns this session may SEE: `_route_defs`
2066
- # drops every route column the per-field wall hides, so a user with no grant on
2067
- # `route_route_1` would be offered "Route 1" as their default, send it, and be refused
2068
- # `field_key_taken` on a name the app itself put in the box. Allocated over the WHOLE shared
2069
- # stratum, the suggestion can never name a column that already exists.
2070
- #
2071
- # ⚠ IT LEAKS NOTHING. What travels is the first FREE name, which is a fact about absence.
2072
- import aios_grid
2073
- return {"fields": out,
2074
- "nextLabel": _next_route_label(shared_fields(st=session.runtime) or {},
2075
- aios_grid.FIELDS)}
2076
-
2077
-
2078
- @router.post("/customers/route-order")
2079
- def route_order_write(body: dict = Body(default=None),
2080
- session: Session = Depends(module_gate(MODULE))):
2081
- """Create (or re-solve) a tenant-wide route-order column and fill it, in ONE call.
2082
-
2083
- `{label?, field?, ranks: {"<pid>": <int>}, inputsHash, roundTrip?, startPid?, depot?}`
2084
-
2085
- When `label` is omitted for a new column, the door allocates the next unused `Destination N`
2086
- label. This keeps route creation one-click while preserving unique, readable field names.
2087
-
2088
- ⛔ THE DEFINITION IS WRITTEN FIRST AND THE GRANT CLAIMED SECOND — inside
2089
- `shared_overlay.mint_field` since W41-T05, which is where the `set_grants` call a reader looks
2090
- for in this function now lives. It is `patch_shared_cell`'s
2091
- order and it is deliberate: the window where a column is MARKED and UNCLAIMED fails CLOSED
2092
- (governed, nobody granted, so only an admin and the creator see it, and an admin can share
2093
- it). The other order would leave a grant record pointing at nothing.
2094
-
2095
- ⛔ RE-SOLVING IS CREATOR-OR-ADMIN, WHICH CREATING IS NOT. Writing these numbers changes what
2096
- every account in the workspace reads, at once, for the whole cohort. That is the wall
2097
- `routes_tables.delete_shared_field` already applies to the destructive half of this stratum,
2098
- and a new door does not get to inherit the loose half of an asymmetry somebody has flagged.
2099
- A permitted teammate READS the numbers; they do not silently re-plan somebody's day.
2100
- """
2101
- from core import shared_overlay
2102
- import core.perm_scope as perm_scope
2103
- from routes_grid import MAX_BULK_ROWS
2104
-
2105
- body = body if isinstance(body, dict) else {}
2106
- label = " ".join(str(body.get("label") or "").split())[:120]
2107
- import aios_grid
2108
- defs = shared_fields(st=session.runtime) or {}
2109
- requested_key = str(body.get("field") or "").strip()
2110
- if requested_key:
2111
- key = requested_key
2112
- elif label:
2113
- key = _route_slug(label)
2114
- else:
2115
- label = _next_route_label(defs, aios_grid.FIELDS)
2116
- key = _route_slug(label)
2117
- if not key:
2118
- raise err(400, "bad_request", "a name is required for the route order column")
2119
- if not key.startswith(ROUTE_KEY_PREFIX):
2120
- raise err(400, "bad_field_key",
2121
- f"a route order column's key starts with '{ROUTE_KEY_PREFIX}', so it cannot "
2122
- f"collide with a column this database already owns")
2123
- if key in {f.get("key") for f in aios_grid.FIELDS}:
2124
- raise err(400, "field_key_taken",
2125
- "this database already has a column with that key")
2126
-
2127
- existing = defs.get(key) if isinstance(defs.get(key), dict) else None
2128
- if existing is not None:
2129
- # ⛔⛔ A REFUSAL MUST NOT DESCRIBE A COLUMN THE CALLER CANNOT SEE. The two refusals below
2130
- # name the column's KIND and its CREATOR, which is exactly the information the field wall
2131
- # exists to withhold: a stranger who guesses the key would otherwise learn that a route
2132
- # order exists on this database and who planned it. `routes_shares._can_see_object` makes
2133
- # the same choice for the same reason (a non-grantee gets the answer a non-existent id
2134
- # gets). The name is already taken either way, so the honest refusal says only that.
2135
- if key in perm_scope.hidden_keys(
2136
- session.user, MODULE,
2137
- _merge_shared_fields(list(aios_grid.FIELDS), defs), st=session.runtime):
2138
- raise err(400, "field_key_taken",
2139
- "that column name is already in use on this database")
2140
- if existing.get("kind") != ROUTE_KIND:
2141
- raise err(400, "not_a_route_column",
2142
- "that column is shared but it is not a route order column, so re-solving "
2143
- "it would overwrite values this door did not write")
2144
- owner = str(existing.get("createdBy") or "")
2145
- if not session.admin and owner != session.uname:
2146
- raise err(403, "forbidden",
2147
- f"a route order can be re-solved by the person who planned it or by an "
2148
- f"administrator. This one was planned by {owner or 'somebody else'}, and "
2149
- f"re-solving it would change the visit numbers for every account at once")
2150
-
2151
- if "depot" in body:
2152
- depot = _clean_route_depot(body.get("depot"))
2153
- else:
2154
- prior_route = (existing or {}).get("route") if isinstance(existing, dict) else {}
2155
- depot = prior_route.get("depot") if isinstance(prior_route, dict) else None
2156
-
2157
- raw = body.get("ranks")
2158
- if not isinstance(raw, dict) or not raw:
2159
- raise err(400, "bad_ranks", 'expected {ranks: {"<pid>": <visit number>}}')
2160
- # ⛔ REPORTED, NEVER TRUNCATED (standing rule 1's second sentence, and `MAX_BULK_ROWS`' own
2161
- # note). The ceiling is `routes_grid`'s so there is ONE of them, not two that drift.
2162
- if len(raw) > MAX_BULK_ROWS:
2163
- raise err(400, "too_many_rows",
2164
- f"at most {MAX_BULK_ROWS} records per route; this one carried {len(raw)}")
2165
-
2166
- pool = allowed_pids(session)
2167
- ranks, not_in_pool, bad_value = {}, [], []
2168
- for raw_pid, value in raw.items():
2169
- try:
2170
- pid = int(raw_pid)
2171
- except (TypeError, ValueError):
2172
- not_in_pool.append(str(raw_pid)[:40])
2173
- continue
2174
- # ⚠ THE POOL IS THE WALL, and it is the SAME predicate the read path applies
2175
- # (`apply_row_scope` inside `allowed_pids`), so a caller cannot number a record they
2176
- # could not be shown, including one in the other business unit.
2177
- if pid not in pool:
2178
- not_in_pool.append(str(raw_pid)[:40])
2179
- continue
2180
- # ⛔ A BOOL IS AN `int` IN PYTHON and `True` would store as a visit number 1. Excluded by
2181
- # name rather than by hoping nobody sends one.
2182
- if isinstance(value, bool) or not isinstance(value, int) or value < 1:
2183
- bad_value.append(str(raw_pid)[:40])
2184
- continue
2185
- ranks[pid] = value
2186
-
2187
- # ⛔⛔ A PARTLY HONOURED ROUTE IS NOT A ROUTE, AND THIS REFUSES THE WHOLE CALL RATHER THAN
2188
- # WRITING THE PART IT COULD. Caught by this ticket's own gate: a body carrying one record
2189
- # outside the caller's book still produced a clean 1..N over what was left, so the door minted
2190
- # a permanent tenant-wide column and filled it with a SHORTER route than the one that was
2191
- # solved. Every number in it was plausible and the day was wrong.
2192
- # ⚠ REPORTED, WITH THE SAMPLE, which is standing rule 1's second sentence: the refusal names
2193
- # what it could not take, so the caller can fix it rather than guess.
2194
- if not_in_pool:
2195
- raise err(400, "rows_not_in_your_book",
2196
- f"{len(not_in_pool)} of those records are not in your book, so the route "
2197
- f"cannot be written as it was solved. First few: "
2198
- f"{', '.join(sorted(not_in_pool)[:5])}")
2199
- if bad_value:
2200
- raise err(400, "rows_not_a_visit_number",
2201
- f"a visit number is a whole number from 1 upwards; {len(bad_value)} records "
2202
- f"carried something else. First few: {', '.join(sorted(bad_value)[:5])}")
2203
- if not ranks:
2204
- raise err(400, "no_rows_in_your_book",
2205
- "none of those records are in your book, so there is nothing to number")
2206
- # ⛔ A ROUTE IS A SEQUENCE, SO THE NUMBERS ARE 1..N WITH NO REPEAT AND NO GAP. A body that
2207
- # arrives truncated, doubled or partly applied would otherwise land as a plausible half
2208
- # route: every row carrying a number, and the day in the wrong order.
2209
- seq = sorted(ranks.values())
2210
- if seq != list(range(1, len(seq) + 1)):
2211
- raise err(400, "not_a_sequence",
2212
- f"a route order is the numbers 1 to {len(seq)}, each used once. This one "
2213
- f"carried {len(seq)} records numbered up to {seq[-1]} with "
2214
- f"{len(seq) - len(set(seq))} repeated")
2215
-
2216
- stamp = time.strftime("%Y-%m-%d %H:%M")
2217
- defn = {
2218
- "key": key,
2219
- "label": label or (existing or {}).get("label") or key,
2220
- # ⭐⭐ OWNER ITEM 7 (2026-08-23) — THE SAVED ROUTE IS A **NUMBER** COLUMN.
2221
- #
2222
- # Owner: *"the Route field once saved should be saved as a number Field. Make sure we can
2223
- # edit it, BUT also make sure that none of the number can be a duplicate, so its like a
2224
- # number order field."* It used to be a `select` whose declared choices were the strings
2225
- # "1".."N", which sorted and rendered as a list rather than as an order and forced a
2226
- # re-solve to widen the vocabulary before a stop could be numbered past N.
2227
- #
2228
- # ⛔ UNIQUENESS IS NOT A PROPERTY OF THE TYPE, SO IT LIVES AT THE WRITE DOOR. `int` has no
2229
- # "no duplicates" flag anywhere in this contract; `_patch_route_ranks` in `patch_customer`
2230
- # is what keeps the column a permutation, by SWAPPING rather than by refusing.
2231
- #
2232
- # ⚠ EXISTING COLUMNS ARE NOT MIGRATED, they are UPGRADED BY RE-SOLVE. This dict is
2233
- # rebuilt whole on every write, so the first re-solve of a `Destination N` column turns it
2234
- # into a number column; one nobody re-solves keeps working as the select it was, and the
2235
- # write door reads the KIND rather than the type, so both edit identically.
2236
- "type": "int",
2237
- "source": "overlay",
2238
- "shared": True,
2239
- "kind": ROUTE_KIND,
2240
- # Stored as well as projected so every read door starts from the same explicit contract.
2241
- # This is presentation metadata: the route stays visible/manageable and its values remain.
2242
- OFFERABLE_KEY: False,
2243
- # ⭐⭐ W41-T05 — THE DESCRIPTION, CARRIED BY **PRESENCE** AND NOT BY TRUTHINESS.
2244
- # `ROUTE_FIELD_NOTE` says why the column cannot be born without one and why `""` has to
2245
- # survive a re-solve: `route_order_rename` clears a description by storing exactly that,
2246
- # and `existing.get("note") or ROUTE_FIELD_NOTE` would hand the default straight back to
2247
- # the person who had just deleted it. `"note" in existing` is the question with an
2248
- # answer; truthiness is a different question wearing the same shape.
2249
- "note": (existing["note"] if isinstance(existing, dict) and "note" in existing
2250
- else ROUTE_FIELD_NOTE),
2251
- # ⭐⭐ OWNER, 2026-08-23 — A NEW ROUTE READS AS **PRIVATE**, NEVER "Shared with everyone".
2252
- #
2253
- # Owner: *"Right now the Route is 'Shared with everyone' in terms of the Field status when
2254
- # i check the Route Field. It should always default to private first."*
2255
- #
2256
- # ⛔ A CLASSIFICATION FIX, NOT A TIGHTENING, AND THE DIFFERENCE IS THE WHOLE POINT. This
2257
- # column was ALREADY private in the only sense that governs a reader: `FIELD_GRANT_MARK`
2258
- # plus the empty-entry grant claimed below means creator-and-admin and nobody else. What
2259
- # was wrong was the WORD ON SCREEN. `FieldsHidePanel` sections the field list by
2260
- # `types.fieldEditMode`, which is `cleanFieldPermissions(field.permissions,
2261
- # "collaborative")` — so a definition carrying NO permissions bag fell to that fallback
2262
- # and was filed under "Shared with everyone" while being shared with nobody at all.
2263
- #
2264
- # ⚠ AND IT MOVES NO WALL, CHECKED RATHER THAN REASONED. `grid_events._may_edit_field_value`
2265
- # short-circuits on `definition.get('shared') or definition.get('granted')` BEFORE it reads
2266
- # `stored_permissions`, so the creator's own rank edits and `_patch_route_ranks`' swap are
2267
- # decided by `_field_share_role` and not by this bag; the client twin `mayEditField` takes
2268
- # the same branch in the same order. `field_permissions.migrate_legacy_fields` only ever
2269
- # rewrites a PER-USER field carrying `custom: True`, which a route definition is not, so it
2270
- # leaves this key alone. `fieldEditMode` has exactly one other consumer: none.
2271
- #
2272
- # ⛔ NO MIGRATION, AND IT IS THE SAME DELIBERATE CHOICE `_next_route_label` MAKES ABOUT
2273
- # `Destination N`. This dict is rebuilt whole on every write, so a column minted before
2274
- # today gains the bag on its next RE-SOLVE and not one moment sooner — until then it
2275
- # keeps reading "Shared with everyone" in the Hide fields panel while being shared with
2276
- # nobody. Backfilling every stored route definition on a read is a write nobody asked
2277
- # for, on a tenant-wide stratum, triggered by opening a page; re-solving is one click and
2278
- # it is the click the owner is already making. Stated here rather than left to be
2279
- # rediscovered as "the fix did not work".
2280
- "permissions": {"edit": "personal"},
2281
- # ⭐⭐ THE PER-FIELD GRANT MARKER (T16). It is an EXPLICIT write-once declaration and it is
2282
- # what makes the wall fail CLOSED: a grant wall has the opposite absence-polarity to a
2283
- # deny wall, so keying visibility on "does a grant record exist" would publish this column
2284
- # to the whole tenant on one unreadable read of `object_shares`. Stamped, never inferred.
2285
- perm_scope.FIELD_GRANT_MARK: True,
2286
- "createdBy": (existing or {}).get("createdBy") or session.uname,
2287
- # ⭐ THE FINGERPRINT RIDES THE DEFINITION, ONCE. One `planRoute` run solves the whole
2288
- # cohort, so this string is identical for every record in it; per row it would be the same
2289
- # value written N times, and `shared_overlay._value` raises on a dict anyway.
2290
- "route": {
2291
- "inputsHash": str(body.get("inputsHash") or "")[:64],
2292
- "roundTrip": bool(body.get("roundTrip")),
2293
- "startPid": int(body["startPid"]) if isinstance(body.get("startPid"), int)
2294
- and not isinstance(body.get("startPid"), bool) else None,
2295
- "stops": len(ranks),
2296
- "depot": depot,
2297
- "solvedAt": stamp,
2298
- },
2299
- }
2300
- # ⭐⭐ W41-T05 / CONTRACT C3 — A BIRTH GOES THROUGH `mint_field`, A RE-SOLVE THROUGH
2301
- # `put_field`, AND THE SPLIT IS THE WHOLE FIX. C3 names this door as the one bypass in the
2302
- # tree: it reached around the column menu into the raw definition writer because
2303
- # `aios_grid._field_extras` would have stripped the `route` bag. W41-T04 widened the
2304
- # allowlist to carry that bag, so the bypass buys nothing any more, and `mint_field` is the
2305
- # entrance that REFUSES a column born without a creator, a grant list and a description.
2306
- #
2307
- # ⛔⛔ EVERY MEMBER OF THE TRIPLE STAYS IN THE LITERAL ABOVE, AND THAT IS NOT REDUNDANCY.
2308
- # `mint_field` stamps `createdBy`, `granted` and `note` itself, but it runs on the MINT ONLY;
2309
- # a re-solve goes to `put_field`, whose allowlist makes an omitted key CLEAR the stored one
2310
- # ("an allowlisted key follows the caller exactly"). Leaning on the mint for the mark would
2311
- # give a perfect create and a re-solve that silently UNMARKS the column and re-opens the very
2312
- # leak this ticket closes. The literal is what makes both paths land the same definition.
2313
- #
2314
- # ⚠ THE EMPTY GRANT LIST IS THE POINT, and `mint_field` keeps it: `set_grants` stores a record
2315
- # with an owner and no entries, so "shared with nobody" is a STORED fact and a different one
2316
- # from "never shared". Without the owner the column is unmanageable — `may_administer` fails
2317
- # closed on an ownerless record, so nobody could ever share it. The definition still lands
2318
- # BEFORE the claim (inside `mint_field`, same order, same reason): a marked and unclaimed
2319
- # column is admin-and-creator only, which is recoverable; the other order is not.
2320
- if existing is None:
2321
- try:
2322
- shared_overlay.mint_field(
2323
- _shared_key(), key, defn,
2324
- created_by=defn["createdBy"], grants=[], description=defn["note"],
2325
- grant_topic=SHARE_TOPIC, st=session.runtime)
2326
- except ValueError as exc:
2327
- # ⛔ `mint_field` REFUSES rather than overwriting, and only two things can raise here.
2328
- # The triple is supplied one line up, so the reachable refusal is "that key already
2329
- # exists" — which `existing` above said it did not. The two disagree in exactly one
2330
- # case: `existing` is TYPE-checked (`isinstance(..., dict)`) while `is_shared` is a
2331
- # bare membership test, so a junk non-dict entry parked under the key reads as absent
2332
- # to one and present to the other. It answers with the taken-name 400 this door
2333
- # already has rather than a 500, and anything else re-raises rather than being
2334
- # relabelled as a name collision it is not.
2335
- if not shared_overlay.is_shared(_shared_key(), key, st=session.runtime):
2336
- raise
2337
- raise err(400, "field_key_taken",
2338
- "that column name is already in use on this database") from exc
2339
- else:
2340
- shared_overlay.put_field(_shared_key(), key, defn, st=session.runtime)
2341
-
2342
- # ⛔ AND THE RECORDS THAT LOST THEIR NUMBER ARE CLEARED. A re-solve over a SMALLER cohort
2343
- # would otherwise leave the previous run's ranks sitting on the records that dropped out —
2344
- # plausible integers, from a route nobody is driving. `""` is the house spelling of an empty
2345
- # overlay cell (`rows_from_pool` defaults an absent one to exactly that), so this needs no new
2346
- # vocabulary and no tombstone nobody else reads.
2347
- stale = {}
2348
- for raw_pid, cells in (shared_cells(pool, st=session.runtime) or {}).items():
2349
- if not isinstance(cells, dict) or cells.get(key) in (None, ""):
2350
- continue
2351
- try:
2352
- gone = int(raw_pid)
2353
- except (TypeError, ValueError):
2354
- continue
2355
- if gone not in ranks:
2356
- stale[gone] = {key: ""}
2357
- written = shared_overlay.put_rows(
2358
- _shared_key(), {**{p: {key: str(v)} for p, v in ranks.items()}, **stale},
2359
- st=session.runtime)
2360
-
2361
- out = {"ok": True, "field": key, "label": defn["label"], "type": "int",
2362
- "stops": len(ranks), "cleared": len(stale),
2363
- "rows_written": len(written), "inputsHash": defn["route"]["inputsHash"],
2364
- "depot": defn["route"]["depot"],
2365
- "solvedAt": stamp}
2366
- return out
2367
-
2368
-
2369
- @router.delete("/customers/route-order/{field_key}")
2370
- def route_order_delete(field_key: str,
2371
- session: Session = Depends(module_gate(MODULE))):
2372
- """Remove a Destination column and every visit number in it.
2373
-
2374
- ⛔⛔ WHY THIS DOOR HAD TO EXIST. `route_order_write` mints a TENANT-WIDE column and nothing
2375
- could ever remove it: the grid's own Delete is offered for a per-user `custom_` column
2376
- (`menuField.custom && !menuField.shared`) or for a `ut_*` definition field, and a route order
2377
- is neither — it is a SHARED column on a registry topic. So `Destination 1` was permanent for
2378
- the whole workspace, which is [[reachable-is-not-the-same-as-built]] from the other end:
2379
- `shared_overlay.drop_field` was complete and correct and no route on this topic called it.
2380
-
2381
- ⛔ CREATOR-OR-ADMIN, the same wall `routes_tables.delete_shared_field` applies and for the
2382
- same reason: writing a cell changes a value, dropping the column deletes that value for every
2383
- account at once. It is deliberately NOT the looser wall `route_order_write` uses for CREATE.
2384
-
2385
- ⛔ AND A CALLER WHO CANNOT SEE THE COLUMN GETS THE ANSWER A NONEXISTENT KEY GETS. The refusals
2386
- below would otherwise teach a stranger that a route order exists on this database and who
2387
- planned it, which is exactly what the per-field wall withholds — the choice already argued at
2388
- `route_order_write`'s `field_key_taken` and in `routes_shares._can_see_object`.
2389
- """
2390
- from core import shared_overlay
2391
- import core.perm_scope as perm_scope
2392
- import core.table_store as table_store
2393
- import aios_grid
2394
-
2395
- key = str(field_key or "").strip()
2396
- all_defs = shared_fields(st=session.runtime) or {}
2397
- defn = all_defs.get(key) if isinstance(all_defs.get(key), dict) else None
2398
- # ⭐⭐ OWNER, 2026-08-23 — A PRIVATE FORK IS ALSO A COLUMN TO DELETE. See `_own_route_fork`
2399
- # above: once any per-user write has forked this key, the fork is what the person is looking
2400
- # at and it OUTLIVES a drop of the tenant-wide definition. Answering 404 about a column that
2401
- # is on screen is exactly the refusal the owner hit.
2402
- fork = _own_route_fork(session, key)
2403
- subject = defn or fork
2404
- unknown = err(404, "unknown_field",
2405
- "that column is not a route order column on this database")
2406
- if not subject:
2407
- raise unknown
2408
- # The wall FIRST, so a hidden column is indistinguishable from an absent one.
2409
- # ⚠ ASKED ABOUT THE TENANT-WIDE DEFINITION ONLY, and that is not a hole. The wall reads
2410
- # `FIELD_GRANT_MARK` off the MERGED contract; with the definition already gone there is no
2411
- # marked column left for it to hide, and a fork lives in this caller's OWN stratum, which no
2412
- # grant has ever governed. Not asking when there is nothing to ask about beats asking of a
2413
- # contract that no longer carries the key and reading the empty answer as "not hidden".
2414
- if defn and key in perm_scope.hidden_keys(
2415
- session.user, MODULE,
2416
- _merge_shared_fields(list(aios_grid.FIELDS), all_defs), st=session.runtime):
2417
- raise unknown
2418
- # ⛔ KIND-CHECKED, NOT PREFIX-CHECKED. `ROUTE_KEY_PREFIX` is a naming convention and a
2419
- # convention is not a declaration (the comment on `ROUTE_KIND` says so); a door that deleted
2420
- # by prefix would happily drop a shared column somebody else's feature owns.
2421
- if subject.get("kind") != ROUTE_KIND:
2422
- raise err(400, "not_a_route_column",
2423
- "that column is shared but it is not a route order column, so this door will "
2424
- "not remove it")
2425
- owner = str(subject.get("createdBy") or "")
2426
- if not session.admin and owner != session.uname:
2427
- raise err(403, "forbidden",
2428
- f"a route order column can be removed by the person who planned it or by an "
2429
- f"administrator. This one was planned by {owner or 'somebody else'}, and "
2430
- f"removing it would delete the visit numbers for every account at once")
2431
-
2432
- dropped = bool(defn) and shared_overlay.drop_field(_shared_key(), key, st=session.runtime)
2433
- # ⛔⛔ AND THE FORK GOES IN THE SAME CALL. Dropping only the tenant-wide definition is what
2434
- # made the first delete look like it had worked and then undo itself: the fork still declares
2435
- # the column, `_merge_shared_fields` still yields to it, and the next paint brings it back.
2436
- # `delete_field` scrubs this user's overlay values under the key too, which is right: the
2437
- # tenant-wide cells went with `drop_field` above, and a private leftover would resurface under
2438
- # whatever column later took the key.
2439
- if fork is not None:
2440
- try:
2441
- table_store.make(_shared_key(), st=session.runtime).delete_field(session.uname, key)
2442
- except Exception: # noqa: BLE001
2443
- # The definition is already gone, so a failed fork scrub must not turn a delete that
2444
- # succeeded into a 500. Worst case the column lingers for this one account until its
2445
- # next write, which is recoverable; a 500 over completed work is not.
2446
- pass
2447
- # ⭐⭐ THE GRANT DIES WITH THE COLUMN. `route_order_write` claims
2448
- # `shares.field_oid(SHARE_TOPIC, key)` on create, so skipping this would leave a grant record
2449
- # pointing at nothing — a ghost in every receiver's "Shared with me" that 404s on open, and
2450
- # worse, one that silently re-arms on the next column to take the key, because `drop_field`
2451
- # scrubs the cells precisely so the key CAN be re-used.
2452
- # ⚠ Same order and same tolerance as `routes_tables.delete_shared_field`: the column is
2453
- # already gone, so a failed release must not turn a completed delete into a 500.
2454
- try:
2455
- import core.shares as shares
2456
- shares.drop_objects([("field", shares.field_oid(SHARE_TOPIC, key))], st=session.runtime)
2457
- except Exception: # noqa: BLE001
2458
- pass
2459
- return {"ok": True, "field": key, "dropped": bool(dropped or fork is not None)}
2460
-
2461
-
2462
- @router.patch("/customers/route-order/{field_key}")
2463
- def route_order_rename(field_key: str, body: dict = Body(default=None),
2464
- session: Session = Depends(module_gate(MODULE))):
2465
- """Rename a route order column, or write its description, format or summary.
2466
-
2467
- Body: `{label?, note?, format?, agg?}`.
2468
-
2469
- ⭐⭐ OWNER ITEM 6 (2026-08-23) — "Edit field" MUST BE ABLE TO RENAME THIS COLUMN.
2470
-
2471
- A route order is a SHARED column on the customers REGISTRY topic. The grid's Edit-field pane
2472
- offers a Name box only when the host supplies `onRename`, and the host supplies it only for
2473
- `isUserSchemaField` — a per-user `custom_` column, or a `ut_*` definition field. A route order
2474
- is neither, so the pane showed a DISABLED Name box reading *"A source field keeps its name and
2475
- type from the data source"* about a column the person had created themselves an hour earlier.
2476
- That is the same shape as owner item 3's missing Delete, one stratum over.
2477
-
2478
- ⛔⛔ THE KEY IS FROZEN. `_route_slug` derives the store key from the label AT CREATION, and
2479
- only there. Re-slugging on a rename would leave every written visit number sitting under the
2480
- old key in `shared_overlay`, every saved view's `colId` pointing at a column that no longer
2481
- exists, and every field grant naming an oid nobody can reach — a rename that looks perfect on
2482
- a fresh column and quietly empties a used one. The label moves; nothing else does.
2483
-
2484
- ⛔ CREATOR-OR-ADMIN, and a caller who cannot SEE the column gets the answer a nonexistent key
2485
- gets. Both walls are `route_order_delete`'s, verbatim and for its reasons: this changes what
2486
- every account in the workspace reads, and a refusal that said "forbidden" would confirm to a
2487
- stranger that a route order exists here and who planned it.
2488
-
2489
- ⛔⛔ THE DESCRIPTION RIDES THIS DOOR TOO, AND IT HAD TO. The Edit-field pane writes a
2490
- description through `onNote`, which is `saveField` — a PER-USER `field_upsert`. Traced through
2491
- `grid_events`: a route key is not `custom`-marked in the shared stratum, so the `shared_field`
2492
- branch does not take it; it IS in the merged contract, so the `key in field_by_key` branch
2493
- does, and it stores `{**base, note}` in THIS USER'S field definitions. `_merge_shared_fields`
2494
- then skips the shared definition, because a key the contract already declares wins — so that
2495
- user is left reading a private copy of a tenant-wide column, frozen at the label it had when
2496
- they typed the description, and a later rename through this door is invisible to them.
2497
- Pre-existing, and unreachable enough to have gone unnoticed; owner item 6 makes that pane the
2498
- place people go for route columns, so it stops being unreachable on the same day.
2499
-
2500
- ⛔⛔ D-468 / W46-T22 — **FORMAT AND SUMMARY RIDE THIS DOOR FOR THE SAME REASON THE
2501
- DESCRIPTION DOES, AND THEY ARE THE LAST TWO.** Owner item 6 closed `onNote` and `onRename`.
2502
- Two rows of the same pane were left calling `saveField`, which is the per-user `field_upsert`
2503
- traced above: the **Format** row (`onFormat`, unconditional) and the **Summary** row
2504
- (`onAggregate`, whose `isUserTable` arm is false on this registry topic). Both therefore land
2505
- in `grid_events`'s `key in field_by_key` branch, which writes `format` and `agg` into THAT
2506
- reader's private definitions, `_merge_shared_fields` yields to the fork, and setting a Format
2507
- on a tenant-wide route column silently privatises it for the person who set it, frozen at the
2508
- label it wore that day. This door writes both into the SHARED definition instead, so every
2509
- account keeps reading one column.
2510
-
2511
- ⚠ THE VOCABULARY IS BORROWED, NEVER RE-AUTHORED. `format` goes through
2512
- `aios_grid._clean_format` against the column's own stored type, and `agg` must be a member of
2513
- `aios_grid.FIELD_AGGS`. An unbounded blob on a tenant-wide stratum is a widening, and a second
2514
- copy of these bounds is a second thing to keep in step with `grid_events`.
2515
-
2516
- ⚠ PRESENCE, NOT TRUTHINESS, and a cleared value POPS the key. That is `note`'s rule for
2517
- `note`'s reason: clearing a Format has to be expressible, and a definition with no Format is
2518
- one with no `format` key, which is what every reader of the merged contract already assumes.
2519
-
2520
- ⛔ THE CLIENT HALF IS NOT HERE. `ColumnMenu.tsx::onFormat` and `::onAggregate` still call
2521
- `saveField` for a `kind: route_order` column; they belong to another fence and are booked as
2522
- an amendment. Until they route here the fork is still reachable from the pane, and this door
2523
- is the destination waiting for them, exercised by nothing else.
2524
- """
2525
- from core import shared_overlay
2526
- import core.perm_scope as perm_scope
2527
- import aios_grid
2528
-
2529
- body = body if isinstance(body, dict) else {}
2530
- key = str(field_key or "").strip()
2531
- label = " ".join(str(body.get("label") or "").split())[:120]
2532
- # ⚠ `"note" in body` AND NOT a truthiness test: an empty string is how a description is
2533
- # CLEARED, and a door that read it as "unchanged" would leave one nobody can delete.
2534
- note = str(body.get("note") or "")[:2000] if "note" in body else None
2535
- # ⛔ D-468: the guard below used to read `not label and note is None`, which answered 400 to a
2536
- # format-only or summary-only body and would have left the new door unreachable from the one
2537
- # pane that needs it. Presence of ANY writable key is what makes this a request.
2538
- wants_format, wants_agg = "format" in body, "agg" in body
2539
- if not label and note is None and not wants_format and not wants_agg:
2540
- raise err(400, "bad_request", "a route order column needs a name")
2541
- if "label" in body and not label:
2542
- raise err(400, "bad_request", "a route order column needs a name")
2543
-
2544
- all_defs = shared_fields(st=session.runtime) or {}
2545
- defn = all_defs.get(key) if isinstance(all_defs.get(key), dict) else None
2546
- unknown = err(404, "unknown_field",
2547
- "that column is not a route order column on this database")
2548
- if not defn:
2549
- raise unknown
2550
- if key in perm_scope.hidden_keys(
2551
- session.user, MODULE,
2552
- _merge_shared_fields(list(aios_grid.FIELDS), all_defs), st=session.runtime):
2553
- raise unknown
2554
- if defn.get("kind") != ROUTE_KIND:
2555
- raise err(400, "not_a_route_column",
2556
- "that column is shared but it is not a route order column, so this door will "
2557
- "not rename it")
2558
- owner = str(defn.get("createdBy") or "")
2559
- if not session.admin and owner != session.uname:
2560
- raise err(403, "forbidden",
2561
- f"a route order column can be renamed by the person who planned it or by an "
2562
- f"administrator. This one was planned by {owner or 'somebody else'}, and its "
2563
- f"name is what every account in the workspace reads")
2564
-
2565
- # ⚠ THE COLLISION CHECK LOOKS AT LABELS AND NOT AT KEYS, because the key is frozen: this
2566
- # rename can never take another column's key, only its NAME. Two columns wearing one name on
2567
- # the same grid is the confusion `_next_route_label` exists to prevent at creation, so the
2568
- # rename door refuses it too. The column's OWN current label is excluded, so re-saving an
2569
- # unchanged name is a no-op rather than a refusal.
2570
- _keys, occupied_labels = _occupied(
2571
- {k: v for k, v in all_defs.items() if k != key}, aios_grid.FIELDS)
2572
- if label and label.casefold() in occupied_labels:
2573
- raise err(400, "field_label_taken",
2574
- "this database already has a column with that name")
2575
-
2576
- patch = dict(defn)
2577
- if label:
2578
- patch["label"] = label
2579
- if note is not None:
2580
- patch["note"] = note
2581
- if wants_format:
2582
- cleaned = aios_grid._clean_format(body.get("format"), defn.get("type"))
2583
- if cleaned:
2584
- patch["format"] = cleaned
2585
- else:
2586
- patch.pop("format", None)
2587
- if wants_agg:
2588
- summary = body.get("agg")
2589
- if summary in aios_grid.FIELD_AGGS:
2590
- patch["agg"] = summary
2591
- else:
2592
- patch.pop("agg", None)
2593
- shared_overlay.put_field(_shared_key(), key, patch, st=session.runtime)
2594
- return {"ok": True, "field": key, "label": patch.get("label") or key,
2595
- "note": patch.get("note") or "",
2596
- "format": patch.get("format"), "agg": patch.get("agg")}
2597
-
2598
-
2599
  # ---------------------------------------------------------------------------
2600
  # W43C-T03 / C2 — scheduled, frozen route delivery
2601
  # ---------------------------------------------------------------------------
 
24
  import datetime as _dt
25
  import hashlib
26
  import json
 
27
  import time
28
 
29
  from fastapi import APIRouter, Body, Depends
30
 
31
  import scope_cache
32
+ from deps import Session, err, module_gate
33
 
34
  router = APIRouter(prefix="/api/v1")
35
 
 
394
  # only order in which the per-field grant marker is ever presented to `hidden_keys`.
395
  _strata = {}
396
  fields = _merge_shared_fields(fields, _defs, session=session, strata=_strata)
397
+ # ⭐ A display-hide for MIGRATED legacy `route_order` columns stood here. It was a projection
398
+ # only — the column stayed in the shared document for rollback while its receipt proved parity.
399
+ # Every such column has since been deleted from every tenant schema and each receipt carries
400
+ # `legacyFieldDeleted`, so the filter could only ever match nothing. A rollback net for a
401
+ # rollback nobody can perform is not a net.
 
 
 
 
402
  fields = _mark_offerability(fields)
403
  # ⭐⭐ W41-T01 / RULING R5 / CONTRACTS C1 + C8 — **THE THREE BADGES, STAMPED ONCE, HERE.**
404
  #
 
562
  # read-only customer fields; neither is a generic Link or an editable user-table cell.
563
  # Route names and membership are object data too: a private Route must not leak through the
564
  # derived customer column while its navigator correctly hides it.
565
+ from core import route_system
566
  normalized_routes = [route for route, _mark in _visible_normalized_routes(session)]
567
  normalized_zones = route_system.list_zones(rt, rows_src)
568
  fields = [field for field in fields if field.get("key") not in {"routes", "zone"}]
 
788
  f"to update an existing {subject}")
789
 
790
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
791
  def _route_share_records(session):
792
  """One normalized registry read for list visibility and every share mark."""
793
  from core import field_permissions
 
831
  return visible
832
 
833
 
834
+ def _visible_routes(session, records=None):
835
+ """Every normalized Route this caller may see.
836
+
837
+ ⭐⭐ THIS WAS `_compatible_routes`, AND THE RENAME IS THE POINT: there is nothing left to be
838
+ compatible WITH. It used to append a read-only projection of the legacy one-column-per-route
839
+ scheme (`route_system.compatible_routes` over `_legacy_route_defs_readonly`) so those Routes
840
+ did not vanish before an administrator ran the migration. That scheme is RETIRED — the
841
+ migration has run against every tenant schema in the database (`t_gtmlab`, `t_loopable`,
842
+ `t_nurilab`, `t_qa_b`, `t_qa_pg`, `t_royal_imports`) and every one of them now holds zero
843
+ `route_order` columns, with the deletion stamped on each column's own verified receipt.
844
 
845
+ ⛔ A NAME THAT PROMISES COMPATIBILITY OUTLIVES THE THING IT WAS COMPATIBLE WITH, and then the
846
+ next reader keeps the branch alive because the name says it matters. So it goes with the code.
 
 
 
847
  """
848
+ return [route for route, _mark in _visible_normalized_routes(session, records)]
 
 
 
 
 
 
 
 
 
849
 
850
 
851
  def _legacy_route_navigation(session):
 
874
  if int(stop.get("customerPid")) in allowed]
875
  visible = [int(stop["customerPid"]) for stop in stops]
876
  active = {int(pid) for pid in active if int(pid) in allowed}
 
877
  mark = share_mark if isinstance(share_mark, dict) else _route_share_mark(session, route)
878
  owns_route = bool(session.admin or (
879
  mark.get("owner") and mark.get("owner") == str(session.uname or "").strip().lower()))
 
893
  # `owns_route`), an explicit `edit` share on the Route, then an editor of the source View.
894
  # `can_duplicate` stays `source_edit` alone, because `duplicate_route` genuinely does raise
895
  # `route_view_read_only` without it — that door is not the one R6 corrected.
896
+ # ⭐ `not compatibility and ...` led this expression until the legacy projection was retired.
897
+ # Only a projected Route ever carried that marker, and nothing mints one now.
898
+ can_edit = bool(owns_route or mark.get("sharedRole") == "edit" or source_edit)
899
  dto = {"id": route["id"], "name": route["name"], "color": route["color"],
900
  "number": route["number"], "visibleStopIds": visible,
901
  "outsideFilter": bool(active) and not bool(active.intersection(visible)),
 
916
  "sharedOut": mark["sharedOut"], "hasShares": mark["hasShares"],
917
  "sharedRole": mark["sharedRole"], "shareId": mark["shareId"],
918
  "folderId": route.get("folderId"), "navOrder": route.get("navOrder", 0)}
 
 
919
  if route.get("mapsUrl"):
920
  dto["mapsUrl"] = route["mapsUrl"]
921
  return dto
 
1024
 
1025
 
1026
  def _route_nav_mutation_context(session):
1027
+ routes = _visible_routes(session)
1028
  folders, placements = _legacy_route_navigation(session)
1029
  return routes, folders, placements
1030
 
 
1122
  """
1123
  allowed = allowed_pids(session)
1124
  records = _route_share_records(session)
1125
+ navigation = _route_navigation(session, _visible_routes(session, records))
1126
  return {"routes": [_route_dto(
1127
  route, allowed, (), session,
1128
  _route_share_mark(session, route, records))
 
1377
  from core import route_system
1378
  raw = dict(body or {})
1379
  chosen = [str(item) for item in raw.get("routeIds") or ()]
1380
+ compatible = _visible_routes(session)
1381
  known = {route["id"] for route in compatible}
1382
  if any(route_id not in known for route_id in chosen):
1383
  raise err(404, "route_not_found", "a selected Route does not exist")
 
1453
  return {"today": g["today"], "exports": exports}
1454
 
1455
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1456
  def _zone_can_edit(session, source_view_id):
1457
  return bool(session.admin) or _route_view_can_edit(session, source_view_id)
1458
 
 
1538
  return {"deleted": True}
1539
 
1540
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1541
  @router.patch("/customers/{pid}")
1542
  def patch_customer(pid: int, body: dict = Body(default=None),
1543
  session: Session = Depends(module_gate(MODULE))):
 
1594
  # paste, fill, undo, the record drawer — comes through this one door; a client-side branch
1595
  # would have to be repeated at each of them and would be wrong at the first one nobody
1596
  # remembered.
 
 
1597
  if updates:
1598
  try:
1599
  grid_events.handle_one(
 
1603
  raise err(503, "store_unavailable",
1604
  "the tenant store is unavailable. Your change was not saved")
1605
 
1606
+ # ⭐ The legacy route-rank interception used to sit here: a `route_order` column stored a
1607
+ # customer's POSITION as a cell, so an ordinary cell patch had to be split out and rank-swapped
1608
+ # before it reached `grid_events`. Stops live on the Route record now, so a cell is just a cell.
1609
  route_accepted, route_swaps, route_taken = ({}, [], set())
1610
+ route_updates = {}
 
 
1611
 
1612
  # What actually landed, read back from the store rather than echoed from the request: a
1613
  # refused key or a truncated value must not be reported as accepted.
 
1706
  SHARE_TOPIC = MODULE
1707
 
1708
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1709
  # ---------------------------------------------------------------------------
1710
  # W43C-T03 / C2 — scheduled, frozen route delivery
1711
  # ---------------------------------------------------------------------------
platform/core/route_system.py CHANGED
The diff for this file is too large to render. See raw diff
 
web/src/customer-grid/CustomerGrid.tsx CHANGED
The diff for this file is too large to render. See raw diff
 
web/src/customer-grid/MapView.tsx CHANGED
@@ -675,7 +675,7 @@ export function MapView({
675
  /** C3 Zone chooser/editor state. `null` means the tenant read has not answered; an empty
676
  * array is an honest, editable no-Zones state. */
677
  const [zones, setZones] = useState<MapZone[] | null>(null);
678
- /** C2 named-route read model. Legacy route-order columns remain compatibility only. */
679
  const [namedRoutes, setNamedRoutes] = useState<MapRouteDto[]>([]);
680
  const [routeFolders, setRouteFolders] = useState<MapRouteFolderDto[]>([]);
681
  const [routeAssignees, setRouteAssignees] = useState<RouteAssigneeDirectory | null>(null);
@@ -1301,7 +1301,7 @@ export function MapView({
1301
  const actionAllowed = "starred" in patch
1302
  ? route.capabilities?.star === true
1303
  : scheduleChange ? route.permission.canEdit === true : route.capabilities?.rename === true;
1304
- if (!actionAllowed || route.compatibility === "legacy-route-order")
1305
  return "This Route is read-only.";
1306
  try {
1307
  const res = await fetch(`/api/v1/customers/routes/${encodeURIComponent(route.id)}`, {
@@ -1320,7 +1320,7 @@ export function MapView({
1320
  }, []);
1321
 
1322
  const deleteNamedRoute = useCallback(async (route: MapRouteDto): Promise<string | null> => {
1323
- if (route.capabilities?.delete !== true || route.compatibility === "legacy-route-order")
1324
  return "This Route is read-only.";
1325
  try {
1326
  const res = await fetch(`/api/v1/customers/routes/${encodeURIComponent(route.id)}`, {
@@ -1368,7 +1368,7 @@ export function MapView({
1368
  setRoutePinNotice("Open a route first.");
1369
  return;
1370
  }
1371
- if (!activeNamedRoute.permission.canEdit || activeNamedRoute.compatibility === "legacy-route-order") {
1372
  setRoutePinPrompt(null);
1373
  setRoutePinNotice("This Route is read-only.");
1374
  return;
@@ -1467,7 +1467,7 @@ export function MapView({
1467
  } catch { return "The Route could not be created."; }
1468
  }, [activeView, loadNamedRoutes]);
1469
  const duplicateNamedRoute = useCallback(async (route: MapRouteDto): Promise<string | null> => {
1470
- if (route.capabilities?.duplicate !== true || route.compatibility === "legacy-route-order")
1471
  return "This Route cannot be duplicated.";
1472
  try {
1473
  const res = await fetch(`/api/v1/customers/routes/${encodeURIComponent(route.id)}/duplicate`, {
@@ -1484,7 +1484,7 @@ export function MapView({
1484
  } catch { return "The Route could not be duplicated."; }
1485
  }, [loadNamedRoutes]);
1486
  const shareNamedRoute = useCallback(async (route: MapRouteDto): Promise<string | null> => {
1487
- if (route.capabilities?.share !== true || route.compatibility === "legacy-route-order")
1488
  return "Only the Route owner can share this Route.";
1489
  try {
1490
  const res = await fetch(`/api/v1/customers/routes/${encodeURIComponent(route.id)}/share-ready`, {
@@ -3226,7 +3226,7 @@ export function MapView({
3226
  return `${title}. Click or press Enter to open the record. ${selectionHint}`;
3227
  if (!activeNamedRoute)
3228
  return `${title}. Routes are open. Open a route first. ${selectionHint}`;
3229
- if (!activeNamedRoute.permission.canEdit || activeNamedRoute.compatibility === "legacy-route-order")
3230
  return `${title}. ${activeNamedRoute.name} is read-only. ${selectionHint}`;
3231
  const action = activeNamedRoute.visibleStopIds.includes(point.pid) ? "remove" : "add";
3232
  return `${title}. Plain click or Enter asks to ${action} this stop ${action === "add" ? "to" : "from"} ${activeNamedRoute.name}. ${selectionHint}`;
@@ -3843,7 +3843,7 @@ export function MapView({
3843
  Scroll to zoom · drag to pan · {lassoTool ? "shift-drag to lasso" : "shift-drag to select"}{" "}
3844
  · shift-alt-drag to extend the selection · {routePanelOpen
3845
  ? activeNamedRoute
3846
- ? activeNamedRoute.permission.canEdit && activeNamedRoute.compatibility !== "legacy-route-order"
3847
  ? `click or press Enter on a pin to ask to add or remove it from ${activeNamedRoute.name}`
3848
  : `${activeNamedRoute.name} is read-only; plain click or Enter does not open a record`
3849
  : "open a route first; plain click or Enter does not open a record"
 
675
  /** C3 Zone chooser/editor state. `null` means the tenant read has not answered; an empty
676
  * array is an honest, editable no-Zones state. */
677
  const [zones, setZones] = useState<MapZone[] | null>(null);
678
+ /** C2 named-route read model. */
679
  const [namedRoutes, setNamedRoutes] = useState<MapRouteDto[]>([]);
680
  const [routeFolders, setRouteFolders] = useState<MapRouteFolderDto[]>([]);
681
  const [routeAssignees, setRouteAssignees] = useState<RouteAssigneeDirectory | null>(null);
 
1301
  const actionAllowed = "starred" in patch
1302
  ? route.capabilities?.star === true
1303
  : scheduleChange ? route.permission.canEdit === true : route.capabilities?.rename === true;
1304
+ if (!actionAllowed)
1305
  return "This Route is read-only.";
1306
  try {
1307
  const res = await fetch(`/api/v1/customers/routes/${encodeURIComponent(route.id)}`, {
 
1320
  }, []);
1321
 
1322
  const deleteNamedRoute = useCallback(async (route: MapRouteDto): Promise<string | null> => {
1323
+ if (route.capabilities?.delete !== true)
1324
  return "This Route is read-only.";
1325
  try {
1326
  const res = await fetch(`/api/v1/customers/routes/${encodeURIComponent(route.id)}`, {
 
1368
  setRoutePinNotice("Open a route first.");
1369
  return;
1370
  }
1371
+ if (!activeNamedRoute.permission.canEdit) {
1372
  setRoutePinPrompt(null);
1373
  setRoutePinNotice("This Route is read-only.");
1374
  return;
 
1467
  } catch { return "The Route could not be created."; }
1468
  }, [activeView, loadNamedRoutes]);
1469
  const duplicateNamedRoute = useCallback(async (route: MapRouteDto): Promise<string | null> => {
1470
+ if (route.capabilities?.duplicate !== true)
1471
  return "This Route cannot be duplicated.";
1472
  try {
1473
  const res = await fetch(`/api/v1/customers/routes/${encodeURIComponent(route.id)}/duplicate`, {
 
1484
  } catch { return "The Route could not be duplicated."; }
1485
  }, [loadNamedRoutes]);
1486
  const shareNamedRoute = useCallback(async (route: MapRouteDto): Promise<string | null> => {
1487
+ if (route.capabilities?.share !== true)
1488
  return "Only the Route owner can share this Route.";
1489
  try {
1490
  const res = await fetch(`/api/v1/customers/routes/${encodeURIComponent(route.id)}/share-ready`, {
 
3226
  return `${title}. Click or press Enter to open the record. ${selectionHint}`;
3227
  if (!activeNamedRoute)
3228
  return `${title}. Routes are open. Open a route first. ${selectionHint}`;
3229
+ if (!activeNamedRoute.permission.canEdit)
3230
  return `${title}. ${activeNamedRoute.name} is read-only. ${selectionHint}`;
3231
  const action = activeNamedRoute.visibleStopIds.includes(point.pid) ? "remove" : "add";
3232
  return `${title}. Plain click or Enter asks to ${action} this stop ${action === "add" ? "to" : "from"} ${activeNamedRoute.name}. ${selectionHint}`;
 
3843
  Scroll to zoom · drag to pan · {lassoTool ? "shift-drag to lasso" : "shift-drag to select"}{" "}
3844
  · shift-alt-drag to extend the selection · {routePanelOpen
3845
  ? activeNamedRoute
3846
+ ? activeNamedRoute.permission.canEdit
3847
  ? `click or press Enter on a pin to ask to add or remove it from ${activeNamedRoute.name}`
3848
  : `${activeNamedRoute.name} is read-only; plain click or Enter does not open a record`
3849
  : "open a route first; plain click or Enter does not open a record"
web/src/customer-grid/RouteNav.tsx CHANGED
The diff for this file is too large to render. See raw diff
 
web/src/customer-grid/apiBridge.ts CHANGED
The diff for this file is too large to render. See raw diff
 
web/src/customer-grid/display.ts CHANGED
The diff for this file is too large to render. See raw diff
 
web/src/customer-grid/routeZoneTypes.ts CHANGED
@@ -1,150 +1,148 @@
1
- // Wave 44 Route / Zone wire model. MapView never writes a legacy Destination N field.
2
- export type ZoneGeometry =
3
- | { type: "Polygon"; coordinates: number[][][] }
4
- | { type: "MultiPolygon"; coordinates: number[][][][] }
5
- | { type: "Circle"; center: [number, number]; radiusMeters: number };
6
-
7
- export interface MapZoneDto {
8
- id: string; name: string; color: string; geometryGeoJson: ZoneGeometry | null;
9
- zipCodes: string[]; visible: boolean; memberships: number[];
10
- geographicField?: string;
11
- membershipRevision?: number;
12
- sourceViewId?: string | null;
13
- createdBy?: string;
14
- createdAt?: string;
15
- permission?: { canEdit?: boolean; canDelete?: boolean };
16
- }
17
-
18
- export interface RouteDeliveryDto {
19
- id: string;
20
- name: string;
21
- recipient: string;
22
- schedule: { cron?: string; enabled?: boolean; timezone?: string };
23
- snapshot: {
24
- routeId: string;
25
- sourceViewId: string;
26
- sourceViewRevision: string;
27
- sourceViewName: string;
28
- timezone: string;
29
- routeField: string;
30
- orderedStopIds: number[];
31
- mapsPerLink: number;
32
- };
33
- createdBy?: string;
34
- created?: string;
35
- }
36
-
37
- export interface RouteDeliveryRequest {
38
- recipient: string;
39
- timezone: string;
40
- mapsPerLink: number;
41
- }
42
-
43
- export interface RouteAssignee {
44
- username: string;
45
- name: string;
46
- }
47
-
48
- export interface RouteAssigneeDirectory {
49
- today: string;
50
- people: RouteAssignee[];
51
- }
52
-
53
- export interface MapRouteDto {
54
- id: string; name: string; color: string; number: number; visibleStopIds: number[];
55
- outsideFilter: boolean;
56
- permission: { canEdit: boolean; sourceViewId: string | null };
57
- source: { viewId: string | null; revision: string | null };
58
- /** Read-through of a saved route-order field. It remains visible without mutating on GET. */
59
- compatibility?: "legacy-route-order";
60
- mapsUrl?: string;
61
- owner: string;
62
- shared: boolean;
63
- sharedOut: boolean;
64
- hasShares: boolean;
65
- sharedRole: "view" | "edit" | null;
66
- /** Generic field bridge address consumed by the established Share dialog. */
67
- shareId: string;
68
- /** This reader's personal Route filing; it never changes the shared Route object. */
69
- folderId: string | null;
70
- navOrder: number;
71
- assignee: string | null;
72
- date: string | null;
73
- /** D-599: the Zone this Route belongs to, or null. Always present on the wire; every Route
74
- * saved before wave 46's hotfix legitimately has none, so null is data and not an error. */
75
- zoneId: string | null;
76
- starred?: boolean;
77
- capabilities?: Partial<Record<"rename" | "duplicate" | "star" | "share" | "delete", boolean>>;
78
- }
79
-
80
- export interface MapRouteFolderDto {
81
- id: string;
82
- name: string;
83
- parent: string | null;
84
- order: number;
85
- }
86
-
87
- export type MapRouteUpdate = {
88
- name?: string;
89
- mapsUrl?: string;
90
- /** OWNER 2026-08-31 item 2 - the Route's own colour, the one `MapView::overlaidRoutes` strokes
91
- * the line with and the one the rail's checkbox swatch shows. `route_system.py::_color`
92
- * already validated and persisted it on every write; nothing could SEND it until now.
93
- * ⚠ An unrecognised value is not an error: the server falls back to the ordinal default
94
- * rather than letting an empty string paint the SVG initial black (W47-T02's defect). */
95
- color?: string;
96
- starred?: boolean;
97
- assignee?: string | null;
98
- date?: string | null;
99
- /** D-599. Absent inherits the stored Zone; an explicit null clears it. The server refuses an
100
- * id no Zone on this database carries, with `unknown_zone`. */
101
- zoneId?: string | null;
102
- };
103
-
104
- export interface RouteSelectionRequest { routeIds: string[]; viewState: Record<string, unknown>; }
105
-
106
- export interface RouteSelectionResponse {
107
- managedBy: "loopable";
108
- viewState: Record<string, unknown>;
109
- }
110
-
111
- /** The authored sources that can become a named Route.
112
- * ⭐ W47-T06 (owner instruction 7) added `filtered`. The owner: *"The 'Create all X filtered
113
- * records' we don't need this button under Routes navigation ... when we click Create route it
114
- * should show 3 options instead of 2 now in the Route source section."* So the capability MOVED
115
- * into the picker rather than being deleted; the standalone button is gone. */
116
- export type MapRouteSource = {
117
- id: "selection" | "zones" | "filtered";
118
- label: string;
119
- pids: number[];
120
- };
121
-
122
- /** A map may show one navigator at a time. The Routes rail wins when its host toggle is open. */
123
- export function mapNavigatorMode(routeOpen: boolean, zoneOpen: boolean): "routes" | "zones" | null {
124
- if (!routeOpen) return null;
125
- return zoneOpen ? "zones" : "routes";
126
- }
127
-
128
- /** Toggle exactly one named Route while preserving the existing multi-selection. */
129
- export function toggleRouteSelection(selected: ReadonlySet<string>, routeId: string): Set<string> {
130
- const next = new Set(selected);
131
- if (next.has(routeId)) next.delete(routeId);
132
- else next.add(routeId);
133
- return next;
134
- }
135
-
136
- /** Route creation never submits duplicate, empty, or non-customer IDs from either source. */
137
- export function routeSourceStopIds(pids: Iterable<number>): number[] {
138
- return [...new Set([...pids].filter((pid) => Number.isSafeInteger(pid) && pid > 0))];
139
- }
140
-
141
- /** Only a bounded HTTPS Google Maps link may leave the in-app Route detail. */
142
- export function boundedGoogleMapsUrl(value: string | undefined): string | null {
143
- if (!value || value.length > 2_048) return null;
144
- try {
145
- const url = new URL(value);
146
- return url.protocol === "https:" && /(^|\.)google\.[a-z.]+$/i.test(url.hostname) ? url.href : null;
147
- } catch {
148
- return null;
149
- }
150
- }
 
1
+ // Wave 44 Route / Zone wire model. MapView never writes a legacy Destination N field.
2
+ export type ZoneGeometry =
3
+ | { type: "Polygon"; coordinates: number[][][] }
4
+ | { type: "MultiPolygon"; coordinates: number[][][][] }
5
+ | { type: "Circle"; center: [number, number]; radiusMeters: number };
6
+
7
+ export interface MapZoneDto {
8
+ id: string; name: string; color: string; geometryGeoJson: ZoneGeometry | null;
9
+ zipCodes: string[]; visible: boolean; memberships: number[];
10
+ geographicField?: string;
11
+ membershipRevision?: number;
12
+ sourceViewId?: string | null;
13
+ createdBy?: string;
14
+ createdAt?: string;
15
+ permission?: { canEdit?: boolean; canDelete?: boolean };
16
+ }
17
+
18
+ export interface RouteDeliveryDto {
19
+ id: string;
20
+ name: string;
21
+ recipient: string;
22
+ schedule: { cron?: string; enabled?: boolean; timezone?: string };
23
+ snapshot: {
24
+ routeId: string;
25
+ sourceViewId: string;
26
+ sourceViewRevision: string;
27
+ sourceViewName: string;
28
+ timezone: string;
29
+ routeField: string;
30
+ orderedStopIds: number[];
31
+ mapsPerLink: number;
32
+ };
33
+ createdBy?: string;
34
+ created?: string;
35
+ }
36
+
37
+ export interface RouteDeliveryRequest {
38
+ recipient: string;
39
+ timezone: string;
40
+ mapsPerLink: number;
41
+ }
42
+
43
+ export interface RouteAssignee {
44
+ username: string;
45
+ name: string;
46
+ }
47
+
48
+ export interface RouteAssigneeDirectory {
49
+ today: string;
50
+ people: RouteAssignee[];
51
+ }
52
+
53
+ export interface MapRouteDto {
54
+ id: string; name: string; color: string; number: number; visibleStopIds: number[];
55
+ outsideFilter: boolean;
56
+ permission: { canEdit: boolean; sourceViewId: string | null };
57
+ source: { viewId: string | null; revision: string | null };
58
+ mapsUrl?: string;
59
+ owner: string;
60
+ shared: boolean;
61
+ sharedOut: boolean;
62
+ hasShares: boolean;
63
+ sharedRole: "view" | "edit" | null;
64
+ /** Generic field bridge address consumed by the established Share dialog. */
65
+ shareId: string;
66
+ /** This reader's personal Route filing; it never changes the shared Route object. */
67
+ folderId: string | null;
68
+ navOrder: number;
69
+ assignee: string | null;
70
+ date: string | null;
71
+ /** D-599: the Zone this Route belongs to, or null. Always present on the wire; every Route
72
+ * saved before wave 46's hotfix legitimately has none, so null is data and not an error. */
73
+ zoneId: string | null;
74
+ starred?: boolean;
75
+ capabilities?: Partial<Record<"rename" | "duplicate" | "star" | "share" | "delete", boolean>>;
76
+ }
77
+
78
+ export interface MapRouteFolderDto {
79
+ id: string;
80
+ name: string;
81
+ parent: string | null;
82
+ order: number;
83
+ }
84
+
85
+ export type MapRouteUpdate = {
86
+ name?: string;
87
+ mapsUrl?: string;
88
+ /** OWNER 2026-08-31 item 2 - the Route's own colour, the one `MapView::overlaidRoutes` strokes
89
+ * the line with and the one the rail's checkbox swatch shows. `route_system.py::_color`
90
+ * already validated and persisted it on every write; nothing could SEND it until now.
91
+ * ⚠ An unrecognised value is not an error: the server falls back to the ordinal default
92
+ * rather than letting an empty string paint the SVG initial black (W47-T02's defect). */
93
+ color?: string;
94
+ starred?: boolean;
95
+ assignee?: string | null;
96
+ date?: string | null;
97
+ /** D-599. Absent inherits the stored Zone; an explicit null clears it. The server refuses an
98
+ * id no Zone on this database carries, with `unknown_zone`. */
99
+ zoneId?: string | null;
100
+ };
101
+
102
+ export interface RouteSelectionRequest { routeIds: string[]; viewState: Record<string, unknown>; }
103
+
104
+ export interface RouteSelectionResponse {
105
+ managedBy: "loopable";
106
+ viewState: Record<string, unknown>;
107
+ }
108
+
109
+ /** The authored sources that can become a named Route.
110
+ * ⭐ W47-T06 (owner instruction 7) added `filtered`. The owner: *"The 'Create all X filtered
111
+ * records' we don't need this button under Routes navigation ... when we click Create route it
112
+ * should show 3 options instead of 2 now in the Route source section."* So the capability MOVED
113
+ * into the picker rather than being deleted; the standalone button is gone. */
114
+ export type MapRouteSource = {
115
+ id: "selection" | "zones" | "filtered";
116
+ label: string;
117
+ pids: number[];
118
+ };
119
+
120
+ /** A map may show one navigator at a time. The Routes rail wins when its host toggle is open. */
121
+ export function mapNavigatorMode(routeOpen: boolean, zoneOpen: boolean): "routes" | "zones" | null {
122
+ if (!routeOpen) return null;
123
+ return zoneOpen ? "zones" : "routes";
124
+ }
125
+
126
+ /** Toggle exactly one named Route while preserving the existing multi-selection. */
127
+ export function toggleRouteSelection(selected: ReadonlySet<string>, routeId: string): Set<string> {
128
+ const next = new Set(selected);
129
+ if (next.has(routeId)) next.delete(routeId);
130
+ else next.add(routeId);
131
+ return next;
132
+ }
133
+
134
+ /** Route creation never submits duplicate, empty, or non-customer IDs from either source. */
135
+ export function routeSourceStopIds(pids: Iterable<number>): number[] {
136
+ return [...new Set([...pids].filter((pid) => Number.isSafeInteger(pid) && pid > 0))];
137
+ }
138
+
139
+ /** Only a bounded HTTPS Google Maps link may leave the in-app Route detail. */
140
+ export function boundedGoogleMapsUrl(value: string | undefined): string | null {
141
+ if (!value || value.length > 2_048) return null;
142
+ try {
143
+ const url = new URL(value);
144
+ return url.protocol === "https:" && /(^|\.)google\.[a-z.]+$/i.test(url.hostname) ? url.href : null;
145
+ } catch {
146
+ return null;
147
+ }
148
+ }