fsanyoto commited on
Commit
8229039
·
verified ·
1 Parent(s): 74f72af

Deploy AIOS web (React glide grid + FastAPI slice)

Browse files
RELEASES.json CHANGED
@@ -1,6 +1,12 @@
1
  {
2
- "current": "v62 (2c8f702)",
3
  "releases": [
 
 
 
 
 
 
4
  {
5
  "version": "v62",
6
  "sha": "2c8f702",
 
1
  {
2
+ "current": "v63 (ec75cb8)",
3
  "releases": [
4
+ {
5
+ "version": "v63",
6
+ "sha": "ec75cb8",
7
+ "date": "2026-08-31",
8
+ "subject": "release v63"
9
+ },
10
  {
11
  "version": "v62",
12
  "sha": "2c8f702",
VERSION CHANGED
@@ -1 +1 @@
1
- v62 (2c8f702)
 
1
+ v63 (ec75cb8)
api/routes_grid.py CHANGED
@@ -1145,6 +1145,167 @@ def recurrence_preview(body: dict = Body(default=None),
1145
  }
1146
 
1147
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1148
  # ── ⭐⭐ W47-T26 (owner instruction 13 / ruling R2, contract C5): THE NEXT DATE IS A REAL CELL ─
1149
  #
1150
  # R2, verbatim: the computed next date is STORED in the cell, "so it filters, sorts and groups
 
1145
  }
1146
 
1147
 
1148
+ # ── ⭐⭐ OWNER 2026-08-31 — A REPEAT RULE BELONGS TO THE RECORD, AND IT REVERSES WAVE 47's R1/R2 ─
1149
+ #
1150
+ # Owner, verbatim: *"THE EDIT REPEAT IS STILL NOT PER FIELD."* Asked which of three readings that
1151
+ # was, and shown wave 47's own ruling that a column anchor is what makes a rule per-record, they
1152
+ # chose *"Each ROW stores its own repeat rule. Reverse R1/R2."* A current owner instruction beats
1153
+ # a recorded older one, and the comment the older one left behind is rewritten in the same change
1154
+ # rather than left for the next reader to undo (`core/record_recurrence.py`'s header).
1155
+ #
1156
+ # ⛔ THE FIELD'S RULE SURVIVES AS THE DEFAULT A ROW INHERITS. `_recurrence_columns` and
1157
+ # `_materialise_recurrence_cells` are untouched: a column with a rule and no per-record overrides
1158
+ # behaves exactly as it did this morning. What changes is that the picker now writes the RECORD.
1159
+ #
1160
+ # ⭐⭐ AND THIS IS WHAT CLOSES THE SECOND HALF OF THE OWNER'S COMPLAINT — *"IT STILL DOESN'T
1161
+ # POPULATE THE CELL AS THE NEXTDATE WHEN I CLICK IT ... IT IS ONLY POPULATING WHEN I CLICK THE DATE
1162
+ # IN THE CALENDAR ITSELF."* `_materialise_recurrence_cells` writes the cell on `field_upsert`, and
1163
+ # its own scope note says it materialises for `ut_*` USER TABLES ONLY, because the registry topics
1164
+ # patch ONE pid per call and writing ~3,600 customer rows that way is a performance defect. A
1165
+ # PER-RECORD rule is one row by construction, so that wall is simply not on this path: this door
1166
+ # returns the ONE next date and the browser writes it through `patchAndRecord`, the same door a
1167
+ # typed edit takes, keeping the undo stack and the permission check that already exist.
1168
+ #
1169
+ # ⚠ ROW-LEVEL PERMISSION, STATED RATHER THAN ASSUMED. `workspace()` refuses a scope this session
1170
+ # cannot open and `govern_date_recurrence` refuses a field it cannot see, so the COLUMN is walled.
1171
+ # The bucket is tenant-bound through `session.runtime`, so no rule can cross a tenant. There is no
1172
+ # per-ROW wall here beyond that, which matches every other per-record sidecar in the tree
1173
+ # (`record_comments` reaches its rows the same way); a cohort-scoped reader can therefore store a
1174
+ # rule against a pid outside their cohort if they can name it. Booked rather than hidden.
1175
+
1176
+
1177
+ def _record_next_date(recurrence, anchor_value, condition_fields):
1178
+ """The next date ONE record's rule names, with the empty-cell fallback this door owns.
1179
+
1180
+ ⭐⭐ THE CASE THAT SHIPPED BROKEN THE FIRST TIME, and it is the likeliest one there is: a
1181
+ person opens an EMPTY date cell and sets a repeat. `recurrence_row_next_date` answers `None`
1182
+ for an empty anchor, so the rule stored, the door answered `nextDate: null`, and the browser's
1183
+ `if (data.nextDate)` wrote nothing - the cell stayed empty, which is the owner's complaint
1184
+ verbatim. Found by driving the door against `anchorValue: null` on the deployed build.
1185
+
1186
+ ⛔ THIS DOES NOT OVERTURN W47-T25, AND THE DISTINCTION IS THE WHOLE ARGUMENT. That ruling
1187
+ forbids falling back to the FIELD-level `startDate`, because a field's rule is shared by every
1188
+ row and the fallback would hand a whole column the SAME date - "a column full of confident
1189
+ wrong values instead of an honestly empty one", in its own words. A PER-RECORD rule's
1190
+ `startDate` is `selectedIso`: the day THAT row's picker was showing when the person pressed
1191
+ Save. One row, one date, chosen by the person looking at it. The reason the ruling gives does
1192
+ not reach this case.
1193
+
1194
+ ⚠ THE COLUMN SWEEP IS UNTOUCHED. `recurrence_row_next_date` keeps its behaviour exactly, so
1195
+ `_materialise_recurrence_cells` and the nightly roll-forward still answer empty for an empty
1196
+ anchor. The fallback lives HERE, on the per-record door, and nowhere else.
1197
+ """
1198
+ import aios_grid
1199
+
1200
+ if not isinstance(recurrence, dict):
1201
+ return None
1202
+ today = time.strftime("%Y-%m-%d")
1203
+ answer = aios_grid.recurrence_row_next_date(
1204
+ recurrence, anchor_value, today=today, condition_fields=condition_fields)
1205
+ if answer or str(anchor_value or "").strip():
1206
+ return answer
1207
+ return aios_grid.recurrence_row_next_date(
1208
+ recurrence, recurrence.get("startDate"), today=today,
1209
+ condition_fields=condition_fields)
1210
+
1211
+
1212
+ def _record_recurrence_request(body):
1213
+ """The three things every door below needs, validated once."""
1214
+ body = body if isinstance(body, dict) else {}
1215
+ scope = _scope_or_400(body.get("scopeKey"))
1216
+ try:
1217
+ pid = int(body.get("pid"))
1218
+ except (TypeError, ValueError):
1219
+ raise err(400, "bad_record", "a per-record repeat rule names one record")
1220
+ field_key = str(body.get("field") or "").strip()
1221
+ if not field_key:
1222
+ raise err(400, "bad_field", "a per-record repeat rule names one Date field")
1223
+ return scope, pid, field_key
1224
+
1225
+
1226
+ @router.post("/grid/record-recurrence/read")
1227
+ def record_recurrence_read(body: dict = Body(default=None),
1228
+ session: Session = Depends(require_session)):
1229
+ """ONE record's stored rule for ONE column, plus the next date it currently names.
1230
+
1231
+ A POST rather than a GET because the scope key, the pid and the field key are three
1232
+ parameters this app already sends as a body everywhere else on this router, and because a
1233
+ read that names a record does not belong in a URL that lands in a browser history.
1234
+
1235
+ ``inherited`` is the honest fourth state beside "has a rule": the row has none of its own and
1236
+ is answering with the COLUMN's, which is a different sentence from "no repeat" and the picker
1237
+ renders it as one.
1238
+ """
1239
+ from core import record_recurrence
1240
+
1241
+ scope, pid, field_key = _record_recurrence_request(body)
1242
+ current = workspace(scope=scope, session=session)["workspace"]
1243
+ fields = current.get("fields") or []
1244
+ field = next((item for item in fields
1245
+ if isinstance(item, dict) and str(item.get("key")) == field_key), None)
1246
+ if not field or field.get("type") != "date":
1247
+ raise err(404, "unknown_field", "that Date field is not visible on this database")
1248
+ try:
1249
+ stored = record_recurrence.rule_for(session.runtime, pid, field_key, scope=scope)
1250
+ except record_recurrence.RecurrenceUnavailable as exc:
1251
+ raise err(503, "recurrence_unavailable", str(exc))
1252
+ inherited = stored is None
1253
+ effective = stored if stored is not None else field.get("recurrence")
1254
+ condition_fields = {str(item.get("key")) for item in fields
1255
+ if isinstance(item, dict) and item.get("key")}
1256
+ next_date = _record_next_date(effective, body.get("anchorValue"), condition_fields)
1257
+ return {"recurrence": effective if isinstance(effective, dict) else None,
1258
+ "inherited": inherited, "nextDate": next_date}
1259
+
1260
+
1261
+ @router.post("/grid/record-recurrence")
1262
+ def record_recurrence_write(body: dict = Body(default=None),
1263
+ session: Session = Depends(require_session)):
1264
+ """Store, replace or clear ONE record's repeat rule, and answer with its next date.
1265
+
1266
+ ⛔ THE SAME AUTHORITY THE FIELD-LEVEL WRITE PASSES THROUGH, CALLED RATHER THAN RESTATED.
1267
+ `govern_date_recurrence` is what validates the anchor, the conditions and every rule kind for
1268
+ the preview and for `field_upsert`; a second validator here is how the two doors come to
1269
+ disagree about what a legal rule is.
1270
+
1271
+ ⚠ THE CELL IS NOT WRITTEN HERE. The browser writes it through the ordinary patch door, so
1272
+ the edit joins the undo stack and meets the field-permission check that already guards a typed
1273
+ date. A second writer sitting outside those guards is the shape D-12 exists to refuse.
1274
+ """
1275
+ from core import record_recurrence
1276
+
1277
+ scope, pid, field_key = _record_recurrence_request(body)
1278
+ current = workspace(scope=scope, session=session)["workspace"]
1279
+ fields = current.get("fields") or []
1280
+ field = next((item for item in fields
1281
+ if isinstance(item, dict) and str(item.get("key")) == field_key), None)
1282
+ if not field or field.get("type") != "date":
1283
+ raise err(404, "unknown_field", "that Date field is not visible on this database")
1284
+
1285
+ raw = body.get("recurrence")
1286
+ clean = None
1287
+ if raw is not None:
1288
+ try:
1289
+ clean = govern_date_recurrence(session, scope, fields, raw)
1290
+ except ValueError as exc:
1291
+ raise err(400, "bad_recurrence", str(exc))
1292
+ try:
1293
+ stored = record_recurrence.put_rule(session.runtime, pid, field_key, clean, scope=scope)
1294
+ except ValueError as exc:
1295
+ raise err(400, "bad_recurrence", str(exc))
1296
+ except record_recurrence.RecurrenceUnavailable as exc:
1297
+ raise err(503, "recurrence_unavailable", str(exc))
1298
+
1299
+ condition_fields = {str(item.get("key")) for item in fields
1300
+ if isinstance(item, dict) and item.get("key")}
1301
+ # ⚠ CLEARING A RECORD'S RULE FALLS BACK TO THE COLUMN'S, it does not fall back to nothing:
1302
+ # the row is inheriting again, and answering `null` here would tell the picker the opposite.
1303
+ effective = stored if stored is not None else field.get("recurrence")
1304
+ next_date = _record_next_date(effective, body.get("anchorValue"), condition_fields)
1305
+ return {"recurrence": effective if isinstance(effective, dict) else None,
1306
+ "inherited": stored is None, "nextDate": next_date}
1307
+
1308
+
1309
  # ── ⭐⭐ W47-T26 (owner instruction 13 / ruling R2, contract C5): THE NEXT DATE IS A REAL CELL ─
1310
  #
1311
  # R2, verbatim: the computed next date is STORED in the cell, "so it filters, sorts and groups
platform/core/grid_events.py CHANGED
@@ -2761,8 +2761,28 @@ def handle_one(event, ctx):
2761
  # key self-heal on their next autosave, the rule every stale colId already rides.
2762
  key = str(event.get('key') or '')[:80]
2763
  import aios_grid as _ag3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2764
  if not (key.startswith('custom_') or key.startswith(_ag3.MEASURE_FIELD_PREFIX)):
2765
- return False
 
 
 
 
 
2766
  # ⭐⭐ W41-T02 / RULING R6a+R6b / CONTRACT C2 — THE RIGHT, ASKED OF THE ONE PAIR THAT OWNS
2767
  # IT. Until now this door had NO rights test at all: the prefix above was the whole of
2768
  # the wall, so any holder of a grid could delete a column somebody else made and shared
 
2761
  # key self-heal on their next autosave, the rule every stale colId already rides.
2762
  key = str(event.get('key') or '')[:80]
2763
  import aios_grid as _ag3
2764
+ # ⭐⭐ OWNER 2026-08-31 — THE LEGACY ROUTE-ORDER STRATUM JOINS THE DELETABLE ONES.
2765
+ # Owner: *"Can you also delete all the stale routes and their field ... We don't need
2766
+ # those. It's legacy I believe."* They are right about what these are: a field with
2767
+ # `kind == 'route_order'` is the ONLY thing `route_system.legacy_route_plan` projects a
2768
+ # read-only `compatibility: 'legacy-route-order'` Route from, so the column IS the route
2769
+ # and deleting one deletes both. There was no door for it at all — the prefix test above
2770
+ # is on a KEY, and these are named `route_<name>`, so the column could be neither
2771
+ # deleted nor edited by anybody, on any surface.
2772
+ #
2773
+ # ⛔ IT IS A KIND TEST, NOT A `route_` PREFIX TEST, and that distinction is the wall. A
2774
+ # prefix would let a browser delete any base contract column it could name `route_`;
2775
+ # `kind` is read from the STORED definition below, which the client does not author.
2776
+ # ⚠ The RIGHTS wall underneath is untouched: `may_delete_field` still decides, so this
2777
+ # widens which stratum is structurally deletable and gives nobody a new right.
2778
+ _legacy_route = False
2779
  if not (key.startswith('custom_') or key.startswith(_ag3.MEASURE_FIELD_PREFIX)):
2780
+ _probe = field_by_key.get(key)
2781
+ if not isinstance(_probe, dict):
2782
+ _probe = (ws.get('fields') or {}).get(key)
2783
+ _legacy_route = isinstance(_probe, dict) and _probe.get('kind') == 'route_order'
2784
+ if not _legacy_route:
2785
+ return False
2786
  # ⭐⭐ W41-T02 / RULING R6a+R6b / CONTRACT C2 — THE RIGHT, ASKED OF THE ONE PAIR THAT OWNS
2787
  # IT. Until now this door had NO rights test at all: the prefix above was the whole of
2788
  # the wall, so any holder of a grid could delete a column somebody else made and shared
platform/core/record_recurrence.py ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """A repeat rule that belongs to ONE RECORD, one bucket per database.
2
+
3
+ ⭐⭐ OWNER RULING 2026-08-31, AND IT REVERSES R1/R2 OF WAVE 47 ON PURPOSE.
4
+
5
+ Wave 47's R1/R2 read: *"A date rule anchors on a COLUMN, and that is why it is per-record"* — the
6
+ rule stayed on `Field.recurrence` and every row computed its own answer from its own anchor cell.
7
+ Asked directly whether that still stood, the owner chose *"Each ROW stores its own repeat rule.
8
+ Reverse R1/R2."* So a row's rule is now a record of its own, and the field's rule becomes the
9
+ DEFAULT a row inherits until it is given one.
10
+
11
+ ⛔ THE FIELD'S RULE IS NOT DELETED, and that is not timidity. `Field.recurrence` is what
12
+ ``aios_grid.project_date_recurrences`` publishes, what ``routes_grid._recurrence_columns`` sweeps
13
+ and what every already-saved column holds; dropping it would silently retire live rules on tables
14
+ nobody was asked about. Inheritance keeps both true: a row with no rule of its own still repeats
15
+ the way its column says, and the first time somebody edits that row's repeat it stops listening.
16
+
17
+ ⛔ AND IT IS A SIBLING STRATUM, NEVER A COLUMN IN THE ROW. ``user_tables.add_row`` builds a row as
18
+ field-keys-only by construction, so a reserved key inside one is stripped on the way in — the
19
+ measured reason ``AI_ENRICH_MARK_KEY`` lives beside ``rows`` rather than in them. This follows
20
+ ``core/record_comments.py``'s shape instead: ONE BUCKET PER DATABASE, keyed by bare pid, held in
21
+ AIOS's own writable tenant store. That is what makes it work over a read-only Odoo topic, where a
22
+ per-record rule has nowhere else it could possibly live.
23
+
24
+ ⚠ WHAT IT DELIBERATELY DOES NOT DO: it never computes a date. ``aios_grid.recurrence_row_next_date``
25
+ is the one evaluator and stays the one evaluator; this module stores a config and hands it back.
26
+ """
27
+ from __future__ import annotations
28
+
29
+ STORE_KEY = "customer_record_recurrence"
30
+
31
+ #: A record may carry a repeat rule on at most this many of its Date columns. The bound exists
32
+ #: for the same reason ``MAX_PER_RECORD`` does in ``record_comments``: this document is copied
33
+ #: whole on every read, so a per-record bag with no ceiling is a store problem wearing a
34
+ #: feature's name. Twelve matches ``govern_date_recurrence``'s own rule and condition ceilings.
35
+ MAX_PER_RECORD = 12
36
+
37
+ #: Mirrors ``record_comments.LEGACY_SCOPES``. Restated rather than imported for the same reason
38
+ #: that file gives: ``core/`` does not import ``modules/``, and the customer topic keeps the bare
39
+ #: key so a bucket written under one name is never orphaned by a later rename.
40
+ LEGACY_SCOPES = frozenset({"", "customer", "cohort"})
41
+
42
+
43
+ class RecurrenceUnavailable(RuntimeError):
44
+ """The tenant store cannot currently provide durable per-record repeat rules."""
45
+
46
+
47
+ def key_for(scope=None):
48
+ """The bucket ONE database's per-record rules live in."""
49
+ s = str(scope or "customer").strip().lower()
50
+ return STORE_KEY if s in LEGACY_SCOPES else f"{s}_record_recurrence"
51
+
52
+
53
+ def _record_key(pid):
54
+ return str(int(pid))
55
+
56
+
57
+ def _read(runtime, scope=None):
58
+ if not runtime.available():
59
+ raise RecurrenceUnavailable("the tenant store is unavailable")
60
+ try:
61
+ data = runtime.get(key_for(scope))
62
+ except Exception as exc:
63
+ raise RecurrenceUnavailable("per-record repeat rules could not be read") from exc
64
+ return data if isinstance(data, dict) else {}
65
+
66
+
67
+ def for_record(runtime, pid, scope=None):
68
+ """``{field_key: recurrence}`` for ONE record. Absent = the record inherits its columns."""
69
+ bag = _read(runtime, scope).get(_record_key(pid))
70
+ if not isinstance(bag, dict):
71
+ return {}
72
+ return {str(key): dict(value) for key, value in bag.items() if isinstance(value, dict)}
73
+
74
+
75
+ def rule_for(runtime, pid, field_key, scope=None):
76
+ """ONE record's rule for ONE column, or ``None`` when it inherits the column's."""
77
+ got = for_record(runtime, pid, scope=scope).get(str(field_key))
78
+ return dict(got) if isinstance(got, dict) else None
79
+
80
+
81
+ def put_rule(runtime, pid, field_key, recurrence, scope=None):
82
+ """Store, replace or clear ONE record's rule for ONE column, atomically.
83
+
84
+ ``recurrence=None`` REMOVES the record's own rule, which is not the same act as storing an
85
+ empty one: the row goes back to inheriting its column. An empty record bag is dropped rather
86
+ than left behind, so a bucket cannot accumulate a key per record anybody ever opened.
87
+ """
88
+ key = str(field_key or "").strip()
89
+ if not key:
90
+ raise ValueError("a per-record repeat rule names a field")
91
+ if recurrence is not None and not isinstance(recurrence, dict):
92
+ raise ValueError("a per-record repeat rule must be an object")
93
+ # ⛔ AN EMPTY RULE IS REFUSED, NOT STORED, AND THIS GATE FOUND IT. A `{}` here would sit in the
94
+ # bag as the record's own rule: `rule_for` would answer it, `inherited` would read False, and
95
+ # the row would stop following its column while repeating by nothing. That is the "feature
96
+ # that looks like it worked" shape, and CLEARING already has an unambiguous spelling - `None`.
97
+ # `govern_date_recurrence` refuses it upstream too; a door is not a reason to leave the
98
+ # primitive willing.
99
+ if isinstance(recurrence, dict) and not recurrence.get("rules"):
100
+ raise ValueError("a repeat rule needs at least one repeat clause; pass null to clear it")
101
+ if not runtime.available():
102
+ raise RecurrenceUnavailable("the tenant store is unavailable")
103
+ record = _record_key(pid)
104
+
105
+ def _apply(data):
106
+ if not isinstance(data, dict):
107
+ data = {}
108
+ bag = data.get(record)
109
+ if not isinstance(bag, dict):
110
+ bag = {}
111
+ if recurrence is None:
112
+ bag.pop(key, None)
113
+ else:
114
+ if key not in bag and len(bag) >= MAX_PER_RECORD:
115
+ raise ValueError(
116
+ f"a record may carry a repeat rule on at most {MAX_PER_RECORD} columns")
117
+ bag[key] = dict(recurrence)
118
+ if bag:
119
+ data[record] = bag
120
+ else:
121
+ data.pop(record, None)
122
+ return data
123
+
124
+ try:
125
+ runtime.update(key_for(scope), _apply, flush="sync")
126
+ except ValueError:
127
+ raise
128
+ except Exception as exc:
129
+ raise RecurrenceUnavailable("the repeat rule was not saved") from exc
130
+ return None if recurrence is None else dict(recurrence)
web/src/customer-grid/CustomerGrid.tsx CHANGED
@@ -3534,6 +3534,29 @@ function CustomerGridSurface({
3534
  embeddedSelectable ? embeddedSelectedIds : [],
3535
  !embedded ? `aios:grid-selection:${scope}` : undefined
3536
  );
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3537
  // A Link picker is controlled by its modal parent. Do not treat the parent's PREVIOUS prop as
3538
  // a new command after the child has just ticked a row: doing that reset the checkbox before the
3539
  // child effect could report the new selection upward, so it visibly flickered. Only a prop
@@ -9957,7 +9980,18 @@ function CustomerGridSurface({
9957
  </button>
9958
  )}
9959
  <button type="button" className="cg-btn" style={ONE_LINE}
9960
- onClick={() => { setServerFilteredSelection(null); clearSelection(); }}>
 
 
 
 
 
 
 
 
 
 
 
9961
  Clear
9962
  </button>
9963
  </div>
@@ -10069,7 +10103,7 @@ function CustomerGridSurface({
10069
  </button>
10070
  )}
10071
  <button type="button" className="cg-btn" style={ONE_LINE}
10072
- onClick={clearSelection}>
10073
  Clear
10074
  </button>
10075
  </div>
@@ -10843,11 +10877,14 @@ function CustomerGridSurface({
10843
  anchor={datePicker.anchor}
10844
  field={dateField}
10845
  fields={fields}
 
 
 
 
10846
  scopeKey={scope}
10847
  value={dateValue}
10848
  today={today}
10849
  onChange={(value) => patchAndRecord(datePicker.pid, { [dateField.key]: value }, "a date")}
10850
- onRecurrence={(recurrence) => saveField({ ...dateField, recurrence: recurrence ?? null })}
10851
  onClose={() => {
10852
  setDatePicker(null);
10853
  requestAnimationFrame(() => gridRef.current?.focus());
 
3534
  embeddedSelectable ? embeddedSelectedIds : [],
3535
  !embedded ? `aios:grid-selection:${scope}` : undefined
3536
  );
3537
+ /**
3538
+ * ⭐⭐ OWNER 2026-08-31 item 1 - WHAT "CLEAR" MEANS WHEN A ROUTE PUT ROWS IN THE TABLE.
3539
+ *
3540
+ * Owner: *"When I press clear after I selected the Route that has records not actually a part of
3541
+ * the filter. The record stays, only when I change the filter it actually move back."*
3542
+ *
3543
+ * ⛔⛔ AND THE FIRST FIX FOR THIS WAS WRONG BECAUSE IT PATCHED ONE CALL SITE. There are TWO
3544
+ * selection bars in this file - `data-kind="server-filtered-selection"` for a windowed table and
3545
+ * the plain `.cg-selbar` for a whole-book one - and only the windowed one was repaired. The
3546
+ * customers map is whole-book, so the button the owner actually presses was the untouched one:
3547
+ * MEASURED on the deployed build, ticking an out-of-filter Route took 1,318 -> 1,321 records and
3548
+ * Clear left it at 1,321 with the filter chip unchanged. Exactly the report, still true after a
3549
+ * fix that looked right. [[a-traced-seam-can-name-too-few-callers]]
3550
+ *
3551
+ * ⚠ SO THE CLAUSE DROP LIVES IN ONE FUNCTION AND BOTH BARS CALL IT. Patching the second call
3552
+ * site is how a third one gets written. `clearSelection` itself is deliberately NOT changed: it
3553
+ * has many callers (bulk update, delete, cohort edits) that clear a selection as a step and have
3554
+ * no business withdrawing a Route inclusion the person did not ask to drop.
3555
+ */
3556
+ const clearSelectionAndRouteInclusion = useCallback(() => {
3557
+ clearSelection();
3558
+ setManagedRouteClause(undefined);
3559
+ }, [clearSelection]);
3560
  // A Link picker is controlled by its modal parent. Do not treat the parent's PREVIOUS prop as
3561
  // a new command after the child has just ticked a row: doing that reset the checkbox before the
3562
  // child effect could report the new selection upward, so it visibly flickered. Only a prop
 
9980
  </button>
9981
  )}
9982
  <button type="button" className="cg-btn" style={ONE_LINE}
9983
+ /* ⭐⭐ OWNER 2026-08-31 item 1 - CLEAR CLEARS THE ROUTE INCLUSION TOO.
9984
+ This is the button the owner's *"when I press clear"* is most likely to be:
9985
+ it sits under the map, on the bar that appears the moment a Route is ticked
9986
+ or opened, and it says Clear. It emptied the SELECTION and left the managed
9987
+ OR clause standing, so the out-of-filter records the Route brought in kept
9988
+ their rows until the next filter edit rebuilt the pipeline - the "only when
9989
+ I change the filter it actually move back" they reported. The Map's own
9990
+ `addedPids` follows through the empty-selection effect in `MapView`. */
9991
+ onClick={() => {
9992
+ setServerFilteredSelection(null);
9993
+ clearSelectionAndRouteInclusion();
9994
+ }}>
9995
  Clear
9996
  </button>
9997
  </div>
 
10103
  </button>
10104
  )}
10105
  <button type="button" className="cg-btn" style={ONE_LINE}
10106
+ onClick={clearSelectionAndRouteInclusion}>
10107
  Clear
10108
  </button>
10109
  </div>
 
10877
  anchor={datePicker.anchor}
10878
  field={dateField}
10879
  fields={fields}
10880
+ /* ⭐⭐ OWNER 2026-08-31 - the repeat rule is the RECORD's now, so the picker needs to
10881
+ know WHICH record. `onRecurrence` is gone with the field-level write it fed; see the
10882
+ header on `DatePicker` for the ruling that retired it. */
10883
+ pid={datePicker.pid}
10884
  scopeKey={scope}
10885
  value={dateValue}
10886
  today={today}
10887
  onChange={(value) => patchAndRecord(datePicker.pid, { [dateField.key]: value }, "a date")}
 
10888
  onClose={() => {
10889
  setDatePicker(null);
10890
  requestAnimationFrame(() => gridRef.current?.focus());
web/src/customer-grid/DatePicker.tsx CHANGED
@@ -142,9 +142,30 @@ function recurrenceSentence(rules: DateRule[], ends: RecurrenceEnds, calendars:
142
  return `Repeats ${body}.`;
143
  }
144
 
145
- export function DatePicker({ anchor, field, fields, scopeKey, value, today, onChange, onRecurrence, onClose }: {
146
- anchor: AnchorRect; field: Field; fields: Field[]; scopeKey: string; value: unknown; today?: string; onChange: (value: string) => void;
147
- onRecurrence: (recurrence: DateRecurrence | null) => void; onClose: () => void;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
148
  }) {
149
  const selected = parseIso(value) ?? parseIso(today) ?? new Date();
150
  const selectedIso = iso(selected);
@@ -158,7 +179,14 @@ export function DatePicker({ anchor, field, fields, scopeKey, value, today, onCh
158
  // `?? undefined` is load-bearing: `LinkedRecurrence` now widens `rules`, so the assertion is
159
  // only legal in the direction DateRecurrence -> LinkedRecurrence, and a `null` on the source
160
  // side has no counterpart in the target union.
161
- const storedRecurrence = (field.recurrence ?? undefined) as LinkedRecurrence | undefined;
 
 
 
 
 
 
 
162
  const [anchorTable, setAnchorTable] = useState(() => storedRecurrence?.anchorField?.table ?? "same");
163
  // W47-T24: the anchor DEFAULTS to this field's own column. `govern_date_recurrence` requires an
164
  // `anchorField` on every recurrence it admits, and the picker used to emit none until somebody
@@ -195,6 +223,43 @@ export function DatePicker({ anchor, field, fields, scopeKey, value, today, onCh
195
  ...(ends.kind !== "never" ? { ends } : {}),
196
  }) : null, [anchorField, anchorTable, conditions, ends, linkedVia, previewCount, rules, selectedIso]);
197
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
198
  // Server-evaluated preview: the exact payload saved below is sent here, so edited previews
199
  // cannot differ from the default next date after refresh because of timezone/holiday drift.
200
  useEffect(() => {
@@ -240,8 +305,46 @@ export function DatePicker({ anchor, field, fields, scopeKey, value, today, onCh
240
  setChooserOpen(false);
241
  setStep("date");
242
  };
243
- const saveEditor = () => { onRecurrence(recurrence as DateRecurrence | null); setRestorePoint(null); setChooserOpen(false); setStep("date"); };
244
- const removeRepeat = () => { setRules([]); setEnds({ kind: "never" }); setConditions([]); setShowAnchor(false); setShowConditions(false); onRecurrence(null); setRestorePoint(null); setChooserOpen(false); setStep("date"); };
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
245
  const monthStart = new Date(Date.UTC(cursor.getUTCFullYear(), cursor.getUTCMonth(), 1));
246
  const leading = (monthStart.getUTCDay() + 6) % 7;
247
  const days = new Date(Date.UTC(cursor.getUTCFullYear(), cursor.getUTCMonth() + 1, 0)).getUTCDate();
@@ -396,9 +499,16 @@ export function DatePicker({ anchor, field, fields, scopeKey, value, today, onCh
396
  reads beside the preview it sizes rather than behind the door that adds rules. */}
397
  <div className="cg-date-preview" aria-live="polite"><div className="cg-pop-title">Next dates{nextDate ? ` · next ${nextDate}` : ""}<label className="w46-recur-preview-count">Show next <select className="cg-select" value={previewCount} aria-label="Number of preview dates" onChange={(event) => setPreviewCount(bounded(event.target.value, 1, 50, 10))}>{[3, 5, 10, 20, 50].map((count) => <option key={count} value={count}>{count}</option>)}</select> dates</label></div>{preview.map((date) => <span key={date}>{date}</span>)}{rules.length > 0 && !preview.length && !previewError && <span>Calculating the server preview…</span>}{previewError && <span role="status">{previewError}</span>}</div>
398
  <div className="w46-recur-foot">
399
- {storedRecurrence?.rules?.length ? <button type="button" className="w46-recur-quiet is-danger" onClick={removeRepeat}>Remove repeat</button> : null}
400
- <button type="button" className="w46-recur-quiet" onClick={cancelEditor}>Cancel</button>
401
- <button type="button" className="w46-recur-save" onClick={saveEditor}>Save</button>
 
 
 
 
 
 
 
402
  </div>
403
  </div>}
404
  </AnchoredOverlay>;
 
142
  return `Repeats ${body}.`;
143
  }
144
 
145
+ /**
146
+ * ⭐⭐ OWNER 2026-08-31 - THE REPEAT RULE BELONGS TO THE RECORD, AND WAVE 47's R1/R2 IS REVERSED.
147
+ *
148
+ * Owner: *"THE EDIT REPEAT IS STILL NOT PER FIELD."* Shown R1/R2 - *"a date rule anchors on a
149
+ * COLUMN, and that is why it is per-record"* - and asked which reading they meant, they chose
150
+ * *"Each ROW stores its own repeat rule. Reverse R1/R2."* So this picker no longer writes the
151
+ * FIELD at all: it reads and writes `/grid/record-recurrence` for the row it was opened on.
152
+ *
153
+ * ⛔ `field.recurrence` IS STILL READ, as the default a row INHERITS until it is given a rule of
154
+ * its own. Every column saved before today has one, and treating those as "no repeat" would
155
+ * silently retire live rules on tables nobody was asked about.
156
+ *
157
+ * ⭐⭐ AND SAVING NOW WRITES THE CELL, which is the other half of what the owner reported: *"IT
158
+ * STILL DOESN'T POPULATE THE CELL AS THE NEXTDATE WHEN I CLICK IT. WHY IS IT ONLY POPULATING ONLY
159
+ * WHEN I CLICK THE DATE IN THE CALENDAR ITSELF NOT UNDER REPEAT BUTTON."* It was literal:
160
+ * `onChange` - the ONLY path to `patchAndRecord` - was called by a calendar day and by nothing
161
+ * else, and the server-side materialiser that did write cells (`routes_grid.py`) declares in its
162
+ * own scope note that it runs for `ut_*` user tables only. A per-record rule is one row, so that
163
+ * limit is not on this path; `saveEditor` writes the returned next date through the same
164
+ * `onChange` a typed date takes, undo stack and permission check included.
165
+ */
166
+ export function DatePicker({ anchor, field, fields, pid, scopeKey, value, today, onChange, onClose }: {
167
+ anchor: AnchorRect; field: Field; fields: Field[]; pid: number; scopeKey: string; value: unknown; today?: string; onChange: (value: string) => void;
168
+ onClose: () => void;
169
  }) {
170
  const selected = parseIso(value) ?? parseIso(today) ?? new Date();
171
  const selectedIso = iso(selected);
 
179
  // `?? undefined` is load-bearing: `LinkedRecurrence` now widens `rules`, so the assertion is
180
  // only legal in the direction DateRecurrence -> LinkedRecurrence, and a `null` on the source
181
  // side has no counterpart in the target union.
182
+ /** The rule this row is currently answering with, and whether it is the row's own. Seeded
183
+ * from the FIELD so the picker paints something correct before the record read lands, then
184
+ * replaced by that read. */
185
+ const [storedRecurrence, setStoredRecurrence] = useState<LinkedRecurrence | undefined>(
186
+ () => (field.recurrence ?? undefined) as LinkedRecurrence | undefined
187
+ );
188
+ const [inherited, setInherited] = useState(true);
189
+ const [saving, setSaving] = useState(false);
190
  const [anchorTable, setAnchorTable] = useState(() => storedRecurrence?.anchorField?.table ?? "same");
191
  // W47-T24: the anchor DEFAULTS to this field's own column. `govern_date_recurrence` requires an
192
  // `anchorField` on every recurrence it admits, and the picker used to emit none until somebody
 
223
  ...(ends.kind !== "never" ? { ends } : {}),
224
  }) : null, [anchorField, anchorTable, conditions, ends, linkedVia, previewCount, rules, selectedIso]);
225
 
226
+ /**
227
+ * THE RECORD'S OWN RULE, read once per opened cell.
228
+ *
229
+ * ⚠ IT RESEEDS EVERY DRAFT, not just `rules`. The anchor, the conditions and the Ends clause
230
+ * are all parts of ONE stored config, and reseeding a subset would leave the editor showing
231
+ * this row's repeat rules under the COLUMN's end date - a mixture that belongs to neither and
232
+ * would be saved as if somebody had authored it.
233
+ */
234
+ useEffect(() => {
235
+ const controller = new AbortController();
236
+ void fetch(`${API_V1}/grid/record-recurrence/read`, {
237
+ method: "POST", credentials: CREDENTIALS, signal: controller.signal,
238
+ headers: { "Content-Type": "application/json" },
239
+ body: JSON.stringify({ scopeKey, pid, field: field.key, anchorValue: parseIso(value) ? selectedIso : null }),
240
+ }).then(async (response) => {
241
+ if (!response.ok) return null;
242
+ return await response.json().catch(() => null) as
243
+ { recurrence?: LinkedRecurrence | null; inherited?: boolean } | null;
244
+ }).then((data) => {
245
+ if (!data || controller.signal.aborted) return;
246
+ const got = (data.recurrence ?? undefined) as LinkedRecurrence | undefined;
247
+ setStoredRecurrence(got);
248
+ setInherited(data.inherited !== false);
249
+ setRules(got?.rules ?? []);
250
+ setPreviewCount(got?.previewCount ?? 10);
251
+ setAnchorTable(got?.anchorField?.table ?? "same");
252
+ setAnchorField(got?.anchorField?.field ?? field.key);
253
+ setLinkedVia(got?.anchorField?.linkedVia ?? "");
254
+ setConditions(got?.conditions ?? []);
255
+ setEnds(got?.ends ?? { kind: "never" });
256
+ }).catch(() => { /* The picker still edits a date when the sidecar cannot be read. */ });
257
+ return () => controller.abort();
258
+ // One read per opened cell. The drafts below are what changes afterwards, and re-running on
259
+ // them would overwrite the edit in progress with the stored rule on every keystroke.
260
+ // eslint-disable-next-line react-hooks/exhaustive-deps
261
+ }, [field.key, pid, scopeKey]);
262
+
263
  // Server-evaluated preview: the exact payload saved below is sent here, so edited previews
264
  // cannot differ from the default next date after refresh because of timezone/holiday drift.
265
  useEffect(() => {
 
305
  setChooserOpen(false);
306
  setStep("date");
307
  };
308
+ /**
309
+ * Persist the ROW's rule, then write the date it names into the ROW's cell.
310
+ *
311
+ * ⛔ THE CELL IS WRITTEN FROM THE SERVER'S ANSWER, never from `nextDate` in local state. The
312
+ * preview effect and this write would then be two computations of one number, and the one the
313
+ * cell keeps has to be the one the store agrees with - which is the same reason the preview
314
+ * itself is a server call rather than arithmetic in this file.
315
+ * ⚠ A refusal leaves the editor OPEN with its message. Closing on a failed save is how a
316
+ * person walks away believing a rule is stored that is not.
317
+ */
318
+ const persistRecurrence = (next: LinkedRecurrence | null) => {
319
+ setSaving(true);
320
+ setPreviewError("");
321
+ void fetch(`${API_V1}/grid/record-recurrence`, {
322
+ method: "POST", credentials: CREDENTIALS,
323
+ headers: { "Content-Type": "application/json" },
324
+ body: JSON.stringify({ scopeKey, pid, field: field.key, recurrence: next,
325
+ anchorValue: parseIso(value) ? selectedIso : null }),
326
+ }).then(async (response) => {
327
+ const data = await response.json().catch(() => ({}));
328
+ if (!response.ok) throw new Error(String(data?.detail?.message ?? data?.error?.message
329
+ ?? "Could not save this repeat"));
330
+ return data as { recurrence?: LinkedRecurrence | null; inherited?: boolean; nextDate?: string | null };
331
+ }).then((data) => {
332
+ setStoredRecurrence((data.recurrence ?? undefined) as LinkedRecurrence | undefined);
333
+ setInherited(data.inherited !== false);
334
+ if (data.nextDate) onChange(data.nextDate);
335
+ setRestorePoint(null);
336
+ setChooserOpen(false);
337
+ setStep("date");
338
+ }).catch((error: unknown) => {
339
+ setPreviewError(error instanceof Error ? error.message : "Could not save this repeat");
340
+ }).finally(() => setSaving(false));
341
+ };
342
+ const saveEditor = () => persistRecurrence(recurrence);
343
+ const removeRepeat = () => {
344
+ setRules([]); setEnds({ kind: "never" }); setConditions([]);
345
+ setShowAnchor(false); setShowConditions(false);
346
+ persistRecurrence(null);
347
+ };
348
  const monthStart = new Date(Date.UTC(cursor.getUTCFullYear(), cursor.getUTCMonth(), 1));
349
  const leading = (monthStart.getUTCDay() + 6) % 7;
350
  const days = new Date(Date.UTC(cursor.getUTCFullYear(), cursor.getUTCMonth() + 1, 0)).getUTCDate();
 
499
  reads beside the preview it sizes rather than behind the door that adds rules. */}
500
  <div className="cg-date-preview" aria-live="polite"><div className="cg-pop-title">Next dates{nextDate ? ` · next ${nextDate}` : ""}<label className="w46-recur-preview-count">Show next <select className="cg-select" value={previewCount} aria-label="Number of preview dates" onChange={(event) => setPreviewCount(bounded(event.target.value, 1, 50, 10))}>{[3, 5, 10, 20, 50].map((count) => <option key={count} value={count}>{count}</option>)}</select> dates</label></div>{preview.map((date) => <span key={date}>{date}</span>)}{rules.length > 0 && !preview.length && !previewError && <span>Calculating the server preview…</span>}{previewError && <span role="status">{previewError}</span>}</div>
501
  <div className="w46-recur-foot">
502
+ {/* ⚠ THE SENTENCE THAT STOPS A SURPRISE. A row with no rule of its own is answering with
503
+ its COLUMN's, and pressing Save here gives the row a rule of its OWN - after which
504
+ the column can change and this row will not follow. Saying so beats letting somebody
505
+ discover it a month later. */}
506
+ {inherited && storedRecurrence?.rules?.length ? (
507
+ <span className="w46-recur-word">Repeating from this column's rule. Saving makes it this record's own.</span>
508
+ ) : null}
509
+ {storedRecurrence?.rules?.length && !inherited ? <button type="button" className="w46-recur-quiet is-danger" disabled={saving} onClick={removeRepeat}>Remove repeat</button> : null}
510
+ <button type="button" className="w46-recur-quiet" disabled={saving} onClick={cancelEditor}>Cancel</button>
511
+ <button type="button" className="w46-recur-save" disabled={saving} onClick={saveEditor}>{saving ? "Saving" : "Save"}</button>
512
  </div>
513
  </div>}
514
  </AnchoredOverlay>;
web/src/customer-grid/MapView.tsx CHANGED
@@ -625,6 +625,13 @@ export function MapView({
625
  const [routeOn, setRouteOn] = useState(false);
626
  /** Route navigation is an index first; planning begins only after the explicit Create route
627
  * action or an existing saved route has been opened. */
 
 
 
 
 
 
 
628
  const [roundTrip, setRoundTrip] = useState(false);
629
  const [routeStartPid, setRouteStartPid] = useState<number | null>(null);
630
  const askRoadRef = useRef(false);
@@ -1226,9 +1233,50 @@ export function MapView({
1226
  onManagedRouteViewState?.(body.viewState);
1227
  setRouteSelectionWarning(route.outsideFilter && next.has(route.id) ? `${route.name} is included through its managed route group.` : null);
1228
  const pids = namedRoutes.filter((item) => next.has(item.id)).flatMap((item) => item.visibleStopIds);
1229
- onSelectPids([...new Set(pids)], "add");
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1230
  } catch { setRouteSelectionWarning("Route inclusion could not be changed."); }
1231
- }, [activeView, managedRouteViewState, namedRoutes, onManagedRouteViewState, onSelectPids, selectedRouteIds]);
1232
  const moveNamedRouteStop = useCallback(async (route: MapRouteDto, customerPid: number, order: number): Promise<string | null> => {
1233
  try {
1234
  const res = await fetch(`/api/v1/customers/routes/${encodeURIComponent(route.id)}/stops/move`, {
@@ -2429,6 +2477,12 @@ export function MapView({
2429
  * `customerRoutable < 2` teardown effect above.
2430
  */
2431
  const armedRouteRef = useRef<string>("");
 
 
 
 
 
 
2432
  useEffect(() => {
2433
  if (!activeNamedRoute) {
2434
  armedRouteRef.current = "";
@@ -2439,6 +2493,7 @@ export function MapView({
2439
  const signature = `${activeNamedRoute.id}:${stops.join(",")}`;
2440
  if (armedRouteRef.current === signature) return;
2441
  armedRouteRef.current = signature;
 
2442
  setAddedPids((prev) => {
2443
  const next = new Set(prev);
2444
  for (const pid of stops) next.add(pid);
@@ -2450,6 +2505,32 @@ export function MapView({
2450
  setRouteOn(true);
2451
  }, [activeNamedRoute, onSelectPids]);
2452
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2453
  /**
2454
  * ⭐⭐ W47-T07 (owner instruction 9) — EVERY TICKED ROUTE ON THE MAP AT ONCE, EACH IN ITS OWN
2455
  * COLOUR. Owner: *"we also need a checkbox for us to be able to see each route all together on
@@ -2688,7 +2769,7 @@ export function MapView({
2688
  // migration code, but its second navigator is deliberately gone. Keep these compatibility
2689
  // hooks live until route-order columns are retired server-side; none renders a second Route UI.
2690
  void [
2691
- formatDuration, ROUTE_STOP_CAP, RecordPicker, setRoundTrip, setDepot, setTravelMode, travelModes,
2692
  roadBusy, roadErr, routeEditBusy, routeEditErr, routeCopyMsg,
2693
  openErr, naming, nameDraft, setNameDraft,
2694
  saveBusy, saveMsg, saveErr, unroutable, unroutableNames,
@@ -3460,6 +3541,12 @@ export function MapView({
3460
  onOpenRecord={onOpen}
3461
  stopLabels={routeStopLabels}
3462
  stopCoords={routeStopCoords}
 
 
 
 
 
 
3463
  onCreate={createNamedRoute}
3464
  onMoveToOrder={moveNamedRouteStop}
3465
  onUpdate={updateNamedRoute}
 
625
  const [routeOn, setRouteOn] = useState(false);
626
  /** Route navigation is an index first; planning begins only after the explicit Create route
627
  * action or an existing saved route has been opened. */
628
+ /** ⭐⭐ OWNER 2026-08-31 - *"wtf I don't see the button to make it either 1 single trip or
629
+ * round trip. The algorithm was there its not being displayed anymore"*. Correct, and the
630
+ * record was in the code: this state's ONLY writer, `setRoundTrip`, sat in the retired
631
+ * `void []` compatibility list below, so the value was pinned at false with no control
632
+ * anywhere while `planRoute`, `twoOptOrder`, `tourLength` and `routes_geo.py` all still read
633
+ * it. It lives HERE, not in `RouteNav`, because the drawn `plan` and the panel's drive time
634
+ * have to answer the same question - two copies is how they come to disagree. */
635
  const [roundTrip, setRoundTrip] = useState(false);
636
  const [routeStartPid, setRouteStartPid] = useState<number | null>(null);
637
  const askRoadRef = useRef(false);
 
1233
  onManagedRouteViewState?.(body.viewState);
1234
  setRouteSelectionWarning(route.outsideFilter && next.has(route.id) ? `${route.name} is included through its managed route group.` : null);
1235
  const pids = namedRoutes.filter((item) => next.has(item.id)).flatMap((item) => item.visibleStopIds);
1236
+ /**
1237
+ * ⭐⭐ OWNER 2026-08-31 item 1 - UNTICKING A ROUTE UNDOES EVERYTHING TICKING IT DID.
1238
+ *
1239
+ * Owner: *"When I press clear after I selected the Route that has records not actually a
1240
+ * part of the filter. The record stays, only when I change the filter it actually move
1241
+ * back."* Confirmed with them: the control is the route's own checkbox, and the records
1242
+ * stay in the grid AND on the map.
1243
+ *
1244
+ * ⛔ THE ADD PATH WROTE THREE STORES AND THE REMOVE PATH CLEARED ONE. Ticking a Route
1245
+ * writes (a) the server's managed OR clause, (b) the host row selection, and (c) - once
1246
+ * the Route has also been opened - `addedPids`, which is what earns an out-of-filter stop
1247
+ * a pin through `mapRows`. Unticking sent `"add"` with the REMAINING routes' pids, and
1248
+ * `"add"` is monotone: it can never take a pid back out. So (b) and (c) survived, the
1249
+ * record kept its row and its pin, and the next filter edit rebuilt the pipeline from
1250
+ * scratch - which is exactly the "only when I change the filter" the owner described.
1251
+ *
1252
+ * ⚠ ONLY THE PIDS NO SURVIVING ROUTE STILL CLAIMS ARE DROPPED. Two ticked routes sharing
1253
+ * a stop must not lose it when one of them is unticked, and a record the person picked by
1254
+ * hand is not this callback's to remove either - hence the subtraction is computed
1255
+ * against `keep`, and the host selection is rebuilt from what it currently holds rather
1256
+ * than replaced by the route union.
1257
+ */
1258
+ if (isAdding) {
1259
+ onSelectPids([...new Set(pids)], "add");
1260
+ } else {
1261
+ const keep = new Set(pids);
1262
+ const dropped = (route.visibleStopIds || []).filter((pid) => !keep.has(pid));
1263
+ if (dropped.length) {
1264
+ const gone = new Set(dropped);
1265
+ onSelectPids([...selectedPids].filter((pid) => !gone.has(pid)), "replace");
1266
+ setAddedPids((prev) => {
1267
+ if (![...gone].some((pid) => prev.has(pid))) return prev;
1268
+ const remaining = new Set(prev);
1269
+ for (const pid of gone) remaining.delete(pid);
1270
+ return remaining;
1271
+ });
1272
+ for (const pid of gone) routeAddedRef.current.delete(pid);
1273
+ }
1274
+ // The opened Route detail is armed from `activeNamedRoute`; leaving the arming key set
1275
+ // would refuse to re-arm this Route on a later tick, because the signature would match.
1276
+ if (armedRouteRef.current.startsWith(`${route.id}:`)) armedRouteRef.current = "";
1277
+ }
1278
  } catch { setRouteSelectionWarning("Route inclusion could not be changed."); }
1279
+ }, [activeView, managedRouteViewState, namedRoutes, onManagedRouteViewState, onSelectPids, selectedPids, selectedRouteIds]);
1280
  const moveNamedRouteStop = useCallback(async (route: MapRouteDto, customerPid: number, order: number): Promise<string | null> => {
1281
  try {
1282
  const res = await fetch(`/api/v1/customers/routes/${encodeURIComponent(route.id)}/stops/move`, {
 
2477
  * `customerRoutable < 2` teardown effect above.
2478
  */
2479
  const armedRouteRef = useRef<string>("");
2480
+ /** ⭐⭐ OWNER 2026-08-31 item 1 - WHICH added pids a ROUTE put there, so a clear can withdraw
2481
+ * exactly those. `addedPids` has two writers: opening a Route arms its stops, and the map's
2482
+ * own "add a record" search adds one by hand. Dropping the whole set on a clear would take
2483
+ * the hand-picked record with it, which is somebody else's work; dropping none is the defect
2484
+ * the owner reported. This ref is the difference between the two. */
2485
+ const routeAddedRef = useRef<Set<number>>(new Set());
2486
  useEffect(() => {
2487
  if (!activeNamedRoute) {
2488
  armedRouteRef.current = "";
 
2493
  const signature = `${activeNamedRoute.id}:${stops.join(",")}`;
2494
  if (armedRouteRef.current === signature) return;
2495
  armedRouteRef.current = signature;
2496
+ for (const pid of stops) routeAddedRef.current.add(pid);
2497
  setAddedPids((prev) => {
2498
  const next = new Set(prev);
2499
  for (const pid of stops) next.add(pid);
 
2505
  setRouteOn(true);
2506
  }, [activeNamedRoute, onSelectPids]);
2507
 
2508
+ /**
2509
+ * ⭐⭐ OWNER 2026-08-31 item 1 — AN EMPTIED SELECTION WITHDRAWS WHAT THE ROUTES PUT ON THE MAP.
2510
+ *
2511
+ * The host's Clear button (`CustomerGrid.tsx`'s selection bar) empties the selection and drops
2512
+ * the managed OR clause; the map's half is here, because `addedPids` is MapView's own state and
2513
+ * the host has no handle on it. Without this, the grid loses the rows and the map keeps the
2514
+ * pins — half a fix, and the half a person is looking at while they press the button.
2515
+ *
2516
+ * ⚠ ONLY ROUTE-ORIGIN PIDS, and only when the selection is EMPTY. A record added by hand from
2517
+ * the map's own search stays; a Route still ticked always holds a selection, so this cannot
2518
+ * fire underneath one.
2519
+ */
2520
+ useEffect(() => {
2521
+ if (selectedPids.size > 0 || routeAddedRef.current.size === 0) return;
2522
+ const withdraw = routeAddedRef.current;
2523
+ routeAddedRef.current = new Set();
2524
+ armedRouteRef.current = "";
2525
+ setSelectedRouteIds((current) => (current.size ? new Set<string>() : current));
2526
+ setAddedPids((prev) => {
2527
+ if (![...withdraw].some((pid) => prev.has(pid))) return prev;
2528
+ const next = new Set(prev);
2529
+ for (const pid of withdraw) next.delete(pid);
2530
+ return next;
2531
+ });
2532
+ }, [selectedPids]);
2533
+
2534
  /**
2535
  * ⭐⭐ W47-T07 (owner instruction 9) — EVERY TICKED ROUTE ON THE MAP AT ONCE, EACH IN ITS OWN
2536
  * COLOUR. Owner: *"we also need a checkbox for us to be able to see each route all together on
 
2769
  // migration code, but its second navigator is deliberately gone. Keep these compatibility
2770
  // hooks live until route-order columns are retired server-side; none renders a second Route UI.
2771
  void [
2772
+ formatDuration, ROUTE_STOP_CAP, RecordPicker, setDepot, setTravelMode, travelModes,
2773
  roadBusy, roadErr, routeEditBusy, routeEditErr, routeCopyMsg,
2774
  openErr, naming, nameDraft, setNameDraft,
2775
  saveBusy, saveMsg, saveErr, unroutable, unroutableNames,
 
3541
  onOpenRecord={onOpen}
3542
  stopLabels={routeStopLabels}
3543
  stopCoords={routeStopCoords}
3544
+ roundTrip={roundTrip}
3545
+ onRoundTripChange={setRoundTrip}
3546
+ onStopAdded={(updated) => setNamedRoutes((current) => current.map((item) =>
3547
+ item.id === updated.id
3548
+ ? { ...item, ...updated, folderId: item.folderId, navOrder: item.navOrder }
3549
+ : item))}
3550
  onCreate={createNamedRoute}
3551
  onMoveToOrder={moveNamedRouteStop}
3552
  onUpdate={updateNamedRoute}
web/src/customer-grid/RouteNav.tsx CHANGED
@@ -1,6 +1,7 @@
1
  import { useEffect, useMemo, useRef, useState } from "react";
 
2
  import { createPortal } from "react-dom";
3
- import { folderPath, levelAt, resolveStoredPath } from "./dataPath";
4
  import {
5
  formatSeconds, haversineKm, isPlottable, parseRouteAnswer, previewSeconds,
6
  routeCaveats, routeSaving, routeTimeLabel, routeTimeTone,
@@ -53,11 +54,56 @@ const ROUTE_PRINTING_CLASS = "cg-w46-route-printing";
53
  const PRINT_RELEASE_MS = 120_000;
54
 
55
  const ROUTE_DOOR = "/api/v1/geo/route";
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56
  const SETTLE_DEBOUNCE_MS = 400;
57
- /** Both halves of the figure must ask the same question, or the number jumps on drop by the size
58
- * of a closing edge and the reorder gets blamed for it. These two travel together, into
59
- * `previewSeconds` during the drag and into the request body on drop. */
60
- const ROUTE_ROUND_TRIP = false;
 
 
 
 
 
 
 
 
 
61
  const ROUTE_MODE = "driving";
62
 
63
  /**
@@ -103,7 +149,8 @@ export function RouteNav({ routes, folders, selectedIds, activeRouteId, sources,
103
  onMoveToOrder, onUpdate, onDuplicate, onDelete, onShare, onRouteMove, onRouteReorder, stopLabels = {},
104
  stopCoords = {},
105
  onFolderCreate, onFolderUpdate, onFolderDelete, onFolderReorder, onCreateStart, mapLinks, mapLinkRefusal, deliveries, onSchedule,
106
- onDeleteDelivery, assignees, routeToday, assigneeError, zones = [] }: {
 
107
  routes: MapRouteDto[];
108
  folders: MapRouteFolderDto[];
109
  selectedIds: ReadonlySet<string>;
@@ -155,24 +202,66 @@ export function RouteNav({ routes, folders, selectedIds, activeRouteId, sources,
155
  * mounts in a render harness with no host behind it. An empty list renders the selector
156
  * disabled with a sentence, never a silently empty dropdown. */
157
  zones?: MapZoneDto[];
 
 
 
 
 
 
 
158
  }) {
159
- const routePathKey = `aios-routes-at-${storageKey}`;
160
- const [at, setAt] = useState<string | null>(() => {
161
- if (typeof window === "undefined") return null;
162
- try { return window.localStorage.getItem(routePathKey); } catch { return null; }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
163
  });
 
 
 
 
 
 
 
164
  const [creating, setCreating] = useState(false);
165
  const [creatingFolder, setCreatingFolder] = useState(false);
166
  const [name, setName] = useState("");
167
  const [folderName, setFolderName] = useState("");
168
  const [sourceId, setSourceId] = useState<MapRouteSource["id"]>("selection");
169
  const [error, setError] = useState<string | null>(null);
170
- const [orderDrafts, setOrderDrafts] = useState<Record<number, string>>({});
171
  const [orderErrors, setOrderErrors] = useState<Record<number, string>>({});
 
 
 
172
  const [titleDraft, setTitleDraft] = useState<string | null>(null);
173
  const [editMapsUrl, setEditMapsUrl] = useState("");
174
  /** D-599 - the Route's Zone, as a draft, saved by the same Save Route button as the Maps URL. */
175
  const [editZoneId, setEditZoneId] = useState("");
 
 
 
176
  const [assignmentAssignee, setAssignmentAssignee] = useState("");
177
  const [assignmentDate, setAssignmentDate] = useState("");
178
  const [assignmentNotice, setAssignmentNotice] = useState<string | null>(null);
@@ -181,7 +270,6 @@ export function RouteNav({ routes, folders, selectedIds, activeRouteId, sources,
181
  const [deleteConfirm, setDeleteConfirm] = useState(false);
182
  const [menuId, setMenuId] = useState<string | null>(null);
183
  const [renameId, setRenameId] = useState<string | null>(null);
184
- const [renameDraft, setRenameDraft] = useState("");
185
  const [busy, setBusy] = useState(false);
186
  const [deliveryMapsPerLink, setDeliveryMapsPerLink] = useState(10);
187
  const [deliveryNotice, setDeliveryNotice] = useState<string | null>(null);
@@ -224,6 +312,39 @@ export function RouteNav({ routes, folders, selectedIds, activeRouteId, sources,
224
  ),
225
  [activeStopIds, activeStopRouteId, removedStops]
226
  );
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
227
  const assigneeNames = useMemo(
228
  () => new Set((assignees || []).map((person) => person.username)),
229
  [assignees]
@@ -232,37 +353,72 @@ export function RouteNav({ routes, folders, selectedIds, activeRouteId, sources,
232
  route?.assignee && !assigneeNames.has(route.assignee)
233
  );
234
  const knownFolders = useMemo(() => new Set(folders.map((folder) => folder.id)), [folders]);
235
- const validAt = resolveStoredPath(at, knownFolders);
236
- const level = useMemo(
237
- () => levelAt(validAt, folders, routes, (item) => item.folderId),
238
- [folders, routes, validAt]
239
- );
240
- const crumbs = useMemo(() => folderPath(validAt, folders), [folders, validAt]);
241
  const deliveryTimezone = useMemo(() => {
242
  try { return Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC"; }
243
  catch { return "UTC"; }
244
  }, []);
245
 
246
- const navigate = (folderId: string | null) => {
247
- setAt(folderId);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
248
  setMenuId(null);
249
- setError(null);
250
- try {
251
- if (folderId) window.localStorage.setItem(routePathKey, folderId);
252
- else window.localStorage.removeItem(routePathKey);
253
- } catch { /* Navigation remains usable when storage is unavailable. */ }
 
 
254
  };
255
-
256
- useEffect(() => {
257
- if (at && !validAt) navigate(null);
258
- // `navigate` deliberately remains a local action; validity is the only reactive input.
259
- // eslint-disable-next-line react-hooks/exhaustive-deps
260
- }, [at, validAt]);
261
  useEffect(() => {
262
  setTitleDraft(null);
263
  setEditMapsUrl(route?.mapsUrl || "");
264
  setEditZoneId(route?.zoneId || "");
265
- setOrderDrafts({});
266
  setOrderErrors({});
267
  setDeleteConfirm(false);
268
  setError(null);
@@ -373,11 +529,6 @@ export function RouteNav({ routes, folders, selectedIds, activeRouteId, sources,
373
  setOrderErrors((current) => ({ ...current, [pid]: message }));
374
  return;
375
  }
376
- setOrderDrafts((current) => {
377
- const next = { ...current };
378
- delete next[pid];
379
- return next;
380
- });
381
  setOrderErrors((current) => {
382
  const next = { ...current };
383
  delete next[pid];
@@ -385,6 +536,47 @@ export function RouteNav({ routes, folders, selectedIds, activeRouteId, sources,
385
  });
386
  }).finally(() => setBusy(false));
387
  };
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
388
  const commitStopRemove = (target: MapRouteDto, pid: number) => {
389
  setBusy(true);
390
  setOrderErrors((current) => {
@@ -409,11 +601,6 @@ export function RouteNav({ routes, folders, selectedIds, activeRouteId, sources,
409
  setOrderErrors((current) => ({ ...current, [pid]: message }));
410
  return;
411
  }
412
- setOrderDrafts((current) => {
413
- const next = { ...current };
414
- delete next[pid];
415
- return next;
416
- });
417
  setRemovedStops((current) => current.routeId === target.id
418
  ? (current.pids.includes(pid) ? current : { routeId: target.id, pids: [...current.pids, pid] })
419
  : { routeId: target.id, pids: [pid] });
@@ -424,14 +611,6 @@ export function RouteNav({ routes, folders, selectedIds, activeRouteId, sources,
424
  }
425
  })();
426
  };
427
- const swap = (ids: string[], id: string, delta: number) => {
428
- const index = ids.indexOf(id);
429
- const other = index + delta;
430
- if (index < 0 || other < 0 || other >= ids.length) return null;
431
- const next = [...ids];
432
- [next[index], next[other]] = [next[other], next[index]];
433
- return next;
434
- };
435
 
436
  /* ── W46-T19: the drive time, the saving, and the number that moves during a drag ─────────
437
  The whole feature is state and arithmetic here, and exactly one request, so that the two
@@ -564,7 +743,7 @@ export function RouteNav({ routes, folders, selectedIds, activeRouteId, sources,
564
  }
565
  if (order.length < 2) return null;
566
  const geo: GeoStop[] = locatedStops.map((stop) => ({ lat: stop.lat, lon: stop.lon }));
567
- return previewSeconds(order, geo, haversineKm, ROUTE_ROUND_TRIP);
568
  };
569
 
570
  const cancelSettle = () => {
@@ -600,7 +779,7 @@ export function RouteNav({ routes, folders, selectedIds, activeRouteId, sources,
600
  // the one-click apply has no record to move. `fallback: true` is what makes an
601
  // arithmetic answer come back as `source: "haversine"` instead of an error.
602
  body: JSON.stringify({
603
- stops, mode: ROUTE_MODE, roundTrip: ROUTE_ROUND_TRIP, fallback: true,
604
  }),
605
  });
606
  const payload = await res.json().catch(() => null);
@@ -804,6 +983,21 @@ export function RouteNav({ routes, folders, selectedIds, activeRouteId, sources,
804
  : timerLabel ? "Drive time" : "Add two located stops"}
805
  </span>
806
  </div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
807
  {unlocatedCount > 0 && (
808
  <p className="cg-w46-timer-note">
809
  {unlocatedCount.toLocaleString()} stop{unlocatedCount === 1 ? " has" : "s have"} no
@@ -835,11 +1029,29 @@ export function RouteNav({ routes, folders, selectedIds, activeRouteId, sources,
835
  ))}
836
  {timerError && <p className="cg-w46-timer-error" role="alert">{timerError}</p>}
837
  </section>
 
 
 
 
 
 
 
 
 
838
  {stopIds.length ? (
839
- <ol className="cg-w44-route-stops">
840
  {displayIds.map((pid, index) => (
841
  <li key={pid}
842
- className={dragPid === pid ? "cg-w46-stop-dragging" : undefined}
 
 
 
 
 
 
 
 
 
843
  onDragOver={(event) => {
844
  if (dragPid === null) return;
845
  event.preventDefault();
@@ -850,96 +1062,55 @@ export function RouteNav({ routes, folders, selectedIds, activeRouteId, sources,
850
  event.preventDefault();
851
  dropStopDrag(stopView, pid);
852
  }}>
853
- {/* The grip is POINTER ONLY and hidden from assistive technology on purpose:
854
- Move earlier, Position and Move later already reorder this list from the
855
- keyboard, and a focusable duplicate of them would be a second tab stop that
856
- announces nothing a keyboard user can act on. */}
857
- {canEdit && (
858
- <span className="cg-w46-stop-grip" draggable aria-hidden="true"
859
- title="Drag to reorder this stop"
860
- onDragStart={(event) => {
861
- event.dataTransfer.effectAllowed = "move";
862
- try { event.dataTransfer.setData("text/plain", String(pid)); }
863
- catch { /* Some browsers refuse a payload; the drag still works. */ }
864
- beginStopDrag(pid);
865
- }}
866
- onDragEnd={() => endStopDrag()}>
867
- <svg viewBox="0 0 16 16" aria-hidden="true">
868
- <circle cx="6" cy="4" r="1" /><circle cx="10" cy="4" r="1" />
869
- <circle cx="6" cy="8" r="1" /><circle cx="10" cy="8" r="1" />
870
- <circle cx="6" cy="12" r="1" /><circle cx="10" cy="12" r="1" />
871
- </svg>
872
- </span>
873
- )}
874
- <button type="button" className="cg-w44-route-stop-open"
875
  aria-label={`Open stop ${index + 1} record`}
 
 
 
 
 
 
 
 
 
 
 
 
876
  aria-describedby={`cg-route-stop-name-${pid}`} onClick={() => onOpenRecord(pid)}>
877
  {/* The ordinal is furniture: it says where in the drive this falls, and the
878
  accessible name above already carries it, so it is hidden from the reader
879
  rather than announced twice. */}
880
  <span className="cg-w46-stop-index" aria-hidden="true">{index + 1}</span>
881
- <span className="cg-w46-stop-name" id={`cg-route-stop-name-${pid}`}>
882
- {stopIdentity(stopLabels[pid], pid)}
 
 
883
  </span>
884
  </button>
 
 
 
 
 
 
 
 
885
  {canEdit && (
886
- <span className="cg-w44-route-stop-actions">
887
- <button type="button" className="cg-w44-route-step" disabled={busy || index === 0}
888
- aria-label={`Move stop ${index + 1} earlier`}
889
- title="Move earlier" onClick={() => commitStopMove(stopView, pid, String(index))}>
890
- <svg viewBox="0 0 16 16" aria-hidden="true"><path d="M10 3 5 8l5 5" /></svg>
891
- </button>
892
- <label className="cg-w44-route-position"><span>Position</span>
893
- <input className="cg-w44-route-order" type="text" inputMode="numeric" pattern="[0-9]*"
894
- disabled={busy}
895
- value={orderDrafts[pid] ?? String(index + 1)}
896
- aria-invalid={orderErrors[pid] ? true : undefined}
897
- aria-describedby={orderErrors[pid] ? `cg-route-order-error-${pid}` : undefined}
898
- onFocus={(event) => event.currentTarget.select()}
899
- onChange={(event) => {
900
- const raw = event.target.value;
901
- setOrderDrafts((current) => ({ ...current, [pid]: raw }));
902
- setOrderErrors((current) => {
903
- const next = { ...current };
904
- delete next[pid];
905
- return next;
906
- });
907
- }}
908
- onKeyDown={(event) => {
909
- if (event.key === "Enter") {
910
- event.preventDefault();
911
- commitStopMove(stopView, pid, event.currentTarget.value);
912
- } else if (event.key === "Escape") {
913
- event.preventDefault();
914
- setOrderDrafts((current) => {
915
- const next = { ...current };
916
- delete next[pid];
917
- return next;
918
- });
919
- setOrderErrors((current) => {
920
- const next = { ...current };
921
- delete next[pid];
922
- return next;
923
- });
924
- }
925
- }} />
926
- </label>
927
- <button type="button" className="cg-w44-route-position-apply" disabled={busy}
928
- onClick={() => commitStopMove(stopView, pid, orderDrafts[pid] ?? String(index + 1))}>
929
- Move
930
- </button>
931
- <button type="button" className="cg-w44-route-step"
932
- disabled={busy || index === displayIds.length - 1}
933
- aria-label={`Move stop ${index + 1} later`}
934
- title="Move later" onClick={() => commitStopMove(stopView, pid, String(index + 2))}>
935
- <svg viewBox="0 0 16 16" aria-hidden="true"><path d="m6 3 5 5-5 5" /></svg>
936
- </button>
937
- <button type="button" className="cg-w44-route-step" disabled={busy}
938
- aria-label={`Remove stop ${index + 1} from this route`}
939
- title="Remove stop" onClick={() => commitStopRemove(route, pid)}>
940
- <svg viewBox="0 0 16 16" aria-hidden="true"><path d="m4 4 8 8M12 4l-8 8" /></svg>
941
- </button>
942
- </span>
943
  )}
944
  {orderErrors[pid] && <span id={`cg-route-order-error-${pid}`}
945
  className="cg-w44-route-order-error" role="alert">{orderErrors[pid]}</span>}
@@ -947,6 +1118,57 @@ export function RouteNav({ routes, folders, selectedIds, activeRouteId, sources,
947
  ))}
948
  </ol>
949
  ) : <p className="cg-w44-route-empty">No stops yet. Add customers from a route source.</p>}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
950
  {mapsUrl && <a className="cg-w44-route-maps" href={mapsUrl} target="_blank" rel="noopener noreferrer">Open Maps</a>}
951
  {route.mapsUrl && !mapsUrl && <span className="cg-w44-route-empty">Maps link is unavailable.</span>}
952
  <section className="cg-w44-route-map-links" aria-labelledby="cg-route-map-links-title">
@@ -1047,6 +1269,35 @@ export function RouteNav({ routes, folders, selectedIds, activeRouteId, sources,
1047
  <input className="cg-input" type="url" value={editMapsUrl} maxLength={2048}
1048
  placeholder="https://www.google.com/maps/..." onChange={(event) => setEditMapsUrl(event.target.value)} />
1049
  </label>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1050
  {/* ⭐⭐ D-599 / W46-T22 - THE ROUTE'S ZONE. Until wave 46's hotfix no route record
1051
  carried a zone at all, so this control had nothing to write and did not exist:
1052
  Routes and Zones were two separate tables and `__zone__` was a field on a CUSTOMER
@@ -1075,7 +1326,7 @@ export function RouteNav({ routes, folders, selectedIds, activeRouteId, sources,
1075
  <div className="cg-form-actions">
1076
  <button type="button" className="cg-btn cg-btn--primary" disabled={busy}
1077
  onClick={() => finish(onUpdate(route, { mapsUrl: editMapsUrl.trim(),
1078
- zoneId: editZoneId || null }))}>
1079
  Save Route
1080
  </button>
1081
  <button type="button" className="cg-btn" disabled={busy} onClick={() => finish(onShare(route))}>Share</button>
@@ -1152,22 +1403,50 @@ export function RouteNav({ routes, folders, selectedIds, activeRouteId, sources,
1152
  </section>
1153
  )}
1154
  {canEdit && (
 
 
 
 
 
 
 
 
 
1155
  <section className="cg-w44-route-delivery" aria-labelledby="cg-route-delivery-title">
1156
- <div>
1157
- <h3 id="cg-route-delivery-title">Daily delivery</h3>
1158
- <p>Freeze this Route now and send it to the assignee's Inbox each day at 08:00 ({deliveryTimezone}).</p>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1159
  </div>
1160
- <label className="cg-w44-route-label">Stops per Maps link
1161
- <input className="cg-input" type="number" min={2} max={10} value={deliveryMapsPerLink}
1162
- onChange={(event) => setDeliveryMapsPerLink(
1163
- Math.max(2, Math.min(10, Number(event.target.value) || 2))
1164
- )} />
1165
- </label>
1166
- <button type="button" className="cg-btn cg-btn--primary"
1167
- disabled={deliveryBusy || stopIds.length < 2 || !route.assignee || savedAssigneeUnavailable}
1168
- onClick={() => scheduleDelivery(route)}>
1169
- {deliveryBusy ? "Scheduling" : "Schedule delivery"}
1170
- </button>
1171
  {stopIds.length < 2 && (
1172
  <span className="cg-w44-route-empty">Add at least two stops before scheduling.</span>
1173
  )}
@@ -1241,60 +1520,94 @@ export function RouteNav({ routes, folders, selectedIds, activeRouteId, sources,
1241
  );
1242
  }
1243
 
1244
- const routeIds = level.leaves.map((item) => item.id);
1245
- const folderIds = level.folders.map((item) => item.id);
1246
- return (
1247
- <section className="cg-w44-route-nav" aria-label="Named routes">
1248
- <div className="cg-w44-route-head">
1249
- <div className="cg-w44-route-title">Routes</div>
1250
- <button type="button" className="cg-w44-route-detail" onClick={() => {
1251
- setError(null); onCreateStart(); setCreating(true);
1252
- }}>Create route</button>
1253
- </div>
1254
- <nav className="cg-w44-route-path" aria-label="Route folder path">
1255
- <button type="button" aria-current={!validAt ? "page" : undefined} onClick={() => navigate(null)}>Routes</button>
1256
- {crumbs.map((folder) => <span key={folder.id}><b aria-hidden="true">›</b>
1257
- <button type="button" aria-current={validAt === folder.id ? "page" : undefined}
1258
- onClick={() => navigate(folder.id)}>{folder.name}</button></span>)}
1259
- </nav>
1260
- <div className="cg-w44-route-folder-tools">
1261
- {validAt && <button type="button" className="cg-w44-route-back" onClick={() => navigate(level.parent)}>Up</button>}
1262
- <button type="button" className="cg-w44-route-detail" onClick={() => setCreatingFolder((value) => !value)}>New folder</button>
1263
- </div>
1264
- {creatingFolder && <div className="cg-w44-route-folder-create">
1265
- <input className="cg-input" value={folderName} maxLength={80} aria-label="New Route folder name"
1266
- onChange={(event) => setFolderName(event.target.value)} />
1267
- <button type="button" className="cg-btn cg-btn--primary" disabled={busy || !folderName.trim()}
1268
- onClick={() => { setBusy(true); void onFolderCreate(folderName.trim(), validAt).then((message) => {
1269
- setError(message); if (!message) { setFolderName(""); setCreatingFolder(false); }
1270
- }).finally(() => setBusy(false)); }}>Create</button>
1271
- </div>}
1272
- <div className="cg-w44-route-level" aria-label={level.folder ? `${level.folder.name} contents` : "Route folder contents"}>
1273
- {level.folders.map((folder, index) => (
1274
- <div key={folder.id} className="cg-w44-route-folder-row">
1275
- {renameId === `folder:${folder.id}` ? <>
1276
- <input className="cg-input" value={renameDraft} maxLength={80} aria-label={`Rename ${folder.name}`}
1277
- onChange={(event) => setRenameDraft(event.target.value)} />
1278
- <button type="button" disabled={!renameDraft.trim() || busy}
1279
- onClick={() => { setBusy(true); void onFolderUpdate(folder, { name: renameDraft.trim() }).then((message) => {
1280
- setError(message); if (!message) setRenameId(null);
1281
- }).finally(() => setBusy(false)); }}>Save</button>
1282
- </> : <button type="button" className="cg-w44-route-folder-open" onClick={() => navigate(folder.id)}>
1283
- <span className="cg-w44-route-folder-mark" aria-hidden="true" />{folder.name}
1284
- </button>}
1285
- <button type="button" className="cg-w44-route-more" aria-label={`Actions for ${folder.name}`}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1286
  aria-expanded={menuId === `folder:${folder.id}`}
1287
  onClick={() => setMenuId(menuId === `folder:${folder.id}` ? null : `folder:${folder.id}`)}>...</button>
1288
- {menuId === `folder:${folder.id}` && <div className="cg-w44-route-menu" role="menu">
1289
  <button type="button" role="menuitem"
1290
- onClick={() => { setRenameId(`folder:${folder.id}`); setRenameDraft(folder.name); setMenuId(null); }}>Rename</button>
1291
- <button type="button" role="menuitem" disabled={index === 0 || busy}
1292
- onClick={() => { const next = swap(folderIds, folder.id, -1); if (next) finish(onFolderReorder(next)); }}>Move up</button>
1293
- <button type="button" role="menuitem" disabled={index === folderIds.length - 1 || busy}
1294
- onClick={() => { const next = swap(folderIds, folder.id, 1); if (next) finish(onFolderReorder(next)); }}>Move down</button>
1295
  {folder.parent && <button type="button" role="menuitem"
1296
- onClick={() => { setMenuId(null); finish(onFolderUpdate(folder, { parent: level.parent })); }}>Move out one level</button>}
1297
- {folders.filter((target) => target.id !== folder.id).map((target) =>
1298
  <button type="button" role="menuitem" key={target.id}
1299
  onClick={() => { setMenuId(null); finish(onFolderUpdate(folder, { parent: target.id })); }}>
1300
  Move into {target.name}
@@ -1303,53 +1616,148 @@ export function RouteNav({ routes, folders, selectedIds, activeRouteId, sources,
1303
  onClick={() => { setMenuId(null); if (window.confirm(`Delete ${folder.name}? Its contents move to Routes.`)) finish(onFolderDelete(folder)); }}>Delete</button>
1304
  </div>}
1305
  </div>
1306
- ))}
1307
- {level.leaves.map((item, index) => (
1308
- <div key={item.id} className={`cg-w44-route-row${item.outsideFilter ? " is-outside" : ""}`}>
1309
- {/* ⭐ W47-T07 / instruction 9: a REAL checkbox, not a pressed button. The affordance
1310
- already existed as `aria-pressed`, but the owner asked for a checkbox and the
1311
- thing it now controls is visible on the map, so it should look like what it is.
1312
- The swatch stays on it, and it is the SAME `item.color` the drawn line uses. */}
1313
- <label className="cg-w44-route-toggle" title={`Show ${item.name} on the map`}>
1314
- <input type="checkbox" checked={selectedIds.has(item.id)}
1315
- aria-label={`Show ${item.name} on the map`}
1316
- onChange={() => onToggle(item)} />
1317
- <i style={{ backgroundColor: item.color }} aria-hidden="true" />
1318
- </label>
1319
- {/* A Route is renamed at the top of its own panel (W46-T23), never from this row. */}
1320
- <button type="button" className="cg-w44-route-open" onClick={() => {
1321
- setError(null); setCreating(false); onActiveRouteChange(item.id);
1322
- }}>{item.number}. {item.name}</button>
1323
- {(item.shared || item.sharedOut) && <span className="cg-w44-route-share-mark">
1324
- {item.shared ? `Shared by ${item.owner || "another user"}` : "Shared"}
1325
- </span>}
1326
- {item.outsideFilter && <span className="cg-w44-route-outside">Outside filter</span>}
1327
- <button type="button" className="cg-w44-route-more" aria-label={`Actions for ${item.name}`}
1328
- aria-expanded={menuId === item.id} onClick={() => setMenuId(menuId === item.id ? null : item.id)}>...</button>
1329
- {menuId === item.id && <div className="cg-w44-route-menu" role="menu">
1330
- <button type="button" role="menuitem" disabled={!mayRouteAction(item, "duplicate")}
1331
- onClick={() => { setMenuId(null); finish(onDuplicate(item)); }}>Duplicate</button>
1332
- <button type="button" role="menuitem" disabled={!mayRouteAction(item, "star")}
1333
- onClick={() => { setMenuId(null); finish(onUpdate(item, { starred: !item.starred })); }}>
1334
- {item.starred ? "Unstar" : "Star"}
1335
- </button>
1336
- <button type="button" role="menuitem" disabled={!mayRouteAction(item, "share")}
1337
- onClick={() => { setMenuId(null); finish(onShare(item)); }}>Share</button>
1338
- {folders.map((folder) => <button type="button" role="menuitem" key={folder.id}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1339
  onClick={() => { setMenuId(null); finish(onRouteMove(item, folder.id)); }}>Move to {folder.name}</button>)}
1340
- {item.folderId && <button type="button" role="menuitem"
1341
- onClick={() => { setMenuId(null); finish(onRouteMove(item, null)); }}>Move to Routes</button>}
1342
- <button type="button" role="menuitem" disabled={index === 0 || busy}
1343
- onClick={() => { const next = swap(routeIds, item.id, -1); if (next) finish(onRouteReorder(next)); }}>Move up</button>
1344
- <button type="button" role="menuitem" disabled={index === routeIds.length - 1 || busy}
1345
- onClick={() => { const next = swap(routeIds, item.id, 1); if (next) finish(onRouteReorder(next)); }}>Move down</button>
1346
- <button type="button" role="menuitem" disabled={!mayRouteAction(item, "delete")}
1347
- onClick={() => { setMenuId(null); if (window.confirm(`Delete ${item.name}?`)) finish(onDelete(item)); }}>Delete</button>
1348
- </div>}
1349
- </div>
1350
- ))}
1351
- {!level.folders.length && !level.leaves.length && <p className="cg-w44-route-empty">
1352
- {folders.length || routes.length ? "This folder is empty." : "No routes yet. Create one from selected Zones or records."}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1353
  </p>}
1354
  </div>
1355
  {createdRoute && <div className="cg-w44-route-created" role="dialog" aria-label="Route privacy choice">
 
1
  import { useEffect, useMemo, useRef, useState } from "react";
2
+ import type { ReactElement } from "react";
3
  import { createPortal } from "react-dom";
4
+ import { FolderMark } from "./icons";
5
  import {
6
  formatSeconds, haversineKm, isPlottable, parseRouteAnswer, previewSeconds,
7
  routeCaveats, routeSaving, routeTimeLabel, routeTimeTone,
 
54
  const PRINT_RELEASE_MS = 120_000;
55
 
56
  const ROUTE_DOOR = "/api/v1/geo/route";
57
+ /**
58
+ * OWNER 2026-08-31 item 2 - the six defaults a new Route is stamped with, offered back as an
59
+ * edit. ⛔ THIS LIST IS A MIRROR OF `route_system.py::_ROUTE_COLORS` AND MUST STAY ONE. The
60
+ * server is the authority: `_color` falls back to `_ROUTE_COLORS[ordinal % len]` for anything
61
+ * `_COLOR_RE` refuses, so a swatch offered here that the server does not recognise would save
62
+ * as a different colour than the one the person pressed. The free picker beside them is why the
63
+ * list does not need to grow: it is a shortcut, not the vocabulary.
64
+ */
65
+ const ROUTE_SWATCHES = ["#6E4AC7", "#1F4E78", "#C85A54", "#2F8F83", "#B57716", "#A14B8B"];
66
+
67
+ /** The rail's own top level, as a map key. A bare string keeps `foldersByParent` and
68
+ * `routesByFolder` one type instead of `Map<string | null, ...>`, and no folder id can collide
69
+ * with it: `route_system.py` mints folder ids, and none of them is empty. */
70
+ const ROOT_LEVEL = "";
71
+ /* ⛔ TWO DRAG TYPES, ONE PER ROW KIND, and that is the same discrimination `ViewSidebar` makes
72
+ with `FOLD_DRAG_TYPE` against a view's own channel. Sharing one channel would let a folder
73
+ dropped on a Route reorder the Routes, and the handler that fired first would decide which. */
74
+ const ROUTE_DRAG = "application/x-aios-route";
75
+ const ROUTE_FOLDER_DRAG = "application/x-aios-route-folder";
76
+
77
+ /** Owner item 3 - the ONE mark every Route row wears. Deliberately the SAME waypoint path
78
+ * `viewModes.tsx::IconRouteZone` draws, at the same 1.5 stroke: the toolbar button that opens
79
+ * this rail and the rows inside it are one family, and a second route glyph would read as two. */
80
+ function IconRoute() {
81
+ return (
82
+ <svg width="14" height="14" viewBox="0 0 16 16" fill="none" aria-hidden="true"
83
+ className="cg-view-route-mark">
84
+ <path d="M4 2.4a2 2 0 0 1 2 2c0 1.5-2 3.7-2 3.7S2 5.9 2 4.4a2 2 0 0 1 2-2Z" stroke="currentColor"
85
+ strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
86
+ <path d="M12 2.4a2 2 0 0 1 2 2c0 1.5-2 3.7-2 3.7s-2-2.2-2-3.7a2 2 0 0 1 2-2Z" stroke="currentColor"
87
+ strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
88
+ <path d="M4.2 9.4c2.1 2.7 5.5 2.7 7.6 0" stroke="currentColor" strokeWidth="1.5"
89
+ strokeLinecap="round" strokeLinejoin="round" />
90
+ </svg>
91
+ );
92
+ }
93
  const SETTLE_DEBOUNCE_MS = 400;
94
+ /** ⛔ BOTH HALVES OF THE FIGURE MUST ASK THE SAME QUESTION, or the number jumps on drop by the
95
+ * size of a closing edge and the reorder gets blamed for it. That is why the round-trip answer
96
+ * travels as ONE value into `previewSeconds` during the drag and into the request body on drop.
97
+ *
98
+ * ⭐⭐ OWNER 2026-08-31: *"wtf I don't see the button to make it either 1 single trip or round
99
+ * trip. The algorithm was there its not being displayed anymore"*. They are right, and the
100
+ * record says so in code: `MapView.tsx` holds `roundTrip` state whose only writer, `setRoundTrip`,
101
+ * sits in the retired `void []` compatibility list, so the value was pinned at false with no
102
+ * control anywhere. The solver (`mapProjection.ts::planRoute`, `twoOptOrder`, `tourLength`) and
103
+ * the server door (`routes_geo.py`, which reads `roundTrip` off the body) were both live the
104
+ * whole time. So this is a control being re-attached to an algorithm, not a feature being built.
105
+ * It is a PROP rather than local state because the map's drawn plan and this panel's timer must
106
+ * answer the same question; two copies is how they come to disagree. */
107
  const ROUTE_MODE = "driving";
108
 
109
  /**
 
149
  onMoveToOrder, onUpdate, onDuplicate, onDelete, onShare, onRouteMove, onRouteReorder, stopLabels = {},
150
  stopCoords = {},
151
  onFolderCreate, onFolderUpdate, onFolderDelete, onFolderReorder, onCreateStart, mapLinks, mapLinkRefusal, deliveries, onSchedule,
152
+ onDeleteDelivery, assignees, routeToday, assigneeError, zones = [],
153
+ roundTrip = false, onRoundTripChange, onStopAdded }: {
154
  routes: MapRouteDto[];
155
  folders: MapRouteFolderDto[];
156
  selectedIds: ReadonlySet<string>;
 
202
  * mounts in a render harness with no host behind it. An empty list renders the selector
203
  * disabled with a sentence, never a silently empty dropdown. */
204
  zones?: MapZoneDto[];
205
+ /** Owner 2026-08-31 - one way, or back to where the driver started. Owned by the host so the
206
+ * map's drawn plan and this panel's drive time cannot answer different questions. */
207
+ roundTrip?: boolean;
208
+ onRoundTripChange?: (value: boolean) => void;
209
+ /** The Route the membership door answered with, so the host's read model gains the new stop
210
+ * without a second fetch. Mirrors what `moveNamedRouteStop` already does on a reorder. */
211
+ onStopAdded?: (route: MapRouteDto) => void;
212
  }) {
213
+ /* ⭐⭐ OWNER 2026-08-31 item 3 - THE ROUTES RAIL IS THE VIEWS RAIL, NOT A COUSIN OF IT.
214
+ Owner: *"I need the routes LIST navigation and the routes itself to have the exact same
215
+ interface just like how we have it with view, where you can just click it and drag it AND
216
+ its fucking compact. Make it the exact same layout. The only difference is the icon."* and,
217
+ in the grill: *"exactly like how Views rail is, with the +create for folder and find at the
218
+ top. Exactly the same. instead of number it should all just be the same Route icon."*
219
+
220
+ ⛔ SO THE BREADCRUMB PATH IS GONE, AND THAT IS THE STRUCTURAL HALF OF THE ASK. A folder used
221
+ to be a place you NAVIGATED INTO (`levelAt` + `folderPath` + an `Up` button), which is a
222
+ different interaction from the Views rail's disclosure groups however similar the rows look.
223
+ Folders now open and shut in place, and the stored key holds the SHUT set rather than the
224
+ current level - so a person who never touches a folder sees every Route, which is the
225
+ behaviour a rail whose whole job is "pick one" should have.
226
+
227
+ ⚠ THE ROW CLASSES ARE THE VIEWS RAIL'S OWN (`.cg-view-row`, `.cg-view-main`, `.cg-view-text`,
228
+ `.cg-view-name`, `.cg-view-more`, `.cg-fold*`, `.cg-create-new`, `.cg-find-view`), reused
229
+ rather than copied. Copying them into a `cg-w44-route-*` twin is how the two lists drift
230
+ apart again the first time either is polished, and "exact same layout" is a promise that
231
+ only a shared contract can keep. */
232
+ const routePathKey = `aios-routes-shut-${storageKey}`;
233
+ const [shutFolders, setShutFolders] = useState<ReadonlySet<string>>(() => {
234
+ if (typeof window === "undefined") return new Set<string>();
235
+ try {
236
+ const raw = window.localStorage.getItem(routePathKey);
237
+ const parsed = raw ? JSON.parse(raw) : null;
238
+ return new Set<string>(Array.isArray(parsed) ? parsed.filter((id) => typeof id === "string") : []);
239
+ } catch { return new Set<string>(); }
240
  });
241
+ /** Owner item 3 - "find at the top". Local, never persisted: a search is a way of LOOKING at
242
+ * the rail, not a property of it, which is the rule `ViewSidebar`'s own box already follows. */
243
+ const [routeQuery, setRouteQuery] = useState("");
244
+ const [createMenu, setCreateMenu] = useState(false);
245
+ /** The row being carried, and the row it would land ABOVE. Same two marks the Views rail uses. */
246
+ const [rowDrag, setRowDrag] = useState<string | null>(null);
247
+ const [rowOver, setRowOver] = useState<string | null>(null);
248
  const [creating, setCreating] = useState(false);
249
  const [creatingFolder, setCreatingFolder] = useState(false);
250
  const [name, setName] = useState("");
251
  const [folderName, setFolderName] = useState("");
252
  const [sourceId, setSourceId] = useState<MapRouteSource["id"]>("selection");
253
  const [error, setError] = useState<string | null>(null);
 
254
  const [orderErrors, setOrderErrors] = useState<Record<number, string>>({});
255
+ /** Owner 2026-08-31 - the add-record door's own two pieces of state. */
256
+ const [addStopOpen, setAddStopOpen] = useState(false);
257
+ const [addStopQuery, setAddStopQuery] = useState("");
258
  const [titleDraft, setTitleDraft] = useState<string | null>(null);
259
  const [editMapsUrl, setEditMapsUrl] = useState("");
260
  /** D-599 - the Route's Zone, as a draft, saved by the same Save Route button as the Maps URL. */
261
  const [editZoneId, setEditZoneId] = useState("");
262
+ /** OWNER 2026-08-31 item 2 - the Route's colour, as a draft, on the same Save Route button.
263
+ * Seeded from the record so the swatch a person sees selected is the colour the map draws. */
264
+ const [editColor, setEditColor] = useState(ROUTE_SWATCHES[0]);
265
  const [assignmentAssignee, setAssignmentAssignee] = useState("");
266
  const [assignmentDate, setAssignmentDate] = useState("");
267
  const [assignmentNotice, setAssignmentNotice] = useState<string | null>(null);
 
270
  const [deleteConfirm, setDeleteConfirm] = useState(false);
271
  const [menuId, setMenuId] = useState<string | null>(null);
272
  const [renameId, setRenameId] = useState<string | null>(null);
 
273
  const [busy, setBusy] = useState(false);
274
  const [deliveryMapsPerLink, setDeliveryMapsPerLink] = useState(10);
275
  const [deliveryNotice, setDeliveryNotice] = useState<string | null>(null);
 
312
  ),
313
  [activeStopIds, activeStopRouteId, removedStops]
314
  );
315
+ /**
316
+ * ⭐ OWNER 2026-08-31 - the records the add-record dropdown may offer: everything in the book
317
+ * this panel already holds, minus what is already a stop.
318
+ *
319
+ * ⛔ CAPPED AT 50 WITH THE REMAINDER COUNTED, NEVER SILENTLY TRUNCATED. `stopLabels` covers the
320
+ * whole customer book (3,649 rows on tenant #0), and a menu that renders all of them is a
321
+ * frozen tab; one that renders the first fifty and says nothing is standing rule 1's silent
322
+ * cap. The overflow figure is printed with what to do about it.
323
+ */
324
+ const stopSet = useMemo(() => new Set(stopIds), [stopIds]);
325
+ const addStopMatches = useMemo(() => {
326
+ const needle = addStopQuery.trim().toLowerCase();
327
+ const out: { pid: number; label: string }[] = [];
328
+ for (const [key, value] of Object.entries(stopLabels)) {
329
+ const pid = Number(key);
330
+ if (!Number.isSafeInteger(pid) || stopSet.has(pid)) continue;
331
+ const label = stopIdentity(value, pid);
332
+ if (needle && !label.toLowerCase().includes(needle)) continue;
333
+ out.push({ pid, label });
334
+ }
335
+ // ⛔ A NAMELESS RECORD SORTS LAST, AND THIS IS A MEASUREMENT, NOT A PREFERENCE. Tenant #0's
336
+ // customer book carries 57 records whose name in Odoo is literally "?" (counted on the
337
+ // deployed staging build). Plain `localeCompare` puts "?" before every letter, so all 57
338
+ // filled the first fifty rows and the menu opened on nothing anybody could pick. A label
339
+ // with no letter or digit in it is a placeholder rather than a name, so it goes to the end;
340
+ // it is still offered, still searchable, and no record is hidden.
341
+ const named = (label: string) => /[\p{L}\p{N}]/u.test(label);
342
+ out.sort((a, b) => (Number(named(b.label)) - Number(named(a.label)))
343
+ || a.label.localeCompare(b.label));
344
+ return out;
345
+ }, [addStopQuery, stopLabels, stopSet]);
346
+ const addableStops = useMemo(() => addStopMatches.slice(0, 50), [addStopMatches]);
347
+ const addStopOverflow = Math.max(0, addStopMatches.length - addableStops.length);
348
  const assigneeNames = useMemo(
349
  () => new Set((assignees || []).map((person) => person.username)),
350
  [assignees]
 
353
  route?.assignee && !assigneeNames.has(route.assignee)
354
  );
355
  const knownFolders = useMemo(() => new Set(folders.map((folder) => folder.id)), [folders]);
 
 
 
 
 
 
356
  const deliveryTimezone = useMemo(() => {
357
  try { return Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC"; }
358
  catch { return "UTC"; }
359
  }, []);
360
 
361
+ /** Child folders of one parent, in their stored order. `ROOT_LEVEL` is the rail's own top. */
362
+ const foldersByParent = useMemo(() => {
363
+ const map = new Map<string, MapRouteFolderDto[]>();
364
+ for (const folder of folders) {
365
+ const parent = folder.parent && knownFolders.has(folder.parent) ? folder.parent : ROOT_LEVEL;
366
+ const bucket = map.get(parent);
367
+ if (bucket) bucket.push(folder); else map.set(parent, [folder]);
368
+ }
369
+ for (const bucket of map.values()) bucket.sort((a, b) => (a.order || 0) - (b.order || 0));
370
+ return map;
371
+ }, [folders, knownFolders]);
372
+
373
+ /** Routes filed in one folder, in their stored rail order. A Route whose folder this reader
374
+ * cannot see falls to the top level rather than disappearing. */
375
+ const routesByFolder = useMemo(() => {
376
+ const map = new Map<string, MapRouteDto[]>();
377
+ for (const item of routes) {
378
+ const parent = item.folderId && knownFolders.has(item.folderId) ? item.folderId : ROOT_LEVEL;
379
+ const bucket = map.get(parent);
380
+ if (bucket) bucket.push(item); else map.set(parent, [item]);
381
+ }
382
+ for (const bucket of map.values()) bucket.sort((a, b) => (a.navOrder || 0) - (b.navOrder || 0));
383
+ return map;
384
+ }, [routes, knownFolders]);
385
+
386
+ /** ⚠ A FOLDER SURVIVES THE FIND BOX WHEN A DESCENDANT MATCHES, never only when its own name
387
+ * does. Hiding a folder whose contents match is how a search convinces somebody a Route has
388
+ * been deleted. `ViewSidebar` holds the same rule for its groups. */
389
+ const query = routeQuery.trim().toLowerCase();
390
+ const folderMatches = useMemo(() => {
391
+ const hit = new Set<string>();
392
+ if (!query) return hit;
393
+ const walk = (parent: string): boolean => {
394
+ let found = (routesByFolder.get(parent) || []).some(
395
+ (item) => item.name.toLowerCase().includes(query)
396
+ );
397
+ for (const child of foldersByParent.get(parent) || []) {
398
+ const inside = walk(child.id);
399
+ if (inside || child.name.toLowerCase().includes(query)) { hit.add(child.id); found = true; }
400
+ }
401
+ return found;
402
+ };
403
+ walk(ROOT_LEVEL);
404
+ return hit;
405
+ }, [foldersByParent, query, routesByFolder]);
406
+
407
+ const toggleFolder = (folderId: string) => {
408
  setMenuId(null);
409
+ setShutFolders((current) => {
410
+ const next = new Set(current);
411
+ if (next.has(folderId)) next.delete(folderId); else next.add(folderId);
412
+ try { window.localStorage.setItem(routePathKey, JSON.stringify([...next])); }
413
+ catch { /* The rail still opens and shuts when storage is unavailable. */ }
414
+ return next;
415
+ });
416
  };
 
 
 
 
 
 
417
  useEffect(() => {
418
  setTitleDraft(null);
419
  setEditMapsUrl(route?.mapsUrl || "");
420
  setEditZoneId(route?.zoneId || "");
421
+ setEditColor((route?.color || ROUTE_SWATCHES[0]).toUpperCase());
422
  setOrderErrors({});
423
  setDeleteConfirm(false);
424
  setError(null);
 
529
  setOrderErrors((current) => ({ ...current, [pid]: message }));
530
  return;
531
  }
 
 
 
 
 
532
  setOrderErrors((current) => {
533
  const next = { ...current };
534
  delete next[pid];
 
536
  });
537
  }).finally(() => setBusy(false));
538
  };
539
+ /**
540
+ * Put ONE record onto this Route, through the same membership door the x uses.
541
+ *
542
+ * ⛔ NO OPTIMISTIC ROW. The server answers with the whole Route and `onMoveToOrder`'s host
543
+ * already replaces the record from that answer; painting a stop locally first would show a
544
+ * position the server has not agreed to, and a refusal would then have to un-paint it.
545
+ */
546
+ const commitStopAdd = (target: MapRouteDto, pid: number) => {
547
+ setBusy(true);
548
+ setError(null);
549
+ void (async () => {
550
+ try {
551
+ const res = await fetch(
552
+ `/api/v1/customers/routes/${encodeURIComponent(target.id)}/stops/membership`,
553
+ {
554
+ method: "POST", credentials: "same-origin",
555
+ headers: { "Content-Type": "application/json" },
556
+ body: JSON.stringify({ customerPid: pid, present: true }),
557
+ }
558
+ );
559
+ const payload = await res.json().catch(() => null);
560
+ if (!res.ok) {
561
+ setError(payload?.error?.message || payload?.detail?.message
562
+ || "That record could not be added to this Route.");
563
+ return;
564
+ }
565
+ // The removal ledger is what hides a stop this session took OFF the Route. Adding the
566
+ // same record back has to clear its entry, or the row the server just returned would be
567
+ // filtered straight back out and the button would look broken.
568
+ setRemovedStops((current) => current.routeId === target.id
569
+ ? { routeId: target.id, pids: current.pids.filter((item) => item !== pid) }
570
+ : current);
571
+ const routeUpdate = payload?.route as MapRouteDto | undefined;
572
+ if (routeUpdate) onStopAdded?.(routeUpdate);
573
+ } catch {
574
+ setError("That record could not be added to this Route.");
575
+ } finally {
576
+ setBusy(false);
577
+ }
578
+ })();
579
+ };
580
  const commitStopRemove = (target: MapRouteDto, pid: number) => {
581
  setBusy(true);
582
  setOrderErrors((current) => {
 
601
  setOrderErrors((current) => ({ ...current, [pid]: message }));
602
  return;
603
  }
 
 
 
 
 
604
  setRemovedStops((current) => current.routeId === target.id
605
  ? (current.pids.includes(pid) ? current : { routeId: target.id, pids: [...current.pids, pid] })
606
  : { routeId: target.id, pids: [pid] });
 
611
  }
612
  })();
613
  };
 
 
 
 
 
 
 
 
614
 
615
  /* ── W46-T19: the drive time, the saving, and the number that moves during a drag ─────────
616
  The whole feature is state and arithmetic here, and exactly one request, so that the two
 
743
  }
744
  if (order.length < 2) return null;
745
  const geo: GeoStop[] = locatedStops.map((stop) => ({ lat: stop.lat, lon: stop.lon }));
746
+ return previewSeconds(order, geo, haversineKm, roundTrip);
747
  };
748
 
749
  const cancelSettle = () => {
 
779
  // the one-click apply has no record to move. `fallback: true` is what makes an
780
  // arithmetic answer come back as `source: "haversine"` instead of an error.
781
  body: JSON.stringify({
782
+ stops, mode: ROUTE_MODE, roundTrip, fallback: true,
783
  }),
784
  });
785
  const payload = await res.json().catch(() => null);
 
983
  : timerLabel ? "Drive time" : "Add two located stops"}
984
  </span>
985
  </div>
986
+ {/* ⭐⭐ OWNER 2026-08-31 - ONE WAY, OR BACK TO THE START. It sits INSIDE the timer,
987
+ against the figure it changes, because a round trip adds the closing edge and
988
+ therefore a different number; a control for it anywhere else would move a number
989
+ the reader is not looking at. */}
990
+ {onRoundTripChange && (
991
+ <div className="w46-recur-row cg-w46-timer-trip">
992
+ <span className="w46-recur-label">Trip</span>
993
+ <div className="w46-recur-controls" role="group" aria-label="Trip shape">
994
+ <button type="button" className={"w46-recur-pill" + (roundTrip ? "" : " is-on")}
995
+ aria-pressed={!roundTrip} onClick={() => onRoundTripChange(false)}>One way</button>
996
+ <button type="button" className={"w46-recur-pill" + (roundTrip ? " is-on" : "")}
997
+ aria-pressed={roundTrip} onClick={() => onRoundTripChange(true)}>Round trip</button>
998
+ </div>
999
+ </div>
1000
+ )}
1001
  {unlocatedCount > 0 && (
1002
  <p className="cg-w46-timer-note">
1003
  {unlocatedCount.toLocaleString()} stop{unlocatedCount === 1 ? " has" : "s have"} no
 
1029
  ))}
1030
  {timerError && <p className="cg-w46-timer-error" role="alert">{timerError}</p>}
1031
  </section>
1032
+ {/* ⭐⭐ OWNER 2026-08-31 - THE STOP LIST IS THE RAIL, SAME FORMATTING.
1033
+ Owner: *"Same as the rail, same formatting too i believe"*, and then the exact scope:
1034
+ *"The only difference with the rail is that route you can have an x button to remove a
1035
+ record, and also an add record button where it provides the dropdown for the user to
1036
+ add more customer to the route."* So the row wears `.cg-view-row` / `.cg-view-main` /
1037
+ `.cg-view-text` / `.cg-view-name` exactly as a Route row does, drags whole rather than
1038
+ by a grip, and carries the ordinal in the purple disc where the rail carries the Route
1039
+ mark. The `<ol>` stays an `<ol>`: a drive IS an ordered list, and the class the panel's
1040
+ own stylesheet targets rides alongside the rail's. */}
1041
  {stopIds.length ? (
1042
+ <ol className="cg-w44-route-stops cg-view-list">
1043
  {displayIds.map((pid, index) => (
1044
  <li key={pid}
1045
+ className={"cg-view-row cg-w46-stop-row" + (dragPid === pid ? " is-viewdrag" : "")}
1046
+ draggable={canEdit}
1047
+ onDragStart={(event) => {
1048
+ if (!canEdit) return;
1049
+ event.dataTransfer.effectAllowed = "move";
1050
+ try { event.dataTransfer.setData("text/plain", String(pid)); }
1051
+ catch { /* Some browsers refuse a payload; the drag still works. */ }
1052
+ beginStopDrag(pid);
1053
+ }}
1054
+ onDragEnd={() => endStopDrag()}
1055
  onDragOver={(event) => {
1056
  if (dragPid === null) return;
1057
  event.preventDefault();
 
1062
  event.preventDefault();
1063
  dropStopDrag(stopView, pid);
1064
  }}>
1065
+ {/* ⭐⭐ D-619 CLOSED WITHOUT REOPENING WHAT THE OWNER REMOVED. Deleting the per-stop
1066
+ `< >` and the typed Position took the only KEYBOARD reorder with them, because
1067
+ the drag grip is pointer-only. The owner's instruction was that drag replaces
1068
+ those CONTROLS, not that reordering becomes pointer-only, so the gesture moves
1069
+ onto the row's EXISTING focusable element: Alt + Up / Alt + Down, calling the
1070
+ same `commitStopMove` the arrows called, with the same `stopView` target that
1071
+ keeps a pruned list honest. No new tab stop, no new control, nothing wider.
1072
+ ⛔ ALT IS DELIBERATE. A bare ArrowUp/ArrowDown inside a scrolling panel is the
1073
+ reader moving through the list, and stealing it would make the list impossible
1074
+ to walk. `aria-keyshortcuts` is what announces the pair. */}
1075
+ <button type="button" className="cg-view-main"
 
 
 
 
 
 
 
 
 
 
 
1076
  aria-label={`Open stop ${index + 1} record`}
1077
+ aria-keyshortcuts={canEdit ? "Alt+ArrowUp Alt+ArrowDown" : undefined}
1078
+ title={canEdit ? "Alt + Up or Alt + Down moves this stop" : undefined}
1079
+ onKeyDown={(event) => {
1080
+ if (!canEdit || !event.altKey || busy) return;
1081
+ if (event.key === "ArrowUp" && index > 0) {
1082
+ event.preventDefault();
1083
+ commitStopMove(stopView, pid, String(index));
1084
+ } else if (event.key === "ArrowDown" && index < displayIds.length - 1) {
1085
+ event.preventDefault();
1086
+ commitStopMove(stopView, pid, String(index + 2));
1087
+ }
1088
+ }}
1089
  aria-describedby={`cg-route-stop-name-${pid}`} onClick={() => onOpenRecord(pid)}>
1090
  {/* The ordinal is furniture: it says where in the drive this falls, and the
1091
  accessible name above already carries it, so it is hidden from the reader
1092
  rather than announced twice. */}
1093
  <span className="cg-w46-stop-index" aria-hidden="true">{index + 1}</span>
1094
+ <span className="cg-view-text">
1095
+ <span className="cg-view-name" id={`cg-route-stop-name-${pid}`}>
1096
+ {stopIdentity(stopLabels[pid], pid)}
1097
+ </span>
1098
  </span>
1099
  </button>
1100
+ {/* ⛔ OWNER 2026-08-31, TWICE: *"the < > for the route panel where you can choose
1101
+ the numbers i thought they're deleted. I still see them up"*. Move earlier,
1102
+ Position, Move and Move later are gone; DRAG IS THE GESTURE, exactly as it now
1103
+ is for a Route row. The x stays because removing a stop is not a reorder and a
1104
+ drag cannot express it - it is the one difference the owner named.
1105
+ ⚠ THE COST, SAID OUT LOUD: those four controls were the KEYBOARD path, so a
1106
+ stop can no longer be reordered without a pointer. Recorded here so the next
1107
+ reader does not read it as an oversight and quietly put them back. */}
1108
  {canEdit && (
1109
+ <button type="button" className="cg-view-more cg-w46-stop-remove" disabled={busy}
1110
+ aria-label={`Remove stop ${index + 1} from this route`}
1111
+ title="Remove stop" onClick={() => commitStopRemove(route, pid)}>
1112
+ <svg viewBox="0 0 16 16" aria-hidden="true"><path d="m4 4 8 8M12 4l-8 8" /></svg>
1113
+ </button>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1114
  )}
1115
  {orderErrors[pid] && <span id={`cg-route-order-error-${pid}`}
1116
  className="cg-w44-route-order-error" role="alert">{orderErrors[pid]}</span>}
 
1118
  ))}
1119
  </ol>
1120
  ) : <p className="cg-w44-route-empty">No stops yet. Add customers from a route source.</p>}
1121
+ {/* ⭐⭐ OWNER 2026-08-31 - THE OTHER DIFFERENCE FROM THE RAIL: *"an add record button
1122
+ where it provides the dropdown for the user to add more customer to the route."*
1123
+ It wears the rail's own `.cg-create-new` shape, and its list is the rail's
1124
+ `.cg-find-view` box over the book the panel ALREADY HOLDS: `stopLabels` is built from
1125
+ `allRows` in `MapView`, so this needs no second fetch and can only offer records the
1126
+ reader can already see. ⛔ The write is the SAME membership door the x uses, with
1127
+ `present: true` - one door for both directions, so a stop cannot be added through a
1128
+ path the removal wall does not guard. */}
1129
+ {canEdit && (
1130
+ <div className="cg-create-new cg-w46-stop-add">
1131
+ <button type="button" className="cg-link-btn cg-create-btn" aria-haspopup="menu"
1132
+ aria-expanded={addStopOpen} disabled={busy}
1133
+ onClick={() => { setAddStopOpen(!addStopOpen); setAddStopQuery(""); }}>
1134
+ <span className="cg-create-icon" aria-hidden="true">+</span>
1135
+ <span className="cg-create-label">Add record…</span>
1136
+ </button>
1137
+ {addStopOpen && (
1138
+ <div className="cg-view-menu cg-w46-stop-addmenu" role="menu">
1139
+ <div className="cg-find-view">
1140
+ <svg className="cg-find-view-icon" width="14" height="14" viewBox="0 0 16 16"
1141
+ fill="none" aria-hidden="true">
1142
+ <circle cx="7" cy="7" r="4.4" stroke="currentColor" strokeWidth="1.35" />
1143
+ <path d="m10.4 10.4 3.1 3.1" stroke="currentColor" strokeWidth="1.35"
1144
+ strokeLinecap="round" />
1145
+ </svg>
1146
+ <input type="text" value={addStopQuery} placeholder="Find…" autoFocus
1147
+ aria-label="Find a record to add to this Route"
1148
+ onChange={(event) => setAddStopQuery(event.target.value)}
1149
+ onKeyDown={(event) => { if (event.key === "Escape") setAddStopOpen(false); }} />
1150
+ </div>
1151
+ {addableStops.length ? addableStops.map((candidate) => (
1152
+ <button type="button" role="menuitem" key={candidate.pid} disabled={busy}
1153
+ onClick={() => { setAddStopOpen(false); commitStopAdd(route, candidate.pid); }}>
1154
+ {candidate.label}
1155
+ </button>
1156
+ )) : (
1157
+ <span className="cg-w44-route-empty">
1158
+ {addStopQuery.trim()
1159
+ ? "No record matches that search."
1160
+ : "Every record you can see is already on this Route."}
1161
+ </span>
1162
+ )}
1163
+ {addStopOverflow > 0 && (
1164
+ <span className="cg-w44-route-empty">
1165
+ {addStopOverflow.toLocaleString()} more match. Keep typing to narrow them.
1166
+ </span>
1167
+ )}
1168
+ </div>
1169
+ )}
1170
+ </div>
1171
+ )}
1172
  {mapsUrl && <a className="cg-w44-route-maps" href={mapsUrl} target="_blank" rel="noopener noreferrer">Open Maps</a>}
1173
  {route.mapsUrl && !mapsUrl && <span className="cg-w44-route-empty">Maps link is unavailable.</span>}
1174
  <section className="cg-w44-route-map-links" aria-labelledby="cg-route-map-links-title">
 
1269
  <input className="cg-input" type="url" value={editMapsUrl} maxLength={2048}
1270
  placeholder="https://www.google.com/maps/..." onChange={(event) => setEditMapsUrl(event.target.value)} />
1271
  </label>
1272
+ {/* OWNER 2026-08-31 item 4, second half: the Maps link cap belongs to the Google Maps
1273
+ block, not to Daily delivery. It is a property of the LINK, and it was sitting
1274
+ under a scheduling heading where nobody looking for it would think to read. The
1275
+ value still travels in the delivery request; only its place on screen moved. */}
1276
+ <label className="cg-w44-route-label">Stops per Maps link
1277
+ <input className="cg-input" type="number" min={2} max={10} value={deliveryMapsPerLink}
1278
+ onChange={(event) => setDeliveryMapsPerLink(
1279
+ Math.max(2, Math.min(10, Number(event.target.value) || 2))
1280
+ )} />
1281
+ </label>
1282
+ {/* OWNER 2026-08-31 item 2 - EVERY ROUTE GETS ITS OWN COLOUR, EDITABLE HERE.
1283
+ The colour was already the record's own and already painted the line and the
1284
+ sidebar swatch (`MapView.tsx::overlaidRoutes`); what did not exist was any way to
1285
+ CHANGE it. `route_system.py::put_route` already reads `raw.get("color", ...)`
1286
+ through `_color`, so the server door needed nothing: an unrecognised value falls
1287
+ back to the ordinal default rather than painting the SVG initial black. */}
1288
+ <div className="cg-w44-route-label">Route colour
1289
+ <div className="cg-w44-route-colors">
1290
+ {ROUTE_SWATCHES.map((swatch) => (
1291
+ <button key={swatch} type="button" disabled={busy}
1292
+ className={"cg-w44-route-swatch" + (editColor.toUpperCase() === swatch ? " is-on" : "")}
1293
+ style={{ backgroundColor: swatch }} aria-pressed={editColor.toUpperCase() === swatch}
1294
+ aria-label={`Use ${swatch} for this Route`} onClick={() => setEditColor(swatch)} />
1295
+ ))}
1296
+ <input className="cg-w44-route-colorpick" type="color" value={editColor} disabled={busy}
1297
+ aria-label="Pick any colour for this Route"
1298
+ onChange={(event) => setEditColor(event.target.value.toUpperCase())} />
1299
+ </div>
1300
+ </div>
1301
  {/* ⭐⭐ D-599 / W46-T22 - THE ROUTE'S ZONE. Until wave 46's hotfix no route record
1302
  carried a zone at all, so this control had nothing to write and did not exist:
1303
  Routes and Zones were two separate tables and `__zone__` was a field on a CUSTOMER
 
1326
  <div className="cg-form-actions">
1327
  <button type="button" className="cg-btn cg-btn--primary" disabled={busy}
1328
  onClick={() => finish(onUpdate(route, { mapsUrl: editMapsUrl.trim(),
1329
+ zoneId: editZoneId || null, color: editColor }))}>
1330
  Save Route
1331
  </button>
1332
  <button type="button" className="cg-btn" disabled={busy} onClick={() => finish(onShare(route))}>Share</button>
 
1403
  </section>
1404
  )}
1405
  {canEdit && (
1406
+ /* ⭐ OWNER 2026-08-31 item 4 - THIS IS THE "REPEAT EVERY" CONTROL, SAID ABOUT A ROUTE.
1407
+ Owner: *"this whole function needs to be almost the exact same formatting as our
1408
+ 'Repeat every' layout under date field. its practically the same thing."* It IS the
1409
+ same thing: a rule that fires on a cadence. So it borrows the date editor's own
1410
+ `w46-recur-*` contract (`field-panels.css`) rather than growing a second look for
1411
+ one idea, and the sentence reads left to right the way that one does.
1412
+ ⛔ THE CADENCE IS NOT A CHOICE YET, AND THE CONTROL SAYS SO RATHER THAN OFFERING
1413
+ ONE. `route_delivery` mints a fixed daily 08:00 cron; rendering an interval box
1414
+ this server would ignore is the shape of a control that lies. */
1415
  <section className="cg-w44-route-delivery" aria-labelledby="cg-route-delivery-title">
1416
+ <div className="w46-recur-head">
1417
+ <h3 className="cg-pop-title" id="cg-route-delivery-title">Daily delivery</h3>
1418
+ </div>
1419
+ <div className="w46-recur-card">
1420
+ <div className="w46-recur-row">
1421
+ <span className="w46-recur-label">Repeat every</span>
1422
+ <div className="w46-recur-controls">
1423
+ <span className="w46-recur-word">day, at 08:00 ({deliveryTimezone})</span>
1424
+ </div>
1425
+ </div>
1426
+ <div className="w46-recur-row">
1427
+ <span className="w46-recur-label">Send to</span>
1428
+ <div className="w46-recur-controls">
1429
+ <span className="w46-recur-word">
1430
+ {route.assignee ? `${route.assignee}'s Inbox` : "the assignee's Inbox"}
1431
+ </span>
1432
+ </div>
1433
+ </div>
1434
+ <div className="w46-recur-row">
1435
+ <span className="w46-recur-label">Stop order</span>
1436
+ <div className="w46-recur-controls">
1437
+ <span className="w46-recur-word">
1438
+ Frozen as it stands now, {stopIds.length.toLocaleString()} stops.
1439
+ </span>
1440
+ </div>
1441
+ </div>
1442
+ <div className="cg-form-actions">
1443
+ <button type="button" className="cg-btn cg-btn--primary"
1444
+ disabled={deliveryBusy || stopIds.length < 2 || !route.assignee || savedAssigneeUnavailable}
1445
+ onClick={() => scheduleDelivery(route)}>
1446
+ {deliveryBusy ? "Scheduling" : "Schedule delivery"}
1447
+ </button>
1448
+ </div>
1449
  </div>
 
 
 
 
 
 
 
 
 
 
 
1450
  {stopIds.length < 2 && (
1451
  <span className="cg-w44-route-empty">Add at least two stops before scheduling.</span>
1452
  )}
 
1520
  );
1521
  }
1522
 
1523
+ /* ── The rail itself ─────────────────────────────────────────────────────────────────────
1524
+ One recursive level: folders first as `.cg-fold` disclosure groups, then the Routes filed
1525
+ at that level as `.cg-view-row`s. Both kinds of row drag, and both drop ABOVE the row they
1526
+ are released on, which is the gesture `ViewSidebar` teaches.
1527
+
1528
+ ⛔ MOVE UP / MOVE DOWN ARE GONE FROM THE "..." MENU, on the owner's ruling that drag
1529
+ REPLACES them. Two ways to reorder in one rail is what made the menu long enough to need
1530
+ scrolling, and the length of that menu is half of why the row could not be compact. */
1531
+ const dropReorder = (siblings: string[], moved: string, over: string, kind: "route" | "folder") => {
1532
+ const from = siblings.indexOf(moved);
1533
+ const to = siblings.indexOf(over);
1534
+ if (from < 0 || to < 0 || from === to) return;
1535
+ const next = [...siblings];
1536
+ next.splice(to, 0, next.splice(from, 1)[0]);
1537
+ finish(kind === "route" ? onRouteReorder(next) : onFolderReorder(next));
1538
+ };
1539
+
1540
+ const renderLevel = (parent: string, depth: number): ReactElement[] => {
1541
+ const out: ReactElement[] = [];
1542
+ const childFolders = (foldersByParent.get(parent) || [])
1543
+ .filter((folder) => !query || folderMatches.has(folder.id));
1544
+ const childRoutes = (routesByFolder.get(parent) || [])
1545
+ .filter((item) => !query || item.name.toLowerCase().includes(query));
1546
+ const folderIds = childFolders.map((folder) => folder.id);
1547
+ const routeIds = childRoutes.map((item) => item.id);
1548
+
1549
+ for (const folder of childFolders) {
1550
+ // A live find shows every surviving folder open, whatever the stored set holds, and the
1551
+ // chevron is drawn from THAT state so a click means what it looks like (W41-T34's rule).
1552
+ const shut = !query && shutFolders.has(folder.id);
1553
+ const empty = !(foldersByParent.get(folder.id) || []).length
1554
+ && !(routesByFolder.get(folder.id) || []).length;
1555
+ out.push(
1556
+ <div className={"cg-fold" + (rowOver === `folder:${folder.id}` && rowDrag ? " is-drop" : "")}
1557
+ key={`folder:${folder.id}`} style={depth ? { marginLeft: 12 } : undefined}>
1558
+ <div className="cg-fold-head"
1559
+ draggable={renameId !== `folder:${folder.id}`}
1560
+ onDragStart={(event) => {
1561
+ event.dataTransfer.setData(ROUTE_FOLDER_DRAG, folder.id);
1562
+ event.dataTransfer.effectAllowed = "move";
1563
+ setRowDrag(`folder:${folder.id}`);
1564
+ }}
1565
+ onDragEnd={() => { setRowDrag(null); setRowOver(null); }}
1566
+ onDragOver={(event) => {
1567
+ if (!event.dataTransfer.types.includes(ROUTE_FOLDER_DRAG)) return;
1568
+ event.preventDefault();
1569
+ setRowOver(`folder:${folder.id}`);
1570
+ }}
1571
+ onDragLeave={() => setRowOver((current) => current === `folder:${folder.id}` ? null : current)}
1572
+ onDrop={(event) => {
1573
+ const moved = event.dataTransfer.getData(ROUTE_FOLDER_DRAG);
1574
+ setRowDrag(null); setRowOver(null);
1575
+ if (!moved || moved === folder.id) return;
1576
+ event.preventDefault();
1577
+ dropReorder(folderIds, moved, folder.id, "folder");
1578
+ }}>
1579
+ <button type="button" className="cg-fold-toggle" aria-expanded={!shut}
1580
+ aria-label={`${shut ? "Open" : "Close"} folder ${folder.name}`}
1581
+ onClick={() => toggleFolder(folder.id)}>
1582
+ <FolderMark size={16} />
1583
+ {renameId === `folder:${folder.id}` ? (
1584
+ <input className="cg-input cg-fold-rename" autoFocus defaultValue={folder.name}
1585
+ aria-label={`Rename ${folder.name}`} onClick={(event) => event.stopPropagation()}
1586
+ onBlur={(event) => {
1587
+ const value = event.target.value.trim();
1588
+ if (value && value !== folder.name) finish(onFolderUpdate(folder, { name: value }));
1589
+ setRenameId(null);
1590
+ }}
1591
+ onKeyDown={(event) => {
1592
+ if (event.key === "Enter") event.currentTarget.blur();
1593
+ if (event.key === "Escape") setRenameId(null);
1594
+ }} />
1595
+ ) : <span className="cg-fold-name">{folder.name}</span>}
1596
+ <svg className={"cg-fold-chev" + (shut ? " is-shut" : "")} width="12" height="12"
1597
+ viewBox="0 0 16 16" fill="none" aria-hidden="true">
1598
+ <path d="m4 6 4 4 4-4" stroke="currentColor" strokeWidth="1.5"
1599
+ strokeLinecap="round" strokeLinejoin="round" />
1600
+ </svg>
1601
+ </button>
1602
+ <button type="button" className="cg-view-more" aria-label={`Actions for ${folder.name}`}
1603
  aria-expanded={menuId === `folder:${folder.id}`}
1604
  onClick={() => setMenuId(menuId === `folder:${folder.id}` ? null : `folder:${folder.id}`)}>...</button>
1605
+ {menuId === `folder:${folder.id}` && <div className="cg-view-menu" role="menu">
1606
  <button type="button" role="menuitem"
1607
+ onClick={() => { setRenameId(`folder:${folder.id}`); setMenuId(null); }}>Rename</button>
 
 
 
 
1608
  {folder.parent && <button type="button" role="menuitem"
1609
+ onClick={() => { setMenuId(null); finish(onFolderUpdate(folder, { parent: null })); }}>Move to Routes</button>}
1610
+ {folders.filter((target) => target.id !== folder.id && target.id !== folder.parent).map((target) =>
1611
  <button type="button" role="menuitem" key={target.id}
1612
  onClick={() => { setMenuId(null); finish(onFolderUpdate(folder, { parent: target.id })); }}>
1613
  Move into {target.name}
 
1616
  onClick={() => { setMenuId(null); if (window.confirm(`Delete ${folder.name}? Its contents move to Routes.`)) finish(onFolderDelete(folder)); }}>Delete</button>
1617
  </div>}
1618
  </div>
1619
+ {!shut && renderLevel(folder.id, depth + 1)}
1620
+ {!shut && empty && <p className="cg-fold-empty">This folder is empty.</p>}
1621
+ </div>
1622
+ );
1623
+ }
1624
+
1625
+ for (const item of childRoutes) {
1626
+ out.push(
1627
+ <div key={item.id} style={depth ? { marginLeft: 12 } : undefined}
1628
+ className={"cg-view-row"
1629
+ + (activeRouteId === item.id ? " is-active" : "")
1630
+ + (item.outsideFilter ? " is-outside" : "")
1631
+ + (rowDrag === `route:${item.id}` ? " is-viewdrag" : "")
1632
+ + (rowOver === `route:${item.id}` && rowDrag && rowDrag !== `route:${item.id}`
1633
+ ? " is-drop-above" : "")}
1634
+ draggable={renameId !== item.id}
1635
+ onDragStart={(event) => {
1636
+ event.dataTransfer.setData(ROUTE_DRAG, item.id);
1637
+ event.dataTransfer.effectAllowed = "move";
1638
+ setRowDrag(`route:${item.id}`);
1639
+ }}
1640
+ onDragEnd={() => { setRowDrag(null); setRowOver(null); }}
1641
+ onDragOver={(event) => {
1642
+ if (!event.dataTransfer.types.includes(ROUTE_DRAG)) return;
1643
+ event.preventDefault();
1644
+ setRowOver(`route:${item.id}`);
1645
+ }}
1646
+ onDragLeave={() => setRowOver((current) => current === `route:${item.id}` ? null : current)}
1647
+ onDrop={(event) => {
1648
+ const moved = event.dataTransfer.getData(ROUTE_DRAG);
1649
+ setRowDrag(null); setRowOver(null);
1650
+ if (!moved || moved === item.id) return;
1651
+ event.preventDefault();
1652
+ dropReorder(routeIds, moved, item.id, "route");
1653
+ }}>
1654
+ {/* ⭐ W47-T07 / instruction 9: a REAL checkbox, not a pressed button.
1655
+ ⛔ OWNER 2026-08-31, ON SEEING IT DEPLOYED: *"remove the dots below the checkbox on
1656
+ the routes rail, its ugly af, what is that even there for"*. The dot was the Route's
1657
+ colour - the SAME `item.color` the drawn line uses - and it is gone as a separate
1658
+ element. The colour is NOT lost: it tints the checkbox itself through `accentColor`,
1659
+ so ticking a Route still shows you which line on the map is about to be yours,
1660
+ without a second mark in the row. */}
1661
+ <label className="cg-w44-route-toggle" title={`Show ${item.name} on the map`}>
1662
+ {/* ⚠ `accent-color` PAINTS A CHECKED BOX ONLY, so on its own it left an unticked rail
1663
+ with no colour anywhere - a real gap against the owner's *"each route should have a
1664
+ color edit function"*, and one the removal of the dot created. The ring is the
1665
+ same checkbox wearing its own colour at rest, NOT the second mark that was
1666
+ removed: it is drawn on the input itself, adds no element and no width. */}
1667
+ <input type="checkbox" checked={selectedIds.has(item.id)}
1668
+ style={{ accentColor: item.color, boxShadow: `0 0 0 1.5px ${item.color}` }}
1669
+ aria-label={`Show ${item.name} on the map`}
1670
+ onChange={() => onToggle(item)} />
1671
+ </label>
1672
+ <button type="button" className="cg-view-main" onClick={() => {
1673
+ setError(null); setCreating(false); onActiveRouteChange(item.id);
1674
+ }}>
1675
+ {/* Owner item 3: the ONE difference from a view row. Every Route wears the same
1676
+ waypoint mark; the ordinal that used to prefix the name is gone from the rail. */}
1677
+ <IconRoute />
1678
+ <span className="cg-view-text">
1679
+ <span className="cg-view-name">{item.name}</span>
1680
+ {(item.shared || item.sharedOut || item.outsideFilter) && (
1681
+ <span className="cg-view-desc">
1682
+ {item.shared ? `Shared by ${item.owner || "another user"}`
1683
+ : item.sharedOut ? "Shared" : "Outside filter"}
1684
+ </span>
1685
+ )}
1686
+ </span>
1687
+ </button>
1688
+ <button type="button" className="cg-view-more" aria-label={`Actions for ${item.name}`}
1689
+ aria-expanded={menuId === item.id} onClick={() => setMenuId(menuId === item.id ? null : item.id)}>...</button>
1690
+ {menuId === item.id && <div className="cg-view-menu" role="menu">
1691
+ <button type="button" role="menuitem" disabled={!mayRouteAction(item, "duplicate")}
1692
+ onClick={() => { setMenuId(null); finish(onDuplicate(item)); }}>Duplicate</button>
1693
+ <button type="button" role="menuitem" disabled={!mayRouteAction(item, "star")}
1694
+ onClick={() => { setMenuId(null); finish(onUpdate(item, { starred: !item.starred })); }}>
1695
+ {item.starred ? "Unstar" : "Star"}
1696
+ </button>
1697
+ <button type="button" role="menuitem" disabled={!mayRouteAction(item, "share")}
1698
+ onClick={() => { setMenuId(null); finish(onShare(item)); }}>Share</button>
1699
+ {folders.filter((folder) => folder.id !== item.folderId).map((folder) =>
1700
+ <button type="button" role="menuitem" key={folder.id}
1701
  onClick={() => { setMenuId(null); finish(onRouteMove(item, folder.id)); }}>Move to {folder.name}</button>)}
1702
+ {item.folderId && <button type="button" role="menuitem"
1703
+ onClick={() => { setMenuId(null); finish(onRouteMove(item, null)); }}>Move to Routes</button>}
1704
+ <button type="button" role="menuitem" disabled={!mayRouteAction(item, "delete")}
1705
+ onClick={() => { setMenuId(null); if (window.confirm(`Delete ${item.name}?`)) finish(onDelete(item)); }}>Delete</button>
1706
+ </div>}
1707
+ </div>
1708
+ );
1709
+ }
1710
+ return out;
1711
+ };
1712
+
1713
+ const rows = renderLevel(ROOT_LEVEL, 0);
1714
+ return (
1715
+ <section className="cg-w44-route-nav" aria-label="Named routes">
1716
+ {/* Owner item 3 - the SAME create door the Views rail mounts (`.cg-create-new` /
1717
+ `.cg-create-btn` are a shared contract, see `ViewSidebar.tsx`'s note on them), with the
1718
+ two things a Routes rail can make behind it. */}
1719
+ <div className="cg-create-new">
1720
+ <button type="button" className="cg-link-btn cg-create-btn" aria-haspopup="menu"
1721
+ aria-expanded={createMenu} onClick={() => { setMenuId(null); setCreateMenu(!createMenu); }}>
1722
+ <span className="cg-create-icon" aria-hidden="true">+</span>
1723
+ <span className="cg-create-label">Create new…</span>
1724
+ </button>
1725
+ {createMenu && <div className="cg-view-menu" role="menu">
1726
+ <button type="button" role="menuitem" onClick={() => {
1727
+ setCreateMenu(false); setError(null); onCreateStart(); setCreating(true);
1728
+ }}>Route</button>
1729
+ <button type="button" role="menuitem" onClick={() => {
1730
+ setCreateMenu(false); setCreatingFolder(true);
1731
+ }}>Folder</button>
1732
+ </div>}
1733
+ </div>
1734
+ <div className="cg-find-view">
1735
+ <svg className="cg-find-view-icon" width="14" height="14" viewBox="0 0 16 16" fill="none"
1736
+ aria-hidden="true">
1737
+ <circle cx="7" cy="7" r="4.4" stroke="currentColor" strokeWidth="1.35" />
1738
+ <path d="m10.4 10.4 3.1 3.1" stroke="currentColor" strokeWidth="1.35" strokeLinecap="round" />
1739
+ </svg>
1740
+ <input type="text" value={routeQuery} placeholder="Find…" aria-label="Find a route"
1741
+ onChange={(event) => setRouteQuery(event.target.value)}
1742
+ onKeyDown={(event) => { if (event.key === "Escape") setRouteQuery(""); }} />
1743
+ </div>
1744
+ {creatingFolder && <div className="cg-view-create cg-create-form cg-fold-form">
1745
+ <input className="cg-input" value={folderName} maxLength={80} autoFocus
1746
+ aria-label="New Route folder name" onChange={(event) => setFolderName(event.target.value)} />
1747
+ <div className="cg-form-actions">
1748
+ <button type="button" className="cg-btn cg-btn--primary" disabled={busy || !folderName.trim()}
1749
+ onClick={() => { setBusy(true); void onFolderCreate(folderName.trim(), null).then((message) => {
1750
+ setError(message); if (!message) { setFolderName(""); setCreatingFolder(false); }
1751
+ }).finally(() => setBusy(false)); }}>Create</button>
1752
+ <button type="button" className="cg-btn" disabled={busy}
1753
+ onClick={() => { setFolderName(""); setCreatingFolder(false); }}>Cancel</button>
1754
+ </div>
1755
+ </div>}
1756
+ <div className="cg-view-list" aria-label="Route folder contents">
1757
+ {rows}
1758
+ {!rows.length && <p className="cg-w44-route-empty">
1759
+ {query ? "No Route matches that search."
1760
+ : "No routes yet. Create one from selected Zones or records."}
1761
  </p>}
1762
  </div>
1763
  {createdRoute && <div className="cg-w44-route-created" role="dialog" aria-label="Route privacy choice">
web/src/customer-grid/routeZoneTypes.ts CHANGED
@@ -87,6 +87,12 @@ export interface MapRouteFolderDto {
87
  export type MapRouteUpdate = {
88
  name?: string;
89
  mapsUrl?: string;
 
 
 
 
 
 
90
  starred?: boolean;
91
  assignee?: string | null;
92
  date?: string | null;
 
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;
web/src/customer-grid/viewModes.tsx CHANGED
@@ -557,10 +557,10 @@ export function MapSettings({
557
  aria-expanded={routeOpen}
558
  aria-controls="cg-route-popover"
559
  onClick={onToggleRoute}
560
- title="Show or hide Routes and Zones"
561
  >
562
  <IconRouteZone />
563
- <span>Routes and Zones{selectedCount >= 2 ? ` / ${selectedCount} selected` : ""}</span>
564
  </button>
565
  {coordChoices.length > 0 && (
566
  <span className="cg-mode-field-mark" aria-hidden><IconLocation /></span>
 
557
  aria-expanded={routeOpen}
558
  aria-controls="cg-route-popover"
559
  onClick={onToggleRoute}
560
+ title="Show or hide Routes"
561
  >
562
  <IconRouteZone />
563
+ <span>Routes{selectedCount >= 2 ? ` / ${selectedCount} selected` : ""}</span>
564
  </button>
565
  {coordChoices.length > 0 && (
566
  <span className="cg-mode-field-mark" aria-hidden><IconLocation /></span>
web/src/styles/wave42/route-nav.css CHANGED
@@ -445,3 +445,158 @@
445
  font-size: inherit;
446
  white-space: normal;
447
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
445
  font-size: inherit;
446
  white-space: normal;
447
  }
448
+
449
+ /* ═══════ OWNER 2026-08-31 — THE ROUTES RAIL IS THE VIEWS RAIL ════════════════════════════════
450
+ Owner: *"I need the routes LIST navigation and the routes itself to have the exact same
451
+ interface just like how we have it with view ... Make it the exact same layout. The only
452
+ difference is the icon."*
453
+
454
+ ⭐ SO THERE IS ALMOST NO CSS HERE, AND THAT IS THE POINT. `RouteNav` now renders the Views
455
+ rail's own classes (`.cg-view-row`, `.cg-view-main`, `.cg-fold*`, `.cg-create-new`,
456
+ `.cg-find-view`), which index.css already sizes, spaces and hovers. Anything restated below
457
+ would be a second copy free to drift, so the only rules here are the ones that describe what
458
+ this rail has and the Views rail does not: a colour checkbox on the row, and the Route mark.
459
+
460
+ ⛔ `#cg-route-popover` PREFIXES EVERY SELECTOR because this sheet is @imported at the top of
461
+ index.css and therefore loses every equal-specificity tie with it — the rule stated at the
462
+ head of this file. An id beats a class, so these land. */
463
+
464
+ /* ⛔ `display` IS THE LOAD-BEARING DECLARATION HERE, and leaving it out is what put the swatch
465
+ UNDER the checkbox on the first deployed build. The older `.cg-w44-route-toggle` rule above
466
+ sets `display: grid; place-items: center` for the row shape this rail used to have; that rule
467
+ still matches, and an override that names only `flex` and `padding` inherits the grid. */
468
+ #cg-route-popover .cg-view-row > .cg-w44-route-toggle {
469
+ display: inline-flex;
470
+ flex: 0 0 auto;
471
+ align-items: center;
472
+ gap: 5px;
473
+ padding: 0 0 0 6px;
474
+ background: transparent;
475
+ }
476
+
477
+ /* The Route's colour rides the checkbox itself (`accentColor`, set inline from the record), so
478
+ the row carries ONE mark rather than a checkbox and a coloured dot beside it. */
479
+ #cg-route-popover .cg-view-row .cg-w44-route-toggle input { margin: 0; cursor: pointer; }
480
+
481
+ /* The Route mark takes the gutter a view's mode dot occupies, so the two rails' NAMES start at
482
+ the same x. That alignment is what makes "the exact same layout" true rather than approximate. */
483
+ #cg-route-popover .cg-view-main > .cg-view-route-mark {
484
+ flex: 0 0 16px;
485
+ color: var(--lp-primary);
486
+ }
487
+
488
+ /* A Route whose stops sit outside the current filter. The row still reads normally; the mark is
489
+ the `.cg-view-desc` line the row already carries, so nothing here paints. */
490
+ #cg-route-popover .cg-view-row.is-outside .cg-view-desc { color: var(--lp-yellow-deep); }
491
+
492
+ /* ── OWNER 2026-08-31 item 2: the per-Route colour editor ──────────────────────────────────── */
493
+ #cg-route-popover .cg-w44-route-colors {
494
+ display: flex;
495
+ align-items: center;
496
+ gap: 6px;
497
+ flex-wrap: wrap;
498
+ padding-top: 4px;
499
+ }
500
+
501
+ #cg-route-popover .cg-w44-route-swatch {
502
+ width: 22px;
503
+ height: 22px;
504
+ padding: 0;
505
+ border: 2px solid transparent;
506
+ border-radius: var(--lp-r-sm);
507
+ cursor: pointer;
508
+ }
509
+
510
+ /* The selected swatch is marked by a RING outside its own fill, never by a tick drawn on top:
511
+ half these colours are dark and half are not, so an inked mark would vanish on three of six. */
512
+ #cg-route-popover .cg-w44-route-swatch.is-on {
513
+ border-color: var(--lp-ink);
514
+ box-shadow: 0 0 0 2px var(--lp-surface);
515
+ }
516
+
517
+ #cg-route-popover .cg-w44-route-swatch:focus-visible {
518
+ outline: 2px solid var(--lp-blue-deep);
519
+ outline-offset: 2px;
520
+ }
521
+
522
+ #cg-route-popover .cg-w44-route-colorpick {
523
+ width: 28px;
524
+ height: 22px;
525
+ padding: 0;
526
+ border: 1px solid var(--lp-line);
527
+ border-radius: var(--lp-r-sm);
528
+ background: transparent;
529
+ cursor: pointer;
530
+ }
531
+
532
+ /* ── OWNER 2026-08-31: the stop list is the rail, with an x and an add door ─────────────────
533
+ Owner: *"Same as the rail, same formatting too i believe"* / *"The only difference with the
534
+ rail is that route you can have an x button to remove a record, and also an add record button
535
+ where it provides the dropdown."* The rows already wear `.cg-view-row` and `.cg-view-main`, so
536
+ index.css sizes and hovers them; only the two differences and the list reset live here. */
537
+ #cg-route-popover .cg-w44-route-stops.cg-view-list {
538
+ margin: 0;
539
+ padding: 0;
540
+ list-style: none;
541
+ }
542
+
543
+ #cg-route-popover .cg-w46-stop-row.is-viewdrag { opacity: 0.45; }
544
+
545
+ /* The x. It takes `.cg-view-more`'s box, so it appears on hover exactly as the rail's "..." does
546
+ and cannot widen the row. */
547
+ #cg-route-popover .cg-w46-stop-remove {
548
+ display: grid;
549
+ place-items: center;
550
+ color: var(--lp-muted);
551
+ }
552
+
553
+ #cg-route-popover .cg-w46-stop-remove:hover { color: var(--lp-red-deep, #b3261e); }
554
+
555
+ #cg-route-popover .cg-w46-stop-remove svg {
556
+ width: 12px;
557
+ height: 12px;
558
+ fill: none;
559
+ stroke: currentColor;
560
+ stroke-width: 1.6;
561
+ stroke-linecap: round;
562
+ }
563
+
564
+ /* The add-record door and its menu. `position: relative` is what keeps the popover tied to the
565
+ button rather than to the scrolling panel, which is where a menu goes wandering. */
566
+ #cg-route-popover .cg-w46-stop-add { position: relative; }
567
+
568
+ #cg-route-popover .cg-w46-stop-addmenu {
569
+ position: absolute;
570
+ z-index: var(--cg-z-menu);
571
+ left: 0;
572
+ right: 0;
573
+ max-height: 280px;
574
+ overflow-y: auto;
575
+ }
576
+
577
+ /* One row per candidate, ellipsised: a customer name is arbitrary length and a menu that grows
578
+ sideways pushes the panel off the map. */
579
+ #cg-route-popover .cg-w46-stop-addmenu button[role="menuitem"] {
580
+ display: block;
581
+ width: 100%;
582
+ overflow: hidden;
583
+ text-align: left;
584
+ text-overflow: ellipsis;
585
+ white-space: nowrap;
586
+ }
587
+
588
+ /* One way / Round trip, inside the drive-time card it changes. */
589
+ #cg-route-popover .cg-w46-timer-trip { padding-top: 8px; }
590
+
591
+ /* ⛔ `.w46-recur-pill` IS A 28x28 SQUARE, sized for the seven single-letter weekday initials it
592
+ was built for, so borrowing it for "One way" / "Round trip" wrapped both words inside a circle.
593
+ Observed on the deployed build before this rule existed. The pill's paint, hover, selected
594
+ state and focus ring are all still the date editor's - only the box grows to fit a word, which
595
+ is the whole reason to reuse the class rather than mint a second kind of pill. */
596
+ #cg-route-popover .cg-w46-timer-trip .w46-recur-pill {
597
+ width: auto;
598
+ min-width: 0;
599
+ height: 26px;
600
+ padding: 0 10px;
601
+ white-space: nowrap;
602
+ }
web/src/styles/wave46/map-panels.css CHANGED
@@ -102,13 +102,29 @@
102
 
103
  /* `tabular-nums` plus the floor width keeps every name starting on the same x once the route
104
  passes nine stops, so the column of names reads as a column. */
 
 
 
 
 
 
 
 
 
105
  .cg-w46-stop-index {
106
  flex: 0 0 auto;
107
- min-width: 14px;
108
- color: var(--lp-muted);
 
 
 
 
 
109
  font-size: var(--lp-fs-3xs);
 
110
  font-variant-numeric: tabular-nums;
111
- text-align: right;
 
112
  }
113
 
114
  .cg-w46-stop-name {
 
102
 
103
  /* `tabular-nums` plus the floor width keeps every name starting on the same x once the route
104
  passes nine stops, so the column of names reads as a column. */
105
+ /* ⭐ OWNER 2026-08-31 item 3 - THE STOP ORDINAL IS A FILLED PURPLE DISC WITH WHITE INK.
106
+ Owner: *"the details for each stops under each route should only have the number 1, 2, 3 etc.
107
+ put it inside a purple circle and the font be colored white."* Confirmed in the grill that this
108
+ is the OPENED Route panel's stop list; the rail itself carries no numbering at all.
109
+
110
+ ⚠ IT IS A FIXED SQUARE, NOT A PADDED ONE. A disc sized by its own text is an oval at "10" and
111
+ a circle at "1", and a route of a dozen stops shows both on one screen. 18px holds two digits
112
+ at this size; three digits ellipsise rather than reflowing the row, which is the same trade the
113
+ name beside it already makes. */
114
  .cg-w46-stop-index {
115
  flex: 0 0 auto;
116
+ display: inline-grid;
117
+ place-items: center;
118
+ width: 18px;
119
+ height: 18px;
120
+ border-radius: 50%;
121
+ background: var(--lp-primary);
122
+ color: var(--cg-white);
123
  font-size: var(--lp-fs-3xs);
124
+ font-weight: 600;
125
  font-variant-numeric: tabular-nums;
126
+ line-height: 1;
127
+ overflow: hidden;
128
  }
129
 
130
  .cg-w46-stop-name {
web/wiring_rows/wave42_f.py CHANGED
@@ -20,8 +20,12 @@ ROWS: list[tuple[str, str, str, str, str]] = [
20
  ("W42 C6 post-create privacy prompt receives the new Route",
21
  "customer-grid/RouteNav.tsx", r"createdRoute: MapRouteDto \| null;",
22
  "customer-grid/MapView.tsx", r"createdRoute=\{createdRoute\}"),
23
- ("W42 C6 Route folders ride the listing into a current-level path",
24
- "customer-grid/RouteNav.tsx", r"levelAt\(validAt, folders, routes",
 
 
 
 
25
  "customer-grid/MapView.tsx", r"folders=\{routeFolders\}"),
26
  ("W42 C6 personal Route filing reaches the normalized folder door",
27
  "customer-grid/RouteNav.tsx", r"onRouteMove: \(route: MapRouteDto, folderId: string \| null\)",
 
20
  ("W42 C6 post-create privacy prompt receives the new Route",
21
  "customer-grid/RouteNav.tsx", r"createdRoute: MapRouteDto \| null;",
22
  "customer-grid/MapView.tsx", r"createdRoute=\{createdRoute\}"),
23
+ # RE-AIMED 2026-08-31: the owner's *"exact same layout as views"* rail replaced `levelAt`'s
24
+ # one-level path with the Views rail's disclosure tree, so the old declaring literal names
25
+ # nothing. The WIRING this row exists to prove is unchanged and is what stays pinned: the
26
+ # host's folder list reaches the rail and the rail files Routes against it.
27
+ ("W42 C6 Route folders ride the listing into a folder tree",
28
+ "customer-grid/RouteNav.tsx", r"const foldersByParent = useMemo\(",
29
  "customer-grid/MapView.tsx", r"folders=\{routeFolders\}"),
30
  ("W42 C6 personal Route filing reaches the normalized folder door",
31
  "customer-grid/RouteNav.tsx", r"onRouteMove: \(route: MapRouteDto, folderId: string \| null\)",
web/wiring_rows/wave43_shell_repair.py CHANGED
@@ -15,11 +15,14 @@ ROWS: list[tuple[str, str, str, str, str]] = [
15
  "customer-grid/DatePicker.tsx", r"onChange: \(value: string\) => void;",
16
  "customer-grid/CustomerGrid.tsx",
17
  r'onChange=\{\(value\) => patchAndRecord\(datePicker\.pid, \{ \[dateField\.key\]: value \}, "a date"\)\}'),
18
- ("W43C-T02 recurrence is a required DatePicker contract and persists the field definition",
19
- "customer-grid/DatePicker.tsx",
20
- r'onRecurrence: \(recurrence: DateRecurrence \| null\) => void;',
21
- "customer-grid/CustomerGrid.tsx",
22
- r'onRecurrence=\{\(recurrence\) => saveField\(\{ \.\.\.dateField, recurrence: recurrence \?\? null \}\)\}'),
 
 
 
23
  ]
24
 
25
  DELETIONS: list[tuple[str, str, str, str]] = []
 
15
  "customer-grid/DatePicker.tsx", r"onChange: \(value: string\) => void;",
16
  "customer-grid/CustomerGrid.tsx",
17
  r'onChange=\{\(value\) => patchAndRecord\(datePicker\.pid, \{ \[dateField\.key\]: value \}, "a date"\)\}'),
18
+ # RE-AIMED 2026-08-31. The owner reversed wave 47's R1/R2 - *"Each ROW stores its own repeat
19
+ # rule"* - so the picker no longer persists the FIELD definition and `onRecurrence` is gone
20
+ # with the write it fed. The cross-fence fact this row exists to prove survives the reversal
21
+ # intact and is simply restated for the new contract: the picker cannot edit a repeat without
22
+ # being told WHICH RECORD, and the host is what tells it.
23
+ ("W43C-T02 the repeat editor is per RECORD, so the host must name the record",
24
+ "customer-grid/DatePicker.tsx", r'pid: number;',
25
+ "customer-grid/CustomerGrid.tsx", r'pid=\{datePicker\.pid\}'),
26
  ]
27
 
28
  DELETIONS: list[tuple[str, str, str, str]] = []